branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<repo_name>pierrooTH/circle-products<file_sep>/src/Components/Products.js import React, { Component } from 'react'; import '../css/Products.css'; import './ProductsDetails' import {Link} from 'react-router-dom' export default class Products extends Component { render() { // on récupére les données grâce à props, précédemment récupéré dans le composant App // puis on les ajoute dans un nouveau tableau listProduct qui retourne un tableau en JSX avec les valeurs des données const listsProducts = this.props.products.map((listProduct) => { return ( <tbody className="products__body" key={listProduct.id}> <tr> <td className="title__responsive" data-label="Product name"><Link to={{pathname: "/products-details/" + listProduct.id}} // grâce à l'id du produit on peut transférer le produit en question vers une page plus détaillé grâce au react-router-dom et <Link /> >{listProduct.title}</Link> </td> <td className="title__responsive" data-label="Category"><p className={`${listProduct.category==="men's clothing" ? "category__orange" : "category__green"}`} // utilisation de l'opérateur ternaire pour définir le type de catégorie: // si la catégorie est strictement égal à "men's clothing" alors on utilise la classe "category__orange" sinon on utilise "category__green" >{listProduct.category}</p></td> <td className="title__responsive td__price" data-label="Price"> {Number(listProduct.price).toFixed(2) // utilisation de la méthode .toFixed(2) qui permet de garder 2 chiffres après la virgule } € </td> <td className="title__responsive" data-label="Price (including VAT)"> {Number(listProduct.price * 1.2).toFixed(2) // ajout d'une TVA de 20% au prix de l'API, toujours en utilisant la méthode .toFixed(2) pour fixer le prix à deux chiffres après la virgule } € </td> </tr> </tbody> ); }); return ( <main className="products"> <h1 className="products__title">Products management</h1> <table cellSpacing="0"> <thead className="products__head"> <tr> <th className="table--title">Product name</th> <th className="table--title">Category</th> <th className="table--title">Price</th> <th className="table--title">Price (including VAT)</th> </tr> </thead> {listsProducts} </table> </main> ); } } <file_sep>/src/App.js import React, { useState, useEffect } from 'react'; import './css/App.css'; import './css/Products.css'; import axios from 'axios'; import {Oval} from 'react-loading-icons' import Navigation from './Components/Navigation'; import Products from './Components/Products'; import {BrowserRouter as Router, Route, Switch,} from 'react-router-dom'; import ProductsDetails from './Components/ProductsDetails'; export default function App() { /* Déclaration de plusieurs variables d'état */ const [error, setError] = useState(null); // variable d'état error, son état initial vaut null const [productsData, setProductsData] = useState([]); // variable d'état productsData, son état initial vaut un tableau vide const [isLoaded, setIsLoaded] = useState(false); // variable d'état isLoaded, son état initial vaut false // Fonction anonyme qui va permettre de mettre à jour le prix d'une donnée d'une API grâce à son ID et son prix de départ const updatePrice = (id, price) => { setProductsData((productsData) => // cette fonction va créer un nouveau tableau avec les données de l'API (l'ID et le prix) productsData.map((product) => product.id === Number(id) ? { ...product, price: Number(price) } : product ) ); }; // utilisation du Hook useEffect qui va nous servir a récupérer les données de l'API "fake store API" dès que celles-ci sont chargées useEffect(() => { axios.get("https://fakestoreapi.com/products?limit=7").then((res) => { setIsLoaded(true); // à la récupération des données on change l'état de isLoaded en true setProductsData(res.data); // à la récupération des données on change l'état de productsData : // on ajoute les données de l'API à l'intérieur du tableau vide }, (error) => { setIsLoaded(true); setError(error); } ); }, []); /* Si il y a une erreur on retourne un message d'erreur, sinon si isLoaded vaut true on retourne un chargement de la parge sinon on retourne la page qui a correctement chargée */ if (error) { return <div>Erreur : {error.message}</div> } else if (!isLoaded) { return <div className="loading"> <Oval stroke="#564AFF"/> <p>Loading...</p> </div> } else { return ( <div className="App"> <Router // utilisation de react-router-dom qui permet de créer l'illusion d'avoir plusieurs pages dans notre application > <Navigation // ajout du composant Navigation, qui est le menu de l'application /> <Switch> <Route // route qui renvoie un lien /products-details/id du produit path="/products-details/:id" render={(props) => ( <ProductsDetails products={productsData} // renvoie pour utilisation dans le composant « ProductsDetails » la variable d'état « productsData » updatePrice={updatePrice} // renvoie pour utilisation dans le composant « ProductsDetails » la fonction « updatePrice » {...props} // renvoie renvoie pour utilisation dans le composant « ProductsDetails » l'ensemble des propriétés /> )} /> <Route path="/"> <Products products={productsData} // renvoie pour utilisation dans le composant « Products » la variable d'état « productsData » /> </Route> </Switch> </Router> </div> ) } }
e4c2f89803deae714653439396bd7e3412f98ab7
[ "JavaScript" ]
2
JavaScript
pierrooTH/circle-products
3ef950ceb0335cf9023ecca552d6efe156d9f095
bacab98f0f4a22a79a4a85d2c3b2c7d183a62fa6
refs/heads/master
<file_sep>import sys import xml.dom.minidom import csv document = xml.dom.minidom.parse(sys.argv[1]) header = [] table = document.getElementsByTagName('table') strong = document.getElementsByTagName('strong') stockinfo = [] for b in table[3].getElementsByTagName('b'): for node in b.childNodes: if node.nodeType == node.TEXT_NODE: stockinfo.append(node.nodeValue) for node in strong[0].childNodes: if node.nodeType == node.TEXT_NODE: name = node.nodeValue stockinfo[0] = stockinfo[0][1:] stockinfo[1] = stockinfo[1][1:] print("------------------------------------------------") print("COMPANY PROFILE: " + name) print("LAST: " + stockinfo[0]) if stockinfo[2] > stockinfo[0]: print("CHANGE: +" + stockinfo[1]) else: print("CHANGE: -" + stockinfo[1]) print("OPEN: " + stockinfo[2]) print("PREV " + stockinfo[7]) print("HIGH: " + stockinfo[3]) print("LOW: " + stockinfo[8]) print("ASK: " + stockinfo[4]) print("BID: " + stockinfo[9]) print("VOLUME: " + stockinfo[5]) print("OPEN INT: " + stockinfo[10])<file_sep>#!/bin/sh #blahad git add . sleep 1 printf "Enter commit message: " read message git commit -m "$message" sleep 1 git push origin master <file_sep># stonks <h3><u>Projects Description:</u></h3> <b>alpha</b>: A real-time stock terminal based off bash, python, and TagSoup. Run the bash script and enter the symbol of the stock you want and you will recieve real-time information. Check the screenshot for a sample. <file_sep>#!/bin/bash echo "Please type in the stock symbol: " read input ./data.sh $input <file_sep>java -jar tagsoup-1.2.1.jar --files now.html<file_sep>#!/bin/bash while read SYM do if [ $1 = $SYM ] then wget -q -O - http://www.eoddata.com/stockquote/NASDAQ/$1.htm > now.html java -jar tagsoup-1.2.1.jar --files now.html 2> errorOutput.log > output.log & sleep 2 python3 scraper.py now.xhtml exit 1 fi done < symbolList echo "Sorry, your symbol does not exist within the Exchange List"
228732292de67195fc33d3f18e158f5877d4c468
[ "Markdown", "Python", "Shell" ]
6
Python
ananyasingh7/stonks
7740685645c02ead2044f619d828091438d22a5d
0e22191c38929307f3ef16f1862668edbc0c90d0
refs/heads/master
<repo_name>MuminPojk/Prov<file_sep>/Prov_Alice_Pettersson_Jacks/Prov_Alice_Pettersson_Jacks/Customers.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Prov_Alice_Pettersson_Jacks { class Customers { private int money; public string name; Random generator = new Random(); public void Money() //Slumpar fram kundens pengar { money = generator.Next(0, 100); } public void PrintStats()//Skriver ut kundens stats { Console.WriteLine("This is your customers name: " +name); Console.WriteLine("This is "+ name +"s money: " + money); } public void GetName()//Spelaren får skriva in namnet på sin kund { Console.WriteLine("Skriv in namnet på din kund"); string input = Console.ReadLine(); name = input; } } } <file_sep>/Prov_Alice_Pettersson_Jacks/Prov_Alice_Pettersson_Jacks/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Prov_Alice_Pettersson_Jacks { class Program { static void Main(string[] args) { Customers print2 = new Customers(); //Här skapas det så att man kan ankalla metoder från de 2 olika klasserna Books print = new Books(); print.GetName();// Här under ankallas ett par metoder från de två tidigare skapade klasser print.Book(); print.PrintInfo(); Console.WriteLine("Så här mycket tror du att den kostar:"); print.Evaluate(); print2.GetName(); print2.Money(); print2.PrintStats(); Console.ReadLine(); } } } <file_sep>/Prov_Alice_Pettersson_Jacks/Prov_Alice_Pettersson_Jacks/Books.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Prov_Alice_Pettersson_Jacks { class Books { public int price; private string name; private int rarity; // private string category; private int actualValue; // private bool cursed; Random generator = new Random(); public void Book()// Slumpar fram bokens rarity och value { actualValue = generator.Next(0, 200); rarity = generator.Next(1, 10); } public void PrintInfo()//Skriver ut bokens rarity och value { Console.WriteLine("The vaule of the book was: "+actualValue); Console.WriteLine("The rarity of the book was: " + rarity); } public int Evaluate() //rarity och actual multipliceras och delas sedan på en siffra mellan 50 och 150. { price = rarity * actualValue; int randomProcent = generator.Next(50, 150); price = price / randomProcent; Console.WriteLine(price); return price; } public void GetName()//Spelaren får skriva in vad boken ska heta och namnet ändras till det { Console.WriteLine("Vad ska boken heta?"); string input = Console.ReadLine(); name = input; Console.WriteLine(name); } /*GetCategory returnerar helt enkelt värdet av category, och GetName returnerar name. IsCursed returnerar antingen true eller false. Det är 80% chans att den returnerar samma värde som är i variabeln cursed (dvs rätt svar), det är 20% chans att den returnerar det motsatta värdet(dvs fel svar)*/ } }
e26180b2991d8483cb49740e6cc447b6b855e520
[ "C#" ]
3
C#
MuminPojk/Prov
e61883582da19ff39d8332731786bcd0e49b22e4
2a1291b864618710460f2bd7c34b6659457a62c8
refs/heads/master
<repo_name>lotreal/csv<file_sep>/svn/src/pre-commit #!/bin/sh export LANG=en_US.UTF-8 REPOS="$1" TXN="$2" TYPE="$3" if test -z "$TYPE" ; then TYPE="-t" fi SVNLOOK=/usr/local/bin/svnlook CODEP=/root/workspace/codep/svn/src set -e exec 1>&2 ${CODEP}/pre-commit.sh "$REPOS" "$TXN" "$TYPE" || exit 196 ${CODEP}/pre-commit.py "$REPOS" "$TXN" || exit 195 # All checks passed, so allow the commit. exit 0 <file_sep>/svn/src/pre-commit.sh #!/bin/sh export LANG=en_US.UTF-8 REPOS="$1" TXN="$2" TYPE="$3" if test -z "$TYPE" ; then TYPE="-t" fi SVNLOOK=/usr/local/bin/svnlook look() { $SVNLOOK "$@" "$TYPE" "$TXN" "$REPOS" } if look log | grep '.' > /dev/null ; then :; else echo "Must fill in SVN log" 1>&2 exit 1 fi # Make sure that the log message contains some text. if [ "$(look log | wc -m)" -lt 4 ]; then echo "SVN log contains at least three chars" 1>&2 exit 1 fi disexts='\.(bak|tmp|o|obj|log|rar|zip|7z|gz|tar|tgz)$' disfiles='(^|/)(Thumbs\.db|desktop\.ini)$' disdirs='(^|/)(_notes|\.DS_Store|_runtime|cache|tmp|temp)/$' disdot='(^|/)(\.)' diss="$disexts|$disfiles|$disdirs|$disdot" if look changed | grep '^A ' | sed -r 's#^A +##' | grep -iE $diss 1>&2 ; then echo "Temporary files can not be submitted" 1>&2 echo "REM: /*.(bak|tmp|o|obj|log|rar|zip|7z|gz|tar|tgz)" 1>&2 echo "REM: Thumbs.db|desktop.ini" 1>&2 echo "REM: /(_notes|\.DS_Store|_runtime|cache|tmp|temp)/" 1>&2 echo "REM: /.*" 1>&2 exit 1 fi if look log | grep '[SYS-IMG-ONLY]' > /dev/null ; then exit 0 fi disexts='\.(jpg|jpeg|gif|png)$' diss="$disexts" if look changed | grep '^A ' | sed -r 's#^A +##' | grep -iE $diss 1>&2 ; then echo "Pictures can not be submitted unless you specify: [SYS-IMG-ONLY]" 1>&2 echo "REM: *.(jpg|jpeg|gif|png)" 1>&2 exit 1 fi # All checks passed, so allow the commit. exit 0 <file_sep>/svn/src/config.py #!/usr/bin/env python branches = [ 'branches/v2/upload/', 'trunk', ] <file_sep>/svn/src/pre-commit.py #!/usr/bin/env python #-*- coding: utf-8 -*- "Subversion pre-commit hook. " import os import sys exit_code = 0 class Configuration: def __init__(self): self.__branches = [] def load_from_repos(self, repos): sys.path.append("%s/hooks" % repos) from config import branches self.__branches = branches def get_branch(self): return self.__branches _conf = Configuration() def get_conf(): global _conf return _conf def log(str): pass def print_err(str): global exit_code exit_code += 1 sys.stderr.write("%s\n" % str) def command_output(cmd): " Capture a command's standard output. " import subprocess return subprocess.Popen( cmd.split(), stdout=subprocess.PIPE).communicate()[0] def files_changed(look_cmd): """ List the files added or updated by this transaction. "svnlook changed" gives output like: U trunk/file1.cpp A trunk/file2.cpp """ def filename(line): return line[4:] def added_or_updated(line): return line and line[0] in ("A", "U") return [ filename(line) for line in command_output(look_cmd % "changed").split("\n") if added_or_updated(line)] def file_contents(filename, look_cmd): " Return a file's contents for this transaction. " return command_output( "%s %s" % (look_cmd % "cat", filename)) def contains_tabs(filename, look_cmd): " Return True if this version of the file contains tabs. " return "\t" in file_contents(filename, look_cmd) def check_cpp_files_for_tabs(look_cmd): " Check files in this transaction are tab-free. " cpp_files_with_tabs = [ ff for ff in files_changed(look_cmd) if contains_tabs(ff, look_cmd)] if len(cpp_files_with_tabs) > 0: print_err("The following files contain tabs:\n%s\n" % "\n".join(cpp_files_with_tabs)) return len(cpp_files_with_tabs) def check_assets_path(look_cmd): """ Check assets's path. css: a/css js: a/js images: a/img""" def is_js_file(fname): return os.path.splitext(fname)[1] in ".js".split() def is_css_file(fname): return os.path.splitext(fname)[1] in ".css".split() def is_img_file(fname): return os.path.splitext(fname)[1] in ".gif .jpg .png .jpeg".split() def trim_branches(fname): for b in get_conf().get_branch(): trimed = fname[:len(b)] if (fname[:len(b)] == b): return fname[len(b):] return fname def js_path_error(fname): return trim_branches(fname)[:5] != 'a/js/' def css_path_error(fname): return trim_branches(fname)[:6] != 'a/css/' def img_path_error(fname): return trim_branches(fname)[:6] != 'a/img/' files = files_changed(look_cmd) for i in [js for js in files if is_js_file(js) and js_path_error(js)]: print_err('[rule=/a/js/] but: "%s"' % i) for i in [css for css in files if is_css_file(css) and css_path_error(css)]: print_err('[rule=/a/css/] but: "%s"' % i) for i in [img for img in files if is_img_file(img) and img_path_error(img)]: print_err('[rule=/a/img/] but: "%s"' % i) cpp_files_with_tabs = [ ff for ff in files_changed(look_cmd) ] # if len(cpp_files_with_tabs) > 0: # sys.stderr.write("The assets:\n%s\n" # % "\n".join(cpp_files_with_tabs)) # return len(cpp_files_with_tabs) def main(): usage = """usage: %prog REPOS TXN Run pre-commit options on a repository transaction.""" from optparse import OptionParser parser = OptionParser(usage=usage) parser.add_option("-r", "--revision", help="Test mode. TXN actually refers to a revision.", action="store_true", default=False) errors = 0 (opts, (repos, txn_or_rvn)) = parser.parse_args() look_opt = ("--transaction", "--revision")[opts.revision] look_cmd = "/usr/local/bin/svnlook %s %s %s %s" % ( "%s", repos, look_opt, txn_or_rvn) get_conf().load_from_repos(repos); log("<<< LOG_START") log(get_conf().get_branch()) log("opts.revision: %s" % opts.revision) log("LOOK_CMD: %s" % look_cmd) log(">>> LOG_END") # check_cpp_files_for_tabs(look_cmd) check_assets_path(look_cmd) if __name__ == "__main__": import sys main() log('exit_code: %s' % exit_code) sys.exit(exit_code)
5ad3a1fe95dd6d71e864ff77f6af72715d06b8ec
[ "Python", "Shell" ]
4
Shell
lotreal/csv
fde710bc9e24385ac140d18920fa5946fc27ccc9
2768e383d3ea45d0540727ef1a7cbb098bce1c59
refs/heads/master
<file_sep>import '@babel/polyfill'; const React = require('react'); const ReactDOM = require('react-dom'); const Simple = require('./app.jsx'); ReactDOM.render(React.createElement(Simple), document.getElementById('app')); <file_sep>const {stripIndent} = require('common-tags'); const mongoose = require('mongoose'); const docker = require('../engines/docker'); const Contest = require('../models/Contest'); const Language = require('../models/Language'); const Submission = require('../models/Submission'); const User = require('../models/User'); mongoose.Promise = global.Promise; (async () => { await mongoose.connect('mongodb://localhost:27017/esolang-battle'); await User.updateMany({admin: true}, {$set: {admin: false}}); for (const id of ['hideo54', 'sitositositoo', 'syobon_hinata', 'naan112358', 'kombubbu']) { const user = await User.findOne({email: <EMAIL>`}); if (user) { user.admin = true; await user.save(); } } await Contest.updateOne( {id: 'komabasai2021'}, { name: '駒場祭2021 Live CodeGolf Contest', id: 'komabasai2021', start: new Date('2021-11-23T14:05:00+0900'), end: new Date('2021-11-23T15:45:00+0900'), description: { ja: stripIndent` ## 問題 TSG LIVE! 6での東西対決から半年。我が国はTSG派とKMC派の二つに分かれ、混沌を極めていた! あまりに壮絶なその争いに終止符を打つべく、政府は各都道府県に代表者を3名ずつ擁立し、多数決によって都道府県ごとに公認サークルを定めることを決定した。 政府御用達の凄腕プログラマであるあなたの任務は、各都道府県の代表者の投票結果を受け取って、それぞれの公認サークルを発表するプログラムを作ることである。 やること自体はとても単純だ。ただし、開発したコードが長すぎると、TSGやKMCのハッカーにより発見、改ざんされる危険性がある。ハッカー達に見つからないために、できる限り短いプログラムを書いてほしい。 ### 入力 * 47行からなる。 * 各行は\`T\`と\`K\`のみからなる3文字の文字列である(\`T\`のみ、\`K\`のみの可能性もある)。 * 各行(最終行を含む)の末尾には、改行(\`\\n\`)が付与される。 ### 出力 * 各行について、\`T\`の数が\`K\`の数より多ければ\`T\`と、\`K\`の数が\`T\`の数より多ければ\`K\`と出力せよ。 * 出力された文字列に含まれる空白文字(改行含む)は無視される。すなわち、各行ごとに結果を出力してもよいし、1行に結果をまとめて出力してもよい。 * 厳密には、JavaScriptの正規表現で \`/\\s/\` にマッチするすべての文字の違いは無視される。詳細は MDN Web Docs の [文字クラス](https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) のページを参照のこと。 ### 制約 * 特になし ### 入力例 \`\`\` TKK KKT TKK KKT KTT KKK KTK TKT KTK TTK KTK TTT TTK KKT TTK KTK KKK TKK KKT KKT KKT KTT KKK TKK KTT TTK TTT TTT TTK TTK TKT TKT KTT KKT TKK KKT TTK KTT TTK TKK KKT KKK TKT TKT KTT KKT TKK \`\`\` ### 出力例1 \`\`\` K K K K T K K T K T K T T K T K K K K K K T K K T T T T T T T T T K K K T T T K K K T T T K K \`\`\` ### 出力例2 \`\`\` KKKKTKKTKTKTTKTKKKKKKTKKTTTTTTTTTKKKTTTKKKTTTKK \`\`\` ## 盤面 盤面は**2次元トーラス**(上の辺と下の辺、左の辺と右の辺がつながっている正方形)上の4x4マスである。 例えば、下の図の\`A\`のマスは、\`B\`、\`E\`と隣接しているのみならず、\`D\`、\`M\`とも隣接している。 \`\`\` +-+-+-+-+ |A|B|C|D| +-+-+-+-+ |E|F|G|H| +-+-+-+-+ |I|J|K|L| +-+-+-+-+ |M|N|O|P| +-+-+-+-+ \`\`\` 各チームのプレイヤーは、自分のチームの色が塗られているマスか、それに隣接しているマスにコードを提出することができる (ただし、ゲーム開始時に色が塗られているマスは単なるスタート地点であり、コードは提出できない)。 提出したコードがそのマスに書かれた名前のプログラミング言語で解釈したとき問題(上記)を正しく解いており、 かつ、以下のいずれかが成り立つとき、提出は受理され、そのマスが提出者のチームの色に塗り替わる。 * そのマスにおける受理が、ゲームを通じてまだ一度も起きていない。 * そのマスで最後に受理されたコードよりもバイト数が短いコードの提出である。 競技終了時点で、より多くのマスに自分の色が塗られている方のチームが勝者となる。 ## Tips * コードはフォームに直接入力して提出することもできるが、テキストファイルをアップロードして提出することもできる。この場合、Shift-JISなどの文字コードも使うことができる(これでバイト数が短くなる言語があるだろうか?)。 `, en: '', }, }, {upsert: true}, ); for (const slug of [ 'whitespace', 'pure-folders', 'concise-folders', 'produire', ]) { const languages = await Language.find({slug}); for (const language of languages) { const submissions = await Submission.find({language}); for (const submission of submissions) { console.log('procceing:', submission); const disasmInfo = await docker({ id: slug, code: submission.code, stdin: '', trace: false, disasm: true, }); console.log({ stdout: disasmInfo.stdout.toString(), stderr: disasmInfo.stderr.toString(), }); const result = await Submission.update( {_id: submission._id}, {$set: {disasm: disasmInfo.stdout}}, ); console.log({result}); } } } mongoose.connection.close(); })(); <file_sep># esolang-battle @hakatashi が作成した [hakatashi/esolang-battle](https://github.com/hakatashi/esolang-battle) を @hideo54 が改良したもの。 本家に加えて、次のような違いがある: * Dark theme に対応している。黒色ベースのデザインをしている場合に親和性が高い。 * 本家の最新版の commit は dependency update により壊れている状況。本リポジトリのコードは最新版が正常に動作する。 * README がまとも TSG LIVE! 5 (2020年五月祭 (コロナにより9月開催)), TSG LIVE! 7 (2021年駒場祭) では、このリポジトリのコードを使用した。 ## サーバー構築のしかた Node.js **v12** や、Python 2, 3, MongoDB, Docker が必要。詳細は TSG Scrapbox で hideo54 が書いた「LIVE-CONTEST サーバー作業メモ」を参照。全部載っている神記事です (自画自賛)。 言語のインストールは、`data/langs.json` に書いてある slugs の中から、使う言語を探して、`docker pull esolang/${slug}` すると良い。とりあえず全部インストールしようとするのはやめておけ (ものすごい容量が必要になる)。 問題登録や admin 登録などは `bin/migrate.js` を編集し実行すると便利。都度些細なユーザー管理などを行いたい場合、個人的には、[MongoDB Compass](https://www.mongodb.com/products/compass) を使うのが大変便利でおすすめである。 ## 問題の足し方 * `contests/hoge.js` に盤面の隣接情報や正誤判定を登録。 * `data/languages/komabasai2021.js` に各マスごとの使用言語を登録。 * `public/css/main.scss` にトップページのサムネを登録。 * `views/contest.pug` や `public/js/contests/*/app.jsx` に見た目について記述…するのだが、見ていただくとわかる通り、だいたいの場合 mayfes2018 が使い回されているよ。 * pug を知らない人向け: pug は HTML を楽に書ける言語だよ (HTML にコンパイルされる) * jsx を知らない向け: ここでは、フロントエンドを React を使って記述しているファイルだよ まあ雑に `komabasai2021` とか、パクりたい大会の id でプロジェクト全体検索して、適宜コピペすればいいんじゃないかな。 ## tips * コンテストページの末尾に `/admin` をつけると、admin なら admin 向けページにアクセスでき、GUI で簡単にチーム配属を行える。 (例: `/contests/komabasai2021/admin`) * ユーザーのチーム配属を削除することは現在できない。やりたければ MongoDB の users コレクションをいじるといい。 * コンテストが閉じているときでも checker で実行確認したい場合、d002a82 みたいな変更をすればよい。 * 開放されていない言語についても checker で実行確認したい場合、60bbc8b みたいな変更をすればよい。 * 何かわからないことがあれば @hideo54 に聞けばよい。
901ec5ee0c762de6921e29a487b25e4b501b213a
[ "JavaScript", "Markdown" ]
3
JavaScript
Szkieletor37/esolang-battle
7583aea1ea515f91cb9b155597cff75a82242d3d
1117faac7e33f31ebd8475f88169bd5a3c31aa84
refs/heads/master
<repo_name>en0mia/polito-informatica-temi-esame<file_sep>/README.md # polito-informatica-temi-esame Tema d'esame d'informatica risolti Politecnico di Torino <file_sep>/14-02-2020/CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(informazioni_anagrafiche C) set(CMAKE_C_STANDARD 99) add_executable(informazioni_anagrafiche main.c)<file_sep>/14-02-2020/main.c #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct { char name[10]; int people_born; }month; int main(int argc, char *argv[]) { int flag = 0; int wanted_month = -1; if(argc == 4) { if(strcmp("-m", argv[2]) == 0 || strcmp("-M", argv[2]) == 0) { flag = 1; wanted_month = *argv[3] - '0'; } } else if(argc != 2) { printf("Numero di argomenti non corretto"); exit(-1); } month months[12]; // Set months names strcpy(months[0].name, "Gennaio"); strcpy(months[1].name, "Febbraio"); strcpy(months[2].name, "Marzo"); strcpy(months[3].name, "Aprile"); strcpy(months[4].name, "Maggio"); strcpy(months[5].name, "Giugno"); strcpy(months[6].name, "Luglio"); strcpy(months[7].name, "Agosto"); strcpy(months[8].name, "Settembre"); strcpy(months[9].name, "Ottobre"); strcpy(months[10].name, "Novembre"); strcpy(months[11].name, "Dicembre"); for(int i = 0; i < 12; i++) { // Set default months[i].people_born = 0; } FILE* fp = fopen(argv[1], "r"); if(fp == NULL) { exit(-1); } char name[29]; char surname[29]; char city[29]; int date_month; int tmp_day; int tmp_year; FILE *fo; if(flag) { char filename[10]; strcpy(filename, months[wanted_month - 1].name); fo = fopen(strcat(filename, ".txt"), "w"); } int c = 0; while(!feof(fp)) { fscanf(fp, "%s %s %s %d/%d/%d", name, surname, city, &tmp_day, &date_month, &tmp_year); if(flag && (date_month == wanted_month)) { fprintf(fo, "%s %s %s\n", name, surname, city); } months[date_month - 1].people_born = months[date_month - 1].people_born + 1; c++; } fclose(fp); if(flag && (fo != NULL)) { fclose(fo); } int max_people_born = -1; char max_people_month[10]; int tot = 0; for(int m = 11; m >= 0; m--){ if(months[m].people_born > max_people_born) { max_people_born = months[m].people_born; strcpy(max_people_month, months[m].name); } tot = tot + months[m].people_born; } double media = (double) tot / 12.0; printf("Mese con numero massimo di nati: %s\n", max_people_month); printf("Numero medio mensile di nascite: %.2f\n", media); return 0; }
271f8e116cd3c8a7c443aaa7857af2250e042205
[ "Markdown", "C", "CMake" ]
3
Markdown
en0mia/polito-informatica-temi-esame
0de4026fedaa00a3d85dff78c62c3e458db18245
c89117bf1e47bae13a8aaf644fe18e5a73a75638
refs/heads/main
<file_sep># -*- coding: utf-8 -*- import json import tweepy import datetime from requests_oauthlib import OAuth1Session def get_keys(): data = 'keys.json' with open(data,'r') as f: keys = json.load(f) return keys keys = get_keys() consumer_key = keys['api_key'] consumer_secret = keys['api_key_secret'] access_token = keys['access_token'] access_token_secret = keys['access_token_secret'] auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) filters = '-filter:retweets AND -filter:replies AND -filter:mentions' search = 'Avax NFT minted' + filters nTweets = 5 for tweet in tweepy.Cursor(api.search,search).items(nTweets): if(tweet.favorited == True and tweet.retweeted == True): print('Tweet already retweeted and liked') elif(tweet.favorited == True and tweet.retweeted == False): try: tweet.retweet() except tweepy.TweepError as e: print (e.reason) elif(tweet.favorited == False and tweet.retweeted == True): try: tweet.favorite() except tweepy.TweepError as e: print (e.reason) else: try: tweet.retweet() tweet.favorite() except tweepy.TweepError as e: print(e.reason)
8ed88f87b6c8fb9eeb8fda0f1e66fcbc6861b7e3
[ "Python" ]
1
Python
beruz/crypto_twitter_bot
6a8dc03be6fc1e23f676d8fed763c93e61a8d7e3
0a0e85bc4184d21a5a2e0405e03198860b8e396f
refs/heads/master
<file_sep>require 'octokit' require 'rest-client' require 'json' # fetch user information username = 'putnamehere' access_token = 'settings-devsettings-personalaccesstokens' me = 'myname' start_page = 0 per_page = 10 pages = start_page done = false count = 0 # create output files - one for stats and one for specific referrers statsfile = File.open("#{username}_stats.csv", "w") refsfile = File.open("#{username}_referrers.csv", "w") statsfile.puts "count, user, repo, views, clones, watchers" refsfile.puts "user, repo, referrer, unique views" auth_result = JSON.parse(RestClient.get('https://api.github.com/user', {:params => {:oauth_token => access_token} }) ) # keep going until we are out of data while done == false do # fetch repos command = "https://api.github.com/users/#{username}/repos" repo_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token, :per_page => per_page, :page => pages} })) if (repo_result.length <= 0) then done = true else # for each repo, get the data we need repo_result.each do |repo| repo_name = repo["name"] location = start_page * per_page + count puts "#{location}: #{repo_name}" # watchers command = "https://api.github.com/repos/#{username}/#{repo_name}/watchers" watch_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) num_watchers = watch_result.length watchlist = "#{num_watchers}" if (num_watchers > 0) then watch_result.each do |watchers| watcher = watchers["login"] watchlist = watchlist + " #{watcher}" end end # let's put a try/catch here because it looks like i cannot see all of these repos num_clones = 0 num_views = 0 num_watchers = 0 begin # clones command = "https://api.github.com/repos/#{username}/#{repo_name}/traffic/clones" clone_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) num_clones = clone_result.length # referrers command = "https://api.github.com/repos/#{username}/#{repo_name}/traffic/popular/referrers" refer_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) referrers = refer_result.length if (refer_result.length > 0) then refer_result.each do |refer| referral = refer["referrer"] uniques = refer["uniques"] # write one line per file for each ref, could be multiple in one repo refsfile.puts "#{username}, #{repo_name}, #{referral}, #{uniques}" end # each referrer end # there are referrers # views command = "https://api.github.com/repos/#{username}/#{repo_name}/traffic/views" views_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) num_views = views_result.length # hop out here if we had a problem - everything was preset to zero rescue Exception => e puts "[error] API error in repo #{repo_name}: #{e}" end # write to generic stat file statsfile.puts "#{location}, #{username}, #{repo_name}, #{num_views}, #{num_clones}, #{watchlist}" count = count + 1 end # results > 0 pages = pages + 1 end # each call end # thanks! <file_sep># require 'octokit' require 'rest-client' require 'json' # fetch user information username = 'nameoftherepo' access_token = '<PASSWORD>' me = 'nameoftheuser' start_page = 0 per_page = 10 pages = start_page done = false count = 0 # Get date info time = Time.new # puts "Current Time : " + time.inspect datedata = "#{time.year}-#{time.month}-#{time.day}" # create output files - one for stats and one for specific referrers statsfile = File.open("#{username}_stats#{datedata}.csv", "w") refsfile = File.open("#{username}_referrers#{datedata}.csv", "w") clonesfile = File.open("#{username}_cloners#{datedata}.csv", "w") viewsfile = File.open("#{username}_viewers#{datedata}.csv", "w") statsfile.puts "count, user, repo, views, clones, watchers" refsfile.puts "user, repo, referrer, unique views" clonesfile.puts "user, repo, time, clones, unique" viewsfile.puts "user, repo, time, views, unique" auth_result = JSON.parse(RestClient.get('https://api.github.com/user', {:params => {:oauth_token => access_token} }) ) # puts "command is #{command}" while done == false do # fetch repos command = "https://api.github.com/users/#{username}/repos" repo_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token, :per_page => per_page, :page => pages} })) # puts "number of repos is #{repo_result.length}" # puts "page #{pages}" if (repo_result.length <= 0) then done = true else # for each repo, get the data we need repo_result.each do |repo| repo_name = repo["name"] location = start_page * per_page + count puts "#{location}: #{repo_name}" # get the generic repo data command = "https://api.github.com/repos/#{username}/#{repo_name}" repo_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) num_watchers = repo_result["watchers"] # puts "number of watchers is #{num_watchers}" # watchers command = "https://api.github.com/repos/#{username}/#{repo_name}/watchers" watch_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) num_watchers = watch_result.length watchlist = "#{num_watchers}" # puts "watchers #{num_watchers}" if (num_watchers > 0) then watch_result.each do |watchers| watcher = watchers["login"] watchlist = watchlist + " #{watcher}" end end # puts watchlist # let's put a try/catch here because it looks like i cannot see all of these repos num_clones = 0 num_views = 0 num_watchers = 0 begin # referrers # GET /repos/:owner/:repo/traffic/popular/referrers command = "https://api.github.com/repos/#{username}/#{repo_name}/traffic/popular/referrers" refer_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) referrers = refer_result.length # puts "number of referrers is #{referrers}" if (refer_result.length > 0) then refer_result.each do |refer| referral = refer["referrer"] uniques = refer["uniques"] # puts "number of referrals is #{referral} (unique #{uniques})" refsfile.puts "#{username}, #{repo_name}, #{referral}, #{uniques}" end # each referrer end # there are referrers # views command = "https://api.github.com/repos/#{username}/#{repo_name}/traffic/views" views_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) puts "views result is #{views_result}" views_list = views_result["views"] num_views = views_result["count"] if (num_views > 0) then views_list.each do |view| puts "view is #{view}" time = view["timestamp"] views = view["count"] uniques = view["uniques"] puts "views is #{time} #{views} (unique #{uniques})" viewsfile.puts "#{username}, #{repo_name}, #{time}, #{views}, #{uniques}" end # each view end # views list # hop out here if we had a problem rescue Exception => e puts "[error] API error in repo #{repo_name}: #{e}" end # clones # GET /repos/:owner/:repo/traffic/clones command = "https://api.github.com/repos/#{username}/#{repo_name}/traffic/clones" clone_result = JSON.parse(RestClient.get("#{command}", {:params => {:oauth_token => access_token}})) puts "clone result #{clone_result}" num_clones = clone_result["count"] puts "number of clones is #{num_clones}" clone_list = clone_result["clones"] puts "clone_list #{clone_list}" if (num_clones > 0) then clone_list.each do |clone| puts "clone is #{clone}" time = clone["timestamp"] clones = clone["count"] uniques = clone["uniques"] puts "number of clones is #{time} (unique #{uniques})" clonesfile.puts "#{username}, #{repo_name}, #{time}, #{clones}, #{uniques}" end # each clone end # there are clones # write to file statsfile.puts "#{location}, #{username}, #{repo_name}, #{num_views}, #{num_clones}, #{watchlist}" count = count + 1 end # results > 0 pages = pages + 1 end # each call end # thanks! <file_sep># github-stats Make a csv file with metrics, part of them require access token
152ee8f1654dbffd79423ed41aee485ca12f462c
[ "Markdown", "Ruby" ]
3
Ruby
judyj/github-stats
4cfd603c5145fe6689404339b64042033fd63173
460af44f4ea2e0f1bf6ec39befcc019713866ebf
refs/heads/master
<file_sep>namespace System { using IO; public static class StreamExtension { public static Byte[] ToBytes(this Stream stream) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); stream.Seek(0, SeekOrigin.Begin); return bytes; } public static Stream ToStream(this Byte[] bytes) { var stream = new MemoryStream(bytes); return stream; } public static String ToString(this Byte[] bytes) { return String.Empty; } } } <file_sep>namespace PdfWatermark { #region using directives using System; using System.Drawing; #endregion public class WatermarkSetting { public String Id { get; set; } public String Watermark { get; set; } public String WatermarkFont { get; set; } public String WatermarkFontSize { get; set; } public Color WatermarkColor { get; set; } public Double Opacity { get; set; } public Boolean IsRepeated { get; set; } public Int32 Direction { get; set; } } } <file_sep>namespace PdfWatermark { using Aspose.Words; using Aspose.Words.Drawing; using System; using System.Drawing; using System.IO; public class Program { public static void Main() { //ImageScale.Run(); //Word.Run(); //ImageOpeation.SetWatermarkForImage(); //Slides.AddImageWatermarkToSlide(); //AsposeCell.AddWatermarkImageForCells(); //AddPDFWatermark.AddImageWatermark(); //AddPDFWatermark.SplitPdf(); //ConvertToWord.TestDoc(); //AddPDFWatermark.AddImageWatermark(); //ConvertToWord.PdfToDoc(); //ConvertToWord.DocStreamToDoc(); //AddMark(); //LoadLicence(); //Document doc = new Document(@"D:\test.docx"); //InsertWatermarkText(doc, "AvePoint"); //doc.Save(@"D:\testImage.docx"); AsposeCell.AddWatermarkImageForCells(); //Stream stream = new FileInfo(@"D:\sqlCopy.pdf").OpenRead(); //ConvertToWord.PdfStreamToDocx(stream); //var stream1 = AddPDFWatermark.AddWatermark2(stream); //using (var fileStream = File.Create(@"D:\sql07.pdf")) //{ // stream1.Seek(0, SeekOrigin.Begin); // stream1.CopyTo(fileStream); //} Console.WriteLine("success"); Console.ReadKey(); } /// <summary> /// Inserts a watermark into a document. /// </summary> /// <param name="doc">The input document.</param> /// <param name="watermarkText">Text of the watermark.</param> private static void InsertWatermarkText(Document doc, String watermarkText) { // Create a watermark shape. This will be a WordArt shape. // You are free to try other shape types as watermarks. Shape watermark = new Shape(doc, ShapeType.Image); // Set up the text of the watermark. //watermark.TextPath.Text = watermarkText; watermark.ImageData.ImageBytes = new FileInfo(@"D:\test.jpg").OpenRead().ToBytes(); watermark.TextPath.FontFamily = "Arial"; watermark.Width = 500; watermark.Height = 100; // Text will be directed from the bottom-left to the top-right corner. watermark.Rotation = -40; // Remove the following two lines if you need a solid black text. watermark.Fill.Color = Color.Gray; // Try LightGray to get more Word-style watermark watermark.StrokeColor = Color.Gray; // Try LightGray to get more Word-style watermark // Place the watermark in the page center. watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page; watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page; watermark.WrapType = WrapType.None; watermark.VerticalAlignment = VerticalAlignment.Center; watermark.HorizontalAlignment = HorizontalAlignment.Center; // Create a new paragraph and append the watermark to this paragraph. Paragraph watermarkPara = new Paragraph(doc); watermarkPara.AppendChild(watermark); // Insert the watermark into all headers of each document section. foreach (Section sect in doc.Sections) { // There could be up to three different headers in each section, since we want // the watermark to appear on all pages, insert into all headers. InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary); InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst); InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven); } } private static void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType) { HeaderFooter header = sect.HeadersFooters[headerType]; if (header == null) { // There is no header of the specified type in the current section, create it. header = new HeaderFooter(sect.Document, headerType); sect.HeadersFooters.Add(header); } // Insert a clone of the watermark into the header. header.AppendChild(watermarkPara.Clone(true)); } private static void LoadLicence() { Aspose.Words.License license = new Aspose.Words.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); } } } <file_sep>namespace PdfWatermark { using Aspose.Imaging; using Aspose.Imaging.FileFormats.Tiff; using Aspose.Imaging.FileFormats.Tiff.Enums; using Aspose.Imaging.ImageOptions; using Aspose.Imaging.Sources; using System.IO; public class ImageOpeation { public static void SetWatermarkForImage() { TiffOptions outputSettings = new TiffOptions(); outputSettings.BitsPerSample = new ushort[] { 1 }; outputSettings.Compression = TiffCompressions.CcittFax3; outputSettings.Photometric = TiffPhotometrics.MinIsWhite; outputSettings.Source = new StreamSource(new MemoryStream()); int newWidth = 500; int newHeight = 500; string path = @"D:\output.jpg"; using (TiffImage tiffImage = (TiffImage)Image.Create(outputSettings, newWidth, newHeight)) { using (RasterImage ri = (RasterImage)Image.Load(@"D:\test.jpg")) { ri.Resize(newWidth, newHeight, ResizeType.NearestNeighbourResample); TiffFrame frame = tiffImage.ActiveFrame; frame = new TiffFrame(new TiffOptions(outputSettings) /*ensure options are cloned for each frame*/, newWidth, newHeight); // If there is a TIFF image loaded you need to enumerate the frames and perform the following // frame = TiffFrame.CreateFrameFrom(sourceFrame, outputSettings); frame.SavePixels(frame.Bounds, ri.LoadPixels(ri.Bounds)); tiffImage.AddFrame(frame); } tiffImage.Save(path); } } private static void LoadLicence() { Aspose.Imaging.License license = new Aspose.Imaging.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); } } } <file_sep># PdfWatermark Aspose API的学习,通过对API的学习对Pdf文件进行水印的增删操作。 <file_sep>namespace PdfWatermark { using Aspose.Pdf; using Aspose.Pdf.Text; using System; using System.IO; public class AddPDFWatermark { public static void AddWatermark() { //open document string pdffile = @"D:\book\sqlCopy.pdf"; Document pdfDocument = new Document(pdffile); //set coordinates int lowerLeftX = 400; int lowerLeftY = 75; int upperRightX = 550; int upperRightY = 100; //get the page where image needs to be added Page page = pdfDocument.Pages[1]; //load image into stream FileStream imageStream = new FileStream(@"D:\book\test.jpg", FileMode.Open); //add image to Images collection of Page Resources page.Resources.Images.Add(imageStream); //using GSave operator: this operator saves current graphics state page.Contents.Add(new Operator.GSave()); //create Rectangle and Matrix objects Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Aspose.Pdf.DOM.Matrix matrix = new Aspose.Pdf.DOM.Matrix(new double[] {rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY}); //using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed page.Contents.Add(new Operator.ConcatenateMatrix(matrix)); XImage ximage = page.Resources.Images[page.Resources.Images.Count]; //using Do operator: this operator draws image page.Contents.Add(new Operator.Do(ximage.Name)); //using GRestore operator: this operator restores graphics state page.Contents.Add(new Operator.GRestore()); TextStamp textStamp = new TextStamp("my text stamp goes here!"); textStamp.Rotate = Rotation.on90; textStamp.Background = true; textStamp.TextState.FontSize = 5.0F; textStamp.TextState.FontStyle = FontStyles.Bold; textStamp.TextState.FontStyle = FontStyles.Italic; pdfDocument.Pages[1].AddStamp(textStamp); //pdfDocument.Pages[pdfDocument.Pages.Count].Watermark.Image.Save("mywatermark.jpg"); //save updated document //string newpdf_file = signedfolder + "\\" + filename.Substring(0, filename.IndexOf(".pdf")) + "_SIGNED.pdf"; pdfDocument.Save(@"D:\sqloutput.pdf"); imageStream.Close(); } public static void AddWatermark1() { //Stream stream = new FileInfo(@"D:\Program Files (x86)\sqlCopy.pdf").OpenRead(); Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); Document pdfDocument = new Document(@"D:\sqlCopy.pdf"); //create text stamp TextStamp textStamp = new TextStamp("AvePoint"); TextStamp headStamp = new TextStamp("AvePoint In Head"); headStamp.TopMargin = 10; headStamp.HorizontalAlignment = HorizontalAlignment.Center; textStamp.HorizontalAlignment = HorizontalAlignment.Center; headStamp.VerticalAlignment = VerticalAlignment.Top; textStamp.VerticalAlignment = VerticalAlignment.Center; //set origin textStamp.XIndent = 80; textStamp.YIndent = 80; textStamp.Width = 100F; textStamp.Height = 50F; //set whether stamp is background textStamp.Background = true; //rotate stamp textStamp.RotateAngle = 45; textStamp.Opacity = 0.2; //set text properties textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.FontSize = 14.0F; textStamp.TextState.FontStyle = FontStyles.Bold; textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Aqua); //textStamp.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Brown); //add stamp to particular page foreach (Page page in pdfDocument.Pages) { page.AddStamp(headStamp); page.AddStamp(textStamp); } //save output document //var stream1 = new MemoryStream(); //pdfDocument.Save(stream1); //using (var fileStream = File.Create(@"D:\sql03.pdf")) //{ // stream1.Seek(0, SeekOrigin.Begin); // stream1.CopyTo(fileStream); //} pdfDocument.Save(@"D:\sql04.pdf"); } public static Stream AddWatermark2(Stream pdfStream) { Document pdfDocument = new Document(pdfStream); //create text stamp TextStamp textStamp = new TextStamp("AvePoint2016猴年"); TextStamp headStamp = new TextStamp("AvePoint In Head"); headStamp.TopMargin = 10; headStamp.HorizontalAlignment = HorizontalAlignment.Center; headStamp.VerticalAlignment = VerticalAlignment.Top; //set origin textStamp.XIndent = 80; textStamp.YIndent = 80; textStamp.Width = 400F; textStamp.Height = 50F; //set whether stamp is background textStamp.Background = true; //rotate stamp textStamp.Rotate = Rotation.None; //set text properties textStamp.TextState.Font = FontRepository.FindFont("Arial"); textStamp.TextState.FontSize = 14.0F; textStamp.TextState.FontStyle = FontStyles.Bold; textStamp.TextState.FontStyle = FontStyles.Italic; textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Aqua); textStamp.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Brown); //add stamp to particular page foreach (Page page in pdfDocument.Pages) { page.AddStamp(headStamp); page.AddStamp(textStamp); } //save output document var stream1 = new MemoryStream(); pdfDocument.Save(stream1); return stream1; } public static void AddMark() { Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf(); //Add a section to the Pdf object Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add(); Aspose.Pdf.Generator.Text text1 = new Aspose.Pdf.Generator.Text(sec1, "This is text in section1.") { Left = 30, Top = 100 }; sec1.Paragraphs.Add(text1); Aspose.Pdf.Generator.Section sec2 = pdf1.Sections.Add(); Aspose.Pdf.Generator.Text text2 = new Aspose.Pdf.Generator.Text(sec2, "This is text in section2.") { Left = 30, Top = 100 }; sec2.Paragraphs.Add(text2); //setting image watermark Aspose.Pdf.Generator.Image image1 = new Aspose.Pdf.Generator.Image(); image1.ImageInfo.File = @"D:\book\test.jpg"; image1.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Jpeg; image1.ImageScale = 0.1f; Aspose.Pdf.Generator.FloatingBox watermark1 = new Aspose.Pdf.Generator.FloatingBox(108, 80); watermark1.BoxHorizontalAlignment = Aspose.Pdf.Generator.BoxHorizontalAlignmentType.Center; watermark1.BoxVerticalPositioning = Aspose.Pdf.Generator.BoxVerticalPositioningType.Page; watermark1.BoxVerticalAlignment = Aspose.Pdf.Generator.BoxVerticalAlignmentType.Center; watermark1.Paragraphs.Add(image1); //graph watermark Aspose.Pdf.Generator.Graph graph1 = new Aspose.Pdf.Generator.Graph(100, 400); float[] posArr = new float[] {0, 0, 200, 80, 300, 40, 350, 90}; Aspose.Pdf.Generator.Curve curve1 = new Aspose.Pdf.Generator.Curve(graph1, posArr); graph1.Shapes.Add(curve1); Aspose.Pdf.Generator.FloatingBox watermark2 = new Aspose.Pdf.Generator.FloatingBox(108, 80); watermark2.Paragraphs.Add(graph1); //text watermark Aspose.Pdf.Generator.Text text3 = new Aspose.Pdf.Generator.Text("Text Watermark"); Aspose.Pdf.Generator.FloatingBox watermark3 = new Aspose.Pdf.Generator.FloatingBox(108, 80); watermark3.Left = 50; watermark3.Top = 500; watermark3.Paragraphs.Add(text3); pdf1.Watermarks.Add(watermark1); pdf1.Watermarks.Add(watermark2); pdf1.Watermarks.Add(watermark3); pdf1.Save(@"D:\sql2.pdf"); } public static void AddImageWatermark() { Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); Document pdfDocument = new Document(@"D:\pdfDocument.pdf"); //Create image stamp ImageStamp imageStamp = new ImageStamp(@"D:\book\test.jpg"); imageStamp.Background = true; imageStamp.XIndent = 100; imageStamp.YIndent = 100; imageStamp.Height = 300; imageStamp.Width = 300; imageStamp.RotateAngle = 45; imageStamp.Opacity = 0.5; //Add stamp to particular page foreach (Page page in pdfDocument.Pages) { page.AddStamp(imageStamp); } //Save output document pdfDocument.Save(@"D:\sqlimage.pdf"); } public static void SplitPdf() { Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); Document pdfDocument = new Document(); using (Stream stream = new FileInfo(@"D:\pdfDocument.pdf").OpenRead()) { stream.Seek(0, SeekOrigin.Begin); var bs = stream.ToBytes(); var bytes = ConvertPdfToDocX(bs); using (MemoryStream ms = new MemoryStream(bytes)) { Aspose.Words.Document doc = new Aspose.Words.Document(ms); doc.Save(@"D:\ttt.docx"); } } //var newDoc = new Document(); //newDoc.Pages.Add(pdfDocument.Pages[1]); //newDoc.Pages.Add(pdfDocument.Pages[2]); //newDoc.Save(@"D:\tt.pdf", SaveFormat.Pdf); } public static Byte[] ConvertPdfToDocX(Byte[] bytes) { Byte[] docxBytes = null; MemoryStream docStream = new MemoryStream(); try { using (var stream = new MemoryStream(bytes)) { Document pdfDocument = new Document(stream); pdfDocument.Save(docStream, SaveFormat.DocX); docStream.Seek(0, SeekOrigin.Begin); docxBytes = new byte[docStream.Length]; docStream.Read(docxBytes, 0, docxBytes.Length); docStream.Seek(0, SeekOrigin.Begin); } } catch (Exception ex) { throw ex; } finally { if (docStream != null) { docStream.Close(); } } return docxBytes; } } } ; <file_sep>namespace PdfWatermark { using Aspose.Cells; using Aspose.Cells.Drawing; using System.IO; public class AsposeCell { public static void AddWatermarkForCells() { LoadLicence(); //Instantiate a new Workbook Workbook workbook = new Workbook(@"D:\test.xlsx"); //Get the first default sheet //Worksheet sheet = workbook.Worksheets[0]; //Add Watermark foreach (Worksheet sheet in workbook.Worksheets) { Aspose.Cells.Drawing.Shape wordart = sheet.Shapes.AddTextEffect(MsoPresetTextEffect.TextEffect20, "AvePoint", "Arial Black", 50, false, true, 18, 8, 1, 1, 130, 800); //Get the fill format of the word art MsoFillFormat wordArtFormat = wordart.FillFormat; //Set the color wordArtFormat.ForeColor = System.Drawing.Color.Red; //Set the transparency wordArtFormat.Transparency = 0.9; //Make the line invisible MsoLineFormat lineFormat = wordart.LineFormat; lineFormat.IsVisible = false; } //Save the file workbook.Save(@"D:\testWatermarkText.xlsx"); } public static void AddWatermarkImageForCells() { LoadLicence(); //Instantiate a new Workbook Workbook workbook = new Workbook(@"D:\test.xlsx"); //Add Watermark foreach (Worksheet sheet in workbook.Worksheets) { Aspose.Cells.Drawing.Shape wordart = sheet.Shapes.AddPicture(0, 0, new FileInfo(@"D:\test.jpg").OpenRead(), 10, 20); //Get the fill format of the word art wordart.TextDirection = TextDirectionType.Context; var fillformat = wordart.Fill; var format = wordart.FillFormat; fillformat.Scale = 0.2; //Set the transparency format.Transparency = 0.2; //Make the line invisible MsoLineFormat lineFormat = wordart.LineFormat; lineFormat.IsVisible = false; } //Save the workbook workbook.Save(@"D:\testWatermarkImage.xlsx", Aspose.Cells.SaveFormat.Xlsx); } public static void LoadLicence() { Aspose.Cells.License license = new Aspose.Cells.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); } } } <file_sep>namespace PdfWatermark { using Aspose.Slides; using Aspose.Slides.Export; using System.Drawing; public class Slides { public static void AddImageWatermarkToSlide() { //using (Presentation pres = new Presentation()) //{ // //Get the first slide // ISlide sld = pres.Slides[0]; // //Add an AutoShape of Rectangle type // IAutoShape ashp = sld.Shapes.AddAutoShape(ShapeType.Rectangle, 150, 75, 150, 50); // //Add TextFrame to the Rectangle // ashp.AddTextFrame(" "); // //Accessing the text frame // ITextFrame txtFrame = ashp.TextFrame; // //Create the Paragraph object for text frame // IParagraph para = txtFrame.Paragraphs[0]; // //Create Portion object for paragraph // IPortion portion = para.Portions[0]; // //Set Text // portion.Text = "Aspose TextBox"; // //Save the presentation to disk // pres.Save("TextBox.pptx", SaveFormat.Pptx); //} LoadLicence(); using (Presentation pres = new Presentation(@"D:\test.pptx")) { foreach (ISlide slide in pres.Slides) { ////Set the background with Image //slide.Background.Type = BackgroundType.OwnBackground; //slide.Background.FillFormat.FillType = FillType.Picture; //slide.Background.FillFormat.PictureFillFormat.PictureFillMode = PictureFillMode.Stretch; ////Set the picture //System.Drawing.Image img = (System.Drawing.Image)new Bitmap(@"D:\book\test.jpg"); ////Add image to presentation's images collection //IPPImage imgx = pres.Images.AddImage(img); //slide.Background.FillFormat.PictureFillFormat.Picture.Image = imgx; //Add autoshape of rectangle type IShape shp = slide.Shapes.AddAutoShape(ShapeType.OrFlow, 150, 150, 75, 150); //Set the fill type to Picture shp.FillFormat.FillType = FillType.Picture; shp.FillFormat.GradientFormat.GradientDirection = GradientDirection.FromCorner2; //Set the picture fill mode shp.FillFormat.PictureFillFormat.PictureFillMode = PictureFillMode.Stretch; //Set the picture System.Drawing.Image img = (System.Drawing.Image)new Bitmap(@"D:\book\test.jpg"); IPPImage imgx = pres.Images.AddImage(img); shp.FillFormat.PictureFillFormat.Picture.Image = imgx; } //Write the presentation to disk pres.Save(@"D:\RectShpPic1.pptx", SaveFormat.Pptx); } } private static void LoadLicence() { Aspose.Slides.License license = new Aspose.Slides.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); } } } <file_sep>namespace PdfWatermark { using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; public class ImageScale { public static void Run() { var image = Image.FromFile(@"D:\test.jpg"); var scaleImageBytes = ScaleImage(image,1600,1600); var scaleImage = Image.FromStream(scaleImageBytes.ToStream()); scaleImage.Save(@"D:\testScale.jpg", ImageFormat.Bmp); } public static Byte[] ScaleImage(Image image, Int32 width, Int32 height) { var scaledWidth = width; var scaledHeight = height; var format = image.RawFormat; var saveImage = new Bitmap(scaledWidth, scaledHeight); var g = Graphics.FromImage(saveImage); g.Clear(System.Drawing.Color.White); Int32 IntWidth; Int32 IntHeight; if (image.Width > scaledWidth && image.Height <= scaledHeight) { IntWidth = scaledWidth; IntHeight = (IntWidth * image.Height) / image.Width; } else if (image.Width <= scaledWidth && image.Height > scaledHeight) { IntHeight = scaledHeight; IntWidth = (IntHeight * image.Width) / image.Height; } else if (image.Width <= scaledWidth && image.Height <= scaledHeight) { IntHeight = image.Width; IntWidth = image.Height; } else { IntWidth = scaledWidth; IntHeight = (IntWidth * image.Height) / image.Width; if (IntHeight > scaledHeight) { IntHeight = scaledHeight; IntWidth = (IntHeight * image.Width) / image.Height; } } g.DrawImage(image, (scaledWidth - IntWidth) / 2, (scaledHeight - IntHeight) / 2, IntWidth, IntHeight); using (var stream = new MemoryStream()) { saveImage.Save(stream, ImageFormat.Jpeg); stream.Seek(0, SeekOrigin.Begin); return stream.ToBytes(); } } } } <file_sep>namespace PdfWatermark { using Aspose.Pdf; using System; using System.IO; using Document = Aspose.Pdf.Document; using SaveFormat = Aspose.Pdf.SaveFormat; public class ConvertToWord { public static void PdfToDoc() { Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); //open the source PDF document Document pdfDocument = new Document(@"D:\sqlCopy.pdf"); // 1. // saving using direct method // save the file into MS document format pdfDocument.Save("simpleOutput.doc", SaveFormat.Doc); // 2. // save using save options // create DocSaveOptions object DocSaveOptions saveOptions = new DocSaveOptions(); // set the recognition mode as Flow saveOptions.Mode = DocSaveOptions.RecognitionMode.Flow; // set the Horizontal proximity as 2.5 saveOptions.RelativeHorizontalProximity = 2.5f; // enable the value to recognize bullets during conversion process saveOptions.RecognizeBullets = true; // save the resultant DOC file pdfDocument.Save(@"D:\Output.doc", saveOptions); } public static void PdfToDocx() { Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); //open the source PDF document Document pdfDocument = new Document(@"D:\sqlCopy.pdf"); // 1. // saving using direct method // save the file into MS document format pdfDocument.Save("simpleOutput.doc", SaveFormat.Doc); // 2. // save using save options // create DocSaveOptions object DocSaveOptions saveOptions = new DocSaveOptions(); // set the recognition mode as Flow saveOptions.Mode = DocSaveOptions.RecognitionMode.Flow; // Specify the output format as DOCX, 默认为Doc saveOptions.Format = DocSaveOptions.DocFormat.DocX; // set the Horizontal proximity as 2.5 saveOptions.RelativeHorizontalProximity = 2.5f; // enable the value to recognize bullets during conversion process saveOptions.RecognizeBullets = true; // save the resultant DOC file pdfDocument.Save(@"D:\Output.docx", saveOptions); } public static Stream PdfStreamToDocStream(Stream stream) { Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); var doc = new Document(stream); var ms = new MemoryStream(); doc.Save(ms,SaveFormat.Doc); return ms; } public static void PdfStreamToDocx(Stream stream) { Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); var doc = new Document(stream); doc.Save(@"D:\test.docx", SaveFormat.DocX); } public static void DocStreamToDoc() { Aspose.Words.License license = new Aspose.Words.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); Stream stream = new FileInfo(@"D:\sqlCopy.pdf").OpenRead(); var ms = PdfStreamToDocStream(stream); var doc = new Aspose.Words.Document(ms); doc.Save(@"D:\test.doc"); } public static void TestDoc() { Aspose.Words.License license = new Aspose.Words.License(); license.SetLicense("D:/WorkCopy/GitProject/PdfWatermarkTest/PdfWatermark/Aspose.Total.lic"); var doc = new Aspose.Words.Document(@"D:\test.docx"); //foreach (Section sec in doc.Sections) //{ // var i = sec.GetText().Length; // Console.WriteLine(sec.GetText()); // Console.WriteLine(i); //} Console.WriteLine(doc.Sections.Count); Console.WriteLine(doc.PageCount); Console.WriteLine(doc); } } }
b30144bd7bb4c1508026389f54163d8db0bf7293
[ "Markdown", "C#" ]
10
C#
joyang1/PdfWatermark
ed701726b605888f23dbf740ca10bfe9cf79a6c7
35db9d670df6d7f891afc1580986a4abfd0fdb14
refs/heads/master
<repo_name>kentwood/MbcTestServer<file_sep>/src/main/java/com/just4fun/controller/MbcRecvController.java package com.just4fun.controller; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import utils.GsonUtil; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Created by sdt14096 on 2017/5/27. */ @Controller @RequestMapping("test") public class MbcRecvController { private static final Logger log = LoggerFactory.getLogger(MbcRecvController.class); @ResponseBody @RequestMapping(value = "logs") public Map<String,String> tttestMBCServer(@RequestBody String jsonString) throws IOException { log.info("----------"); log.info("the MBC server got data:"); log.info(jsonString); Map<String, String> map = new HashMap<String, String>(); JsonArray myJsonArray = null; JsonObject myJsonObject = null; try { myJsonArray = GsonUtil.getJsonParser().parse(jsonString).getAsJsonArray(); if (myJsonArray.isJsonNull()) { log.info("the jsonArray is empty"); map.put("result", "ERROR"); map.put("detail", " "); return map; } else { log.info("jsonArray:" + myJsonArray); map.put("result", "OK"); map.put("detail", " "); log.info("MBC server send data to skyworth server"); log.info(map.toString()); return map; } }catch (Exception e){ myJsonObject = GsonUtil.getJsonParser().parse(jsonString).getAsJsonObject(); if (myJsonObject.isJsonNull()) { log.info("the jsonObject is empty"); map.put("result", "ERROR"); map.put("detail", " "); return map; } else { log.info("jsonObject:" + myJsonObject); map.put("result", "OK"); map.put("detail", " "); log.info("MBC server send data to skyworth server"); log.info(map.toString()); return map; } } } }
9053dbfa8a47266b71d141d688fd5925416c223a
[ "Java" ]
1
Java
kentwood/MbcTestServer
446bc0b12882fdb7bddc6ea0f851c85bd6ba8f29
6896f7f8c69c56c4c73031e6a3ae269a3b6dcff6
refs/heads/master
<file_sep>package mathdemo; public class MathDemo { public static void main(String[] args) { System.out.println("Примеры вызова функций:"); // Вычисление экспоненты: System.out.println("exp(1)="+ MyMath.Exp(1,30)); // Вычисление синуса: System.out.println("sin(pi)="+ MyMath.Sin(Math.PI,100)); // Вычисление косинуса: System.out.println("cos(pi/2)="+ MyMath.Cos(Math.PI/2,100)); // Вычисление функции Бесселя: System.out.println("J0(mu1)="+ MyMath.BesselJ(2.404825558,100)); // Заполнение массивов коэффициентов рядов Фурье для функции y(x)=x: int m=1000; double[] a=new double[m]; double[] b=new double[m+1]; b[0]= MyMath.L/2; for(int i=1;i<=m;i++){ a[i-1]=(2*(i%2)-1)*2* MyMath.L/Math.PI/i; b[i]=-4*(i%2)* MyMath.L/Math.pow(Math.PI*i,2);} // Вычисление функции y(x)=x через синус-ряд Фурье: System.out.println("2.0->"+ MyMath.FourSin(2.0,a)); // Вычисление функции y(x)=x через косинус-ряд Фурье: System.out.println("2.0->"+ MyMath.FourCos(2.0,b)); System.out.println("Tan: "+ MyMath.Tan(1,30)); System.out.println("CoTan: "+ MyMath.CoTan(1,30)); System.out.println("Sqrt: "+ MyMath.sqrt(3, 3)); System.out.println("Pow: "+ MyMath.Pow(2,4)); } } <file_sep>public class Vehicle { private String speed; private String model; private String ovnerName; private String movingVector; Vehicle(String model, String ovnerName, String speed, String movingVector){ this.speed = speed; this.model = model; this.ovnerName = ovnerName; this.movingVector = movingVector; } private String getSpeed(){ return speed; } private String getOvnerName(){ return ovnerName; } private String getMovingVector(){ return movingVector; } private String getModel(){ return model; } public String toString(){ return "Venicle: "+getModel()+" Ovner: "+getOvnerName()+" Moving speed: "+getSpeed()+" Moving vector: "+getMovingVector(); } } <file_sep>package mathdemo; class MyMath { // Класс с математическими функциями: // Интервал разложения в ряд Фурье: static double L=Math.PI; // Экспонента: static double Exp(double x,int N){ int i; double s=0,q=1; for(i=0;i<N;i++){ s+=q; q*=x/(i+1); } return s+q; } // Синус: static double Sin(double x,int N){ int i; double s=0,q=x; for(i=0;i<N;i++){ s+=q; q*=(-1)*x*x/(2*i+2)/(2*i+3); } return s+q; } // Косинус: static double Cos(double x,int N){ int i; double s=0,q=1; for(i=0;i<N;i++){ s+=q; q*=(-1)*x*x/(2*i+1)/(2*i+2); } return s+q; } // Функция Бесселя: static double BesselJ(double x,int N){ int i; double s=0,q=1; for(i=0;i<N;i++){ s+=q; q*=(-1)*x*x/4/(i+1)/(i+1); } return s+q; } // Ряд Фурье по синусам: static double FourSin(double x,double[] a){ int i,N=a.length; double s=0; for(i=0;i<N;i++){ s+=a[i]*Math.sin(Math.PI*x*(i+1)/L); } return s;} // Ряд Фурье по косинусам: static double FourCos(double x,double[] a){ int i,N=a.length; double s=0; for(i=0;i<N;i++){ s+=a[i]*Math.cos(Math.PI*x*i/L); } return s; } static double Tan(double x, int N){ return Sin(x,N)/Cos(x,N); } static double CoTan(double x, int N){ return Cos(x,N)/Sin(x,N); } static double sqrt(double value, int decimalPoints) { int firstPart=0; /*calculating the integer part*/ while(square(firstPart)<value) { firstPart++; } if(square(firstPart)==value) return firstPart; firstPart--; /*calculating the decimal values*/ double precisionVal=0.1; double[] decimalValues=new double[decimalPoints]; double secondPart=0; for(int i=0;i<decimalPoints;i++) { while(square(firstPart+secondPart+decimalValues[i])<value) { decimalValues[i]+=precisionVal; } if(square(firstPart+secondPart+decimalValues[i])==value) { return (firstPart+secondPart+decimalValues[i]); } decimalValues[i]-=precisionVal; secondPart+=decimalValues[i]; precisionVal*=0.1; } return(firstPart+secondPart); } private static double square(double val) { return val*val; } static double Pow(double pVal, int pPow){ double res = 1; double v1, v2; int n = pPow; v1 = pVal; if ((n & 1) == 1) { res = pVal; } n = n >>> 1; while (n > 0) { v2 = v1 * v1; if ((n & 1) == 1) { res = res * v2; } v1 = v2; n = n >>> 1; } return res; } } <file_sep>import java.util.*; public class Lab1 { public static void main(String[] args) { System.out.println("Lab1"); System.out.println("ex1:"); ex1(); System.out.println("ex2:"); ex2(); System.out.println("ex3:"); ex3(); System.out.println("ex4:"); ex4(); System.out.println("ex5:"); ex5(); System.out.println("ex6:"); ex6(); } /*1. Дан массив из целых чисел A(n), где n=1…25. Напишите метод класса, позволяющий менять местами его максимальный и минимальный элемент. */ private static void ex1(){ ArrayList<Integer>A=generateArray(25); System.out.println(A); int maxInd = A.indexOf(Collections.max(A)); int minInd = A.indexOf(Collections.min(A)); Integer max = Collections.max(A); Integer min = Collections.min(A); A.set(maxInd, min); A.set(minInd, max); System.out.println(A); } /*2. Дан массив из целых чисел B(n), где n известное, но произвольное целое число до 1000. Напишите метод класса, позволяющий упорядочить массив по возрастанию. Алгоритм упорядочения выберите самостоятельно. */ private static void ex2(){ ArrayList<Integer>B=generateArray(1000); System.out.println(B); Collections.sort(B); System.out.println(B); } /*3. Дан массив из целых чисел С(n), где n=1…20. Напишите метод класса, позволяющий найти среднее значение элементов массива и вывести его на консоль.*/ private static void ex3(){ ArrayList<Integer>C=generateArray(20); System.out.println(C); System.out.println(C.stream().mapToInt((x) -> x).average()); } /*4. Дан массив из целых чисел D(n), где n=1…30. Напишите метод класса, позволяющий найти сумму четных и нечетных элементов массива. */ private static void ex4(){ Integer sumEven = 0, sumOdd = 0, sum1, sum2; ArrayList<Integer>D=generateArray(30); System.out.println(D); for (Integer integer : D) { sum1 = (integer % 2 == 0) ? integer : 0; sumEven += sum1; } System.out.println(sumEven); for (Integer integer : D) { sum2 = !(integer % 2 == 0) ? integer : 0; sumOdd += sum2; } System.out.println(sumOdd); } /*5. Напишите программу, выводящую на консоль таблицу размером 3×5 случайных элементов (a(i,j) < 10). */ private static void ex5(){ print(matrixCreation(3,5)); } /*6. Задается пять строк s1, s2, s3, s4 и s5. Напишите метод класса, работающий на основе следующего условия: если строка s4 равна строке s5, нужно выполнить конкатенацию строк s1 и s2, иначе нужно выполнить конкатенацию строк s1 и s3. */ private static void ex6(){ String s1="abcd", s2="1234", s3="ABCD", s4="zxcv", s5="zxcv"; //String s1="abcd", s2="1234", s3="ABCD", s4="zxcv", s5="ZX12"; System.out.println("s1: "+s1); System.out.println("s2: "+s2); System.out.println("s3: "+s3); System.out.println("s4: "+s4); System.out.println("s5: "+s5); if(s4.equals(s5)) System.out.println("Concat "+s1+s2); else System.out.println("Concat "+s1+s3); } static ArrayList<Integer> generateArray(Integer n){ ArrayList<Integer> numbers = new ArrayList<>(Collections.emptyList()); for (int i = 0; i < Math.random()*n; i++) { numbers.add((int) Math.round((Math.random() * n))); } return numbers; } static void print(int[][] puzzle) { for (int[] row : puzzle) { for (int elem : row) { System.out.printf("%4d", elem); } System.out.println(); } System.out.println(); } static void print(double[][] puzzle) { for (double[] row : puzzle) { for (double elem : row) { System.out.printf("%8.3f", elem); } System.out.println(); } System.out.println(); } static int[][] matrixCreation(int m, int n){ int[][] numbers = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { numbers[i][j]=((int) Math.round((Math.random() * 9))); } } return numbers; } }
387ee7b10f8845b1c44ef22d3d28833124d62fb7
[ "Java" ]
4
Java
SergeyZhiltsov/CrossPlatformProgramming
dadea3852a4022dfa23f4436d0518a3f1d5841b4
5106d747f3f522fac44c39c62c0059293508b199
refs/heads/master
<repo_name>BohdanKalynych/PythonAppiumPractice<file_sep>/Base/LaunchApp.py from appium import webdriver import time desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '8' desired_caps['deviceName'] = 'Pixel' desired_caps['automatorName'] = 'UiAutomator2' desired_caps['noSign'] = 'true' desired_caps['app'] = ('/Users/bkalynych/Documents/TestApps/Android_Demo_App.apk') desired_caps['appPackage'] = 'com.code2lead.kwad' desired_caps['appActivity'] = 'com.code2lead.kwad.MainActivity' driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps) ele_id = driver.find_element_by_id("com.code2lead.kwad:id/EnterValue") ele_id.click() time.sleep(3) inp_field = driver.find_element_by_id("com.code2lead.kwad:id/Et1") inp_field.send_keys("<PASSWORD>")<file_sep>/Base/TapElement.py from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By import time desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '8' desired_caps['deviceName'] = 'Pixel' desired_caps['automatorName'] = 'UiAutomator2' desired_caps['noSign'] = 'true' desired_caps['app'] = ('/Users/bkalynych/Documents/TestApps/Android_Demo_App.apk') desired_caps['appPackage'] = 'com.code2lead.kwad' desired_caps['appActivity'] = 'com.code2lead.kwad.MainActivity' driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps) wait = WebDriverWait(driver, 25, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException]) ele = wait.until(lambda x: x.find_element_by_android_uiautomator('new UiScrollable(new UiSelector()).scrollIntoView(text("LOGIN"))')) actions = TouchAction(driver) #actions.tap(None,700,1990,1) actions.tap(ele, 640, 1700, 1) actions.perform() time.sleep(2) <file_sep>/Base/LongClick.py from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By import time desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '8' desired_caps['deviceName'] = 'Pixel' desired_caps['automatorName'] = 'UiAutomator2' desired_caps['noSign'] = 'true' desired_caps['app'] = ('/Users/bkalynych/Documents/TestApps/Android_Demo_App.apk') desired_caps['appPackage'] = 'com.code2lead.kwad' desired_caps['appActivity'] = 'com.code2lead.kwad.MainActivity' driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps) wait = WebDriverWait(driver, 25, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException]) ele = wait.until(lambda x: x.find_element_by_android_uiautomator( 'new UiScrollable(new UiSelector()).scrollIntoView(text("LONG CLICK"))')) actions = TouchAction(driver) actions.long_press(ele) actions.perform() driver.quit() <file_sep>/Base/sandbox.py import json import requests response = requests.get("http://dummy.restapiexample.com/api/v1/employees") json_dict = json.loads(response.text) print(json_dict['data'][0]['employee_name']) print(len(json_dict['data'])) saved_names =[] for x in range(len(json_dict['data'])): saved_names.append(json_dict['data'][x]['employee_name']) print(saved_names) # people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'}, # 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}} # # print(people[1]['name'])
bd5dedfcfbdbe0f94fb7fbb85445c8a29dd0d4e0
[ "Python" ]
4
Python
BohdanKalynych/PythonAppiumPractice
e874b01ac2671a609f2df6ca7249e1e7d3bdc33a
d88239707fc25af287566ec14d53dde47d42287e
refs/heads/master
<file_sep>package main import ( "fmt" "os" "sync" "time" "github.com/codegangsta/cli" docker "github.com/fsouza/go-dockerclient" "github.com/montanaflynn/stats" ) func worker(requests int, image string, completeCh chan time.Duration) { client, err := docker.NewClientFromEnv() if err != nil { panic(err) } for i := 0; i < requests; i++ { start := time.Now() container, err := client.CreateContainer(docker.CreateContainerOptions{ Config: &docker.Config{ Image: image, }}) if err != nil { panic(err) } err = client.StartContainer(container.ID, nil) if err != nil { panic(err) } completeCh <- time.Since(start) } } func session(requests, concurrency int, image string, completeCh chan time.Duration) { var wg sync.WaitGroup n := requests / concurrency for i := 0; i < concurrency; i++ { wg.Add(1) go func() { worker(n, image, completeCh) wg.Done() }() } wg.Wait() } func bench(requests, concurrency int, image string) { start := time.Now() timings := make([]float64, requests) completeCh := make(chan time.Duration) current := 0 go func() { for timing := range completeCh { timings = append(timings, timing.Seconds()) current++ percent := float64(current) / float64(requests) * 100 fmt.Printf("[%3.f%%] %d/%d containers started\n", percent, current, requests) } }() session(requests, concurrency, image, completeCh) close(completeCh) total := time.Since(start) p50th, _ := stats.Median(timings) p90th, _ := stats.Percentile(timings, 90) p99th, _ := stats.Percentile(timings, 99) fmt.Println("") fmt.Printf("Time taken for tests: %s\n", total.String()) fmt.Printf("Time per container: %vms [50th] | %vms [90th] | %vms [99th]\n", int(p50th*1000), int(p90th*1000), int(p99th*1000)) } func main() { app := cli.NewApp() app.Name = "swarm-bench" app.Usage = "Swarm Benchmarking Tool" app.Version = "0.1.0" app.Author = "" app.Email = "" app.Flags = []cli.Flag{ cli.IntFlag{ Name: "concurrency, c", Value: 1, Usage: "Number of multiple requests to perform at a time. Default is one request at a time.", }, cli.IntFlag{ Name: "requests, n", Value: 1, Usage: "Number of containers to start for the benchmarking session. The default is to just start a single container.", }, cli.StringFlag{ Name: "image, i", Usage: "Image to use for benchmarking.", }, } app.Action = func(c *cli.Context) { if c.String("image") == "" { cli.ShowAppHelp(c) os.Exit(1) } bench(c.Int("requests"), c.Int("concurrency"), c.String("image")) } app.Run(os.Args) }
a0e6da2fca83c8b1aac34d6582a99fadcc87c397
[ "Go" ]
1
Go
vieux/swarm-bench
c13b2c2c6224e40d11f66361b4b6aae1a6605195
d46575b610a66728ce58b2835c39959eb299fd0c
refs/heads/master
<file_sep>$(document).ready(function () { $( window ).resize(function() { if ( $(window).width() < 800){ $('#font').css('display','none') $('#logo').css('display','none') $('#menus li').css('display','inline-block') } }); $("#nav").stick_in_parent() $(window).scroll( function() { if($(this).scrollTop() <= 706 && $(window).width() > 800){ console.log(4) $('#logo').css('display','none') $('#menus li').css('display','inline-block') } if ($(this).scrollTop() > 800 && $(window).width() > 800) { $('#logo').fadeIn('slow') $('#logo').css('display','inline-block') } if ($(this).scrollTop() > 800 && $(window).width() < 800) { $('#font').css('display','none') $('#logo').css('display','none') $('#menus li').css('display','inline-block') } }) var scrollLink = $('.scroll'); //Smooth scrolling scrollLink.click(function(event){ event.preventDefault(); $('body,html').animate({ scrollTop: $(this.hash).offset().top -50 },1000); /*offset calculates the distance between top and next part of section this.hash reads the href attribute of the scrollLink object */ }) var TxtRotate = function(el, toRotate, period) { this.toRotate = toRotate; this.el = el; this.loopNum = 0; this.period = parseInt(period, 10) || 2000; this.txt = ''; this.tick(); this.isDeleting = false; }; TxtRotate.prototype.tick = function() { var i = this.loopNum % this.toRotate.length; var fullTxt = this.toRotate[i]; if (this.isDeleting) { this.txt = fullTxt.substring(0, this.txt.length - 1); } else { this.txt = fullTxt.substring(0, this.txt.length + 1); } this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>'; var that = this; var delta = 300 - Math.random() * 100; if (this.isDeleting) { delta /= 2; } if (!this.isDeleting && this.txt === fullTxt) { delta = this.period; this.isDeleting = true; } else if (this.isDeleting && this.txt === '') { this.isDeleting = false; this.loopNum++; delta = 500; } setTimeout(function() { that.tick(); }, delta); }; window.onload = function() { var elements = document.getElementsByClassName('txt-rotate'); for (var i=0; i<elements.length; i++) { var toRotate = elements[i].getAttribute('data-rotate'); var period = elements[i].getAttribute('data-period'); if (toRotate) { new TxtRotate(elements[i], JSON.parse(toRotate), period); } } // INJECT CSS var css = document.createElement("style"); css.type = "text/css"; css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666 }"; document.body.appendChild(css); }; })
a52c3b20ad8515808a0094c85c9675d4bae828ab
[ "JavaScript" ]
1
JavaScript
Kiruxg/Kiruxg.github.io
40034adba512d2aa4dc0fec19c6410a46ffcf7fc
59ec5b37f8d33c1023c060f8362fe60315039809
refs/heads/master
<file_sep>package com.leslie.task_annotation; /** * 任务属性 * * 作者:xjzhao * 时间:2021-06-30 15:06 */ public class TaskMeta { private TaskType type; private int priority; private long delayMills; private Class<?> cls; private TaskMeta(TaskType type, int priority, long delayMills, Class<?> cls) { this.type = type; this.priority = priority; this.delayMills = delayMills; this.cls = cls; } public static TaskMeta build(TaskType type, int priority, long delayMills, Class<?> cls){ return new TaskMeta(type, priority, delayMills, cls); } public TaskType getType() { return type; } public int getPriority() { return priority; } public long getDelayMills() { return delayMills; } public Class<?> getCls() { return cls; } } <file_sep>rootProject.name='annotation' include ':app' include ':task-annotation' <file_sep># task-annotation Android启动任务管理器依赖的annotation 在task-api中使用,详见:[task-api](https://github.com/xjz-111/task-api) <file_sep>apply plugin: 'java-library' apply plugin: 'com.github.dcendents.android-maven' group='com.github.xjz-111' dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) } sourceCompatibility = "7" targetCompatibility = "7" java{ task sourcesJar(type: Jar, dependsOn:classes) { classifier = 'sources' from sourceSets.main.allSource } task javadocJar(type: Jar, dependsOn:javadoc) { classifier = 'javadoc' from javadoc.destinationDir } if (JavaVersion.current().isJava8Compatible()) { allprojects { tasks.withType(Javadoc) { options.addStringOption('Xdoclint:none', '-quiet') } } } artifacts { archives sourcesJar archives javadocJar } } buildscript { repositories { google() jcenter() maven { url 'https://jitpack.io' } } dependencies { classpath 'com.android.tools.build:gradle:3.6.3' classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } }<file_sep>package com.leslie.task_annotation; import java.util.List; /** * 作者:xjzhao * 时间:2021-07-01 16:11 */ public interface ITask { List<TaskMeta> getTasks(); }
ba4e372a6e5df18b8dc3cd7e4ccc809c16e30f8c
[ "Markdown", "Java", "Gradle" ]
5
Java
xjz-111/task-annotation
f7366f58d8e306b34bc50d97eae56e5c724fa656
adb60d70eb408f67317da137b86798db123dc047
refs/heads/master
<repo_name>dbrady/dotfiles<file_sep>/dotplatform-dev #!/bin/bash export PLATFORM_DEV=$HOME/dev shovel() ( $PLATFORM_DEV/script/run shovel "$@"; ) alias de='docker exec -e COLUMNS="$(tput cols)" -e LINES="$(tput lines)" -ti' alias dps='docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}\t{{.Command}}\t{{.Image}}"' # zsh completion - investigate for bash? # export PLATFORM_DEV=$HOME/platform/dev # change to match your local dev directory # fpath=($PLATFORM_DEV/misc/completion/ $fpath) # autoload -U compinit && compinit <file_sep>/osx_or_linux.sh #!/bin/bash echo `uname -a | awk '{print $1}'` case `uname -a | awk '{print $1}'` in Linux) echo 'This is running on Linux!' ;; Darwin) echo 'This is running on OSX!' ;; *) echo 'I have no clue what OS this is. :-(' ;; esac # Here's the same thing as an if test statement if [ `uname -a | awk '{print $1}'` = 'Linux' ]; then echo 'This is running on Linux!'; fi if [ `uname -a | awk '{print $1}'` = 'Darwin' ]; then echo 'This is running on OSX!'; fi <file_sep>/just_your_methods.rb # thing.just_your_methods - Return methods not shared with all Object instances # Differs from object.methods(false) in that it returns methods you inherit from # parent classes (that aren't also inherited by Object instances) class Object def just_your_methods (self.methods - Object.new.methods).sort end end puts "Object#just_your_methods loaded." <file_sep>/ps1_functions #!/usr/bin/env bash # ====================================================================== # ps1_functions # # Originally stol^H^H^H^Hcopied from .rvm/contrib, which I sort of # feel entitled to do since I helped Wayne write the original version # of this script. Well, I watched him do it, at any rate. :-) # Excellent bash programming tutorial video here: # http://vimeo.com/21538711 # # Why I'm forking it: I'm now working on a company laptop where I need # my git config to show my company name/email when I'm working on # company projects, but my personal name/email when I'm working on # personal stuff. # ====================================================================== # # Source this file in your ~/.bash_profile or interactive startup file. # This is done like so: # # [[ -s "$HOME/.rvm/contrib/ps1_functions" ]] && # source "$HOME/.rvm/contrib/ps1_functions" # # Then in order to set your prompt you simply do the following for example # # Examples: # # ps1_set --prompt ∫ # # or # # ps1_set --prompt ∴ # # This will yield a prompt like the following, for example, # # 00:00:50 wayneeseguin@GeniusAir:~/projects/db0/rvm/rvm (git:master:156d0b4) [<EMAIL>] ruby-1.8.7-p334@rvm # ∴ # ps1_titlebar() { case $TERM in (xterm*|rxvt*) printf "%s" "\033]0;\\u@\\h: \W\\007" ;; esac } ps1_identity() { if (( $UID == 0 )) ; then printf "%s" "\[\033[31m\]\\u\[\033[0m\]@\[\033[36m\]\\h\[\033[35m\]:\w\[\033[0m\] " else printf "%s" "\[\033[32m\]\\u\[\033[0m\]@\[\033[36m\]\\h\[\033[35m\]:\w\[\033[0m\] " fi } ps1_git() { local branch="" sha1="" line="" attr="" color=0 pr="" shopt -s extglob # Important, for our nice matchers :) command -v git >/dev/null 2>&1 || { printf " \033[1;37m\033[41m[git not found]\033[m " return 0 } branch=$(git symbolic-ref -q HEAD 2>/dev/null) || return 0 # Not in git repo. branch=${branch##refs/heads/} # Now we display the branch. sha1=$(git rev-parse --short --quiet HEAD) case "${branch:-"(no branch)"}" in production|prod) attr="1;37m\033[" ; color=41 ;; # bold white on red master|develop|dev|development|deploy|main) attr="1;37m\033[" ; color=41 ;; # bold white on red stage|staging) color=33 ;; # yellow next) color=36 ;; # gray *) if [[ -n "${branch}" ]] ; then # Happiness! This is a feature/story branch :) color=32 # green # TODO: don't show PR info if get-pr-id returns -1 pr=" \033[1;37;42mPR-$(git get-pr-id)" else color=0 # reset fi ;; esac [[ $color -gt 0 ]] && printf "\[\033[${attr}${color}m\](git:${branch}$(ps1_git_status):$sha1)${pr}\[\033[0m\] $(ps1_git_email) " } ps1_git_email() { local hash_program="" attr="" fgcolor=0 bgcolor=0 color="" git_email="" hash="" git_email="$(git config --get user.email)" # Hash emails here only because this file is publicly visible ;-) hash_program="md5" command -v $hash_program >/dev/null 2>&1 || $hash_program="md5sum" hash=`echo ${git_email} | ${hash_program} | cut -f 1 -d ' '` prerendered=0 # TODO: 2020-10-11 - Today I did 3 commits from the wrong email even though # it was colorized. Two thoughts about that: For now, just watch for it # (YAGNI: it might have been a one-off?) and if it happens again let's add a # path fragment for each email to belong to, and if it doesn't belong let's # freak right out, like bold white on bright red at a minimum, possibly even # blart an alarm to $stderr if possible? # # In the Interim: these were new repos that also needed add_nocommit to be # run on them. I wonder if I could change git clone to emit a reminder # and/or the same in add_nocommit (I forgot to run add_nocommit too until # later, so eh.) # # IF IT HAPPENS AGAIN but isn't merged, git rebase -i # <commit_before_mistake> and change all of them to "edit", then do 'git # commit --amend author=blah <LOOK THIS UP, BUSY PAIRING>' case $hash in "1d0e58ecbd97780bb36f6db90a2b57ac") bgcolor="" ; fgcolor="32" ;; # shinybit - green "563e2af36b14b3c954f77e938469606b") git_email="\033[1;47;38;5;208mdbrady\033[0m\033[1;47;38;5;125m@\033[0m\033[1;47;38;5;208mcover\033[0m\033[1;47;38;5;125mmy\033[0m\033[1;47;38;5;208mmeds\033[0m" prerendered=1 ;; "abf0f4f7072d77a68ccec42247fe1e4f") fgcolor="1;38;5;27"; bgcolor="48;5;15" ;; # kp - bold blue on white "745932c691e01f288d7b56625296afe8") fgcolor="1;38;5;15"; bgcolor="48;5;17" ;; # ks - bold white on blue "fdbc33b336274f0b0e65030f7e39d435") fgcolor="1;38;5;15"; bgcolor="48;5;33" ;; # acimacredit - bold white on light blue "d9ade019b6afb77f890ac5c93845f029") fgcolor="1;38;5;15"; bgcolor="48;5;33" ;; # acima - bold white on light blue # default *) bgcolor=41 ; fgcolor="1;37" ;; # bold white on bright red esac if [[ 1 -eq $prerendered ]] ; then printf "%s" $git_email else if [[ -n "${bgcolor}" ]] ; then printf "\033[${fgcolor};${bgcolor}m%s\033[0m" $git_email else printf "\033[${fgcolor}m%s\033[0m" $git_email fi fi } ps1_git_status() { local git_status="$(git status 2>/dev/null)" [[ "${git_status}" = *deleted* ]] && printf "%s" "-" [[ "${git_status}" = *Untracked[[:space:]]files:* ]] && printf "%s" "+" [[ "${git_status}" = *modified:* ]] && printf "%s" "*" } ps1_rvm() { command -v rvm-prompt >/dev/null 2>&1 && printf "%s" " $(rvm-prompt) " } ps1_update() { local prompt_char='$' separator="\n" notime=0 thisisdocker='' (( $UID == 0 )) && prompt_char='#' while [[ $# -gt 0 ]] ; do local token="$1" ; shift case "$token" in --trace) export PS4="+ \${BASH_SOURCE##\${rvm_path:-}} : \${FUNCNAME[0]:+\${FUNCNAME[0]}()} \${LINENO} > " set -o xtrace ;; --prompt) prompt_char="$1" shift ;; --noseparator) separator="" ;; --separator) separator="$1" shift ;; --notime) notime=1 ;; *) true # Ignore everything else. ;; esac done if [ "$IS_DOCKER_LOCAL" != "1" ]; then # Not on docker - use my usual prompt nonsense if (( notime > 0 )) ; then PS1="$(ps1_titlebar)$(ps1_identity)$(ps1_git)$(ps1_rvm)$(vpn_display)${separator}${prompt_char} " else PS1="$(ps1_titlebar)\D{%H:%M:%S} $(ps1_identity)$(ps1_git)$(ps1_rvm)$(vpn_display)${separator}${prompt_char} " fi else # Yes on docker - use my alternative prompt nonsense thisisdocker="\033[1;37;105m ~~~ THIS IS DOCKER ~~~ THIS IS DOCKER ~~~ THIS IS DOCKER ~~~ THIS IS DOCKER ~~~ THIS IS DOCKER ~~~ THIS IS DOCKER ~~~ THIS IS DOCKER ~~~ \033[0m" if (( notime > 0 )) ; then PS1="$(ps1_titlebar)$(ps1_identity)$(ps1_git)$(ps1_rvm)${separator}${thisisdocker}${separator}${prompt_char} " else PS1="$(ps1_titlebar)\D{%H:%M:%S} $(ps1_identity)$(ps1_git)$(ps1_rvm)${separator}${thisisdocker}${separator}${prompt_char} " fi fi } ps2_set() { PS2=" \[\033[0;40m\]\[\033[0;33m\]> \[\033[1;37m\]\[\033[1m\]" } ps4_set() { export PS4="+ \${BASH_SOURCE##\${rvm_path:-}} : \${FUNCNAME[0]:+\${FUNCNAME[0]}()} \${LINENO} > " } # WARNING: This clobbers your PROMPT_COMMAND so if you need to write your own, call # ps1_update within your PROMPT_COMMAND with the same arguments you pass # to ps1_set # # The PROMPT_COMMAND is used to help the prompt work if the separator is not a new line. # In the event that the separator is not a new line, the prompt line may become distorted if # you add or delete a certian number of characters, making the string wider than the # $COLUMNS + len(your_input_line). # # This orginally was done with callbacks within the PS1 to add in things like the git # commit, but this results in the PS1 being of an unknown width which results in the prompt # being distorted if you add or remove a certain number of characters. To work around this # it now uses the PROMPT_COMMAND callback to re-set the PS1 with a known width of chracters # each time a new command is entered. See PROMPT_COMMAND for more details. # ps1_set() { PROMPT_COMMAND="ps1_update $@" } ps1_plain() { PROMPT_COMMAND="" PS1="$(ps1_identity)\\$ " } ps1_bare() { PROMPT_COMMAND="" PS1="\\$ " } <file_sep>/xml_load_file.rb # loading a file from disk that contains XML directly into memory is a minor # PITA in Ruby, and it shouldn't be. This creates a global method, load_xml, # that does exactly what you'd expect, as long as you expect it to use Nokogiri # to load the xml file. require "nokogiri" def xml_load_file(filename) Nokogiri::XML(File.read(File.expand_path(filename))) end $stderr.puts "So, doin' a lot of XML work lately, eh? I just created xml_load_file(filename) for you. You're welcome." <file_sep>/dotbash_functions #!/bin/bash # ---------------------------------------------------------------------- # tssh() # # Clever hack from <NAME> -- when in tmate, tssh will put the # tmate_ssh key into the OSX clipboard # ---------------------------------------------------------------------- tssh() { echo "tmate display -p '#{tmate_ssh}'" tmate display -p '#{tmate_ssh}' echo "tmate display -p '#{tmate_ssh}' | pbcopy;" tmate display -p '#{tmate_ssh}' | pbcopy; echo "copied to clipboard." } # ---------------------------------------------------------------------- # makeline() # # 'makeline =' to make terminal width line. Or give 2nd arg count. By # default prints a line of #'s as wide as the terminal. # # Credit due to @climagic: # https://twitter.com/#!/climagic/status/168025763063406593 # # Example: # $ makeline = 40 # ======================================== makeline() { printf "%${2:-$COLUMNS}s\n" ""|tr " " ${1:-#}; } # ======================================== # Interface to calc. Use from prompt! # $ calc "sqrt(37)+(2^7/3)" # 48.74942 # ======================================== calc() { bc <<< "scale=5; $1";} # ---------------------------------------------------------------------- # rspec_alot() # # stolen from <NAME> - do I need to tweak this to bundle exec or # bin/rspec? # ---------------------------------------------------------------------- function rspec_alot() { for i in `seq $1` ; do rspec $2 ; [[ ! $? = 0 ]] && break ; done } <file_sep>/bash_completions #!/bin/sh # Include ports' version of bash_completion (if it exists) if [ -f /opt/local/etc/bash_completion ]; then . /opt/local/etc/bash_completion fi # FIXME: This does not work. Something about the colon causes the # expander to wonk. I think maybe complete treats : as a separate # token? Dono. Anyway, here's what happens: # # You type... You get... # # rake db:<TAB> rake db:db: # rake db:mig<TAB> rake db:migrate # # Custom expansion of rake tasks. WOO! # _rake_tasks() # { # local curw # COMPREPLY=() # curw=${COMP_WORDS[COMP_CWORD]} # # The bit of ruby in there eats the first line of output. Wish # # head/tail had the ability to show all but the n first/last lines # # of a file. # local tasks="$(rake -T | ruby -n -e 'puts $_ if $seen; $seen=true' | awk '{ print $2 }')" # COMPREPLY=($(compgen -W '$tasks' -- $curw)); # return 0 # } # complete -F _rake_tasks rake # dbrady 2008-12-03: Commented out because ports bash_completion does this better than me. # Custom expansion of ssh, using hostnames from .ssh/config # _sshhosts() # { # # cat ~/.ssh/config | grep -Ei '^Host' | awk '{ print $2}' # local curw # COMPREPLY=() # curw=${COMP_WORDS[COMP_CWORD]} # local hosts="$(cat ~/.ssh/config | grep -Ei '^Host' | awk '{ print $2}')" # COMPREPLY=($(compgen -W '$hosts' -- $curw)); # return 0 # } # complete -o default -o nospace -F _sshhosts ssh # complete -o default -o nospace -F _sshhosts scp # Custom expansion for mysql-D <databasename> _mysqldbs() { local cur prev COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" if [[ ${prev} == -D ]] ; then local dbs="$(mysql -e 'show databases')" COMPREPLY=( $(compgen -W "${dbs}" -- ${cur}) ) return 0 fi } complete -o default -o nospace -F _mysqldbs mysql # Custom expansion for mategem _gemdirs() { local curw COMPREPLY=() curw=${COMP_WORDS[COMP_CWORD]} local gems="$(gem environment gemdir)/gems" COMPREPLY=($(compgen -W '$(ls $gems)' -- $curw)); return 0 } complete -F _gemdirs -o dirnames mategem complete -F _gemdirs -o dirnames emgem # cdgem is just an alias script for "cd", but this lets me get # tab-completion into the gems folder. Why yes, I am that # lazy^H^H^H^Hclever, thank you for asking. complete -F _gemdirs -o dirnames cdgem <file_sep>/dotirbrc #!/usr/bin/env ruby # begin # # looksee is awesome. Adds gorgeous Object#ls method # # https://github.com/oggy/looksee # require 'looksee' # rescue LoadError => e # $stderr.puts "~/.irbrc:#{__LINE__}: Could not load looksee/shortcuts: looksee gem not present in this gemset" # end require File.expand_path("~/dotfiles/json_load_file") require File.expand_path("~/dotfiles/xml_load_file") require File.expand_path("~/dotfiles/just_your_methods") # Hello Acima MP Rails if defined? Rails ZBONCAK_ID=41499 ZBONCAK_GUID="merc-5c5d37fb-071c-4739-b832-bfafc93db09b" DAVE_USER_ID=2892 DAVE_API_USER_ID=377 puts 'def load_merchant; Merchant.find(41499); end # Find Zboncak-Adams easily' puts 'def load_user; User.find(2892); end # Find my user easily' puts 'def load_api_user; ApiUser.find(377); end' puts "def load_hacks -> load all files in app/local_hacks" def load_hacks # load all files in app/local_hacks Dir.glob(Rails.root + "app/local_hacks/*").each do |file| puts "Loading #{file}..." load file end puts "Loaded! Call ApiScript.ls to list important/useful methods" end def load_merchant Merchant.find ZBONCAK_ID end def load_location load_merchant.locations.first end def load_user User.find DAVE_USER_ID end def load_api_user ApiUser.find DAVE_API_USER_ID end class User < ApplicationRecord def add_all_roles! puts "Giving all roles to #{full_name}..." user.role_names = "|#{Role.all.pluck(:short_name) * '|'}|" user.save end def remove_all_roles! puts "Removing all roles from #{full_name}..." user.role_names = '' user.save end end # for the 49/99 stuff class Location < ApplicationRecord def banksy? puts "location.settings.can_offer_unbanked_application" settings.can_offer_unbanked_application end def banksy!(enable=true) puts "location.settings.update!(can_offer_unbanked_application: #{enable.inspect})" settings.update!(can_offer_unbanked_application: enable) end end class Lease < ApplicationRecord def banksy? puts "lease.settings.unbanked_application" settings.unbanked_application end def banksy!(enable=true) puts "lease.settings.update!(unbanked_application: #{enable.inspect})" settings.update!(unbanked_application: true) end end end <file_sep>/dotbash_profile #!/bin/sh export EDITOR=$(echo `which emacs` -nw -q -l ~/.emacstiny) export GEMEDITOR=$(echo `which emacs` -nw) export CVSEDITOR=$(echo `which emacs` -nw -q -l ~/.emacstiny) export SVN_EDITOR=$(echo `which emacs` -nw -q -l ~/.emacstiny) # Flags suggested by homebrew export LDFLAGS="-L/opt/homebrew/opt/curl/lib" export CPPFLAGS="-I/opt/homebrew/opt/curl/include" export PKG_CONFIG_PATH="/opt/homebrew/opt/curl/lib/pkgconfig" case `uname -a | awk '{print $1}'` in Linux) # export JAVA_HOME='/usr/lib/jvm/default-java' export JAVA_HOME='/usr/lib/jvm/java-8-openjdk-amd64/' ;; Darwin) export JAVA_HOME='/System/Library/Frameworks/JavaVM.framework/Home' ;; *) echo '~/.bash_profile has no clue what OS this is; not setting JAVA_HOME.' ;; esac # === OSX Specific ====================================================== # Search the ls manpage for "CLICOLOR" and "color designators for an # explanation of this goodness. # CLICOLOR: Search "man ls" for "CLICOLOR" and "color designators". # a: black 1. directory # b: red 2. symbolic link # c: green 3. socket # d: brown 4. pipe # e: blue 5. executable # f: magenta 6. block special # g: cyan 7. character special # h: light grey 8. executable with setuid bit set # A: bold black, usually shows up as dark grey 9. executable with setgid bit set # B: bold red 10. directory writable to others, with sticky bit # C: bold green 11. directory writable to others, without sticky bit # D: bold brown, usually shows up as yellow # E: bold blue # F: bold magenta # G: bold cyan # H: bold light grey; looks like bright white # x: default foreground or background # # The standard Mac OSX colors are: exfxcxdxbxegedabagacad # # TODO: export these to functions or scripts called light_bg or dark_bg, etc. export CLICOLOR=1 # Standard colors look good on a white background # export LSCOLORS=exfxcxdxbxegedabagacad # export LS_COLORS=exfxcxdxbxegedabagacad # Swap blue/cyan for better visibility on dark bg #export LSCOLORS=gxfxcxdxbxegedabagacad # === OSX Specific ====================================================== # Use less by default b/c search works better. But keep most inifile # here for tweaking. #export PAGER="most" export MOST_INIFILE='/etc/most.rc' GREP_OPTIONS='--color=auto' GREP_COLOR='1;32' # ---------------------------------------------------------------------- # Terminal colours (after installing GNU coreutils) NM="\[\033[0;38m\]" #means no background and white lines HI="\[\033[0;37m\]" #change this for letter colors HII="\[\033[0;31m\]" #change this for letter colors SI="\[\033[0;33m\]" #this is for the current directory IN="\[\033[0m\]" export HISTFILESIZE=10000 # Whin SHIFTING dirs onto head of PATH, last shift is the first/winner. # postgres Acima (postgresql@13 because I wanted a psql for reference) if [[ $PATH != *"/opt/homebrew/bin"* ]]; then export PATH=/opt/homebrew/Cellar/postgresql\@13/13.11/bin:$PATH fi if [[ $PATH != *"$HOME/bin"* ]]; then export PATH=$HOME/bin:$PATH fi if [[ $PATH != *"private_bin"* ]]; then export PATH=~/private_bin:$PATH fi # Acima-specific stuffs - if more than this path needs to be here, please make a # .acima file and source_files() it if [[ $PATH != *"acima/bin"* ]]; then export PATH=~/acima/bin:$PATH fi if [[ $PATH != *"acima/devel/merchant_portal/app/local_hacks"* ]]; then export PATH=~/acima/devel/merchant_portal/app/local_hacks:$PATH fi source_files() { local file for file in "$@" ; do file=${file/\~\//$HOME\/} # Expand ~/ if [[ -s "${file}" ]] ; then source "${file}" # else # # I found this useful for debugging, now it's just noisy # if [[ ! -e "${file}" ]] ; then # printf "NOTICE: ${file} does not exist, not loading.\n" # else # true # simply an empty file, no warning necessary. # fi fi done return 0 } source_files ~/.aliases \ ~/.bash_completions \ ~/.git-completion.bash \ ~/.nav \ ~/.private \ ~/.ps1_functions \ ~/.bash_functions \ ~/.current-project \ ~/.hue.conf \ ~/.platform-dev \ ~/.vpn # Turn on path completion for my go command. # This must come after git-completion.bash. complete -o default -o nospace -F _git_checkout go # PS1 EMOJIS if command -v ps1_set >/dev/null 2>&1 ; then if [ `hostname` == "poo.local" ]; then ps1_set --prompt "💩 " export PS2=💩💩 elif [ `hostname` == "poot" ]; then # ps1_set --prompt "💨­" ps1_set --prompt "💨 " export PS2="💨💨 " # ps1_set --prompt "$" elif [ `hostname` == "CMMVMOSX045" ]; then ps1_set --prompt "💊­" export PS2=💊💊­ elif [ `hostname` == "Mac1205Pro.local" ]; then ps1_set --prompt "💳" export PS2=💳💳 elif [ `hostname` == "31b95b7de045" ]; then ps1_set --prompt "🚢" export PS2=🚢🚢 else ps1_set --prompt "🎸" export PS2=🎶🎵 fi else export PS1="!!! It's \D{%H} O'Clock! Check your dotfiles folder for ps1_functions.\n$ " fi # force 256-color terminal in docker if [ "$IS_DOCKER_LOCAL" == "1" ]; then export TERM=xterm-256color fi export MANPATH=/opt/local/share/man:$MANPATH # For some reason unbeknownst to me, emacs started from the CLI opens an XWindows version of emacs but with keyboard input still locked to the terminal. # 2015-02-04 Is this dead code? Has no effect in OSX. Turn back on if linux still needs it. # alias 'emacs'='emacs -nw' export OPSCODE_USER=ratgeyser # 2023-07-31 - Switching to rbenv because the keyserver poisoning is real :'-( # [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function* # Acima if [ `hostname` = "Mac1205Pro.local" ]; then # MP tests need this every time, so export TZ='America/Denver' # This adds 80 seconds to the MP spec suite. It is good to pass in when we # need the whole suite to interop correctly, but when trying to TDD it is # agonizing. # export SPEC_SEED=true # Acima AWS export AWS_PROFILE=acima-nonprod export KUBECONFIG=~/.kube/nonprod/preflight # Atlas>Artemis>Hermes gave the option to install postgresql@13 as an app, # and self-containment is teh win. But now I need the CLI tools in my path, # so... export PATH="$PATH:/Applications/Postgres.app/Contents/Versions/13/bin" else case `uname -s` in Linux) source /etc/profile.d/rvm.sh ;; Darwin) echo "~/.bash_profile: I see you're on OSX but NOT your usual work machine. That's weird, right? NOT setting rvm defaults." ;; *) echo "~/.bash_profile has no clue what OS this is. So that's kinda neat I guess." ;; esac fi if [ `uname -s` = "Darwin" ]; then # I'll never let go of bash until they physically bar me from installing it. # zsh is NOT an acceptable bash unless you're not using any of bash's features. # That said, I get why AAPL is doing this. bash going GPL v3 poses a genuine # threat to the privacy of their OS. export BASH_SILENCE_DEPRECATION_WARNING=1 fi # Setup ssh agent # ssh-add -L &> /dev/null ssh-add -L >/dev/null 2>&1 if [ $? -eq 1 ]; then ssh-add fi # OSX-specific randomness if [ `uname -s` == "Darwin" ]; then test -e "${HOME}/.iterm2_shell_integration.bash" && source "${HOME}/.iterm2_shell_integration.bash" [ -f ~/.fzf.bash ] && source ~/.fzf.bash # capybara-webkit needs quicktime 5.5, which is the last version of QT to support webkit bindings # get it with brew install [email protected] export PATH="/usr/local/opt/[email protected]/bin:$PATH" # for mtr (OSX) export PATH=$PATH:/usr/local/sbin fi # Linux-specific randomness if [ `uname -s` == "Linux" ]; then export FLEX_HOME=/home/dbrady/devel/flex_sdk_4_6/ export PATH=$PATH:$FLEX_HOME/bin fi # my manual implementation of ponysay because lol # sayfortune # if [ -e ~/bin/applejack.txt ] ; then # cat ~/bin/applejack.txt # fi # NVM export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion # $IS_DOCKER_LOCAL is a flag we set in data_services to distinguish between "prodlike, because Docker" and "prodlike, because production" if [ ! "$IS_DOCKER_LOCAL" == "1" ]; then # Let's do birbs for a while. (Acima OSX only, since I don't have my Pictures # folder under git since I don't wanna get my repo copywronged.) Have to call # it "term-birb" because "birb" will "bundle exec irb" lol. term-birb # brew shellenv will dump all the homebrew variables. eval() on it will # export them into the current bash session. eval "$(/opt/homebrew/bin/brew shellenv)" fi # rbenv # eval "$(rbenv init - bash)" # rbenv global 3.2.2 export PATH="/Users/davidbrady/.rbenv/shims/:$PATH" export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES <file_sep>/json_load_file.rb # loading a file from disk that contains JSON directly into memory is a huge # PITA in Ruby, and it shouldn't be. This creates a method directly on the # module, JSON.load_file(filename), that does exactly what you'd expect. require 'json' module JSON def self.load_file(filename, options={}) parse File.read(filename) end def self.purtify(json) pretty_generate parse json end end $stderr.puts "So, doin' a lot of JSON work lately, eh? I just created JSON.load_file(filename [, options]) for you. You're welcome. ([options] are so can symbolize_names: true)" $stderr.puts "Also! I just added JSON.purtify(json). It does JSON.pretty_generate(JSON.parse(json)) so you don't have to!" <file_sep>/dotvpn #!/bin/bash # # 2023-03-28: This checks ifconfig for a specific utun or mtu connection, which # is a mostly-but-not-always-reliable side effect. On Apple Silicon, ifconfig # does not change. So I did some digging around and discovered that Cisco # provides a tool for OSX to determine VPN status directly: # `/opt/cisco/anyconnect/bin/vpn state` will report `state: Disconnected` or # `state: Connected`. (It does this 3 times; I do not know why. So there's still # some magic here to cargo cult around.) # # I don't use any of the other tools here, favoring the GUI, but I do like # seeing if the VPN is up or not on my command-line, so I'm going to comment out # everything in here except for the vpn state detection. # export VPN_USER=david.brady # # # adds VPN password to macOS Keychain # function set-vpn-pw() { # security add-generic-password -s "AnyConnect" -a "$VPN_USER" -p # } # # # removes and adds new VPN password to macOS Keychain # function update-vpn-pw() { # security -q delete-generic-password -s "AnyConnect" -a "$VPN_USER" # set-vpn-pw # } # # # 2022-08-30: The old vpn hiccupped every six minutes all # # afternoon. This was vpndev.acimacredit.com. Talking with IT, they # # had me change just one or two tiny things[1] and switch to a new vpn # # they were testing. # # # # [1] Upgrading my AnyConnect client, which required me to upgrade my # # whole dang OS to Monterey because it didn't run on Catalina. Neet. # # # # 2022-11-14: The new vpn has stopped working as of last week. :'-( # # Going back to vpndev and hoping it's not all hangy-wangy. # # # # testing vpn # # acima-minuteman-wired-wpwdkjgtjq.dynamic-m.com # # # # tried and true and crashy AF vpn # # vpndev.acimacredit.com # function vpnon() { # printf "0\n$VPN_USER\n$(security find-generic-password -s "AnyConnect" -a "$VPN_USER" -w)\npush" | /opt/cisco/# anyconnect/bin/vpn -s connect vpndev.acimacredit.com # # printf "0\n$VPN_USER\n$(security find-generic-password -s "AnyConnect" -a "$VPN_USER" -w)\npush" | /opt/cisco/anyconnect/bin/vpn -s connect acima-minuteman-wired-wpwdkjgtjq.dynamic-m.com # } # # alias vpnoff="/opt/cisco/anyconnect/bin/vpn disconnect" # # function vpn() { # # if [[ $(ifconfig | grep "mtu 1406" ) ]] # if [[ $(ifconfig | grep -E '^utun2: ') ]] # then # echo "You're connected to the VPN" # else # echo "You're not connected to the VPN" # fi # } function vpn_display() { # skip all this crap if we're on Docker. Don't spend all those extra # milliseconds invoking vpn and ifconfig. if [ "$IS_DOCKER_LOCAL" != "1" ]; then if [[ $(/opt/cisco/anyconnect/bin/vpn state | grep 'state: Connected') ]]; then # 32 = green [V] printf " \e[32m[V]\e[0m" else # Check for my onsite dedicated IP. If docker if [[ $(ifconfig | grep 10.1.180.) ]]; then # 96;40 = light cyan [O] = "you are [O]nsite" printf " \e[96m[O]\e[0m" else # 2;31 = dim red [V] printf " \e[2;31m[V]\e[0m" fi fi fi } # -------------------------------------------------------------------------------- # And then this goes in PS1 somewhere: # \$(vpn_display) <file_sep>/setup.sh #!/bin/sh pushd ~ if [ $IS_DOCKER_LOCAL == "1" ]; then ln -s ~/dotfiles/dotbash_profile .bashrc ln -s ~/dotfiles/dotnav.docker .nav else ln -s ~/dotfiles/dotbashrc .bashrc ln -s ~/dotfiles/dotbash_profile .bash_profile ln -s ~/dotfiles/dotnav .nav fi ln -s ~/dotfiles/bash_completions .bash_completions ln -s ~/dotfiles/dotaliases .aliases ln -s ~/dotfiles/dotvimrc .vimrc ln -s ~/dotfiles/dotirbrc .irbrc ln -s ~/dotfiles/git-completion.bash .git-completion.bash ln -s ~/dotfiles/dotgitignore .gitignore echo "# dotprivate - This is your .private file. It generated by setup.sh\nand does not live in git." > ~/dotfiles/dotprivate echo "# dotprivate - This is your .private file. It is autogenerated by\nsetup.sh and does not live in git." > ~/dotfiles/dotprivate ln -s ~/dotfiles/dotprivate .private ln -s dotfiles/ps1_functions .ps1_functions ln -s dotfiles/dotvpn .vpn popd
08a21800850dcb5406b9f71ecd44d426fe47006a
[ "Ruby", "Shell" ]
12
Shell
dbrady/dotfiles
c4ef5549a8a506a57ad804cec92befc95bf00290
7ec6c02af5c523bff99f76dd87c9213597a774d0
refs/heads/master
<file_sep>$(document).ready(function() { $(".fa-search").click(function() { var search = $(".topbar_search input"); search.toggleClass("active"); $(".topbar_search input").focus(); $(".topbar_search").toggleClass("active"); }) }) $(document).ready(function(){ $(".topbar_search input").blur(function(){ $(".topbar_search input").removeClass("active"); $(".topbar_search").removeClass("active"); }) })<file_sep>(function () { var promoteA = $(".promote-box").children("a"); var lis = $(".carousel-banner").find("li"); var i = 0; //显示第一个 lis.eq(0).trigger('click'); change(); function change() { promoteA.each(function() { promoteA.eq(i).fadeIn(); lis.eq(i).addClass('active'); promoteA.eq(i).siblings().fadeOut(); lis.eq(i).siblings().removeClass('active'); }) i++; if(i == lis.length) { i = 0; } } var t = setInterval(change, 3000); lis.click(function() { i = $(this).index(); clearInterval(t); change(); }) })();<file_sep>//var ul = document.getElementsByClassName("index-menu"); //var lis = ul[0].getElementsByTagName("li"); //var line = document.getElementsByClassName("line"); // //for (var i = 0; i<lis.length; i++) { // lis[i].onmouseover = function () { // line[0].style.width = this.offsetWidth + "px"; // line[0].style.left = this.offsetLeft + "px"; // } // // lis[i].onmouseout = function () { // line[0].style.width = 0 + "px"; // } //} $(function() { var $menu = $('.index-menu'); var $line = $('.line') var $lis = $menu.find('li'); $lis.each(function () { $(this).hover(function () { var liWidth = $(this).outerWidth(); var liLeft = $(this).position().left; $line.width(liWidth); $line.css('left', liLeft + 'px') ; }, function () { $line.width(0); $line.css('left', 0 + 'px') ; }) }) }) <file_sep>$(".ali-product>ul>li").click(function() { //切换icon的背景图片 var index = $(this).index(); var lis = $(this).closest(".ali-product").find("li"); $(lis).each(function() { var i = $(this).index(); if(i == index) { $(this).addClass("active"); $(this).find(".ali-product-icon").addClass("active"); } else { $(this).removeClass("active"); $(this).find(".ali-product-icon").removeClass("active"); } }) //指示三角的位置 var $liLeft = $(this).position().left; var $indicatorElmt = $(this).parent().children(".indicator-triangle"); var indicatorLocation = $liLeft + $(this).outerWidth() / 2 - $indicatorElmt.outerWidth() / 2; $indicatorElmt.css("left", indicatorLocation); //切换ali-product // var j = $(this).parents(".ali-product").index(); // $(".ali-product").each(function() { // var index = $(this).index(); // if(index == j) { // $(this).addClass("active"); // $(this).find(".indicator-triangle").addClass("active"); // } else{ // $(this).removeClass("active"); // $(this).find(".ali-product-content").removeClass("active"); // $(this).find(".ali-product-icon").removeClass("active"); // } // }) //切换ali-product // 显示父元素效果 $(this).closest(".ali-product").addClass("active"); $(this).closest(".ali-product").find(".ali-product-content-container").addClass("active"); $(this).closest(".ali-product").find(".ali-product-content-container").show(); $(this).closest(".ali-product").find(".indicator-triangle").addClass("active"); // 隐藏所有兄弟元素 var $hideTable = $(this).closest(".ali-product").siblings(".ali-product"); $hideTable.find(".ali-product-content-container").hide(); $hideTable.find(".ali-product-content").hide(); $hideTable.find(".ali-product-content").removeClass("active"); $hideTable.find("li").removeClass("active"); $hideTable.find(".ali-product-icon").removeClass("active"); $hideTable.find(".indicator-triangle").removeClass("active"); $hideTable.find(".ali-product-content-container").removeClass("active"); $hideTable.removeClass("active"); //切换ali-product-content var divs = $(this).parents(".ali-product").find(".ali-product-content"); $(divs).each(function() { var i = $(this).index(); if(i == index) { $(this).addClass("active"); $(this).fadeIn(); } else { $(this).hide(); $(this).removeClass("active"); } }) }) //默认选中第一个 $(".project").find(".ali-product").first().find("li").first().click(); <file_sep>$(document).ready(function() { //to-top $(".to-top-btn").click(function() { $("html,body").animate({scrollTop:0},"slow"); }) //滚动一定距离后显示to-top-btn $(window).on('scroll', function() { var $scrolltop = $(document).scrollTop(); if($scrolltop > 800) { $(".to-top-btn").show(); } else { $(".to-top-btn").hide(); } }) //.connect-btn $('.help-entry ').hover(function () { $('.connect-panel').addClass('active'); }, function () { $('.connect-panel').removeClass('active'); }) //点击叉号关闭connect-panel $(".panel-close").click(function() { $(".connect-panel").removeClass('active'); }) })<file_sep>$(document).ready(function() { $(".ali-product-show-more").click(function() { // var $more = $(".ali-product-more"); // var display = $more.css("display"); // if(display == "none") { // $(".ali-product-show-more").text("收起"); // }else { // $(".ali-product-show-more").text("查看全部"); // } // $(".ali-product-more").slideToggle(); // $(selector).animate({params},speed,callback); var $more = $(".ali-product-more"); var display = $more.css("display"); if(display == "none") { $more.animate({height:"toggle"}, 1000, function(){ $(".ali-product-show-more").text("收起"); }); } else { $more.animate({height:"toggle"}, 1000, function(){ $(".ali-product-show-more").text("查看全部"); }); } // $("div.ali-product-more:visible").animate({ // height: "toggle" // }, 1000, function() { // $(".ali-product-show-more").text("收起"); // }); // { // $(".ali-product-show-more").text("收起"); // } else { // $more.slideUp(); // $(".ali-product-show-more").text("查看全部"); // } // var $more = $(".ali-product-more"); // var display = $more.css("display"); // if(display == "none") { // $more.slideDown(); // $(".ali-product-show-more").text("收起"); // } else { // $more.slideUp(); // $(".ali-product-show-more").text("查看全部"); // } }) })
3a26aadbca5c6457cee5066532da92a3d1a45f08
[ "JavaScript" ]
6
JavaScript
Alohayao/Alohayao.github.io
c126f1eeaca82bbd35cf4de086740d18d84283f1
282b7e355152c497197b9e27744cbbc87f846b37
refs/heads/master
<repo_name>lingxiaoyi/webpackpro<file_sep>/src/pages/download-app/html.js const content = require('./content.ejs') const layout = require('layout') const config = require('configModule') const pageTitle = '东方体育手机版_NBA直播|CBA直播|足球直播|英超直播吧|CCTV5在线直播' const pageKeywords = '体育赛事,体育赛程,赛程预告,赛程表' const pageDescription = '东方体育赛程频道提供最新的篮球赛程表,足球赛程表,帮助球迷及时了解最新的体育赛事,不错过每一次精彩的体育赛事。' const hasLogo = false module.exports = layout.init({ pageTitle, pageKeywords, pageDescription, hasLogo }).run(content(config)) <file_sep>/src/pages/schedule/html.js const content = require('./content.ejs') const layout = require('layout') const config = require('configModule') const pageTitle = '东方体育手机版app下载' const pageKeywords = '东方体育手机版app,体育赛事,体育赛程,赛程预告,赛程表' const pageDescription = '东方体育手机版app,东方体育赛程频道提供最新的篮球赛程表,足球赛程表,帮助球迷及时了解最新的体育赛事,不错过每一次精彩的体育赛事。' module.exports = layout.init({ pageTitle, pageKeywords, pageDescription }).run(content(config)) <file_sep>/src/public-resource/logic/log.news.js import config from 'configModule' const _util_ = require('../libs/libs.util') let {RZAPI} = config.API_URL $(() => { let $body = $('body') let $J_hot_news = $('#J_hot_news') let qid = _util_.getPageQid()//访客uid let uid = _util_.getUid()//访客uid let OSType = _util_.getOsType()//操作系统 let browserType = _util_.browserType()//浏览器 let refer = _util_.getReferrer()//浏览器 let pixel = window.screen.width + '*' + window.screen.height//客户端分辨率 let pgtype = _util_.getpgtype()//(pgtype=1文字直播;pagetype=0表示新闻,其他为2) let locationUrl = 'http://' + window.location.host + window.location.pathname//当前url let fromUrl = document.referrer//来源url let toUrl = ''//转向的url let {idx = 'null', ishot = 'null', recommendtype = 'null'} = _util_.getSuffixParam(_util_.CookieUtil.get('logdata')) let intervaltime = 10 //间隔多久上传一次数据(当前为10s) class Log { constructor() { this.init() } init() { this.loadActiveApi() this.loadOnlineApi() this.loadClickApi() } loadActiveApi() { /* global _yiji_:true _erji_:true _newstype_:true*/ let data = { qid: qid, uid: uid, from: fromUrl, to: locationUrl, type: _yiji_, subtype: _erji_, idx: idx, remark: 'null', os: OSType, browser: browserType, softtype: 'null', softname: 'null', newstype: _newstype_, ver: 'null', pixel: pixel, refer: refer, appqid: 'null', ttloginid: 'null', apptypeid: 'null', appver: 'null', pgnum: 1, //没有做分页 pgtype: pgtype, ime: 'null', ishot: ishot, recommendtype: recommendtype } _util_.makeJsonp(RZAPI.active, data) } loadOnlineApi() { let data = { url: locationUrl, qid: qid, uid: uid, apptypeid: 'null', loginid: 'null', type: _yiji_, subtype: _erji_, intervaltime: intervaltime, ver: 'null', os: OSType, appqid: 'null', ttloginid: 'null', pgtype: pgtype, ime: 'null', newstype: _newstype_ } //10秒定时去请求传online数据 setInterval(function() { _util_.makeJsonp(RZAPI.online, data) }, intervaltime * 1000) } loadClickApi() { $J_hot_news.on('click', '.hn-list a', function() { toUrl = $(this).attr('href') let {idx = 'null', ishot = 'null', recommendtype = 'null'} = _util_.getSuffixParam($(this).attr('suffix')) idx = $(this).index() let data = { qid: qid, uid: uid, from: locationUrl, to: toUrl, type: _yiji_, subtype: _erji_, idx: idx, remark: 'null', os: OSType, browser: browserType, softtype: 'null', softname: 'null', newstype: _newstype_, ver: 'null', pixel: pixel, refer: refer, appqid: 'null', ttloginid: 'null', apptypeid: 'null', appver: 'null', pgnum: 1, //没有做分页 ime: 'null', ishot: ishot, recommendtype: recommendtype } _util_.makeJsonp(RZAPI.onclick, data) }) $body.on('click', 'a[clickbackurl]', reportLog) function reportLog() { let clickbackurl = $(this).attr('clickbackurl') $body.append('<img src="' + clickbackurl + '" />') } } } new Log() }) <file_sep>/src/public-resource/logic/report.page.js import 'pages/liveing/style.scss' import 'pages/report/style.scss' import './log.js' import FastClick from 'fastclick' import WebStorageCache from 'web-storage-cache' import config from 'configModule' import wx from 'weixin-js-sdk' import '../libs/lib.prototype' const _util_ = require('../libs/libs.util') const _AD_ = require('../libs/ad.channel') let {HOST, HOST_DSP_DETAIL} = config.API_URL $(() => { try { typeof FastClick === 'undefined' || FastClick.attach(document.body) } catch (e) { console.error(e) } let os = _util_.getOsType() let recgid = _util_.getUid() let qid = _util_.getPageQid() qid = _AD_.detailList[qid] ? qid : 'null' //查看广告渠道里有没有这个id没有就是null let domain = 'dfsports_h5' let pixel = window.screen.width + '*' + window.screen.height let locationUrl = 'http://' + window.location.host + window.location.pathname//当前url let wsCache = new WebStorageCache() let $loading = $('<div id="J_loading" class="loading"><div class="spinner"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div><p class="txt">数据加载中</p></div>') let $article = $('.detail') let $secNewsList = $('#zhiboRecommend') let $body = $('body') let $headScore = $('#headScore') let pullUpFinished = false let typecode /* global _articleTagCodes_:true */ typecode = _articleTagCodes_.split(',') function Detail(channel, tpyecode) { this.host = HOST this.channel = channel this.index = 4 //热点新闻中的广告起始下标 this.startkey = '' this.typecode = tpyecode.join('|') this.idx = 1 //热点新闻中的位置下标 this.pgnum = 1 } Detail.prototype = { init: function() { let scope = this scope.showHotNews() scope.setHistoryUrl() scope.queryMatchState() $(window).on('scroll', function() { let scrollTop = $(this).scrollTop() let bodyHeight = $('body').height() - 50 let clientHeight = $(this).height() if (scrollTop + clientHeight >= bodyHeight && pullUpFinished) { pullUpFinished = false scope.getData(scope.startkey) } }) //注册展开 this.unfoldArticle() }, queryMatchState: function() { /* global _matchId_:true */ let data = { matchid: _matchId_ } let that = this _util_.makeJsonp(HOST + 'matchinfo', data).done(function(result) { result = result.data that.headSore(result, that)//填充头部数据 }) }, headSore: function(result, that) { let $zhiboMenu = $('#zhiboMenu') let redirect = _util_.getUrlParam('redirect') let html = '' // 判断参数 有data就切换到数据栏目 let tab = _util_.getUrlParam('tab') /* global _page_type:true */ if (!tab) { html += `<a href="${_page_type === 'zhibo' ? 'javascript:;' : (result.liveurl + '?tab=zhibo')}" class="${_page_type === 'zhibo' ? 'active' : ''}" suffix="btype=live_details&subtype=live&idx=0"><span>图文直播</span></a>` } else { html += `<a href="${_page_type === 'zhibo' ? 'javascript:;' : (result.liveurl + '?tab=zhibo')}" class="${tab === 'zhibo' ? 'active' : ''}" suffix="btype=live_details&subtype=live&idx=0"><span>图文直播</span></a>` } html += `<a href="${_page_type === 'zhibo' ? 'javascript:;' : (result.liveurl + '?tab=saikuang')}" class="${_page_type === 'zhibo' && tab === 'saikuang' ? 'active' : ''}" suffix="btype=live_details&subtype=data&idx=0"><span>赛况</span></a>` html += `<a href="${_page_type === 'zhibo' ? 'javascript:;' : (result.liveurl + '?tab=shuju')}" class="${_page_type === 'zhibo' && tab === 'shuju' ? 'active' : ''}" suffix="btype=live_details&subtype=data&idx=0"><span>数据</span></a>` if (!redirect) { html += `${result.zhanbao_url ? `<a href="${_page_type === 'zhanbao' ? 'javascript:;' : result.zhanbao_url}" suffix="btype=live_details&subtype=zhanbao&idx=0" class="${_page_type === 'zhanbao' ? 'active' : ''}"><span>战报</span></a>` : ``}` } $zhiboMenu.html(html) if (redirect === 'dftth5') { that.loadMatchNews(result.saishi_id, result.home_team + ',' + result.visit_team) } let $zhibo_body = $('.zhibo_body') let $zhiboDataContent = $zhibo_body.children('.zhibo-data-content') if (tab === 'shuju') { $zhiboDataContent.hide() $zhiboDataContent.eq(2).show() } else if (tab === 'saikuang') { $zhiboDataContent.hide() $zhiboDataContent.eq(1).show() } // 比分 let $homeScore = $headScore.find('.home-score') let $visitScore = $headScore.find('.visit-score') let $headScoreP = $headScore.children('p') $homeScore.text(result.home_score / 1 ? result.home_score : 0) $visitScore.text(result.visit_score / 1 ? result.visit_score : 0) if (result.ismatched === '-1') { $headScoreP.text(result.starttime.substr(5)) } else if (result.ismatched === '0') { $headScoreP.text('直播中') } else { $headScoreP.text('完赛') } $headScore.children('.title').text(result.title.split(' ')[1]) // 对阵双方 let $homeLeft = $headScore.prev() let $homeRight = $headScore.next() $homeLeft.find('.sub1').text(result.home_team) $homeLeft.find('.sub2 img').attr('src', result.home_logoname ? result.home_logoname : `${config.DIRS.BUILD_FILE.images['logo_default']}`) $homeRight.find('.sub1').text(result.visit_team) $homeRight.find('.sub2 img').attr('src', result.visit_logoname ? result.visit_logoname : `${config.DIRS.BUILD_FILE.images['logo_default']}`) // 下方对阵双方图标 $('.home-team-logo').attr('src', result.home_logoname).next().text(result.home_team) $('.visit-team-logo').attr('src', result.visit_logoname).next().text(result.visit_team) }, setHistoryUrl: function() { let url = window.location.href let urlNum = url.substring(url.lastIndexOf('/') + 1, url.indexOf('.html')) let historyUrlArr = [] if (wsCache.get('historyUrlArr') && wsCache.get('historyUrlArr').length) { historyUrlArr = wsCache.get('historyUrlArr') } if (historyUrlArr.length >= 5) { historyUrlArr.shift() } historyUrlArr.push(urlNum) wsCache.set('historyUrlArr', historyUrlArr, {exp: 10 * 60}) }, showHotNews: function() { let scope = this $article.after('<section class="gg-item news-gg-img3"><div id="' + _detailsGg_[1] + '""></div></section>') _util_.getScript('//tt123.eastday.com/' + _detailsGg_[1] + '.js', function() {}, $('#' + _detailsGg_[1])[0]) scope.getData(0) //文章下方加展开全文 if ($article.height() >= 1100) { $article.after('<div class="unfold-field" id="unfoldField"><div class="unflod-field__mask"></div><a href="javascript:void(0)" class="unfold-field__text">展开全文</a></div>') } //热点推荐部分; $secNewsList.before('<h3 class="name"><span>为你推荐</span></h3>') $secNewsList.append($loading) }, getData: function(start) { let scope = this let data = { typecode: this.typecode, startkey: this.startkey, pgnum: this.pgnum, url: locationUrl, os: os, recgid: recgid, qid: qid, domain: domain } _util_.makeJsonp(scope.host + 'detailnews', data).done(function(result) { if (result.endkey === '') { $('#noMore').remove() $('#J_hn_list').append('<section id="noMore" class="clearfix">无更多数据了</section>') return } //如果startkey没变化就结束 scope.startkey = result.endkey $secNewsList.append(scope.productHtml(result, start)) pullUpFinished = true scope.pgnum++ }).done(function() { scope.requestDspUrl(3, 1).done(function(data) { let dspData = scope.changeDspDataToObj(data) for (let i = 2; i >= 0; i--) { if (data.data.length && dspData[i]) { $(`#ggModule${scope.index - 4 - 3 + i}`).html(scope.loadDspHtml(dspData, i, '')) } else { let ggid = $(`#ggModule${scope.index - 4 - 3 + i}`).children().attr('id') _util_.getScript('//tt123.eastday.com/' + ggid + '.js', function() { }, $('#' + ggid)[0]) } } scope.reportDspInviewbackurl() }) }) }, productHtml: function(result) { let data = result.data let html = '' let scope = this data.forEach(function(item, i) { let ggid = _detailsGg_[scope.index] let length = item.miniimg.length if (length < 3 && length >= 1) { html += `<li class="clearfix"> <a href="${item.url}" suffix="btype=live_details&subtype=zhanbao_recNews&idx=${scope.idx}"> <div class="img"> <img src="${item.miniimg[0].src}" alt="${item.miniimg[0].alt}"/> </div> <div class="right"> <p class="tit">${item.topic}</p> </div> </a> </li>` } else if (length >= 3) { html += `<li class="clearfix"> <a href="${item.url}" suffix="btype=live_details&subtype=zhanbao_recNews&idx=${scope.idx}"> <div class="tit">${item.topic}</div> <div class="imgs"> <img src="${item.miniimg[0].src}" alt=""> <img src="${item.miniimg[1].src}" alt=""> <img src="${item.miniimg[2].src}" alt=""> </div> <div class="source clearfix"> <div class="l">${item.source}</div> </div> </a> </li>` } // 广告位置 if (i === 1 || i === 3 || i === 6) { html += `<li style="padding:0;" id="ggModule${scope.index - 4}" class="clearfix" ><div id="${ggid}"></div></li>` scope.index++ } scope.idx++ }) return html }, requestDspUrl: function(adnum, pgnum) { let readUrl = wsCache.get('historyUrlArr') || 'null' if (readUrl !== 'null') { readUrl = readUrl.join(',') } /* global _sportsType_:true */ let data = { type: _sportsType_, qid: qid, uid: recgid, // 用户ID os: os, readhistory: readUrl, adnum: adnum, pgnum: this.pgnum, adtype: 236, dspver: '1.0.1', softtype: 'news', softname: 'eastday_wapnews', newstype: 'ad', browser_type: _util_.browserType || 'null', pixel: pixel, fr_url: _util_.getReferrer() || 'null', // 首页是来源url(document.referer) site: 'sport' } return _util_.makeGet(HOST_DSP_DETAIL, data) }, changeDspDataToObj: function(data) { let obj = {} data.data.forEach(function(item, i) { obj[item.idx - 1] = item }) return obj }, loadDspHtml: function(dspData, posi, type) { let html = '' let item = dspData[posi] switch (item.adStyle) { case 'big': html += `<a href="${item.url}" suffix="btype=news_details&subtype=hotnews&idx=0" clickbackurl="${item.clickbackurl}" inviewbackurl="${item.inviewbackurl}" data-dsp="hasDsp" style="display:block;height:5.14rem;"> <div class="title">${item.topic}</div> <div class="big-img"> <img class="lazy" src="${item.miniimg[0].src}"/> </div> <div class="source clearfix"> <div class="tag">${item.isadv ? '广告' : '推广'}</div> <div class="souce">${item.source}</div> </div> </a>` break case 'one': html += `<a href="${item.url}" suffix="btype=news_details&subtype=hotnews&idx=0" clickbackurl="${item.clickbackurl}" inviewbackurl="${item.inviewbackurl}" data-dsp="hasDsp"> <div class="img"> <img class="lazy" src="${item.miniimg[0].src}"/> </div> <div class="info"> <div class="title">${item.topic}</div> <div class="source clearfix"> <div class="tag">${item.isadv ? '广告' : '推广'}</div> <div class="l">${item.source}</div> </div> </div> </a>` break case 'group': html += `<a href="${item.url}" suffix="btype=news_details&subtype=hotnews&idx=0" clickbackurl="${item.clickbackurl}" inviewbackurl="${item.inviewbackurl}" data-dsp="hasDsp" > <div class="title">${item.topic}</div> <div class="imgs"> <img class="lazy" src="${item.miniimg[0].src}"> <img class="lazy" src="${item.miniimg[1].src}"> <img class="lazy" src="${item.miniimg[2].src}"> </div> <div class="source clearfix"> <div class="tag">${item.isadv ? '广告' : '推广'}</div> <div class="souce">${item.source}</div> </div> </a>` break case 'full': html += `<a href="${item.url}" suffix="btype=news_details&subtype=hotnews&idx=0" clickbackurl="${item.clickbackurl}" inviewbackurl="${item.inviewbackurl}" data-dsp="hasDsp" style="display:block;height:2.9rem;"> <div class="big-img"> <img class="lazy" src="${item.miniimg[0].src}"/> </div> <div class="source clearfix"> <div class="tag">${item.isadv ? '广告' : '推广'}</div> <div class="l">${item.source}</div> </div> </a>` break } $body.append(`<img style="display: none" src="${item.showbackurl}"/>`) return html }, reportDspInviewbackurl: function() { let cHeight = $(window).height() let offsetArr = [] let eleArr = [] $('a[inviewbackurl]').each(function(i, item) { if (cHeight > $(this).offset().top) { $body.append(`<img style="display: none" src="${$(this).attr('inviewbackurl')}"/>`) $(this).removeAttr('inviewbackurl') } }) $('a[inviewbackurl]').each(function(i, item) { offsetArr.push($(this).offset().top) eleArr.push($(this)) }) $(window).scroll(function() { offsetArr.forEach((item, index) => { if (cHeight + $(this).scrollTop() > item) { if (eleArr[index].attr('inviewbackurl')) { $body.append(`<img style="display: none" src="${eleArr[index].attr('inviewbackurl')}"/>`) eleArr[index].removeAttr('inviewbackurl') } } }) }) }, //展开文章 unfoldArticle() { $body.on('click', '.unfold-field', function() { $article.css({'max-height': '100%'}) $(this).hide() }) } } let en = new Detail(qid, typecode) let _detailsGg_ = _AD_.detailList[qid].concat(_AD_.detailNoChannel) en.init() //头条种隐藏录像集锦 ;(() => { if (_util_.getUrlParam('redirect') === 'app') { $('.crumbs').hide() $('#goTop').children('.back').hide() $headScore.next().next().attr('href', `downloadapp.html?qid=dfttapp`) } })() ;(function shareWebPage() { $.ajax({ type: 'get', url: 'http://xwzc.eastday.com/wx_share/share_check.php', data: { url: window.location.href }, dataType: 'jsonp', jsonp: 'wxkeycallback', //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback) jsonpCallback: 'wxkeycallback', success: function(result) { wx.config({ debug: false, //这里是开启测试,如果设置为true,则打开每个步骤,都会有提示,是否成功或者失败 appId: result.appId, timestamp: result.timestamp, //这个一定要与上面的php代码里的一样。 nonceStr: result.nonceStr, //这个一定要与上面的php代码里的一样。 signature: result.signature, //签名 jsApiList: [ // 所有要调用的 API 都要加到这个列表中 'onMenuShareTimeline', 'onMenuShareAppMessage' ] }) wx.ready(function() { // 分享给朋友 let imgSrc = $('#content img').eq(0).attr('src') if (imgSrc.indexOf('http') === -1) { imgSrc = 'http:' + imgSrc } wx.onMenuShareAppMessage({ title: $('h1.title').text() + '_东方体育', // 分享标题 desc: $('#content p.txt').text(), // 分享描述 link: window.location.href, // 分享链接 imgUrl: imgSrc, // 分享图标 success: function() {}, cancel: function() {} }) wx.onMenuShareTimeline({ title: $('h1.title').text() + '_东方体育', // 分享标题 link: window.location.href, // 分享链接 imgUrl: imgSrc, // 分享图标 success: function() { }, cancel: function() { } }) }) }, error: function() { } }) })() }) <file_sep>/src/public-resource/config/common.config.js const buildFileConfig = require('configDir/build-file.config') const moduleExports = { DIRS: { BUILD_FILE: buildFileConfig }, PAGE_ROOT_PATH: '../../' } /* 帮助确定ie下CORS的代理文件 */ moduleExports.DIRS.SERVER_API_URL = moduleExports.SERVER_API_URL /* global isOnlinepro:true isTestpro:true*/ // 由于ESLint会检测没有定义的变量,因此需要这一个`global`注释声明IS_PRODUCTION是一个全局变量(当然在本例中并不是)来规避warning if (isOnlinepro) { //首页地址 moduleExports.HOME_URL = 'http://msports.eastday.com/' } else if (isTestpro) { moduleExports.HOME_URL = 'http://gxjifen.dftoutiao.com/gx-ued-jser/wangzhijun/msports.resources/msports.east.webpack/build/html/' } else { moduleExports.HOME_URL = '/' } if (isOnlinepro) { // 本项目所用的所有接口 moduleExports.API_URL = { HOST: 'http://dfsports_h5.dftoutiao.com/dfsports_h5/', HOST_LIVE: 'http://dfsportslive.dftoutiao.com/dfsports/', HOST_DSP_LIST: 'http://dftyttd.dftoutiao.com/partner/list', HOST_DSP_DETAIL: 'http://dftyttd.dftoutiao.com/partner/detail', HOME_LUNBO_API: 'http://msports.eastday.com/json/msponts/home_lunbo.json', ORDER_API: 'http://dfty.dftoutiao.com/index.php/Home/WechatOrder/yuyue?system_id=9&machid=', VIDEO_LOG: 'http://dfsportsapplog.dftoutiao.com/dfsportsapplog/videoact', RZAPI: { active: 'http://dfsportsdatapc.dftoutiao.com/dfsportsdatah5/active', onclick: 'http://dfsportsdatapc.dftoutiao.com/dfsportsdatah5/onclick', online: 'http://dfsportsdatapc.dftoutiao.com/dfsportsdatah5/online' } } } else { moduleExports.API_URL = { HOST: 'http://172.18.250.87:8381/dfsports_h5/', HOST_LIVE: 'http://172.18.250.87:8381/dfsports/', HOST_DSP_LIST: 'http://192.168.3.11/partner/list', HOST_DSP_DETAIL: 'http://106.75.98.65/partner/detail', HOME_LUNBO_API: 'http://msports.eastday.com/json/msponts/home_lunbo.json', ORDER_API: 'http://dfty.dftoutiao.com/index.php/Home/WechatOrder/yuyue?system_id=9&machid=', VIDEO_LOG: 'http://172.18.250.87:8380/dfsportsapplog/videoact', RZAPI: { active: 'http://172.18.250.87:8380/dfsportsdatah5/active', onclick: 'http://172.18.250.87:8380/dfsportsdatah5/onclick', online: 'http://172.18.250.87:8380/dfsportsdatah5/online' } } } module.exports = moduleExports <file_sep>/src/public-resource/logic/log.js import config from 'configModule' const _util_ = require('../libs/libs.util') let {RZAPI} = config.API_URL $(() => { let $body = $('body') let soft_type = 'dongfangtiyu' let soft_name = 'DFTYH5' let u_id = _util_.getPageQid()//访客uid let qid = _util_.getUid()//访客uid let OSType = _util_.getOsType()//操作系统 let browserType = _util_.browserType()//浏览器 let _vbb = 'null'//版本号 let remark = 'null'//备注信息 let idx = 'null'//新闻链接位置 let btype = 'null'//大类 let subtype = 'null'//子类 let newstype = 'null'//新闻类别 let pageNo = 'null'//页数 let appqid = 'null'//App渠道号url上追加的appqid let ttloginid = 'null'//App端分享新闻时url上追加的ttloginid let apptypeid = 'null'//App端的软件类别url上追加的apptypeid let appver = 'null'// App版本(010209)url上追加的appver let ttaccid = 'null'//App端分享新闻时url上追加的ttaccid let from = _util_.getReferrer()//浏览器 let pixel = window.screen.width + '*' + window.screen.height//客户端分辨率 let pgtype = _util_.getpgtype()//(pgtype=1文字直播;pagetype=0表示新闻,其他为2) let locationUrl = 'http://' + window.location.host + window.location.pathname//当前url let to = ''//转向的url let intervaltime = 10 //间隔多久上传一次数据(当前为10s) class Log { constructor() { this.init() } init() { this.loadActiveApi() this.loadOnlineApi() this.loadClickApi() } loadActiveApi() { let param = '?qid=' + qid + '&uid=' + u_id + '&from=' + from + '&to=' + locationUrl + '&type=' + btype + '&subtype=' + subtype + '&idx=' + idx + '&remark=' + remark + '&os=' + OSType + '&browser=' + browserType + '&softtype=' + soft_type + '&softname=' + soft_name + '&newstype=' + newstype + '&pixel=' + pixel + '&ver=' + _vbb + '&appqid=' + appqid + '&ttloginid=' + ttloginid + '&apptypeid=' + apptypeid + '&appver=' + appver + '&pgnum=' + pageNo + '&pgtype=' + pgtype let data = {url: param} _util_.makeJsonp(RZAPI.active, data) } loadOnlineApi() { let param = '?qid=' + qid + '&uid=' + u_id + '&url=' + locationUrl + '&apptypeid=' + apptypeid + '&loginid=' + ttaccid + '&loginid=' + ttaccid + '&type=' + btype + '&subtype=' + subtype + '&intervaltime=' + intervaltime + '&ver=' + _vbb + '&os=' + OSType + '&appqid=' + appqid + '&ttloginid=' + ttloginid + '&pgtype=' + pgtype let data = { url: param } //10秒定时去请求传online数据 setInterval(function() { _util_.makeJsonp(RZAPI.online, data) }, intervaltime * 1000) } loadClickApi() { $body.on('click', 'a[suffix]', function() { to = $(this).attr('href') idx = $(this).index() _util_.CookieUtil.set('logdata', $(this).attr('suffix')) let param = '?qid=' + qid + '&uid=' + u_id + '&from=' + from + '&to=' + to + '&type=' + btype + '&subtype=' + subtype + '&idx=' + idx + '&remark=' + remark + '&os=' + OSType + '&browser=' + browserType + '&softtype=' + soft_type + '&softname=' + soft_name + '&newstype=' + newstype + '&pixel=' + pixel + '&ver=' + _vbb + '&appqid=' + appqid + '&ttloginid=' + ttloginid + '&apptypeid=' + apptypeid + '&appver=' + appver + '&pgnum=' + pageNo let data = { url: param } _util_.makeJsonp(RZAPI.onclick, data) }) $body.on('click', 'a[clickbackurl]', reportLog) function reportLog() { let clickbackurl = $(this).attr('clickbackurl') $body.append('<img src="' + clickbackurl + '" />') } } } new Log() }) <file_sep>/src/pages/detail-baijiahao/page.js import '../../public-resource/logic/detail.baijiahao.page.js' <file_sep>/src/public-resource/logic/download.app.page.js import 'pages/schedule/style.scss' import './log.js' import FastClick from 'fastclick' $(() => { try { typeof FastClick === 'undefined' || FastClick.attach(document.body) } catch (e) { console.error(e) } let u = navigator.userAgent /*let app = navigator.appVersion*/ let ua = navigator.userAgent.toLowerCase() let $J_download = $('#J_download') /*function makeJsonp(url, data) { return $.ajax({ type: 'GET', data: data, url: url, dataType: 'json' }) }*/ /* makeJsonp('/data/log_app/log_h5.js',{}).done(function (result) {})*/ //let download_url=result[0].download_url if (ua.match(/MicroMessenger/i) === 'micromessenger') { //微信下 $J_download.attr('href', 'http://a.app.qq.com/o/simple.jsp?pkgname=com.songheng.starsports') window.location.href = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.songheng.starsports' } else { if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { //苹果 $J_download.attr('href', 'https://itunes.apple.com/cn/app/id1271975517?mt=8') window.location.href = 'https://itunes.apple.com/cn/app/id1271975517?mt=8' } else { //安卓 $J_download.attr('href', 'http://m.wa5.com/data/apk/wuxing_android.apk') window.location.href = 'http://m.wa5.com/data/apk/wuxing_android.apk' } } })
2492c5d81730eb39f9a918270c7af322d58b3f12
[ "JavaScript" ]
8
JavaScript
lingxiaoyi/webpackpro
51a1843654409261b708ba203483a18ba902133d
ddab25bda6e128ab150fd6fc8d7e3c9d161721ff
refs/heads/master
<repo_name>vinay-yadav/College-Management-System<file_sep>/main_site/views.py from django.shortcuts import render, HttpResponse,get_object_or_404 from .models import Authenticate def home(request): template_name = 'site/index.html' return render(request, template_name) def login(request): template_name = 'login/login.html' if request.method == 'POST': roll_no = request.POST.get('roll_no') password = request.POST.get('password') try: query = Authenticate.objects.get(roll=roll_no) print(query) if query: if query.password == password: return HttpResponse('<h1>Login Successfull</h1>') else: context = {'match': 'your password is incorrect'} return render(request, template_name, context) except Exception as e: print(e, 'hi') context = {'not_member': "Roll no. didn't found"} return render(request, template_name, context) return render(request, template_name) def sign_up(request): template_name = 'signup/signup.html' if request.method == 'POST': roll_no = request.POST.get('roll_no') email = request.POST.get('email') password = request.POST.get('<PASSWORD>') conf_password = request.POST.get('confirm_password') if password == conf_password: Authenticate.objects.create(roll=roll_no, email=email, password=password) return HttpResponse('<h1>Sign-up successfull</h1>') else: return HttpResponse('<h1>password didn;t match<h1>') return render(request, template_name)<file_sep>/main_site/migrations/0005_remove_authenticate_user.py # Generated by Django 2.2.4 on 2019-08-24 20:18 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main_site', '0004_remove_authenticate_username'), ] operations = [ migrations.RemoveField( model_name='authenticate', name='user', ), ] <file_sep>/main_site/migrations/0004_remove_authenticate_username.py # Generated by Django 2.2.4 on 2019-08-24 18:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main_site', '0003_authenticate'), ] operations = [ migrations.RemoveField( model_name='authenticate', name='username', ), ] <file_sep>/main_site/urls.py from django.urls import path, include from .views import * urlpatterns = [ path('', home), path('login/', login), path('sign_up/', sign_up), ] <file_sep>/main_site/models.py from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Authenticate(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) roll = models.CharField(primary_key=True, max_length=10) # username = models.CharField(unique=True, null=False, blank=False, max_length=50) email = models.CharField(null=False, unique=True, blank=False, max_length=50) password = models.CharField(null=False, blank=False, max_length=220) created = models.DateTimeField(auto_now_add=True, editable=True) class Meta: ordering = ['-created'] <file_sep>/main_site/tests.py from django.test import TestCase # Create your tests here. def signup(request): if request.method == "POST": roll = request.POST.get("Roll") mail = request.POST.get("Email") passw = request.POST.get("password") c_passw = request.POST.get("Confirm_password") try: if passw == c_passw: data = Student_login(roll_no=roll, password=<PASSWORD>, email=mail) data.save() # messages.success(request, ("Succesfully Registered")) return render(request, 'signup/signup.html') else: # messages.success(request,("Password not match")) return render(request, 'signup/signup.html') except Exception as e: print(e) return render(request, 'signup/signup.html') def login(request): if request.method == "POST": roll = request.POST.get("Roll_no") passw = request.POST.get("<PASSWORD>") # print(roll) # print(passw) user = Student_login.objects.filter(roll_no=roll).first() # taking data from database # print(user) try: if user: if user.password == <PASSWORD>: request.session['user'] = roll print("Login success") return HttpResponse("Login Successful") else: print("Pass didn't match") return HttpResponse("Password didn't match") except Exception as e: print(e) return render(request, 'login/login.html') <file_sep>/main_site/migrations/0006_auto_20190824_2054.py # Generated by Django 2.2.4 on 2019-08-24 20:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main_site', '0005_remove_authenticate_user'), ] operations = [ migrations.RenameField( model_name='authenticate', old_name='roll_no', new_name='roll', ), ]
83ed7c834d2136a5b31c3b140f795333234d87d1
[ "Python" ]
7
Python
vinay-yadav/College-Management-System
3a1c334305a8108988c223abe2ff166c9f975b71
f97714c65c8d18ae8164206e7e5967e576591b4d
refs/heads/master
<repo_name>Raselkhan1234/ema-john-with-server<file_sep>/index.js const express = require('express') const bodyParser = require('body-parser') const cors=require('cors') require('dotenv').config() const MongoClient = require('mongodb').MongoClient; const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@<EMAIL>/emaJhonStore?retryWrites=true&w=majority`; const app = express() app.use(bodyParser.json()); app.use(cors()); const port = 5000 app.get('/', (req, res) => { res.send('Hello from db it is working!') }) const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); client.connect(err => { const productCollection = client.db("emaJhonStore").collection("products"); const ordersCollection = client.db("emaJhonStore").collection("products"); app.post('/addOrder',(req, res) => { const order=req.body; ordersCollection.insertOne(order) .then(result => { res.send(result.insertedCount>0); }) }) app.post('/addProduct', (req, res) => { const product=req.body; productCollection.insertOne(product) }) app.get('/products', (req, res)=>{ productCollection.find({}) .toArray((err,documents)=>{ res.send(documents) }) }) app.get('/products/:key', (req, res)=>{ productCollection.find({key:req.params.key}) .toArray((err,documents)=>{ res.send(documents[0]) }) }) app.post('/productByKeys',(req, res)=>{ const productKeys=req.body; productCollection.find({key:{$in:productKeys}}) .toArray((err,documents)=>{ res.send(documents) }) }) console.log('database connected') }); app.listen(process.env.PORT||port);
ec43a4cac99d57ca7dc84183e2ae284d9e79acc9
[ "JavaScript" ]
1
JavaScript
Raselkhan1234/ema-john-with-server
552a540c214120a15cd11a00650c94131df4c9e2
5ae6661090e213411ba0bb9ef46133a7f29185a5
refs/heads/main
<repo_name>choiinsung276/PyQtStudy<file_sep>/SignalSlot/createEventHandler.py import sys from PyQt5.QtWidgets import (QApplication, QWidget, QLCDNumber, QDial, QVBoxLayout, QPushButton, QHBoxLayout) class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): lcd = QLCDNumber(self) dial = QDial(self) btn1 = QPushButton('Big', self) btn2 = QPushButton('Small', self) hbox = QHBoxLayout() hbox.addWidget(btn1) hbox.addWidget(btn2) vbox = QVBoxLayout() vbox.addWidget(lcd) vbox.addWidget(dial) vbox.addLayout(hbox) self.setLayout(vbox) dial.valueChanged.connect(lcd.display) btn1.clicked.connect(self.resizeBig) btn2.clicked.connect(self.resizeSmall) self.setWindowTitle('시그널과슬롯예제') self.setGeometry(300,300,200,200) self.show() def resizeBig(self): self.resize(400,500) def resizeSmall(self): self.resize(200,250) if __name__=='__main__': app=QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_())<file_sep>/widget/QCheckBox.py import sys from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox ,QLabel, QVBoxLayout from PyQt5.QtCore import Qt class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): cb = QCheckBox('박스입니다.',self) cb.move(20,20) cb.toggle() cb.stateChanged.connect(self.changeTitle) self.setWindowTitle('안녕하세요') self.setGeometry(300,300,300,200) self.show() def changeTitle(self,state): if state ==Qt.Checked: self.setWindowTitle('체크박스켰네요.') label1 = QLabel('First Label', self) label1.setAlignment(Qt.AlignCenter) label2 = QLabel('Second Label', self) label2.setAlignment(Qt.AlignVCenter) font1 = label1.font() font1.setPointSize(20) font2 = label2.font() font2.setFamily('Times New Roman') font2.setBold(True) label1.setFont(font1) label2.setFont(font2) layout=QVBoxLayout() layout.addWidget(label1) layout.addWidget(label2) self.setLayout(layout) else: self.setWindowTitle(' ') if __name__=='__main__': app=QApplication(sys.argv) ex=MyApp() sys.exit(app.exec_())<file_sep>/Dialog/QInputDialog.py import sys from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLineEdit, QInputDialog) class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.btn = QPushButton('Dalog', self) self.btn.move(30, 30) self.btn.clicked.connect(self.showDialog) self.le = QLineEdit(self) self.le.move(120, 35) self.setWindowTitle("인풋 다이얼로그 예제") self.setGeometry(300,300,300,200) self.show() def showDialog(self): text, ok = QInputDialog.getText(self, '인풋 다이얼로그', 'Enter your name: ') if ok: self.le.setText(str(text)) #str로 해줘야함 if __name__=='__main__': app=QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_())<file_sep>/widget/absolute.py import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): label1 = QLabel('Label1',self) label1.move(20,20) label2=QLabel('Label2',self) label2.move(20,60) btn1 = QPushButton('Button1',self) btn1.move(100,13) btn2= QPushButton('Button2',self) btn2.move(80,53) self.setWindowTitle('Absolute Positioning') self.setGeometry(300,300,400,200) self.show() if __name__=='__main__': app=QApplication(sys.argv) ex=MyApp() sys.exit(app.exec_()) <file_sep>/widget/Style.py import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): lblred=QLabel('Red') lblgreen=QLabel('Green') lblblue=QLabel('Blue') lblred.setStyleSheet("color:red;" "border-style:solid;" "border-width: 2px;" "border-color: #FA8072;" "border-radius:3px") lblgreen.setStyleSheet("color:green;" "background-color:#7FFFD4") lblblue.setStyleSheet("color:blue;" "background-color: #87CEFA;" "border-style:dashed;" "border-width: 3px;" "border-color: #1E90FF") vbox = QVBoxLayout() vbox.addWidget(lblred) vbox.addWidget(lblgreen) vbox.addWidget(lblblue) self.setLayout(vbox) self.setWindowTitle('Stylesheet') self.setGeometry(300,300,300,200) self.show() if __name__=='__main__': app=QApplication(sys.argv) ex=MyApp() sys.exit(app.exec_())<file_sep>/README.md # PyQtStudy ## reference - https://wikidocs.net/book/2165 - https://wikidocs.net/35486 - https://opentutorials.org/module/544/18844 <file_sep>/widget/datetime.py from PyQt5.QtCore import QDate , Qt, QTime, QDateTime import sys from PyQt5.QtWidgets import QApplication, QMainWindow now = QDate.currentDate() print(now.toString()) print(now.toString('d.M.yy')) print(now.toString('dd.MM.yyyy')) print(now.toString(Qt.ISODate)) print(now.toString(Qt.DefaultLocaleLongDate)) print("=============================") time = QTime.currentTime() print(time.toString()) print(time.toString('h.m.s')) print(time.toString('hh.mm.ss')) print(time.toString(Qt.DefaultLocaleLongDate)) print(time.toString(Qt.DefaultLocaleShortDate)) print("---------------") dt = QDateTime.currentDateTime() print(dt.toString('d.M.yy hh:mm:ss')) print(dt.toString('dd.MM.yyyy, hh:mm:ss')) print(dt.toString(Qt.DefaultLocaleLongDate)) print(dt.toString(Qt.DefaultLocaleShortDate)) class MyApp(QMainWindow): def __init__(self): super().__init__() self.date=QDate.currentDate() self.initUI() def initUI(self): self.statusBar().showMessage(self.date.toString(Qt.DefaultLocaleLongDate)) self.setWindowTitle('Date') self.setGeometry(300,300,400,200) self.show() if __name__=='__main__': app=QApplication(sys.argv) ex=MyApp() sys.exit(app.exec_())<file_sep>/widget/BoxLayout.py import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): okButton = QPushButton('OK') cancelButton = QPushButton('Cancel') okButton1 = QPushButton('OK1') okButton2 = QPushButton('OK2') okButton3 = QPushButton('OK3') okButton4 = QPushButton('OK4') okButton5 = QPushButton('OK5') okButton6 = QPushButton('OK6') okButton7 = QPushButton('OK7') hbox2 = QHBoxLayout() hbox2.addStretch(4) hbox2.addWidget(okButton1) hbox2.addWidget(okButton2) hbox2.addWidget(okButton3) hbox2.addWidget(okButton4) hbox2.addWidget(okButton5) hbox2.addStretch(1) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(okButton) hbox.addWidget(cancelButton) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addStretch(3) vbox.addLayout(hbox) vbox.addStretch(3) vbox.addWidget(okButton6) vbox.addWidget(okButton7) vbox.addLayout(hbox2) vbox.addStretch(1) self.setLayout(vbox) self.setWindowTitle('Box Layout') self.setGeometry(300,100,1500,900) self.show() if __name__=='__main__': app=QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_())
842516657cd90b613d892a60611c3c0b2959a8a9
[ "Markdown", "Python" ]
8
Python
choiinsung276/PyQtStudy
daea1634aa0482729c0eeb05ebbd365efe32ac99
3b0588a5fe24f58cf5e3a46fa4d5e6e0ae7a807b
refs/heads/master
<repo_name>LawrenceLoh/EPDA<file_sep>/src/model/Admin.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.List; import javax.swing.JOptionPane; /** * * @author Acer */ public class Admin { public static boolean Login(int y){ if(y==12345){ return true; } return false; } public static Student createStudent(){ String a = JOptionPane.showInputDialog("Enter student name"); char b = JOptionPane.showInputDialog("Enter student gender").charAt(0); int c = Integer.parseInt(JOptionPane.showInputDialog("Enter student pin")); double d = Double.parseDouble(JOptionPane.showInputDialog("Enter student balance")); return new Student (a,b,c,d); } public static void deleteStudent(List x){ String a = JOptionPane.showInputDialog("Enter student name:"); boolean flag =false; for (int i = 0; i<x.size();i++){ if (a.equals(((Student)(x.get(i))).getName())){ x.remove(i); flag =true; break; } } if(flag){ JOptionPane.showMessageDialog(null,"Done!"); }else{ JOptionPane.showMessageDialog(null,"Wrong Student name!"); } } public static void printReport(List x){ int male = 0; for(int i = 0;i <x.size();i++){ if ('M' == (((Student)(x.get(i))).getGender())){ male++; } } int female= x.size() -male; JOptionPane.showMessageDialog(null,"There are"+male+" male students and "+female+"female studemts."); } } <file_sep>/src/model/Account.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.io.Serializable; /** * * @author Acer */ public class Account implements Serializable { private double balance; public Account (double x){ balance = x; } public void deposit (double x){ balance = balance + x; } public void withdraw (double x){ balance =balance -x; } public double getBalance(){ return balance; } } <file_sep>/src/week01/Week01.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package week01; import data.Database; import javax.swing.JOptionPane; import java.util.logging.Logger; import model.Admin; import model.Student; /** * * @author Acer */ public class Week01 { /** * @param args the command line arguments */ private static final Logger log = Logger.getLogger(Week01.class.getName()); private static Student Loginedstudent; public static void main(String[] args) { // TODO code application logic here Database.readData(); menu(); } public static void menu() { int choice = JOptionPane.showOptionDialog(null, "Select your role?", "Role Selection?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{"Student", "Admin"}, "default"); log.info(String.valueOf(choice)); if (choice == 0 || choice == 1) { boolean selection = (choice == JOptionPane.YES_OPTION); //Student if (selection) { log.info("the student is chosen"); login("Student"); } else { //Admin log.info("the admin is chosen"); login("Admin"); } } } public static void login(String role) { switch (role) { case "Student": studentLogin(); break; case "Admin": adminLogin(); break; } } public static void adminLogin() { boolean loginSuccess = false; while (!loginSuccess) { String password = JOptionPane.showInputDialog(null, "input password"); log.info(password); loginSuccess = Admin.Login(Integer.parseInt(password)); if (loginSuccess) { showAdminMenu(); } } } public static void studentLogin() { Database.readData(); String name = JOptionPane.showInputDialog("Enter your name:"); for (Student student : Database.getData()) { if (student.getName().equals(name)) { Loginedstudent = student; } } if (Loginedstudent == null) { JOptionPane.showMessageDialog(null, "No such student"); studentLogin(); } boolean loginSuccess = false; while (!loginSuccess) { loginSuccess = Loginedstudent.Login(); if (loginSuccess) { showStudentMenu(); } else { JOptionPane.showMessageDialog(null, "Invalid password"); } } } public static void showStudentMenu() { int choice = JOptionPane.showOptionDialog(null, "Student Menu", "Menu", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[]{"Deposit", "Withdraw", "Print", "Logout"}, "default"); log.info(String.valueOf(choice)); switch (choice) { case 0: Loginedstudent.deposit(); Database.writeData(); showStudentMenu(); break; case 1: Loginedstudent.withdraw(); Database.writeData(); showStudentMenu(); break; case 2: Loginedstudent.printing(); showStudentMenu(); break; case 3: menu(); break; } } public static void showAdminMenu() { int choice = JOptionPane.showOptionDialog(null, "Admin Menu", "Menu", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[]{"Create Student", "Delete Student", "Print Report", "Logout"}, "default"); log.info(String.valueOf(choice)); switch (choice) { case 0: Database.readData(); Database.getData().add(Admin.createStudent()); Database.writeData(); showAdminMenu(); break; case 1: Database.readData(); Admin.deleteStudent(Database.getData()); Database.writeData(); showAdminMenu(); break; case 2: Database.readData(); Admin.printReport(Database.getData()); showAdminMenu(); break; case 3: menu(); break; } } }
2288d5de81bcd8352acd17a0e75f53ebe42e8595
[ "Java" ]
3
Java
LawrenceLoh/EPDA
9e76490a9d9722c6df87aa58701b5212ab527e06
b5e2f9559e4b894b182ed3943ec43b754da5d9d6
refs/heads/master
<file_sep>return { Properties = { ["Name"] = "<NAME>"; ["ImageId"] = "rbxassetid://3106190691"; }, Settings = { ["Background Color"] = Color3.new(1, 0.690196, 1); ["Built-in Function Color"] = Color3.new(0, 0.501961, 0.752941); ["Comment Color"] = Color3.new(0, 0.501961, 0); ["Error Color"] = Color3.new(1, 0, 0); ["Find Selection Background Color"] = Color3.new(0.607843, 0.898039, 0.607843); ["Keyword Color"] = Color3.new(0, 0, 1); ["Matching Word Background Color"] = Color3.new(1, 0.501961, 0.752941); ["Number Color"] = Color3.new(1, 0.501961, 0); ["Operator Color"] = Color3.new(0, 0, 0.501961); ["Preprocessor Color"] = Color3.new(0.501961, 0.25098, 0); ["Selection Background Color"] = Color3.new(0.431373, 0.631373, 0.945098); ["Selection Color"] = Color3.new(1, 0.835294, 1); ["String Color"] = Color3.new(0.584314, 0, 0.290196); ["Text Color"] = Color3.new(0, 0, 0); ["Warning Color"] = Color3.new(0, 0, 1); } }<file_sep>return { Properties = { ["Name"] = "Mellow"; ["ImageId"] = "rbxassetid://5013045506"; }, Settings = { ["Background Color"] = Color3.new(0.180392, 0.180392, 0.180392); ["Built-in Function Color"] = Color3.new(0.682353, 0.619608, 0.580392); ["Comment Color"] = Color3.new(0.27451, 0.486275, 0.239216); ["Error Color"] = Color3.new(0.490196, 0, 0); ["Find Selection Background Color"] = Color3.new(0.843137, 0.764706, 0.627451); ["Keyword Color"] = Color3.new(0.580392, 0.654902, 0.682353); ["Matching Word Background Color"] = Color3.new(0.843137, 0.764706, 0.627451); ["Number Color"] = Color3.new(0.815686, 0.827451, 0.713726); ["Operator Color"] = Color3.new(0.490196, 0.47451, 0.690196); ["Preprocessor Color"] = Color3.new(1, 1, 1); ["Selection Background Color"] = Color3.new(0.686275, 0.686275, 0.686275); ["Selection Color"] = Color3.new(0.882353, 0.882353, 0.882353); ["String Color"] = Color3.new(0.333333, 0.666667, 0.498039); ["Text Color"] = Color3.new(0.811765, 0.811765, 0.835294); ["Warning Color"] = Color3.new(0.490196, 0, 0); } }<file_sep>return { Properties = { ["Name"] = "<NAME>"; ["ImageId"] = "rbxassetid://3055225459"; }, Settings = { ["Background Color"] = Color3.fromRGB(35, 35, 35); ["Built-in Function Color"] = Color3.fromRGB(132, 214, 247); ["Comment Color"] = Color3.fromRGB(170, 255, 127); ["Error Color"] = Color3.fromRGB(255, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(255, 245, 80); ["Keyword Color"] = Color3.fromRGB(255, 85, 127); ["Matching Word Background Color"] = Color3.fromRGB(85, 85, 85); ["Number Color"] = Color3.fromRGB(170, 85, 255); ["Operator Color"] = Color3.fromRGB(255, 170, 0); ["Preprocessor Color"] = Color3.fromRGB(102, 255, 204); ["Selection Background Color"] = Color3.fromRGB(50, 50, 50); ["Selection Color"] = Color3.fromRGB(153, 153, 153); ["String Color"] = Color3.fromRGB(170, 255, 127); ["Text Color"] = Color3.fromRGB(255, 255, 255); ["Warning Color"] = Color3.fromRGB(255, 115, 21); } }<file_sep>return { Properties = { ["Name"] = "<NAME>"; ["ImageId"] = "rbxassetid://4932980095"; }, Settings = { ["Background Color"] = Color3.new(0.12549, 0.152941, 0.188235); ["Built-in Function Color"] = Color3.new(0, 0.67451, 0.756863); ["Comment Color"] = Color3.new(0.282353, 0.282353, 0.282353); ["Error Color"] = Color3.new(0.898039, 0.223529, 0.207843); ["Find Selection Background Color"] = Color3.new(0.247059, 0.247059, 0.247059); ["Keyword Color"] = Color3.new(0, 0.67451, 0.756863); ["Matching Word Background Color"] = Color3.new(0.247059, 0.247059, 0.247059); ["Number Color"] = Color3.new(0.431373, 0.870588, 0.647059); ["Operator Color"] = Color3.new(0.8, 0.8, 0.8); ["Preprocessor Color"] = Color3.new(0.431373, 0.870588, 0.647059); ["Selection Background Color"] = Color3.new(0.247059, 0.247059, 0.247059); ["Selection Color"] = Color3.new(1, 1, 1); ["String Color"] = Color3.new(0.431373, 0.870588, 0.647059); ["Text Color"] = Color3.new(0.72549, 0.72549, 0.72549); ["Warning Color"] = Color3.new(0.901961, 0.317647, 0); } }<file_sep># Script Editor Themes Roblox plugin that changes the theme of your script editor. <hr> Please note: this code is by no means optimized as well as it could be and I do not enourage use of these scripts verbatim. However, it does get the job done. <br> <br> I appriciate any imporvements and will definitely merge any pull requests that better the code. <file_sep>return { Properties = { ["Name"] = "Visual Studio Code"; ["ImageId"] = "rbxassetid://2919695305"; }, Settings = { ["Background Color"] = Color3.fromRGB(30, 30, 30); ["Built-in Function Color"] = Color3.fromRGB(220, 220, 170); ["Comment Color"] = Color3.fromRGB(56, 96, 55); ["Error Color"] = Color3.fromRGB(125, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(215, 195, 160); ["Keyword Color"] = Color3.fromRGB(162, 102, 144); ["Matching Word Background Color"] = Color3.fromRGB(215, 195, 160); ["Number Color"] = Color3.fromRGB(165, 90, 175); ["Operator Color"] = Color3.fromRGB(181, 192, 119); ["Preprocessor Color"] = Color3.fromRGB(255, 255, 255); ["Selection Background Color"] = Color3.fromRGB(175, 175, 175); ["Selection Color"] = Color3.fromRGB(225, 225, 225); ["String Color"] = Color3.fromRGB(206, 145, 120); ["Text Color"] = Color3.fromRGB(212, 212, 212); ["Warning Color"] = Color3.fromRGB(125, 0, 0); } }<file_sep>return { Properties = { ["Name"] = "Toasty"; ["ImageId"] = "rbxassetid://3045996470"; }, Settings = { ["Background Color"] = Color3.fromRGB(40, 40, 40); ["Built-in Function Color"] = Color3.fromRGB(221, 184, 99); ["Comment Color"] = Color3.fromRGB(119, 83, 104); ["Error Color"] = Color3.fromRGB(255, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(255, 245, 80); ["Keyword Color"] = Color3.fromRGB(200, 92, 66); ["Matching Word Background Color"] = Color3.fromRGB(85, 85, 85); ["Number Color"] = Color3.fromRGB(247, 207, 73); ["Operator Color"] = Color3.fromRGB(232, 92, 19); ["Preprocessor Color"] = Color3.fromRGB(102, 255, 104); ["Selection Background Color"] = Color3.fromRGB(84, 30, 30); ["Selection Color"] = Color3.fromRGB(203, 117, 117); ["String Color"] = Color3.fromRGB(201, 127, 40); ["Text Color"] = Color3.fromRGB(210, 167, 167); ["Warning Color"] = Color3.fromRGB(228, 146, 146); } }<file_sep>return { Properties = { ["Name"] = "Spacemacs"; ["ImageId"] = "rbxassetid://2919668248"; }, Settings = { ["Background Color"] = Color3.fromRGB(40, 45, 45); ["Built-in Function Color"] = Color3.fromRGB(190, 110, 195); ["Comment Color"] = Color3.fromRGB(90, 95, 95); ["Error Color"] = Color3.fromRGB(125, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(215, 195, 160); ["Keyword Color"] = Color3.fromRGB(70, 135, 165); ["Matching Word Background Color"] = Color3.fromRGB(215, 195, 160); ["Number Color"] = Color3.fromRGB(165, 90, 175); ["Operator Color"] = Color3.fromRGB(115, 145, 195); ["Preprocessor Color"] = Color3.fromRGB(255, 255, 255); ["Selection Background Color"] = Color3.fromRGB(175, 175, 175); ["Selection Color"] = Color3.fromRGB(225, 225, 225); ["String Color"] = Color3.fromRGB(45, 150, 115); ["Text Color"] = Color3.fromRGB(185, 185, 185); ["Warning Color"] = Color3.fromRGB(125, 0, 0); } }<file_sep>return { Properties = { ["Name"] = "CMD"; ["ImageId"] = "rbxassetid://3055248272"; }, Settings = { ["Background Color"] = Color3.fromRGB(0,0,0); ["Built-in Function Color"] = Color3.fromRGB(0, 170, 255); ["Comment Color"] = Color3.fromRGB(0, 255, 0); ["Error Color"] = Color3.fromRGB(255, 0, 127); ["Find Selection Background Color"] = Color3.fromRGB(255, 255, 255); ["Keyword Color"] = Color3.fromRGB(44, 153, 255); ["Matching Word Background Color"] = Color3.fromRGB(0, 255, 0); ["Number Color"] = Color3.fromRGB(255, 255, 255); ["Operator Color"] = Color3.fromRGB(0, 170, 255); ["Preprocessor Color"] = Color3.fromRGB(0, 170, 0); ["Selection Background Color"] = Color3.fromRGB(175, 175, 175); ["Selection Color"] = Color3.fromRGB(255, 255, 255); ["String Color"] = Color3.fromRGB(0, 170, 0); ["Text Color"] = Color3.fromRGB(43, 255, 6); ["Warning Color"] = Color3.fromRGB(255, 85, 0); } }<file_sep>return { Properties = { ["Name"] = "Reef"; ["ImageId"] = "rbxassetid://3045993740"; }, Settings = { ["Background Color"] = Color3.fromRGB(35, 40, 39); ["Built-in Function Color"] = Color3.fromRGB(134, 164, 189); ["Comment Color"] = Color3.fromRGB(95, 126, 179); ["Error Color"] = Color3.fromRGB(233, 206, 8); ["Find Selection Background Color"] = Color3.fromRGB(57, 81, 122); ["Keyword Color"] = Color3.fromRGB(164, 218, 62); ["Matching Word Background Color"] = Color3.fromRGB(85, 85, 85); ["Number Color"] = Color3.fromRGB(10, 218, 210); ["Operator Color"] = Color3.fromRGB(134, 157, 197); ["Preprocessor Color"] = Color3.fromRGB(170, 255, 127); ["Selection Background Color"] = Color3.fromRGB(57, 81, 122); ["Selection Color"] = Color3.fromRGB(129, 154, 195); ["String Color"] = Color3.fromRGB(10, 218, 210); ["Text Color"] = Color3.fromRGB(179, 195, 219); ["Warning Color"] = Color3.fromRGB(10, 218, 217); } }<file_sep>-- If you're uploading this yourself -- -- Change the name of the "Name" property to the name of your theme. -- Take a screenshot of the script editor, about 150x80. Does not have to be perfect. <- the current image is "original light," so it will default to that if you do not provide a screenshot. -- Rename this ModuleScript to "MainModule" and upload to Roblox. Be sure to allow copying. <- this step is important. -- Reply to https://devforum.roblox.com/t/script-editor-themes-plugin/262870 with the ID and the *exact name* of the module. -- If you want me to upload -- -- Reply to https://devforum.roblox.com/t/script-editor-themes-plugin/262870 with the code contained in this module. -- Preferably in a spoiler. return { Properties = { ["Name"] = "Gruvbox Dark Soft"; ["ImageId"] = "rbxassetid://2919688393"; }, Settings = { ["Background Color"] = Color3.new(0.156863, 0.156863, 0.156863); ["Built-in Function Color"] = Color3.new(0.556863, 0.752941, 0.486275); ["Comment Color"] = Color3.new(0.572549, 0.513726, 0.454902); ["Error Color"] = Color3.new(1, 0, 0); ["Find Selection Background Color"] = Color3.new(0.192157, 0.172549, 0.152941); ["Keyword Color"] = Color3.new(0.984314, 0.286275, 0.203922); ["Matching Word Background Color"] = Color3.new(0.192157, 0.172549, 0.152941); ["Number Color"] = Color3.new(0.827451, 0.52549, 0.607843); ["Operator Color"] = Color3.new(0.921569, 0.858824, 0.698039); ["Preprocessor Color"] = Color3.new(0.921569, 0.858824, 0.698039); ["Selection Background Color"] = Color3.new(0.192157, 0.172549, 0.152941); ["Selection Color"] = Color3.new(0.666667, 0.6, 0.529412); ["String Color"] = Color3.new(0.721569, 0.733333, 0.14902); ["Text Color"] = Color3.new(0.921569, 0.858824, 0.698039); ["Warning Color"] = Color3.new(1, 0.45098, 0.0823529); } }<file_sep>return [[ -- If you're uploading this yourself -- -- Replace UserID with your UserId so you get credit for your theme. -- Rename this ModuleScript to "MainModule" and upload to Roblox. Be sure to allow copying. <- this step is important. -- Reply to https://devforum.roblox.com/t/script-editor-themes-plugin/262870 with the ID of the module. -- If you want me to upload -- -- Reply to https://devforum.roblox.com/t/script-editor-themes-plugin/262870 with the code contained in this module. -- Preferably in a spoiler. local Players = game:GetService("Players") local UserID = 1 local function GetUserInfo(ID) local URL, Ready = Players:GetUserThumbnailAsync(ID, Enum.ThumbnailType.AvatarBust, Enum.ThumbnailSize.Size100x100); local Username = Players:GetNameFromUserIdAsync(ID) if Ready and Username then return {AvatarThumbnailURL = URL, Username = Username} end end return GetUserInfo(UserID)]]<file_sep>return { Properties = { ["Name"] = "<NAME>"; ["ImageId"] = "rbxassetid://5013022225"; }, Settings = { ["Background Color"] = Color3.fromRGB(41, 41, 41); ["Built-in Function Color"] = Color3.fromRGB(128, 113, 93); ["Comment Color"] = Color3.fromRGB(75, 75, 75); ["Error Color"] = Color3.fromRGB(255, 0, 4); ["Find Selection Background Color"] = Color3.fromRGB(33, 125, 52); ["Keyword Color"] = Color3.fromRGB(33, 125, 52); ["Matching Word Background Color"] = Color3.fromRGB(22, 125, 52); ["Number Color"] = Color3.fromRGB(190, 165, 26); ["Operator Color"] = Color3.fromRGB(110, 108, 95); ["Preprocessor Color"] = Color3.fromRGB(33, 125, 52); ["Selection Background Color"] = Color3.fromRGB(200, 200, 200); ["Selection Color"] = Color3.fromRGB(100, 100, 100); ["String Color"] = Color3.fromRGB(190, 165, 26); ["Text Color"] = Color3.fromRGB(188, 187, 185); ["Warning Color"] = Color3.fromRGB(255, 255, 0); } }<file_sep>local Players = game:GetService("Players") local UserID = 117127881; local function GetUserInfo(ID) local URL, Ready = Players:GetUserThumbnailAsync(ID, Enum.ThumbnailType.AvatarBust, Enum.ThumbnailSize.Size100x100); local Username = Players:GetNameFromUserIdAsync(ID) if Ready and Username then return {URL, Username} elseif not Ready and Username then return {"rbxassetid://8167273", Username} elseif Ready and not Username then return {Ready, "UNKNOWN (error)"} elseif not Ready and not Username then return {"rbxassetid://8167273", "UNKNOWN (error)"} end end return GetUserInfo(UserID)<file_sep>return { Properties = { ["Name"] = "Breeze"; ["ImageId"] = "rbxassetid://3109174602"; }, Settings = { ["Background Color"] = Color3.fromRGB(30, 30, 30); ["Built-in Function Color"] = Color3.fromRGB(163, 47, 230); ["Comment Color"] = Color3.fromRGB(56, 96, 55); ["Error Color"] = Color3.fromRGB(125, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(215, 195, 160); ["Keyword Color"] = Color3.fromRGB(160, 178, 255); ["Matching Word Background Color"] = Color3.fromRGB(215, 195, 160); ["Number Color"] = Color3.fromRGB(82, 147, 227); ["Operator Color"] = Color3.fromRGB(134, 134, 200); ["Preprocessor Color"] = Color3.fromRGB(255, 255, 255); ["Selection Background Color"] = Color3.fromRGB(175, 175, 175); ["Selection Color"] = Color3.fromRGB(225, 225, 225); ["String Color"] = Color3.fromRGB(85, 170, 127); ["Text Color"] = Color3.fromRGB(212, 212, 212); ["Warning Color"] = Color3.fromRGB(125, 0, 0); } }<file_sep>return { Properties = { ["Name"] = "Atom"; ["ImageId"] = "rbxassetid://5013004766"; }, Settings = { ["Background Color"] = Color3.fromRGB(40, 44, 52); ["Built-in Function Color"] = Color3.fromRGB(224, 108, 117); ["Comment Color"] = Color3.fromRGB(92, 99, 112); ["Error Color"] = Color3.fromRGB(209, 59, 46); ["Find Selection Background Color"] = Color3.fromRGB(89, 89, 89); ["Keyword Color"] = Color3.fromRGB(198, 120, 221); ["Matching Word Background Color"] = Color3.fromRGB(115, 115, 115); ["Number Color"] = Color3.fromRGB(198, 146, 97); ["Operator Color"] = Color3.fromRGB(171, 178, 191); ["Preprocessor Color"] = Color3.fromRGB(255, 255, 255); ["Selection Background Color"] = Color3.fromRGB(74, 105, 171); ["Selection Color"] = Color3.fromRGB(146, 146, 178); ["String Color"] = Color3.fromRGB(116, 195, 121); ["Text Color"] = Color3.fromRGB(171, 178, 191); ["Warning Color"] = Color3.fromRGB(255, 125, 32); } }<file_sep>return { Properties = { ["Name"] = "<NAME>"; ["ImageId"] = "rbxassetid://5012847878"; }, Settings = { ["Background Color"] = Color3.fromRGB(255, 255, 255); ["Built-in Function Color"] = Color3.fromRGB(0, 0, 127); ["Comment Color"] = Color3.fromRGB(0, 88, 132); ["Error Color"] = Color3.fromRGB(0, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(255, 255, 255); ["Keyword Color"] = Color3.fromRGB(44, 153, 255); ["Matching Word Background Color"] = Color3.fromRGB(0, 255, 0); ["Number Color"] = Color3.fromRGB(255, 255, 255); ["Operator Color"] = Color3.fromRGB(0, 44, 67); ["Preprocessor Color"] = Color3.fromRGB(0, 131, 197); ["Selection Background Color"] = Color3.fromRGB(0, 255, 255); ["Selection Color"] = Color3.fromRGB(0, 49, 74); ["String Color"] = Color3.fromRGB(0, 133, 200); ["Text Color"] = Color3.fromRGB(0, 169, 253); ["Warning Color"] = Color3.fromRGB(0, 85, 255); } }<file_sep>return { Properties = { ["Name"] = "Forest"; ["ImageId"] = "rbxassetid://5132074114"; }, Settings = { ["Background Color"] = Color3.fromRGB(0, 20, 30); ["Built-in Function Color"] = Color3.fromRGB(0, 70, 255); ["Comment Color"] = Color3.fromRGB(0, 170, 127); ["Error Color"] = Color3.fromRGB(255, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(0, 0, 127); ["Keyword Color"] = Color3.fromRGB(85, 0, 255); ["Matching Word Background Color"] = Color3.fromRGB(0, 20, 30); ["Number Color"] = Color3.fromRGB(170, 255, 255); ["Operator Color"] = Color3.fromRGB(255, 255, 0); ["Preprocessor Color"] = Color3.fromRGB(102, 255, 204); ["Selection Background Color"] = Color3.fromRGB(0, 0, 0); ["Selection Color"] = Color3.fromRGB(85, 85, 255); ["String Color"] = Color3.fromRGB(0, 168, 81); ["Text Color"] = Color3.fromRGB(182, 182, 182); ["Warning Color"] = Color3.fromRGB(255, 115, 21); } }<file_sep>return { Properties = { ["Name"] = "Dolphin"; ["ImageId"] = "rbxassetid://3498873582"; }, Settings = { ["Background Color"] = Color3.fromRGB(221, 221, 225); ["Built-in Function Color"] = Color3.fromRGB(0, 127, 25); ["Comment Color"] = Color3.fromRGB(189, 142, 0); ["Error Color"] = Color3.fromRGB(255, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(246, 185, 63); ["Keyword Color"] = Color3.fromRGB(127, 0, 125); ["Matching Word Background Color"] = Color3.fromRGB(226, 230, 214); ["Number Color"] = Color3.fromRGB(4, 26, 127); ["Operator Color"] = Color3.fromRGB(127, 127, 0); ["Preprocessor Color"] = Color3.fromRGB(110, 127, 0); ["Selection Background Color"] = Color3.fromRGB(246, 185, 63); ["Selection Color"] = Color3.fromRGB(225, 225, 225); ["String Color"] = Color3.fromRGB(214, 0, 3); ["Text Color"] = Color3.fromRGB(65, 70, 89); ["Warning Color"] = Color3.fromRGB(125, 0, 0); } }<file_sep>return { Properties = { ["Name"] = "Jungle"; ["ImageId"] = "rbxassetid://3045989200"; }, Settings = { ["Background Color"] = Color3.fromRGB(40, 39, 32); ["Built-in Function Color"] = Color3.fromRGB(170, 170, 255); ["Comment Color"] = Color3.fromRGB(170, 255, 127); ["Error Color"] = Color3.fromRGB(189, 189, 189); ["Find Selection Background Color"] = Color3.fromRGB(170, 255, 127); ["Keyword Color"] = Color3.fromRGB(170, 170, 255); ["Matching Word Background Color"] = Color3.fromRGB(85, 85, 85); ["Number Color"] = Color3.fromRGB(170, 170, 255); ["Operator Color"] = Color3.fromRGB(170, 255, 127); ["Preprocessor Color"] = Color3.fromRGB(170, 255, 127); ["Selection Background Color"] = Color3.fromRGB(255, 255, 255); ["Selection Color"] = Color3.fromRGB(203, 117, 117); ["String Color"] = Color3.fromRGB(170, 255, 127); ["Text Color"] = Color3.fromRGB(255, 255, 255); ["Warning Color"] = Color3.fromRGB(170, 255, 127); } }<file_sep>return { Properties = { ["Name"] = "Alva"; ["ImageId"] = "rbxassetid://3059176841"; }, Settings = { ["Background Color"] = Color3.fromRGB(37, 37, 37); ["Built-in Function Color"] = Color3.fromRGB(0, 170, 255); ["Comment Color"] = Color3.fromRGB(102, 102, 102); ["Error Color"] = Color3.fromRGB(255, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(255, 245, 80); ["Keyword Color"] = Color3.fromRGB(0, 170, 255); ["Matching Word Background Color"] = Color3.fromRGB(85, 85, 85); ["Number Color"] = Color3.fromRGB(0, 170, 255); ["Operator Color"] = Color3.fromRGB(255, 255, 255); ["Preprocessor Color"] = Color3.fromRGB(102, 255, 204); ["Selection Background Color"] = Color3.fromRGB(50, 50, 50); ["Selection Color"] = Color3.fromRGB(153, 153, 153); ["String Color"] = Color3.fromRGB(173, 241, 149); ["Text Color"] = Color3.fromRGB(255, 255, 255); ["Warning Color"] = Color3.fromRGB(255, 115, 21); } }<file_sep>return { Properties = { ["Name"] = "1337"; ["ImageId"] = "rbxassetid://3109160941"; }, Settings = { ["Background Color"] = Color3.new(0.0509804, 0.00784314, 0.0313726); ["Built-in Function Color"] = Color3.new(0, 1, 0.254902); ["Comment Color"] = Color3.new(0, 0.356863, 0); ["Error Color"] = Color3.new(0.654902, 1, 0); ["Find Selection Background Color"] = Color3.new(0.690196, 1, 0.690196); ["Keyword Color"] = Color3.new(0, 0.560784, 0.0666667); ["Matching Word Background Color"] = Color3.new(0.843137, 1, 0.627451); ["Number Color"] = Color3.new(0, 0.984314, 0); ["Operator Color"] = Color3.new(0.941177, 1, 0.823529); ["Preprocessor Color"] = Color3.new(1, 1, 1); ["Selection Background Color"] = Color3.new(0.176471, 0.27451, 0.176471); ["Selection Color"] = Color3.new(0, 1, 0); ["String Color"] = Color3.new(0, 0.560784, 0.0666667); ["Text Color"] = Color3.new(0.72549, 0.72549, 0.72549); ["Warning Color"] = Color3.new(0, 0.498039, 0); } }<file_sep>return { Properties = { ["Name"] = "Mesopelagic"; ["ImageId"] = "rbxassetid://5013011414"; }, Settings = { ["Background Color"] = Color3.fromRGB(0, 73, 104); ["Built-in Function Color"] = Color3.fromRGB(74, 255, 101); ["Comment Color"] = Color3.fromRGB(111, 111, 255); ["Error Color"] = Color3.fromRGB(244, 55, 7); ["Find Selection Background Color"] = Color3.fromRGB(21, 214, 0); ["Keyword Color"] = Color3.fromRGB(200, 0, 255); ["Matching Word Background Color"] = Color3.fromRGB(115, 130, 131); ["Number Color"] = Color3.fromRGB(0, 255, 140); ["Operator Color"] = Color3.fromRGB(127, 0, 191); ["Preprocessor Color"] = Color3.fromRGB(236, 236, 236); ["Selection Background Color"] = Color3.fromRGB(85, 166, 73); ["Selection Color"] = Color3.fromRGB(29, 0, 255); ["String Color"] = Color3.fromRGB(201, 161, 229); ["Text Color"] = Color3.fromRGB(0, 170, 243); ["Warning Color"] = Color3.fromRGB(44, 54, 56); } }<file_sep>return { Properties = { ["Name"] = "Easy On the Eyes"; ["ImageId"] = "rbxassetid://5012872546"; }, Settings = { ["Background Color"] = Color3.fromRGB(47, 47, 47); ["Built-in Function Color"] = Color3.fromRGB(30, 120, 255); ["Comment Color"] = Color3.fromRGB(147, 147, 147); ["Error Color"] = Color3.fromRGB(147, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(94, 124, 127); ["Keyword Color"] = Color3.fromRGB(68, 126, 180); ["Matching Word Background Color"] = Color3.fromRGB(121, 121, 121); ["Number Color"] = Color3.fromRGB(59, 199, 0); ["Operator Color"] = Color3.fromRGB(88, 160, 180); ["Preprocessor Color"] = Color3.fromRGB(217, 217, 217); ["Selection Background Color"] = Color3.fromRGB(95, 95, 95); ["Selection Color"] = Color3.fromRGB(34, 19, 19); ["String Color"] = Color3.fromRGB(203, 203, 203); ["Text Color"] = Color3.fromRGB(230, 230, 230); ["Warning Color"] = Color3.fromRGB(191, 154, 59); } }<file_sep>return { Properties = { ["Name"] = "<NAME>"; ["ImageId"] = "rbxassetid://3059179181"; }, Settings = { ["Background Color"] = Color3.fromRGB(37, 37, 37); ["Built-in Function Color"] = Color3.fromRGB(81, 134, 247); ["Comment Color"] = Color3.fromRGB(113, 255, 37); ["Error Color"] = Color3.fromRGB(255, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(255, 245, 80); ["Keyword Color"] = Color3.fromRGB(98, 158, 255); ["Matching Word Background Color"] = Color3.fromRGB(85, 85, 85); ["Number Color"] = Color3.fromRGB(135, 253, 255); ["Operator Color"] = Color3.fromRGB(204, 204, 204); ["Preprocessor Color"] = Color3.fromRGB(102, 255, 204); ["Selection Background Color"] = Color3.fromRGB(50, 50, 50); ["Selection Color"] = Color3.fromRGB(153, 153, 153); ["String Color"] = Color3.fromRGB(222, 74, 241); ["Text Color"] = Color3.fromRGB(204, 204, 204); ["Warning Color"] = Color3.fromRGB(255, 115, 21); } }<file_sep>local Toolbar = plugin:CreateToolbar("Script Editor Themes") local ToolbarButton = Toolbar:CreateButton("View Themes", "View themes to select", "rbxassetid://3037837976") local Mouse = plugin:GetMouse() local GUI = script.ScriptEditorThemesUI for _,gui in next, game.CoreGui:GetChildren() do if gui.Name == "ScriptEditorThemesUI" then gui:Destroy() end end --if game.CoreGui:FindFirstChild("ScriptEditorThemesUI") then game.CoreGui:FindFirstChild("ScriptEditorThemesUI"):Destroy() end GUI.Parent = game.CoreGui ToolbarButton.Click:Connect(function() GUI.Enabled = not GUI.Enabled end) local function ChangeTheme(Name, SettingsTable) if not type(SettingsTable) == "table" then warn'Theme module does not contain a table.' else for setting, color in next, SettingsTable do if settings().Studio[setting] then settings().Studio[setting] = color end end print('Successfully changed theme to '..Name..'!') end end local function GetStudioTheme() local Settings = { "Color3.new("..(tostring(settings().Studio["Background Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Built-in Function Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Comment Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Error Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Find Selection Background Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Keyword Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Matching Word Background Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Number Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Operator Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Preprocessor Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Selection Background Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Selection Color"]))..")"; "Color3.new("..(tostring(settings().Studio["String Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Text Color"]))..")"; "Color3.new("..(tostring(settings().Studio["Warning Color"]))..")"; } return Settings end local function doRipple(button, buttonPos) if button:IsA("GuiButton") then local ripple = GUI.Back.Utilities.Ripple:Clone() ripple.ImageColor3 = Color3.new(button.BackgroundColor3.r*.25, button.BackgroundColor3.g*.25, button.BackgroundColor3.b*.25) ripple.Visible = true ripple.Position = buttonPos ripple.Parent = button ripple:TweenSize(UDim2.new(0, 250, 0, 250), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, .55, true) for i = 2, 10, .5 do ripple.ImageTransparency = i/10 wait() end ripple:Destroy() end end local function scaleCanvasSize(frame) local gridLayout = frame:FindFirstChild("UIGridLayout", true) if gridLayout then frame.CanvasSize = UDim2.new(0, 0, 0, math.ceil(gridLayout.AbsoluteContentSize.Y)+40) else warn('No GridLayout found in '..frame.Name) end end --[[ GUI Handler 8/21/19 11:19pm By: Misdo aka SimplyRekt --]] local GuiColors = { LightMain = Color3.fromRGB(236, 240, 241), DarkMain = Color3.fromRGB(44, 62, 80), On = Color3.fromRGB(0, 85, 0), Off = Color3.fromRGB(85, 0, 0) } local CurrentlyViewing = "Themes" local TopbarButtons = GUI.Back.TopbarButtons local Selected = TopbarButtons.Selected local DarkOn = plugin:GetSetting("Dark") local Themes = GUI.Back.Themes local Utilities = GUI.Back.Utilities local Credits = GUI.Back.Credits local Positions = { Themes = UDim2.new(.15, 0, 0, -10); Utilities = UDim2.new(.5, 0, 0, -10); Credits = UDim2.new(.85, 0, 0, -10) } if plugin:GetSetting("Dark") then GUI.Back.BackgroundColor3 = GuiColors.DarkMain for _,v in next, TopbarButtons:GetChildren() do if v:IsA("TextButton") then v.BackgroundColor3 = GuiColors.DarkMain v.TextColor3 = GuiColors.LightMain elseif v:IsA("Frame") then v.BackgroundColor3 = GuiColors.LightMain end end for _,v in next, Themes.Back.Container:GetChildren() do if v:IsA("Frame") then v.ThemeName.TextColor3 = GuiColors.LightMain end end for _,v in next, Credits.Back.Container:GetChildren() do if v:IsA("Frame") then v.CreditedName.TextColor3 = GuiColors.LightMain v.Info.TextColor3 = GuiColors.LightMain end end Themes.Back.ScrollBarImageColor3 = GuiColors.LightMain Credits.Back.ScrollBarImageColor3 = GuiColors.LightMain GUI.Back.Utilities.Back.DarkTheme.BackgroundColor3 = GuiColors.On GUI.Back.Utilities.Back.DarkTheme.Text = "Dark: On" end local ThemeScriptSource = Utilities.ThemeScriptSource local UtilityFunctions = { ["DarkTheme"] = function() DarkOn = not DarkOn plugin:SetSetting("Dark", DarkOn) if DarkOn then GUI.Back.BackgroundColor3 = GuiColors.DarkMain for _,v in next, TopbarButtons:GetChildren() do if v:IsA("TextButton") then v.BackgroundColor3 = GuiColors.DarkMain v.TextColor3 = GuiColors.LightMain elseif v:IsA("Frame") then v.BackgroundColor3 = GuiColors.LightMain end end for _,v in next, Themes.Back.Container:GetChildren() do if v:IsA("Frame") or v:IsA("ScrollingFrame") then v.ThemeName.TextColor3 = GuiColors.LightMain end end for _,v in next, Credits.Back.Container:GetChildren() do if v:IsA("Frame") or v:IsA("ScrollingFrame") then v.CreditedName.TextColor3 = GuiColors.LightMain v.Info.TextColor3 = GuiColors.LightMain end end Themes.Back.ScrollBarImageColor3 = GuiColors.LightMain Credits.Back.ScrollBarImageColor3 = GuiColors.LightMain GUI.Back.Utilities.Back.DarkTheme.BackgroundColor3 = GuiColors.On GUI.Back.Utilities.Back.DarkTheme.Text = "Dark: On" elseif not DarkOn then GUI.Back.BackgroundColor3 = GuiColors.LightMain for _,v in next, TopbarButtons:GetChildren() do if v:IsA("TextButton") then v.BackgroundColor3 = GuiColors.LightMain v.TextColor3 = GuiColors.DarkMain elseif v:IsA("Frame") then v.BackgroundColor3 = GuiColors.DarkMain end end for _,v in next, Themes.Back.Container:GetChildren() do if v:IsA("Frame") or v:IsA("ScrollingFrame") then v.ThemeName.TextColor3 = GuiColors.DarkMain end end for _,v in next, Credits.Back.Container:GetChildren() do if v:IsA("Frame") or v:IsA("ScrollingFrame") then v.CreditedName.TextColor3 = GuiColors.DarkMain v.Info.TextColor3 = GuiColors.DarkMain end end Themes.Back.ScrollBarImageColor3 = GuiColors.DarkMain Credits.Back.ScrollBarImageColor3 = GuiColors.DarkMain GUI.Back.Utilities.Back.DarkTheme.BackgroundColor3 = GuiColors.Off GUI.Back.Utilities.Back.DarkTheme.Text = "Dark: Off" end end, ["ThemeData"] = function() local ThemeScript = Instance.new("ModuleScript") local CreditScript = Instance.new("ModuleScript") local StudioTheme = GetStudioTheme() ThemeScript.Source = require(Utilities.ThemeScriptSource).getString(GetStudioTheme()) CreditScript.Source = require(Utilities.CreditScriptSource) ThemeScript.Name = "README" CreditScript.Name = "README" ThemeScript.Parent = game:GetService("ReplicatedStorage") CreditScript.Parent = game:GetService("ReplicatedStorage") print("ModuleScripts parented to 'ReplicatedStorage'. Very important, please read.") end } for i,v in next, TopbarButtons:GetChildren() do if v:IsA("TextButton") then v.MouseButton1Down:Connect(function() if GUI.Back:FindFirstChild(v.Name) then local mousePos = Vector2.new(Mouse.X, Mouse.Y) - v.AbsolutePosition GUI.Back[CurrentlyViewing].Back.Visible = false spawn(function() doRipple(v, UDim2.new(0, mousePos.X, 0, mousePos.Y)) end) Selected:TweenPosition(Positions[v.Name], "InOut", "Sine", .25, true) GUI.Back[v.Name].Back.Visible = true CurrentlyViewing = v.Name else print("Cannot find "..v.Name.." in 'Back'") end end) end end local themeModules = Themes.ThemeModules for _,t in next, themeModules:GetChildren() do if t:IsA("ModuleScript") then local Success, Info = pcall(require, t) if Success then local Info = require(t); local Frame = Themes.Back.Container["Template"]:Clone() Frame.Name = Info["Properties"].Name Frame.ThemeName.Text = Info["Properties"].Name Frame.Preview.Image = Info["Properties"].ImageId Frame.Parent = Themes.Back.Container else warn(Info) end elseif t:IsA("IntValue") then local Success, Info = pcall(require, t.Value) if Success then local Frame = Themes.Back.Container["Template"]:Clone() Frame.Name = Info["Properties"].Name Frame.ThemeName.Text = Info["Properties"].Name Frame.Preview.Image = Info["Properties"].ImageId Frame.Parent = Themes.Back.Container else warn(Info) end end end Themes.Back.Container["Template"]:Destroy() scaleCanvasSize(Themes.Back) local creditModules = Credits.CreditModules local creditsBack = Credits.Back for _,c in next, creditModules:GetChildren() do if c:IsA("ModuleScript") then --print(c.Name) local Success, Return = pcall(require, c) --print( (Success and "Got " or "Did not get ") .. c.Name) if Success then local Frame = creditsBack.Container["Template"]:Clone() Frame.Name = c.Name Frame.CreditedName.Text = Return[2] Frame.Info.Text = c.Name Frame.Avatar.Image = Return[1] Frame.Parent = creditsBack.Container else warn(Return) end elseif c:IsA("IntValue") then local Success, Return = pcall(require, c.Value) if Success then local Frame = creditsBack.Container["Template"]:Clone() Frame.Name = c.Name Frame.CreditedName.Text = Return[2] Frame.Info.Text = c.Name Frame.Avatar.Image = Return[1] Frame.Parent = creditsBack.Container else warn(Return) end end end creditsBack.Container.Template:Destroy() scaleCanvasSize(Credits.Back) local themeFrames = Themes.Back.Container:GetChildren() for _,f in next, themeFrames do local ImageButton = f:FindFirstChildWhichIsA("ImageButton") if ImageButton then ImageButton.MouseButton1Down:Connect(function() if themeModules[f.Name] then local ThemeModule = require(themeModules[f.Name]) ChangeTheme(ThemeModule.Properties.Name, ThemeModule.Settings) else warn("\""..f.Name.."\" module not found") end end) end end local Utility = Utilities.Back:GetChildren() for _,s in next, Utility do if s:IsA("TextButton") then s.MouseButton1Down:Connect(function() local mousePos = Vector2.new(Mouse.X, Mouse.Y) - s.AbsolutePosition spawn(function() doRipple(s, UDim2.new(0, mousePos.X, 0, mousePos.Y)) end) UtilityFunctions[s.Name]() end) end end Themes.Back.Container.ChildAdded:Connect(function() scaleCanvasSize(Themes.Back) end) Credits.Back.Container.ChildAdded:Connect(function() scaleCanvasSize(Credits.Back) end) <file_sep>return { Properties = { ["Name"] = "Forlorn"; ["ImageId"] = "rbxassetid://3094734890"; }, Settings = { ["Background Color"] = Color3.new(0.0666667, 0.0784314, 0.0823529); ["Built-in Function Color"] = Color3.new(0.431373, 0.709804, 0.427451); ["Comment Color"] = Color3.new(0.498039, 0.454902, 0.317647); ["Error Color"] = Color3.new(1, 0, 0); ["Find Selection Background Color"] = Color3.new(0.690196, 0.686275, 0.843137); ["Keyword Color"] = Color3.new(0.901961, 0.482353, 0.109804); ["Matching Word Background Color"] = Color3.new(0.741176, 0.831373, 0.843137); ["Number Color"] = Color3.new(0.25098, 1, 0.627451); ["Operator Color"] = Color3.new(0.752941, 0.54902, 0.137255); ["Preprocessor Color"] = Color3.new(1, 1, 1); ["Selection Background Color"] = Color3.new(0.392157, 0.686275, 0.376471); ["Selection Color"] = Color3.new(1, 1, 1); ["String Color"] = Color3.new(0.4, 0.792157, 1); ["Text Color"] = Color3.new(0.792157, 0.847059, 0.862745); ["Warning Color"] = Color3.new(1, 0, 0.819608); } }<file_sep>return { Properties = { ["Name"] = "Original Light"; ["ImageId"] = "rbxassetid://2919688393"; }, Settings = { ["Background Color"] = Color3.fromRGB(255, 255, 255); ["Built-in Function Color"] = Color3.fromRGB(0, 0, 127); ["Comment Color"] = Color3.fromRGB(0, 127, 0); ["Error Color"] = Color3.fromRGB(255, 0, 0); ["Find Selection Background Color"] = Color3.fromRGB(246, 185, 63); ["Keyword Color"] = Color3.fromRGB(0, 0, 127); ["Matching Word Background Color"] = Color3.fromRGB(226, 230, 214); ["Number Color"] = Color3.fromRGB(0, 127, 127); ["Operator Color"] = Color3.fromRGB(127, 127, 195); ["Preprocessor Color"] = Color3.fromRGB(127, 0, 0); ["Selection Background Color"] = Color3.fromRGB(110, 161, 241); ["Selection Color"] = Color3.fromRGB(225, 225, 225); ["String Color"] = Color3.fromRGB(127, 0, 127); ["Text Color"] = Color3.fromRGB(0, 0, 0); ["Warning Color"] = Color3.fromRGB(0, 0, 255); } }<file_sep>return { Properties = { ["Name"] = "Playful"; ["ImageId"] = "rbxassetid://5013036339"; }, Settings = { ["Background Color"] = Color3.new(0.145098, 0.145098, 0.145098); ["Built-in Function Color"] = Color3.new(0.768628, 0.368627, 0.368627); ["Comment Color"] = Color3.new(0.364706, 0.760784, 0.431373); ["Error Color"] = Color3.new(0.490196, 0, 0); ["Find Selection Background Color"] = Color3.new(0.843137, 0.764706, 0.627451); ["Keyword Color"] = Color3.new(0.666667, 0.666667, 1); ["Matching Word Background Color"] = Color3.new(0.843137, 0.764706, 0.627451); ["Number Color"] = Color3.new(0.815686, 0.815686, 0.403922); ["Operator Color"] = Color3.new(0.870588, 0.670588, 0.427451); ["Preprocessor Color"] = Color3.new(1, 1, 1); ["Selection Background Color"] = Color3.new(0.686275, 0.686275, 0.686275); ["Selection Color"] = Color3.new(0.882353, 0.882353, 0.882353); ["String Color"] = Color3.new(0.333333, 0.666667, 0.498039); ["Text Color"] = Color3.new(0.815686, 0.815686, 0.815686); ["Warning Color"] = Color3.new(0.490196, 0, 0); } }<file_sep>local ThemeScriptSource = {} ThemeScriptSource.getString = function(StudioTheme) return ([[ -- If you're uploading this yourself -- -- Change the name of the "Name" property to the name of your theme. -- Take a screenshot of the script editor, about 150x80. Does not have to be perfect. <- the current image is "original light," so it will default to that if you do not provide a screenshot. -- Rename this ModuleScript to "MainModule" and upload to Roblox. Be sure to allow copying. <- this step is important. -- Reply to https://devforum.roblox.com/t/script-editor-themes-plugin/262870 with the ID and the *exact name* of the module. -- If you want me to upload -- -- Reply to https://devforum.roblox.com/t/script-editor-themes-plugin/262870 with the code contained in this module. -- Preferably in a spoiler. return { Properties = { ["Name"] = "Theme"; ["ImageId"] = "rbxassetid://2919688393"; }, Settings = { ["Background Color"] = %s; ["Built-in Function Color"] = %s; ["Comment Color"] = %s; ["Error Color"] = %s; ["Find Selection Background Color"] = %s; ["Keyword Color"] = %s; ["Matching Word Background Color"] = %s; ["Number Color"] = %s; ["Operator Color"] = %s; ["Preprocessor Color"] = %s; ["Selection Background Color"] = %s; ["Selection Color"] = %s; ["String Color"] = %s; ["Text Color"] = %s; ["Warning Color"] = %s; } }]]):format(unpack(StudioTheme)) end return ThemeScriptSource
0c300f9f4db8d068fb7428edb348e2bab108bbbd
[ "Markdown", "Lua" ]
30
Lua
SimplyRekt/Script-Editor-Themes
1258fdb07eeb2744846dea7cbc554ebb36202cfb
f8565b2e7e9642d6a7e09915b8d2794792baf4ab
refs/heads/master
<file_sep>using GamingWorld.API.Security.Domain.Models; namespace GamingWorld.API.Business.Domain.Models { public class Participant { public int Id { get; set; } //Relationships public int Points { get; set; } public int UserId { get; set; } public User User { get; set; } public int TournamentId { get; set; } } }<file_sep>using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Shared.Inbound.Games.Domain.Models; using GamingWorld.API.Shared.Inbound.Games.Domain.Services; using Microsoft.AspNetCore.Mvc; namespace GamingWorld.API.Shared.Inbound.Games.Controllers { [ApiController] [Route("/api/v1/[controller]")] public class GamesController : ControllerBase { private readonly IGamesService _gamesService; private readonly int DEFAULT_LIMIT = 10; public GamesController(IGamesService gamesService) { _gamesService = gamesService; } [HttpGet] public async Task<IEnumerable<Game>> GetRandomListAsync(int limit) { return await _gamesService.ListRandomAsync(limit); } [HttpGet("{id}")] public async Task<Game> GetByIdAsync(int id) { return await _gamesService.GetById(id); } [HttpGet("find")] public async Task<IEnumerable<Game>> GetByNameAsync(string name, int limit) { return await _gamesService.FindByName(name, limit); } [HttpGet("top")] public async Task<string> GetTopGames(int limit) { return await _gamesService.FindTopGames(limit); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Business.Domain.Models; namespace GamingWorld.API.Business.Domain.Repositories { public interface ITournamentRepository { Task<IEnumerable<Tournament>> ListAsync(); Task AddAsync(Tournament tournament); Task<Tournament> FindByIdAsync(int id); Tournament FindById(int id); Task<Tournament> ListWithParticipantsById(int id); void Update(Tournament tournament); void Remove(Tournament tournament); } }<file_sep>using System.Collections.Generic; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Security.Resources; namespace GamingWorld.API.Business.Resources { public class ParticipantResource { public int Id { get; set; } public UserResource User { get; set; } public int TournamentId { get; set; } public int Points { get; set; } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Repositories; using GamingWorld.API.Shared.Persistence.Contexts; using GamingWorld.API.Shared.Persistence.Repositories; using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Business.Persistence.Repositories { public class TournamentRepository : BaseRepository, ITournamentRepository { public TournamentRepository(AppDbContext context) : base(context) { } public async Task<IEnumerable<Tournament>> ListAsync() { return await _context.Tournaments.ToListAsync(); } public async Task AddAsync(Tournament tournament) { await _context.Tournaments.AddAsync(tournament); } public Tournament FindById(int id) { return _context.Tournaments.Find(id); } public async Task<Tournament> ListWithParticipantsById(int id) { return await _context.Tournaments.Include(t=> t.Participants).ThenInclude(u=>u.User).FirstOrDefaultAsync(t=>t.Id==id); } public async Task<Tournament> FindByIdAsync(int id) { return await _context.Tournaments.FindAsync(id); } public void Update(Tournament tournament) { _context.Tournaments.Update(tournament); } public void Remove(Tournament tournament) { _context.Tournaments.Remove(tournament); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Security.Domain.Models; namespace GamingWorld.API.Security.Domain.Repositories { public interface IUserRepository { Task<IEnumerable<User>> ListAsync(); Task AddAsync(User user); Task<User> FindByIdAsync(int id); Task<User> FindByUsernameAsync(string username); bool ExistsByUsername(string username); void Update(User user); void Remove(User user); Task<User> FindByEmailAsync(string email); } }<file_sep>using System.ComponentModel; namespace GamingWorld.API.Profiles.Domain.Models { public enum EGamingLevel : short { [Description("Newbie")] Newbie = 1, [Description("Medium")] Medium = 2, [Description("Advanced")] Advanced = 3, } }<file_sep>using System; using System.Linq; using System.Net.Http; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using GamingWorld.API; using GamingWorld.API.Profiles.Resources; using Microsoft.AspNetCore.Mvc.Testing; using Newtonsoft.Json; using SpecFlow.Internal.Json; using TechTalk.SpecFlow; using TechTalk.SpecFlow.Assist; using Xunit; namespace GamingWorldBackEnd.Tests.UserProfiles { [Binding] public class PostUserProfileServiceStepsDefinition { private readonly WebApplicationFactory<Startup> _factory; private HttpClient _client; private Uri _baseUri; private Task<HttpResponseMessage> Response { get; set; } public PostUserProfileServiceStepsDefinition(WebApplicationFactory<Startup> factory) { _factory = factory; } [Given(@"the endpoint https://localhost:(.*)/api/v(.*)/profiles is available")] public void GivenTheEndpointHttpLocalhostApiVUserprofilesIsAvailable(int port, int version) { _baseUri = new Uri($"https://localhost:{port}/api/v{version}/profiles"); _client = _factory.CreateClient(new WebApplicationFactoryClientOptions {BaseAddress = _baseUri}); } [When(@"a POST Request is sent with this body")] public void WhenApostRequestIsSentWithThisBody(Table saveUserProfileResource) { var resource = saveUserProfileResource.CreateSet<SaveProfileResource>().First(); var content = new StringContent(resource.ToJson(), Encoding.UTF8, MediaTypeNames.Application.Json); Response = _client.PostAsync(_baseUri, content); } [Then(@"a UserProfile resource is included in the response body\.")] public async void ThenAUserProfileResourceIsIncludedInTheResponseBody(Table expectedUserProfileResource) { var expectedResource = expectedUserProfileResource.CreateSet<ProfileResource>().First(); var responseData = await Response.Result.Content.ReadAsStringAsync(); var resource = JsonConvert.DeserializeObject<ProfileResource>(responseData); expectedResource.Id = resource.Id; var jsonExpectedResource = expectedResource.ToJson(); var jsonActualResource = resource.ToJson(); Assert.Equal(jsonExpectedResource, jsonActualResource); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Resources; namespace GamingWorld.API.Business.Domain.Models { public class Tournament { public int Id { get; set; } //Relationships public int ParticipantLimit { get; set; } public int PrizePool { get; set; } public string TournamentDate { get; set; } public Publication Publication { get; set; } public string TournamentHour { get; set; } public IEnumerable<Participant> Participants { get; set; } public bool TournamentStatus { get; set; } } }<file_sep>using AutoMapper; using GamingWorld.API.Security.Domain.Models; using GamingWorld.API.Security.Domain.Services.Communication; using GamingWorld.API.Security.Resources; namespace GamingWorld.API.Security.Mapping { public class ModelToResourceProfile : Profile { public ModelToResourceProfile() { CreateMap<User, AuthenticateResponse>(); CreateMap<User, UserResource>(); } } }<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Repositories; using GamingWorld.API.Business.Domain.Services; using GamingWorld.API.Business.Domain.Services.Communication; using GamingWorld.API.Business.Resources; using GamingWorld.API.Security.Exceptions; using GamingWorld.API.Shared.Domain.Repositories; namespace GamingWorld.API.Business.Services { public class TournamentService : ITournamentService { private readonly ITournamentRepository _tournamentRepository; private readonly IParticipantRepository _participantRepository; private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; public TournamentService(IMapper mapper, ITournamentRepository tournamentRepository, IUnitOfWork unitOfWork, IParticipantRepository participantRepository) { _mapper = mapper; _tournamentRepository = tournamentRepository; _unitOfWork = unitOfWork; _participantRepository = participantRepository; } public async Task<IEnumerable<Tournament>> ListAsync() { return await _tournamentRepository.ListAsync(); } public async Task<TournamentResponse> SaveAsync(Tournament tournament) { //Validate try { await _tournamentRepository.AddAsync(tournament); await _unitOfWork.CompleteAsync(); return new TournamentResponse(tournament); } catch (Exception e) { return new TournamentResponse($"An error occured while saving the publication: {e.Message}"); } } public async Task<Tournament> ListWithParticipantsByIdAsync(int tournamentId) { return await _tournamentRepository.ListWithParticipantsById(tournamentId); } public async Task<ParticipantResponse> UpdateParticipantPoints(int tournamentId, int participantId, int points) { var existingTournament = await _tournamentRepository.FindByIdAsync(tournamentId); if (existingTournament == null) return new ParticipantResponse("Tournament Not Found"); var existingParticipant = await _participantRepository.FindByIdAsync(participantId); if (existingParticipant == null) return new ParticipantResponse("Participant Not Found"); if (points < 0) return new ParticipantResponse("Points must be positive."); try { existingParticipant.Points = points; _participantRepository.Update(existingParticipant); await _unitOfWork.CompleteAsync(); return new ParticipantResponse(existingParticipant); } catch (Exception e) { return new ParticipantResponse($"An error occurred while updating the participant."); } } public async Task<TournamentResponse> UpdateAsync(int id, Tournament tournament) { var existingTournament = await _tournamentRepository.FindByIdAsync(id); if (existingTournament == null) return new TournamentResponse("Tournament Not Found"); existingTournament.Id = tournament.Id; try { _tournamentRepository.Update(tournament); await _unitOfWork.CompleteAsync(); return new TournamentResponse(existingTournament); } catch (Exception e) { return new TournamentResponse($"An error occurred while updating the user: {tournament}"); } } public async Task<TournamentResponse> DeleteAsync(int id) { var existingTournament = await GetById(id); if (existingTournament == null) return new TournamentResponse("Tournament not found"); try { _tournamentRepository.Remove(existingTournament); await _unitOfWork.CompleteAsync(); return new TournamentResponse(existingTournament); } catch (Exception e) { return new TournamentResponse($"An error occurred while deleting publication:{e.Message}"); } } public async Task<Tournament> GetById(int id) { var tournament = await _tournamentRepository.FindByIdAsync(id); await _unitOfWork.CompleteAsync(); if (tournament == null) throw new KeyNotFoundException("Tournament not found."); return tournament; } public async Task<TournamentResponse> EndTournament(int id, bool status) { var tournament = await _tournamentRepository.FindByIdAsync(id); await _unitOfWork.CompleteAsync(); if (tournament == null) throw new KeyNotFoundException("Tournament not found."); tournament.TournamentStatus = status; _tournamentRepository.Update(tournament); await _unitOfWork.CompleteAsync(); return new TournamentResponse(tournament); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Security.Domain.Models; using GamingWorld.API.Security.Domain.Services.Communication; namespace GamingWorld.API.Security.Domain.Services { public interface IUserService { Task<AuthenticateResponse> Authenticate(AuthenticateRequest request); Task RegisterAsync(RegisterRequest request); Task<IEnumerable<User>> ListAsync(); Task<User> GetByIdAsync(int userId); Task<User> ListByUserUsernameAsync(int username); Task<UserResponse> SaveAsync(User user); Task<UserResponse> UpdateAsync(int id, User user); Task<UserResponse> DeleteAsync(int id); } }<file_sep>using AutoMapper; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Resources; namespace GamingWorld.API.Publications.Mapping { public class ModelToResourceProfile : Profile { public ModelToResourceProfile() { CreateMap<Publication, PublicationResource>(); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Publications.Domain.Models; namespace GamingWorld.API.Publications.Domain.Repositories { public interface IPublicationRepository { Task<IEnumerable<Publication>> ListAsync(); Task<IEnumerable<Publication>> ListByTypeAsync(); Task AddAsync(Publication publication); Task<Publication> FindByIdAsync(int id); void Update(Publication publication); void Remove(Publication publication); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Profiles.Domain.Repositories; using GamingWorld.API.Profiles.Domain.Services; using GamingWorld.API.Profiles.Domain.Services.Communication; using GamingWorld.API.Security.Domain.Repositories; using IUnitOfWork = GamingWorld.API.Shared.Domain.Repositories.IUnitOfWork; namespace GamingWorld.API.Profiles.Services { public class ProfileService : IUProfileService { private readonly IProfileRepository _profileRepository; private readonly IUserRepository _userRepository; private readonly IUnitOfWork _unitOfWork; public ProfileService(IProfileRepository profileRepository, IUserRepository userRepository, IUnitOfWork unitOfWork) { _profileRepository = profileRepository; _userRepository = userRepository; _unitOfWork = unitOfWork; } public async Task<IEnumerable<Profile>> ListAsync() { return await _profileRepository.ListAsync(); } public async Task<Profile> ListByUserIdAsync(int userId) { return await _profileRepository.FindByUserId(userId); } public async Task<Profile> ListByIdAsync(int id) { return await _profileRepository.FindByIdAsync(id); } public async Task<ProfileResponse> SaveAsync(Profile profile) { var existingUserId = await _profileRepository.FindByUserId(profile.UserId); if (existingUserId != null) return new ProfileResponse("User already has a profile."); var user = await _userRepository.FindByIdAsync(profile.UserId); if (user == null) return new ProfileResponse("User not found"); try { await _profileRepository.AddAsync(profile); await _unitOfWork.CompleteAsync(); return new ProfileResponse(profile); } catch (Exception e) { return new ProfileResponse($"An error occurred while saving the profile: {e.Message}"); } } public async Task<ProfileResponse> UpdateAsync(int id, Profile profile) { var existingProfile = await _profileRepository.FindByIdAsync(id); if (existingProfile == null) return new ProfileResponse("Profile not found."); existingProfile.GamingLevel = profile.GamingLevel; existingProfile.IsStreamer = profile.IsStreamer; existingProfile.GameExperiences = profile.GameExperiences; existingProfile.FavoriteGames = profile.FavoriteGames; existingProfile.StreamingCategories = profile.StreamingCategories; existingProfile.TournamentExperiences = profile.TournamentExperiences; existingProfile.StreamerSponsors = profile.StreamerSponsors; try { _profileRepository.Update(existingProfile); await _unitOfWork.CompleteAsync(); return new ProfileResponse(existingProfile); } catch (Exception e) { return new ProfileResponse($"An error occurred while updating the profile: {e.Message}"); } } public async Task<ProfileResponse> DeleteAsync(int id) { var existingProfile = await _profileRepository.FindByIdAsync(id); if (existingProfile == null) return new ProfileResponse("Profile not found. "); try { _profileRepository.Remove(existingProfile); await _unitOfWork.CompleteAsync(); return new ProfileResponse(existingProfile); } catch (Exception e) { return new ProfileResponse($"An error occurred while deleting the profile: {e.Message}"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Business.Domain.Repositories; using GamingWorld.API.Business.Domain.Services; using GamingWorld.API.Business.Persistence.Repositories; using GamingWorld.API.Business.Services; using GamingWorld.API.Profiles.Domain.Repositories; using GamingWorld.API.Profiles.Domain.Services; using GamingWorld.API.Profiles.Persistence.Repositories; using GamingWorld.API.Profiles.Services; using GamingWorld.API.Publications.Domain.Repositories; using GamingWorld.API.Publications.Domain.Services; using GamingWorld.API.Publications.Persistence.Repositories; using GamingWorld.API.Publications.Services; using GamingWorld.API.Security.Authorization.Handlers.Implementations; using GamingWorld.API.Security.Authorization.Handlers.Interfaces; using GamingWorld.API.Security.Authorization.Middleware; using GamingWorld.API.Security.Authorization.Settings; using GamingWorld.API.Security.Domain.Repositories; using GamingWorld.API.Security.Domain.Services; using GamingWorld.API.Security.Persistence.Repositories; using GamingWorld.API.Security.Services; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Repositories; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Persistence.Repositories; using GamingWorld.API.Shared.Inbound.Games.Domain.Services; using GamingWorld.API.Shared.Inbound.Games.Services; using GamingWorld.API.Shared.Inbound.News.Domain.Services; using GamingWorld.API.Shared.Inbound.News.Services; using GamingWorld.API.Shared.Persistence.Contexts; using GamingWorld.API.Shared.Persistence.Repositories; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using IUnitOfWork = GamingWorld.API.Shared.Domain.Repositories.IUnitOfWork; namespace GamingWorld.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddControllers(); services.AddRouting(options => options.LowercaseUrls = true); services.AddDbContext<AppDbContext>(options => { //options.UseInMemoryDatabase("supermarket-api-in-memory"); options.UseMySQL(Configuration.GetConnectionString("Default")); }); services.AddSwaggerGen(c => { c.DocumentFilter<SnakeCaseDocumentFilter>(); c.OperationFilter<SnakeCaseOperationFilter>(); c.SwaggerDoc("v1", new OpenApiInfo {Title = "GamingWorld.API", Version = "v1"}); }); services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IPublicationRepository, PublicationRepository>(); services.AddScoped<IPublicationService, PublicationService>(); services.AddScoped<ITournamentRepository, TournamentRepository>(); services.AddScoped<ITournamentService, TournamentService>(); services.AddScoped<IParticipantRepository, ParticipantRepository>(); services.AddScoped<IParticipantService, ParticipantService>(); services.AddScoped<IProfileRepository, ProfileRepository>(); services.AddScoped<IUProfileService, ProfileService>(); services.AddScoped<IExternalAPIRepository, ExternalAPIRepository>(); services.AddScoped<IGamesService, GamesService>(); services.AddScoped<INewsService, NewsService>(); services.AddScoped<IUnitOfWork, UnitOfWork>(); services.AddScoped<IJwtHandler, JwtHandler>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // For this course purpose we allow Swagger in release mode. app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "GamingWorld.API v1")); app.UseMiddleware<ErrorHandlerMiddleware>(); app.UseMiddleware<JwtMiddleware>(); app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Business.Domain.Models; namespace GamingWorld.API.Business.Domain.Repositories { public interface IParticipantRepository { Task<IEnumerable<Participant>> ListAsync(); Task AddAsync(Participant participant); Task<Participant> FindByIdAsync(int id); void Update(Participant participant); Participant FindById(int id); void Remove(Participant participant); } }<file_sep>using System.ComponentModel.DataAnnotations; namespace GamingWorld.API.Publications.Resources { public class SavePublicationResource { [Required] public short PublicationType { get; set; } [Required] [MinLength(15)] public string Title { get; set; } [Required] [MinLength(40)] public string Content { get; set; } public int ParticipantLimit { get; set; } public int PrizePool { get; set; } public string TournamentDate { get; set; } public string TournamentHour { get; set; } public string UrlToImage { get; set; } [Required] public string CreatedAt { get; set; } public int GameId { get; set; } [Required] public int UserId { get; set; } } } <file_sep>#nullable enable using System; using System.Globalization; namespace GamingWorld.API.Security.Exceptions { public class AppException : Exception { public AppException() : base() { } public AppException(string? message) : base(message) { } public AppException(string message, params object[] args) : base(String.Format(CultureInfo.CurrentCulture, message, args)) { } } }<file_sep>using System; using System.ComponentModel.DataAnnotations; namespace GamingWorld.API.Business.Resources { public class SaveTournamentResource { //Relationships [Required] public int PublicationId { get; set; } [Required] public int ParticipantLimit { get; set; } [Required] public int PrizePool { get; set; } [Required] public string TournamentDate { get; set; } [Required] public string TournamentHour { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Repositories; using GamingWorld.API.Business.Domain.Services; using GamingWorld.API.Business.Domain.Services.Communication; using GamingWorld.API.Security.Domain.Repositories; using GamingWorld.API.Security.Exceptions; using GamingWorld.API.Shared.Domain.Repositories; namespace GamingWorld.API.Business.Services { public class ParticipantService : IParticipantService { private readonly IParticipantRepository _participantRepository; private readonly ITournamentRepository _tournamentRepository; private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; public ParticipantService(IMapper mapper, IParticipantRepository participantRepository, IUnitOfWork unitOfWork, ITournamentRepository tournamentRepository) { _mapper = mapper; _participantRepository = participantRepository; _unitOfWork = unitOfWork; _tournamentRepository = tournamentRepository; } public async Task<IEnumerable<Participant>> ListAsync() { return await _participantRepository.ListAsync(); } public async Task<ParticipantResponse> SaveAsync(int tournamentId, Participant participant) { var tournament = await _tournamentRepository.ListWithParticipantsById(tournamentId); if(tournament==null) return new ParticipantResponse("Tournament Not Found"); if (tournament.Participants != null) { if (tournament.Participants.Count() >= tournament.ParticipantLimit) return new ParticipantResponse("This tournament is full."); if (tournament.Participants.Any(x => x.UserId == participant.UserId)) return new ParticipantResponse("This user already is a participant."); } try { participant.TournamentId = tournamentId; await _participantRepository.AddAsync(participant); await _unitOfWork.CompleteAsync(); return new ParticipantResponse(participant); } catch (Exception e) { return new ParticipantResponse($"An error occured while saving the publication: {e.Message}"); } } public async Task<bool> ValidateParticipantTournament(int tournamentId, int participantId) { var tournament = await _tournamentRepository.ListWithParticipantsById(tournamentId); var participant = await _participantRepository.FindByIdAsync(participantId); if(tournament==null) return true; if (tournament.Participants != null) { if (tournament.Participants.Count() >= tournament.ParticipantLimit) return false; if (tournament.Participants.Any(x => x.UserId == participant.UserId)) return false; } return true; } public async Task<ParticipantResponse> UpdateAsync(int id, Participant tournament) { var existingParticipant = GetById(id); if (existingParticipant == null) return new ParticipantResponse("Participant Not Found"); existingParticipant.Points = tournament.Points; try { _participantRepository.Update(tournament); await _unitOfWork.CompleteAsync(); return new ParticipantResponse(existingParticipant); } catch (Exception e) { return new ParticipantResponse($"An error occurred while updating the user: {tournament}"); } } public async Task<ParticipantResponse> DeleteAsync(int id) { var existingParticipant = GetById(id); if (existingParticipant == null) return new ParticipantResponse("Participant not found"); try { _participantRepository.Remove(existingParticipant); await _unitOfWork.CompleteAsync(); return new ParticipantResponse(existingParticipant); } catch (Exception e) { return new ParticipantResponse($"An error occurred while deleting participant:{e.Message}"); } } private Participant GetById(int id) { var participant = _participantRepository.FindById(id); if (participant == null) throw new KeyNotFoundException("Participant not found."); return participant; } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Repositories; using GamingWorld.API.Shared.Persistence.Contexts; using GamingWorld.API.Shared.Persistence.Repositories; using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Business.Persistence.Repositories { public class ParticipantRepository : BaseRepository, IParticipantRepository { public ParticipantRepository(AppDbContext context) : base(context) { } public async Task<IEnumerable<Participant>> ListAsync() { return await _context.Participants.ToListAsync(); } public async Task AddAsync(Participant participant) { await _context.Participants.AddAsync(participant); } public async Task<Participant> FindByIdAsync(int id) { return await _context.Participants.FindAsync(id); } public void Update(Participant participant) { _context.Participants.Update(participant); } public Participant FindById(int id) { return _context.Participants.Find(id); } public void Remove(Participant participant) { _context.Participants.Remove(participant); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Services.Communication; using GamingWorld.API.Profiles.Domain.Services.Communication; namespace GamingWorld.API.Business.Domain.Services { public interface IParticipantService { Task<IEnumerable<Participant>> ListAsync(); Task<ParticipantResponse> SaveAsync(int tournamentId, Participant participant); Task<ParticipantResponse> UpdateAsync(int id, Participant participant); Task<ParticipantResponse> DeleteAsync(int id); } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GamingWorld.API.Security.Domain.Models; using GamingWorld.API.Security.Domain.Repositories; using GamingWorld.API.Shared.Persistence.Contexts; using GamingWorld.API.Shared.Persistence.Repositories; using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Security.Persistence.Repositories { public class UserRepository : BaseRepository, IUserRepository { public UserRepository(AppDbContext context) : base(context) { } public async Task<IEnumerable<User>> ListAsync() { return await _context.Users.ToListAsync(); } public async Task AddAsync(User user) { await _context.Users.AddAsync(user); } public async Task<User> FindByIdAsync(int id) { return await _context.Users.FirstOrDefaultAsync(p => p.Id == id); } public async Task<User> FindByUsernameAsync(string username) { return await _context.Users.FirstOrDefaultAsync(p => p.Username == username); } public bool ExistsByUsername(string username) { return _context.Users.Any(u => u.Username == username); } public async Task<User> FindByEmailAsync(string email) { return await _context.Users.FirstOrDefaultAsync(p => p.Email == email); } public void Update(User user) { _context.Users.Update(user); } public void Remove(User user) { _context.Users.Remove(user); } } }<file_sep>using System; using System.Net.Http; using System.Threading.Tasks; using System.Web; using GamingWorld.API.Security.Exceptions; using GamingWorld.API.Shared.Inbound.News.Domain.Services; namespace GamingWorld.API.Shared.Inbound.News.Services { public class NewsService: INewsService { private readonly string NEWS_URL = "https://newsapi.org/v2/everything"; public async Task<string> ListByTheme(string theme) { using var client = new HttpClient(); var builder = new UriBuilder(NEWS_URL); builder.Port = -1; var query = HttpUtility.ParseQueryString(builder.Query); query["q"] = theme; query["language"] = "es"; query["apiKey"] = "<KEY>"; builder.Query = query.ToString(); string requestURL = builder.ToString(); var content = await client.GetStringAsync(requestURL); return content; } } }<file_sep>using System; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using GamingWorld.API; using GamingWorld.API.Security.Domain.Services.Communication; using GamingWorld.API.Security.Resources; using Microsoft.AspNetCore.Mvc.Testing; using Newtonsoft.Json; using SpecFlow.Internal.Json; using TechTalk.SpecFlow; using TechTalk.SpecFlow.Assist; using Xunit; namespace GamingWorldBackEnd.Tests.Users { [Binding] public class PostUsersServiceStepsDefinition { private readonly WebApplicationFactory<Startup> _factory; private HttpClient _client; private Uri _baseUri; private Task<HttpResponseMessage> Response { get; set; } public PostUsersServiceStepsDefinition(WebApplicationFactory<Startup> factory) { _factory = factory; } [Given(@"the endpoint https://localhost:(.*)/api/v(.*)/users/auth/sign-up is available")] public void GivenTheEndpointHttpLocalhostApiVUsersIsAvailable(int port, int version) { _baseUri = new Uri($"https://localhost:{port}/api/v{version}/users/auth/sign-up"); _client = _factory.CreateClient(new WebApplicationFactoryClientOptions {BaseAddress = _baseUri}); } [When(@"a POST Request is sent")] public void WhenApostRequestIsSent(Table saveUserResource) { var resource = saveUserResource.CreateSet<RegisterRequest>().First(); var content = new StringContent(resource.ToJson(), Encoding.UTF8, MediaTypeNames.Application.Json); Response = _client.PostAsync(_baseUri, content); } [Then(@"a Response With Status (.*) is received")] public void ThenAResponseIsReceivedWithStatus(int expectedStatus) { var expectedStatusCode3 = ((HttpStatusCode) expectedStatus).ToString(); var actualStatusCode3 = Response.Result.StatusCode.ToString(); Assert.Equal(expectedStatusCode3, actualStatusCode3); } [Then(@"a User Resource is included in the response body\.")] public async void ThenAUserResourceIsIncludedInTheResponseBody(Table expectedUserResource) { var expectedResource = expectedUserResource.CreateSet<UserResource>().First(); var responseData = await Response.Result.Content.ReadAsStringAsync(); var resource = JsonConvert.DeserializeObject<UserResource>(responseData); expectedResource.Id = resource.Id; var jsonExpectedResource = expectedResource.ToJson(); var jsonActualResource = resource.ToJson(); Assert.Equal(jsonExpectedResource, jsonActualResource); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Profiles.Domain.Services; using GamingWorld.API.Profiles.Resources; using GamingWorld.API.Shared.Extensions; using Microsoft.AspNetCore.Mvc; using Profile = GamingWorld.API.Profiles.Domain.Models.Profile; namespace GamingWorld.API.Profiles.Controllers { [ApiController] [Route("/api/v1/[controller]")] public class ProfilesController : ControllerBase { private readonly IUProfileService _uProfileService; private readonly IMapper _mapper; public ProfilesController(IUProfileService uProfileService, IMapper mapper) { _uProfileService = uProfileService; _mapper = mapper; } [HttpGet] public async Task<IEnumerable<ProfileResource>> GetAllAsync() { var profiles = await _uProfileService.ListAsync(); var resources = _mapper.Map<IEnumerable<Profile>, IEnumerable<ProfileResource>>(profiles); return resources; } [HttpGet("{id}")] public async Task<ProfileResource> GetById(int id) { var profile = await _uProfileService.ListByIdAsync(id); var resources = _mapper.Map<Profile, ProfileResource>(profile); return resources; } [HttpGet("user/{userId}")] public async Task<ProfileResource> GetByUserId(int userId) { var profile = await _uProfileService.ListByUserIdAsync(userId); var resources = _mapper.Map<Profile, ProfileResource>(profile); return resources; } [HttpPost] public async Task<IActionResult> PostAsync([FromBody] SaveProfileResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var profile = _mapper.Map<SaveProfileResource, Profile>(resource); var result = await _uProfileService.SaveAsync(profile); if (!result.Success) return BadRequest(result.Message); var profileResource = _mapper.Map<Profile, ProfileResource>(result.Resource); return Ok(profileResource); } [HttpPut("{id}")] public async Task<IActionResult> PutAsync(int id, [FromBody] SaveProfileResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var profile = _mapper.Map<SaveProfileResource, Profile>(resource); var result = await _uProfileService.UpdateAsync(id, profile); if (!result.Success) return BadRequest(result.Message); var profileResource = _mapper.Map<Profile, ProfileResource>(result.Resource); return Ok(profileResource); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteAsync(int id) { var result = await _uProfileService.DeleteAsync(id); if (!result.Success) return BadRequest(result.Message); var profileResource = _mapper.Map<Profile, ProfileResource>(result.Resource); return Ok(profileResource); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Domain.Repositories; using GamingWorld.API.Shared.Persistence.Contexts; using GamingWorld.API.Shared.Persistence.Repositories; using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Publications.Persistence.Repositories { public class PublicationRepository : BaseRepository, IPublicationRepository { public PublicationRepository(AppDbContext context) : base(context) { } public async Task<IEnumerable<Publication>> ListAsync() { return await _context.Publications.Include(p=>p.Tournament).ToListAsync(); } public async Task<IEnumerable<Publication>> ListByTypeAsync() { return await _context.Publications.Include(p=>p.Tournament).ToListAsync(); } public async Task AddAsync(Publication publication) { await _context.Publications.AddAsync(publication); } public async Task<Publication> FindByIdAsync(int id) { return await _context.Publications.Include(p=>p.Tournament).FirstOrDefaultAsync(p=>p.Id==id); } public void Update(Publication publication) { _context.Publications.Update(publication); } public void Remove(Publication publication) { _context.Publications.Remove(publication); } } }<file_sep>using GamingWorld.API.Business.Domain.Models; namespace GamingWorld.API.Publications.Domain.Models { public class Publication { public int Id { get; set; } public short PublicationType { get; set; } public string Title { get; set; } public string Content { get; set; } public string UrlToImage { get; set; } public int? TournamentId { get; set; } public Tournament Tournament { get; set; } public string CreatedAt { get; set; } //Relationships public int GameId { get; set; } public int UserId { get; set; } } }<file_sep>namespace GamingWorld.API.Profiles.Domain.Models { public class FavoriteGame { public int Id { get; set; } public string GameName { get; set; } // Relations public int ProfileId { get; set; } //public Profile Profile { get; set; } } }<file_sep>namespace GamingWorld.API.Shared.Inbound.Games.Domain.Models { public class GameCover { // NOT FOLLOWING THE NAMING CONVENTION BECAUSE WE NEED TO MAP EXACT FIELD NAMES FROM OBJECT RESPONSE FROM IGDB. public int id { get; set; } public string url { get; set; } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Services.Communication; using GamingWorld.API.Profiles.Domain.Services.Communication; namespace GamingWorld.API.Business.Domain.Services { public interface ITournamentService { Task<Tournament> GetById(int id); Task<IEnumerable<Tournament>> ListAsync(); Task<Tournament> ListWithParticipantsByIdAsync(int tournamentId); Task<TournamentResponse> SaveAsync(Tournament tournament); Task<ParticipantResponse> UpdateParticipantPoints(int tournamentId, int participantId, int points); Task<TournamentResponse> EndTournament(int tournamentId, bool tournamentStatus); } }<file_sep>using AutoMapper; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Resources; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Resources; namespace GamingWorld.API.Business.Mapping { public class ResourceToModelProfile : AutoMapper.Profile { public ResourceToModelProfile() { CreateMap<SaveTournamentResource, Tournament>(); CreateMap<SaveParticipantResource, Participant>(); } } }<file_sep>using System; using System.Linq; using GamingWorld.API.Security.Domain.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace GamingWorld.API.Security.Authorization.Attributes { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorizeAttribute : Attribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any(); // When Action is decorated with [AllowAnonymous] attribute // Then skip authorization process if (allowAnonymous) return; // Authorization Process var user = (User)context.HttpContext.Items["User"]; // If user is null then Unauthorized Request if (user == null) context.Result = new JsonResult( new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized }; } } }<file_sep>using System.ComponentModel; using System.Reflection; namespace GamingWorld.API.Shared.Extensions { public static class EnumExtensions { public static string ToDescriptionString<TEnum>(this TEnum sourceEnum) { FieldInfo info = sourceEnum.GetType().GetField(sourceEnum.ToString()); var attributes = (DescriptionAttribute[]) info.GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes?[0].Description ?? sourceEnum.ToString(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using GamingWorld.API.Shared.Extensions; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; namespace GamingWorld.API { public class SnakeCaseDocumentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var paths = swaggerDoc.Paths; // New Keys var newPaths = new Dictionary<string, OpenApiPathItem>(); var removeKeys = new List<string>(); // Old keys foreach (var path in paths) { var newKey = path.Key.ToLower(); if (newKey != path.Key) { removeKeys.Add(path.Key); newPaths.Add(newKey, path.Value); } } foreach (var path in newPaths) { swaggerDoc.Paths.Add(path.Key, path.Value); } // Removing old keys foreach (var key in removeKeys) { swaggerDoc.Paths.Remove(key); } } } public class SnakeCaseOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { for (int i = 0; i < operation.Tags.Count; ++i) { operation.Tags[i].Name = operation.Tags[i].Name.ToSnakeCase(); } } } }<file_sep>using System; namespace GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Models { public class ExternalAPI { public int Id { get; set; } public string Name { get; set; } public string Token { get; set; } public DateTime Expiration { get; set; } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Security.Authorization.Attributes; using GamingWorld.API.Security.Domain.Services; using GamingWorld.API.Security.Domain.Services.Communication; using GamingWorld.API.Security.Resources; using GamingWorld.API.Shared.Extensions; using Microsoft.AspNetCore.Mvc; namespace GamingWorld.API.Security.Controllers { [Authorize] [ApiController] [Route("/api/v1/[controller]")] public class UsersController : ControllerBase { private readonly IUserService _userService; private readonly IMapper _mapper; public UsersController(IUserService userService, IMapper mapper) { _userService = userService; _mapper = mapper; } [AllowAnonymous] [HttpPost("auth/sign-in")] public async Task<IActionResult> Authenticate( AuthenticateRequest request) { var response = await _userService.Authenticate(request); return Ok(response); } [AllowAnonymous] [HttpPost("auth/sign-up")] public async Task<IActionResult> Register( RegisterRequest request) { await _userService.RegisterAsync(request); return Ok(new {message = "Registration successful."}); } [HttpGet] public async Task<IEnumerable<UserResource>> GetAllAsync() { var users = await _userService.ListAsync(); var resources = _mapper.Map<IEnumerable<Domain.Models.User>, IEnumerable<UserResource>>(users); return resources; } /* [HttpPost] public async Task<IActionResult> PostAsync([FromBody] SaveUserResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var user = _mapper.Map<SaveUserResource, Domain.Models.User>(resource); var result = await _userService.SaveAsync(user); if (!result.Success) return BadRequest(result.Message); var productResource = _mapper.Map<Domain.Models.User, UserResource>(result.Resource); return Ok(productResource); } */ [HttpPut("{id}")] public async Task<IActionResult> PutAsync(int id, [FromBody] SaveUserResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var user = _mapper.Map<SaveUserResource, Domain.Models.User>(resource); var result = await _userService.UpdateAsync(id, user); if (!result.Success) return BadRequest(result.Message); var userResource = _mapper.Map<Domain.Models.User, UserResource>(result.Resource); return Ok(userResource); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteAsync(int id) { var result = await _userService.DeleteAsync(id); if (!result.Success) return BadRequest(result.Message); var productResource = _mapper.Map<Domain.Models.User, UserResource>(result.Resource); return Ok(productResource); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Domain.Services.Communication; using GamingWorld.API.Publications.Resources; namespace GamingWorld.API.Publications.Domain.Services { public interface IPublicationService { Task<IEnumerable<Publication>> ListAsync(); Task<IEnumerable<Publication>> ListByTypeAsync(int type); Task<Publication> GetById(int id); Task<PublicationResponse> SaveAsync(SavePublicationResource publication); Task<PublicationResponse> UpdateAsync(int id, Publication publication); Task<PublicationResponse> DeleteAsync(int id); } }<file_sep>using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Shared.Domain.Services.Communication; namespace GamingWorld.API.Business.Domain.Services.Communication { public class ParticipantResponse : BaseResponse<Participant> { public ParticipantResponse(string message) : base(message) { } public ParticipantResponse(Participant participant) : base(participant) { } } }<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Profiles.Domain.Repositories; using GamingWorld.API.Security.Authorization.Handlers.Interfaces; using GamingWorld.API.Security.Domain.Models; using GamingWorld.API.Security.Domain.Repositories; using GamingWorld.API.Security.Domain.Services; using GamingWorld.API.Security.Domain.Services.Communication; using GamingWorld.API.Security.Exceptions; using GamingWorld.API.Shared.Domain.Repositories; using GamingWorld.API.Shared.Extensions; using BCryptNet = BCrypt.Net.BCrypt; using Profile = GamingWorld.API.Profiles.Domain.Models.Profile; namespace GamingWorld.API.Security.Services { public class UserService : IUserService { private readonly IUserRepository _userRepository; private readonly IProfileRepository _profileRepository; private readonly IUnitOfWork _unitOfWork; private readonly IJwtHandler _jwtHandler; private readonly IMapper _mapper; public UserService(IUserRepository userRepository, IProfileRepository profileRepository, IUnitOfWork unitOfWork, IMapper mapper, IJwtHandler jwtHandler) { _userRepository = userRepository; _profileRepository = profileRepository; _unitOfWork = unitOfWork; _mapper = mapper; _jwtHandler = jwtHandler; } public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest request) { var user = await _userRepository.FindByUsernameAsync(request.Username); //Validate if (user == null || !BCryptNet.Verify(request.Password, user.PasswordHash)) throw new AppException("Username or password is incorrect"); //Authentication successful var response = _mapper.Map<AuthenticateResponse>(user); response.Token = _jwtHandler.GenerateToken(user); return response; } public async Task RegisterAsync(RegisterRequest request) { //Validate if (_userRepository.ExistsByUsername(request.Username)) throw new AppException($"Username {request.Username} is already taken."); //Map request to User object var user = _mapper.Map<User>(request); //Has password user.PasswordHash = <PASSWORD>(request.Password); //Save User try { await _userRepository.AddAsync(user); await _unitOfWork.CompleteAsync(); var profile = new Profile(); profile.UserId = user.Id; profile.GamingLevel = EGamingLevel.Newbie; profile.IsStreamer = true; await _profileRepository.AddAsync(profile); await _unitOfWork.CompleteAsync(); } catch (Exception e) { throw new AppException($"An error occurred while saving the user: {user}"); } } public async Task<IEnumerable<User>> ListAsync() { return await _userRepository.ListAsync(); } public async Task<User> GetByIdAsync(int userId) { return await _userRepository.FindByIdAsync(userId); } public async Task<User> ListByUserUsernameAsync(int userId) { return await _userRepository.FindByIdAsync(userId); } public async Task<UserResponse> SaveAsync(User user) { //Validate Username var existingUsername = await _userRepository.FindByUsernameAsync(user.Username); if (existingUsername != null) return new UserResponse("Username already exists."); try { await _userRepository.AddAsync(user); await _unitOfWork.CompleteAsync(); return new UserResponse(user); } catch (Exception e) { return new UserResponse($"An error occurred while saving the user: {e.Message}"); } } public async Task<UserResponse> UpdateAsync(int id, User user) { //Validate Id var existingUserById = await _userRepository.FindByIdAsync(id); if (existingUserById == null) return new UserResponse("User not found."); //Validate Username var existingUserByUsername = await _userRepository.FindByUsernameAsync(user.Username); if (existingUserByUsername != null && existingUserByUsername.Id != id) return new UserResponse("Username already used."); //Validate Email var existingUserByEmail = await _userRepository.FindByEmailAsync(user.Email); if (existingUserByEmail != null && existingUserByEmail.Id != id) return new UserResponse("Email already used."); existingUserById.Email = user.Email; existingUserById.Username = user.Username; existingUserById.Premium = user.Premium; try { _userRepository.Update(existingUserById); await _unitOfWork.CompleteAsync(); return new UserResponse(existingUserById); } catch (Exception e) { return new UserResponse($"An error occurred while updating the user: {e.Message}"); } } public async Task<UserResponse> DeleteAsync(int id) { //Validate User Id var existingUser = await _userRepository.FindByIdAsync(id); if (existingUser == null) return new UserResponse("User not found."); try { _userRepository.Remove(existingUser); await _unitOfWork.CompleteAsync(); return new UserResponse(existingUser); } catch (Exception e) { return new UserResponse($"An error occurred while deleting the user: {e.Message}"); } } } }<file_sep>using System; using System.Collections.Generic; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Resources; namespace GamingWorld.API.Business.Resources { public class TournamentResource { public int Id { get; set; } public int ParticipantLimit { get; set; } public int PrizePool { get; set; } public string TournamentDate { get; set; } public string TournamentHour { get; set; } public int PublicationId { get; set; } public bool TournamentStatus { get; set; } //Relationships public IEnumerable<Participant> Participants { get; set; } } }<file_sep>using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Security.Domain.Models; using GamingWorld.API.Shared.Extensions; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Models; using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Shared.Persistence.Contexts { public class AppDbContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<Publication> Publications { get; set; } public DbSet<Profile> Profiles { get; set; } public DbSet<Tournament> Tournaments { get; set; } public DbSet<Participant> Participants { get; set; } public DbSet<ExternalAPI> ExternalApis { get; set; } public AppDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // External APIs builder.Entity<ExternalAPI>().ToTable("ExternalApis"); builder.Entity<ExternalAPI>().HasKey(api => api.Id); builder.Entity<ExternalAPI>().Property(api => api.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<ExternalAPI>().Property(api => api.Name).IsRequired(); builder.Entity<ExternalAPI>().Property(api => api.Expiration).IsRequired(); builder.Entity<ExternalAPI>().Property(api => api.Token).IsRequired(); //Profiles builder.Entity<Profile>().ToTable("Profiles"); builder.Entity<Profile>().HasKey(p => p.Id); builder.Entity<Profile>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<Profile>().Property(p => p.UserId).IsRequired(); builder.Entity<Profile>().Property(p => p.GamingLevel).IsRequired(); builder.Entity<Profile>().Property(p => p.IsStreamer).IsRequired(); builder.Entity<Profile>().HasMany(p => p.GameExperiences).WithOne(); builder.Entity<Profile>().HasMany(p => p.StreamingCategories).WithOne(); builder.Entity<Profile>().HasMany(p => p.StreamerSponsors).WithOne(); builder.Entity<Profile>().HasMany(p => p.FavoriteGames).WithOne(); builder.Entity<Profile>().HasMany(p => p.TournamentExperiences).WithOne(); /*builder.Entity<Profile>().HasData ( new Profile {Id = 1, UserId = 1, GamingLevel = EGamingLevel.A, IsStreamer = true}, new Profile {Id = 2, UserId = 2, GamingLevel = EGamingLevel.N, IsStreamer = true}, new Profile {Id = 3, UserId = 3, GamingLevel = EGamingLevel.M, IsStreamer = false}, new Profile {Id = 4, UserId = 4, GamingLevel = EGamingLevel.A, IsStreamer = false} );*/ // Profiles: GameExperiences builder.Entity<GameExperience>().ToTable("GameExperiences"); builder.Entity<GameExperience>().HasKey(ge => ge.Id); builder.Entity<GameExperience>().Property(ge => ge.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<GameExperience>().Property(ge => ge.GameName).IsRequired(); builder.Entity<GameExperience>().Property(ge => ge.Time).IsRequired(); builder.Entity<GameExperience>().Property(ge => ge.TimeUnit).IsRequired(); builder.Entity<GameExperience>().Property(ge => ge.ProfileId).IsRequired(); /*builder.Entity<GameExperience>().HasData ( new GameExperience {Id = 1, GameName = "Among Us", Time = 5, TimeUnit = EGameExperienceTime.M, ProfileId = 1}, new GameExperience {Id = 2, GameName = "Call of Duty", Time = 4, TimeUnit = EGameExperienceTime.Y, ProfileId = 2}, new GameExperience {Id = 3, GameName = "Manco's Combat", Time = 25, TimeUnit = EGameExperienceTime.D, ProfileId = 3} );*/ // Profiles: StreamingCategories builder.Entity<StreamingCategory>().ToTable("StreamingCategories"); builder.Entity<StreamingCategory>().HasKey(sc => sc.Id); builder.Entity<StreamingCategory>().Property(sc => sc.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<StreamingCategory>().Property(sc => sc.Name).IsRequired(); builder.Entity<StreamingCategory>().Property(sc => sc.ProfileId).IsRequired(); /*builder.Entity<StreamingCategory>().HasData ( new StreamingCategory {Id = 1, Name = "Battle Royale", ProfileId = 1}, new StreamingCategory {Id = 2, Name = "First Person Shooter", ProfileId = 2}, new StreamingCategory {Id = 3, Name = "Battle Royale", ProfileId = 3} );*/ // Profiles: StreamerSponsors builder.Entity<StreamerSponsor>().ToTable("StreamerSponsors"); builder.Entity<StreamerSponsor>().HasKey(ss => ss.Id); builder.Entity<StreamerSponsor>().Property(ss => ss.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<StreamerSponsor>().Property(ss => ss.Name).IsRequired(); builder.Entity<StreamerSponsor>().Property(ss => ss.ProfileId).IsRequired(); /*builder.Entity<StreamerSponsor>().HasData ( new StreamerSponsor {Id = 1, Name = "<NAME>", ProfileId = 1}, new StreamerSponsor {Id = 2, Name = "Pepsi", ProfileId = 2}, new StreamerSponsor {Id = 3, Name = "Fanta", ProfileId = 3} );*/ // Profiles: TournamentExperiences builder.Entity<TournamentExperience>().ToTable("TournamentExperiences"); builder.Entity<TournamentExperience>().HasKey(te => te.Id); builder.Entity<TournamentExperience>().Property(te => te.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<TournamentExperience>().Property(te => te.Name).IsRequired(); builder.Entity<TournamentExperience>().Property(te => te.Position).IsRequired(); builder.Entity<TournamentExperience>().Property(te => te.ProfileId).IsRequired(); /*builder.Entity<TournamentExperience>().HasData ( new TournamentExperience {Id = 1, Name = "<NAME>", Position = 23, ProfileId = 1}, new TournamentExperience {Id = 2, Name = "<NAME>", Position = 1, ProfileId = 2}, new TournamentExperience {Id = 3, Name = "CODM Championship", Position = 7, ProfileId = 3} );*/ // Profiles: FavoriteGames builder.Entity<FavoriteGame>().ToTable("FavoriteGames"); builder.Entity<FavoriteGame>().HasKey(fg => fg.Id); builder.Entity<FavoriteGame>().Property(fg => fg.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<FavoriteGame>().Property(fg => fg.GameName).IsRequired(); builder.Entity<FavoriteGame>().Property(fg => fg.ProfileId).IsRequired(); /*builder.Entity<FavoriteGame>().HasData ( new FavoriteGame {Id = 1, GameName = "Among Us", ProfileId = 1}, new FavoriteGame {Id = 2, GameName = "Call of Duty", ProfileId = 2}, new FavoriteGame {Id = 3, GameName = "Free Fire", ProfileId = 3} );*/ //Publications //Constraints builder.Entity<Publication>().ToTable("Publications"); builder.Entity<Publication>().HasKey(p => p.Id); builder.Entity<Publication>().Property(p => p.Title).IsRequired(); builder.Entity<Publication>().Property(p => p.Content).IsRequired(); builder.Entity<Publication>().Property(p => p.CreatedAt).IsRequired(); builder.Entity<Publication>().Property(p => p.PublicationType).IsRequired(); builder.Entity<Publication>().Property(p => p.TournamentId).HasDefaultValue(null); builder.Entity<Publication>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<Publication>().HasOne(p => p.Tournament).WithOne(t => t.Publication).HasForeignKey<Tournament>(t => t.Id); //Users builder.Entity<User>().ToTable("Users"); builder.Entity<User>().HasKey(p => p.Id); builder.Entity<User>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<User>().Property(p => p.Username).IsRequired().HasMaxLength(30); builder.Entity<User>().Property(p => p.FirstName).IsRequired().HasMaxLength(30); builder.Entity<User>().Property(p => p.LastName).IsRequired().HasMaxLength(30); builder.Entity<User>().Property(p => p.Email).IsRequired().HasMaxLength(50); builder.Entity<User>().Property(p => p.Premium).IsRequired(); //Tournaments builder.Entity<Tournament>().ToTable("Tournaments"); builder.Entity<Tournament>().HasKey(p => p.Id); builder.Entity<Tournament>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<Tournament>().HasMany(p => p.Participants).WithOne(); /*builder.Entity<Tournament>().HasData ( new Tournament {Id = 1, PublicationId = 1}, new Tournament {Id = 2, PublicationId = 2}, new Tournament {Id = 3, PublicationId = 3} );*/ //Participants builder.Entity<Participant>().ToTable("Participants"); builder.Entity<Participant>().HasKey(p => p.Id); builder.Entity<Participant>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<Participant>().Property(p => p.TournamentId).IsRequired(); builder.Entity<Participant>().Property(p => p.UserId).IsRequired(); /*builder.Entity<Participant>().HasData ( new Participant {Id = 1, TournamentId = 1, Points = 12, UserId = 1}, new Participant {Id = 2, TournamentId = 1, Points = 24, UserId = 2}, new Participant {Id = 3, TournamentId = 2, Points = 2, UserId = 3} );*/ builder.UseSnakeCaseNamingConvention(); } } }<file_sep>namespace GamingWorld.API.Profiles.Domain.Models { public class StreamerSponsor { public int Id { get; set; } public string Name { get; set; } // Relations public int ProfileId { get; set; } } }<file_sep>using System; using System.Threading.Tasks; using GamingWorld.API.Shared.Inbound.News.Domain.Services; using Microsoft.AspNetCore.Mvc; namespace GamingWorld.API.Shared.Inbound.News.Controllers { [ApiController] [Route("/api/v1/[controller]")] public class NewsController : ControllerBase { private readonly INewsService _newsService; public NewsController(INewsService newsService) { _newsService = newsService; } [HttpGet] public async Task<String> GetRandomListAsync(string theme) { return await _newsService.ListByTheme(theme); } } }<file_sep>using AutoMapper; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Profiles.Resources; using Profile = GamingWorld.API.Profiles.Domain.Models.Profile; namespace GamingWorld.API.Profiles.Mapping { public class ResourceToModelProfile : AutoMapper.Profile { public ResourceToModelProfile() { CreateMap<SaveProfileResource, Profile>() .ForMember(target => target.GamingLevel, options => options.MapFrom(source => (EGamingLevel) source.GamingLevel)); } } }<file_sep>using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Shared.Domain.Services.Communication; namespace GamingWorld.API.Publications.Domain.Services.Communication { public class PublicationResponse : BaseResponse<Publication> { public PublicationResponse(string message) : base(message) { } public PublicationResponse(Publication publication) : base(publication) { } } }<file_sep>using System.Threading.Tasks; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Models; namespace GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Repositories { public interface IExternalAPIRepository { Task AddAsync(ExternalAPI externalApi); Task<ExternalAPI> FindByNameAsync(string name); void Update(ExternalAPI externalApi); void Remove(ExternalAPI externalApi); } }<file_sep>using GamingWorld.API.Business.Resources; namespace GamingWorld.API.Publications.Resources { public class PublicationResource { public int Id { get; set; } public short PublicationType { get; set; } public string Title { get; set; } public string Content { get; set; } /*public int ParticipantLimit { get; set; }*/ /*public int PrizePool { get; set; } public int TournamentId { get; set; } public string TournamentDate { get; set; } public string TournamentHour { get; set; }*/ public string UrlToImage { get; set; } public string CreatedAt { get; set; } /*public int TournamentId { get; set; }*/ public TournamentResource Tournament { get; set; } //Relationships public int GameId { get; set; } public int UserId { get; set; } } }<file_sep>using System.Collections.Generic; using GamingWorld.API.Security.Domain.Models; namespace GamingWorld.API.Profiles.Domain.Models { public class Profile { public int Id { get; set; } public int UserId { get; set; } public EGamingLevel GamingLevel { get; set; } public bool IsStreamer { get; set; } public User User { get; set; } public IEnumerable<GameExperience> GameExperiences { get; set; } = new List<GameExperience>(); public IEnumerable<StreamingCategory> StreamingCategories { get; set; } = new List<StreamingCategory>(); public IEnumerable<StreamerSponsor> StreamerSponsors { get; set; } = new List<StreamerSponsor>(); public IEnumerable<TournamentExperience> TournamentExperiences { get; set; } = new List<TournamentExperience>(); public IEnumerable<FavoriteGame> FavoriteGames { get; set; } = new List<FavoriteGame>(); } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Services; using GamingWorld.API.Business.Resources; using GamingWorld.API.Business.Services; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Domain.Services; using GamingWorld.API.Publications.Resources; using GamingWorld.API.Shared.Extensions; using Microsoft.AspNetCore.Mvc; namespace GamingWorld.API.Publications.Controllers { [ApiController] [Route("/api/v1/[controller]")] public class PublicationsController : ControllerBase { private readonly IPublicationService _publicationService; private readonly ITournamentService _tournamentService; private readonly IMapper _mapper; public PublicationsController(IPublicationService publicationService, IMapper mapper, ITournamentService tournamentService) { _publicationService = publicationService; _mapper = mapper; _tournamentService = tournamentService; } [HttpGet] public async Task<IEnumerable<PublicationResource>> GetAllAsync([FromQuery] int ?publicationType) { if (publicationType != null) { var publications = await _publicationService.ListByTypeAsync((int)publicationType); var resources = _mapper.Map<IEnumerable<Publication>, IEnumerable<PublicationResource>>(publications); return resources; } else { var publications = await _publicationService.ListAsync(); var resources = _mapper.Map<IEnumerable<Publication>, IEnumerable<PublicationResource>>(publications); return resources; } } [HttpGet("{id}")] public async Task<PublicationResource> GetById(int id) { var publication = await _publicationService.GetById(id); var resource = _mapper.Map<Publication, PublicationResource>(publication); return resource; } [HttpPost] public async Task<IActionResult> PostAsync([FromBody] SavePublicationResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var publicationResult = await _publicationService.SaveAsync(resource); if (!publicationResult.Success) return BadRequest(publicationResult.Message); var publicationResource = _mapper.Map<Publication, PublicationResource>(publicationResult.Resource); return Ok(publicationResource); } [HttpPut("{id}")] public async Task<IActionResult> PutAsync(int id, [FromBody] SavePublicationResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var publication = _mapper.Map<SavePublicationResource, Publication>(resource); var result = await _publicationService.UpdateAsync(id, publication); if (!result.Success) return BadRequest(result.Message); var publicationResource = _mapper.Map<Publication, PublicationResource>(result.Resource); return Ok(publicationResource); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteAsync(int id) { var result = await _publicationService.DeleteAsync(id); if (!result.Success) return BadRequest(result.Message); var categoryResource = _mapper.Map<Publication, PublicationResource>(result.Resource); return Ok(categoryResource); } } }<file_sep>using AutoMapper; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Resources; namespace GamingWorld.API.Publications.Mapping { public class ResourceToModelProfile : Profile { public ResourceToModelProfile() { CreateMap<SavePublicationResource, Publication>(); } } }<file_sep>using AutoMapper; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Profiles.Resources; using GamingWorld.API.Shared.Extensions; using Profile = GamingWorld.API.Profiles.Domain.Models.Profile; namespace GamingWorld.API.Profiles.Mapping { public class ModelToResourceProfile : AutoMapper.Profile { public ModelToResourceProfile() { CreateMap<Profile, ProfileResource>() .ForMember( target => target.GamingLevel, options => options.MapFrom(source => source.GamingLevel.ToDescriptionString())); } } }<file_sep>using System; using System.Threading.Tasks; namespace GamingWorld.API.Shared.Inbound.News.Domain.Services { public interface INewsService { Task<String> ListByTheme(string theme); } }<file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using GamingWorld.API.Profiles.Domain.Models; namespace GamingWorld.API.Business.Resources { public class SaveParticipantResource { [Required] public int UserId { get; set; } public int Points { get; set; } } }<file_sep>using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Shared.Domain.Services.Communication; namespace GamingWorld.API.Profiles.Domain.Services.Communication { public class ProfileResponse : BaseResponse<Profile> { public ProfileResponse(string message) : base(message) { } public ProfileResponse(Profile profile) : base(profile) { } } }<file_sep>using System.ComponentModel; namespace GamingWorld.API.Profiles.Domain.Models { public enum EGameExperienceTime: short { [Description("Days")] D = 1, [Description("Months")] M = 2, [Description("Years")] Y = 3, } }<file_sep>using System.Collections.Generic; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Security.Domain.Models; using GamingWorld.API.Security.Resources; namespace GamingWorld.API.Profiles.Resources { public class ProfileResource { public int Id { get; set; } public int UserId { get; set; } public string GamingLevel { get; set; } public bool IsStreamer { get; set; } // Relations public IEnumerable<GameExperience> GameExperiences { get; set; } = new List<GameExperience>(); public IEnumerable<StreamingCategory> StreamingCategories { get; set; } = new List<StreamingCategory>(); public IEnumerable<StreamerSponsor> StreamerSponsors { get; set; } = new List<StreamerSponsor>(); public IEnumerable<TournamentExperience> TournamentExperiences { get; set; } = new List<TournamentExperience>(); public IEnumerable<FavoriteGame> FavoriteGames { get; set; } = new List<FavoriteGame>(); } }<file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using GamingWorld.API.Profiles.Domain.Models; namespace GamingWorld.API.Profiles.Resources { public class SaveProfileResource { [Required] [Range(1, 3)] public int GamingLevel { get; set; } [Required] public bool IsStreamer { get; set; } // Relations public IEnumerable<GameExperience> GameExperiences { get; set; } = new List<GameExperience>(); public IEnumerable<StreamingCategory> StreamingCategories { get; set; } = new List<StreamingCategory>(); public IEnumerable<StreamerSponsor> StreamerSponsors { get; set; } = new List<StreamerSponsor>(); public IEnumerable<TournamentExperience> TournamentExperiences { get; set; } = new List<TournamentExperience>(); public IEnumerable<FavoriteGame> FavoriteGames { get; set; } = new List<FavoriteGame>(); } }<file_sep>namespace GamingWorld.API.Security.Authorization.Settings { public class AppSettings { public string Secret {get; set;} } }<file_sep>using System.Linq; using System.Threading.Tasks; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Models; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Repositories; using GamingWorld.API.Shared.Persistence.Contexts; using GamingWorld.API.Shared.Persistence.Repositories; using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Shared.Inbound.ExternalAPIs.Persistence.Repositories { public class ExternalAPIRepository : BaseRepository, IExternalAPIRepository { public ExternalAPIRepository(AppDbContext context) : base(context) { } public async Task AddAsync(ExternalAPI externalApi) { await _context.ExternalApis.AddAsync(externalApi); } public async Task<ExternalAPI> FindByNameAsync(string name) { return await _context.ExternalApis.OrderByDescending(api => api.Expiration).FirstOrDefaultAsync(api => api.Name == name); } public void Update(ExternalAPI externalApi) { _context.Update(externalApi); } public void Remove(ExternalAPI externalApi) { _context.Remove(externalApi); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using System.Web; using GamingWorld.API.Security.Exceptions; using GamingWorld.API.Shared.Domain.Repositories; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Models; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Repositories; using GamingWorld.API.Shared.Inbound.Games.Domain.Models; using GamingWorld.API.Shared.Inbound.Games.Domain.Services; using Microsoft.IdentityModel.Tokens; namespace GamingWorld.API.Shared.Inbound.Games.Services { public class GamesService : IGamesService { private readonly string TWITCH_OAUTH_URL = "https://id.twitch.tv/oauth2/token"; private readonly string TWITCH_CLIENT_ID = "8en9cck6wbdrkinl4i0oahhxf3ali1"; private readonly string TWITCH_CLIENT_SECRET = "<KEY>"; private readonly string TWITCH_GRANT_TYPE = "client_credentials"; private readonly string IGDB_GAMES_ENDPOINT_URL = "https://api.igdb.com/v4/games"; private readonly string TWITCH_TOP_GAMES_ENDPOINT = "https://api.twitch.tv/helix/games/top"; private readonly IExternalAPIRepository _externalApiRepository; private readonly IUnitOfWork _unitOfWork; public GamesService(IExternalAPIRepository externalApiRepository, IUnitOfWork unitOfWork) { _externalApiRepository = externalApiRepository; _unitOfWork = unitOfWork; } public async Task<IEnumerable<Game>> ListRandomAsync(int limit) { var body = "fields name, cover.url; sort date desc; limit " + limit + ";"; var response = await MakeIGDBRequest(body); return JsonSerializer.Deserialize<List<Game>>(response); } public async Task<Game> GetById(int id) { var body = "fields name, cover.url; where id=" + id + ";"; var response = await MakeIGDBRequest(body); var responseObject = JsonSerializer.Deserialize<List<Game>>(response); if (responseObject == null) return null; return responseObject.Count > 0 ? responseObject[0] : null; } public async Task<IEnumerable<Game>> FindByName(string name, int limit) { if (name.IsNullOrEmpty()) throw new AppException("Name must not be empty"); var body = "fields name, cover.url; search \"" + name + "\"; limit " + limit + ";"; var response = await MakeIGDBRequest(body); return JsonSerializer.Deserialize<List<Game>>(response); } public async Task<string> FindTopGames(int limit) { ExternalAPI credentials = await GetIGDBCredentials(); if (credentials.Token.IsNullOrEmpty()) throw new AppException("Internal token error."); using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", credentials.Token); client.DefaultRequestHeaders.Add("Client-ID", TWITCH_CLIENT_ID); var builder = new UriBuilder(TWITCH_TOP_GAMES_ENDPOINT); builder.Port = -1; var query = HttpUtility.ParseQueryString(builder.Query); query["first"] = limit.ToString(); builder.Query = query.ToString(); string requestURL = builder.ToString(); var response = await client.GetAsync(requestURL); return await response.Content.ReadAsStringAsync(); } public async Task<ExternalAPI> GetIGDBCredentials() { var externalAPI = await _externalApiRepository.FindByNameAsync("TWITCH_AUTH"); if (externalAPI == null) { if (!await GetNewIGDBCredentials()) return null; } else if (DateTime.Now.ToFileTimeUtc() >= externalAPI.Expiration.ToFileTimeUtc()) { if (!await GetNewIGDBCredentials()) return null; } return await _externalApiRepository.FindByNameAsync("TWITCH_AUTH"); } public async Task<bool> GetNewIGDBCredentials() { //throw new Exception("HERE"); using var client = new HttpClient(); var data = new StringContent("", Encoding.UTF8, "application/json"); var builder = new UriBuilder(TWITCH_OAUTH_URL); builder.Port = -1; var query = HttpUtility.ParseQueryString(builder.Query); query["client_id"] = TWITCH_CLIENT_ID; query["client_secret"] = TWITCH_CLIENT_SECRET; query["grant_type"] = TWITCH_GRANT_TYPE; builder.Query = query.ToString(); string requestURL = builder.ToString(); var response = await client.PostAsync(requestURL, data); var tokenResponse = JsonSerializer.Deserialize<TwitchOAuthResponse>(await response.Content.ReadAsStringAsync()); if (tokenResponse == null || tokenResponse.access_token == null) return false; var externalAPI = new ExternalAPI(); externalAPI.Name = "TWITCH_AUTH"; externalAPI.Token = tokenResponse.access_token; externalAPI.Expiration = DateTime.Now.AddSeconds(tokenResponse.expires_in).AddDays(-1); await _externalApiRepository.AddAsync(externalAPI); await _unitOfWork.CompleteAsync(); return true; } public async Task<string> MakeIGDBRequest(string content) { ExternalAPI credentials = await GetIGDBCredentials(); if (credentials.Token.IsNullOrEmpty()) throw new AppException("Internal token error."); using var client = new HttpClient(); var data = new StringContent(content, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", credentials.Token); client.DefaultRequestHeaders.Add("Client-ID", TWITCH_CLIENT_ID); var response = await client.PostAsync(IGDB_GAMES_ENDPOINT_URL, data); return await response.Content.ReadAsStringAsync(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Repositories; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Domain.Repositories; using GamingWorld.API.Publications.Domain.Services; using GamingWorld.API.Publications.Domain.Services.Communication; using GamingWorld.API.Publications.Resources; using GamingWorld.API.Security.Exceptions; using IUnitOfWork = GamingWorld.API.Shared.Domain.Repositories.IUnitOfWork; namespace GamingWorld.API.Publications.Services { public class PublicationService : IPublicationService { private readonly IPublicationRepository _publicationRepository; private readonly ITournamentRepository _tournamentRepository; private readonly IUnitOfWork _unitOfWork; private readonly IMapper _mapper; public PublicationService(IPublicationRepository publicationRepository,ITournamentRepository tournamentRepository, IUnitOfWork unitOfWork, IMapper mapper) { _tournamentRepository = tournamentRepository; _publicationRepository = publicationRepository; _unitOfWork = unitOfWork; _mapper = mapper; } public async Task<IEnumerable<Publication>> ListAsync() { return await _publicationRepository.ListAsync(); } public async Task<IEnumerable<Publication>> ListByTypeAsync(int type) { var publications = await _publicationRepository.ListAsync(); var filter = publications.Where(c => c.PublicationType == type).ToArray(); return filter; } public async Task<Publication> GetById(int id) { return await _publicationRepository.FindByIdAsync(id); } public async Task<PublicationResponse> SaveAsync(SavePublicationResource publicationResource) { var publication = _mapper.Map<SavePublicationResource, Publication>(publicationResource); try { await _publicationRepository.AddAsync(publication); await _unitOfWork.CompleteAsync(); if (publication.PublicationType == 3) { Tournament tournament = new Tournament(); tournament.ParticipantLimit = publicationResource.ParticipantLimit; tournament.TournamentDate = publicationResource.TournamentDate; tournament.TournamentHour = publicationResource.TournamentHour; tournament.PrizePool = publicationResource.PrizePool; tournament.TournamentStatus = true; tournament.Publication = publication; await _tournamentRepository.AddAsync(tournament); await _unitOfWork.CompleteAsync(); publication.TournamentId = tournament.Id; publication.Tournament = tournament; } _publicationRepository.Update(publication); await _unitOfWork.CompleteAsync(); return new PublicationResponse(publication); } catch (Exception e) { return new PublicationResponse($"An error occured while saving the publication: {e.Message}"); } } public async Task<PublicationResponse> UpdateAsync(int id, Publication publication) { var existingPublication = await _publicationRepository.FindByIdAsync(id); if (existingPublication == null) return new PublicationResponse("Publication Not Found"); existingPublication.Title = publication.Title; try { _publicationRepository.Update(existingPublication); await _unitOfWork.CompleteAsync(); return new PublicationResponse(existingPublication); } catch (Exception e) { return new PublicationResponse($"An error occurred while updating the publication: {e.Message}"); } } public async Task<PublicationResponse> DeleteAsync(int id) { var existingPublication = await _publicationRepository.FindByIdAsync(id); if (existingPublication == null) return new PublicationResponse("Publication not found"); try { _publicationRepository.Remove(existingPublication); await _unitOfWork.CompleteAsync(); return new PublicationResponse(existingPublication); } catch (Exception e) { return new PublicationResponse($"An error occurred while deleting publication:{e.Message}"); } } } }<file_sep>namespace GamingWorld.API.Profiles.Domain.Models { public class GameExperience { public int Id { get; set; } public string GameName { get; set; } public int Time { get; set; } public EGameExperienceTime TimeUnit { get; set; } // Relations public int ProfileId { get; set; } //public Profile Profile { get; set; } } }<file_sep>using AutoMapper; using GamingWorld.API.Security.Domain.Models; using GamingWorld.API.Security.Domain.Services.Communication; using GamingWorld.API.Security.Resources; namespace GamingWorld.API.Security.Mapping { public class ResourceToModelProfile : Profile { public ResourceToModelProfile() { CreateMap<SaveUserResource, User>(); CreateMap<RegisterRequest, User>(); CreateMap<UpdateRequest, User>() .ForAllMembers(options=>options.Condition( (source, Target, property) => { if (property == null) return false; if(property.GetType() == typeof(string) && string.IsNullOrEmpty((string)property)) return false; return true; })); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Profiles.Domain.Services.Communication; namespace GamingWorld.API.Profiles.Domain.Services { public interface IUProfileService { Task<IEnumerable<Profile>> ListAsync(); Task<Profile> ListByUserIdAsync(int userId); Task<Profile> ListByIdAsync(int id); Task<ProfileResponse> SaveAsync(Profile profile); Task<ProfileResponse> UpdateAsync(int id, Profile profile); Task<ProfileResponse> DeleteAsync(int id); } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Profiles.Domain.Models; namespace GamingWorld.API.Profiles.Domain.Repositories { public interface IProfileRepository { Task<IEnumerable<Profile>> ListAsync(); Task AddAsync(Profile profile); Task<Profile> FindByIdAsync (int id); Task<Profile> FindByUserId(int profileId); void Update(Profile profile); void Remove(Profile profile); } }<file_sep>using AutoMapper; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Resources; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Resources; namespace GamingWorld.API.Business.Mapping { public class ModelToResourceProfile : AutoMapper.Profile { public ModelToResourceProfile() { CreateMap<Tournament, TournamentResource>(); CreateMap<Participant, SaveParticipantResource>(); CreateMap<Participant, ParticipantResource>(); CreateMap<Tournament, SaveTournamentResource>(); } } }<file_sep>using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Shared.Domain.Services.Communication; namespace GamingWorld.API.Business.Domain.Services.Communication { public class TournamentResponse : BaseResponse<Tournament> { public TournamentResponse(string message) : base(message) { } public TournamentResponse(Tournament tournament) : base(tournament) { } } }<file_sep>namespace GamingWorld.API.Shared.Inbound.Games.Domain.Models { public class Game { // NOT FOLLOWING THE NAMING CONVENTION BECAUSE WE NEED TO MAP EXACT FIELD NAMES FROM OBJECT RESPONSE FROM IGDB. public int id { get; set; } public string name { get; set; } public GameCover cover { get; set; } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using GamingWorld.API.Business.Domain.Models; using GamingWorld.API.Business.Domain.Services; using GamingWorld.API.Business.Resources; using GamingWorld.API.Publications.Domain.Models; using GamingWorld.API.Publications.Resources; using GamingWorld.API.Shared.Extensions; using Microsoft.AspNetCore.Mvc; namespace GamingWorld.API.Business.Controllers { [ApiController] [Route("/api/v1/[controller]")] public class TournamentsController : ControllerBase { private readonly ITournamentService _tournamentService; private readonly IParticipantService _participantService; private readonly IMapper _mapper; public TournamentsController(IMapper mapper, ITournamentService tournamentService, IParticipantService participantService) { _mapper = mapper; _tournamentService = tournamentService; _participantService = participantService; } [HttpGet] public async Task<IEnumerable<TournamentResource>> GetAllAsync() { var publications = await _tournamentService.ListAsync(); var resources = _mapper.Map<IEnumerable<Tournament>, IEnumerable<TournamentResource>>(publications); return resources; } [HttpGet("{id}")] public async Task<TournamentResource> GetByIdAsync(int id) { var tournament = await _tournamentService.GetById(id); var resource = _mapper.Map<Tournament, TournamentResource>(tournament); return resource; } [HttpGet("{id}/participants")] public async Task<IEnumerable<ParticipantResource>> GetAllParticipantsByTournamentIdAsync(int id) { var tournament = await _tournamentService.ListWithParticipantsByIdAsync(id); var resources = _mapper.Map<IEnumerable<Participant>, IEnumerable<ParticipantResource>>(tournament.Participants); return resources; } [HttpPost] public async Task<IActionResult> PostAsync([FromBody] SaveTournamentResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var publication = _mapper.Map<SaveTournamentResource, Tournament>(resource); var result = await _tournamentService.SaveAsync(publication); if (!result.Success) return BadRequest(result.Message); var publicationResource = _mapper.Map<Tournament, SaveTournamentResource>(result.Resource); return Ok(publicationResource); } [HttpPost( "{id}/participants")] public async Task<IActionResult> PostParticipantAsync([FromBody] SaveParticipantResource resource, int id) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var participant = _mapper.Map<SaveParticipantResource, Participant>(resource); var result = await _participantService.SaveAsync(id, participant); if (!result.Success) return BadRequest(result.Message); var participantResource = _mapper.Map<Participant, ParticipantResource>(result.Resource); return Ok(participantResource); } [HttpPut("{id}/participants/{participantId}")] public async Task<IActionResult> PutAsync(int id,int participantId, [FromQuery] int points) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var result = await _tournamentService.UpdateParticipantPoints(id,participantId, points); if (!result.Success) return BadRequest(result.Message); var profileResource = _mapper.Map<Participant, ParticipantResource>(result.Resource); return Ok(profileResource); } [HttpPut("{id}")] public async Task<IActionResult> PutAsync([FromQuery] bool tournamentStatus, int id) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var result = await _tournamentService.EndTournament(id, tournamentStatus); if (!result.Success) return BadRequest(result.Message); var tournamentResource = _mapper.Map<Tournament, TournamentResource>(result.Resource); return Ok(tournamentResource); } } }<file_sep>using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Shared.Inbound.ExternalAPIs.Domain.Models; using GamingWorld.API.Shared.Inbound.Games.Domain.Models; namespace GamingWorld.API.Shared.Inbound.Games.Domain.Services { public interface IGamesService { Task<IEnumerable<Game>> ListRandomAsync(int limit); Task<Game> GetById(int id); Task<IEnumerable<Game>> FindByName(string name, int limit); Task<string> FindTopGames(int limit); Task<ExternalAPI> GetIGDBCredentials(); Task<bool> GetNewIGDBCredentials(); Task<string> MakeIGDBRequest(string content); } }<file_sep>using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Shared.Extensions { public static class ModelBuilderExtensions { public static void UseSnakeCaseNamingConvention(this ModelBuilder builder) { //Apply Naming Convention for Each Entity foreach (var entity in builder.Model.GetEntityTypes()) { entity.SetTableName(StringExtensions.ToSnakeCase(entity.GetTableName())); foreach (var property in entity.GetProperties()) property.SetColumnName(StringExtensions.ToSnakeCase(property.GetColumnName())); foreach (var key in entity.GetKeys()) key.SetName(StringExtensions.ToSnakeCase(key.GetName())); foreach (var foreignKey in entity.GetForeignKeys()) foreignKey.SetConstraintName(StringExtensions.ToSnakeCase(foreignKey.GetConstraintName())); foreach (var index in entity.GetIndexes()) index.SetDatabaseName(StringExtensions.ToSnakeCase(index.GetDatabaseName())); } } } }<file_sep>using GamingWorld.API.Security.Domain.Models; namespace GamingWorld.API.Security.Authorization.Handlers.Interfaces { public interface IJwtHandler { public string GenerateToken(User user); public int? ValidateToken(string token); } }<file_sep>namespace GamingWorld.API.Shared.Inbound.Games.Domain.Models { public class TwitchOAuthResponse { // NOT FOLLOWING THE NAMING CONVENTION BECAUSE WE NEED TO MAP EXACT FIELD NAMES FROM OBJECT RESPONSE FROM TWITCH OAUTH. public string access_token { get; set; } public long expires_in { get; set; } public string token_type { get; set; } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using GamingWorld.API.Profiles.Domain.Models; using GamingWorld.API.Profiles.Domain.Repositories; using GamingWorld.API.Shared.Persistence.Contexts; using GamingWorld.API.Shared.Persistence.Repositories; using Microsoft.EntityFrameworkCore; namespace GamingWorld.API.Profiles.Persistence.Repositories { public class ProfileRepository : BaseRepository, IProfileRepository { public ProfileRepository(AppDbContext context) : base(context) { } public async Task<IEnumerable<Profile>> ListAsync() { // return await _context.Profiles.Include(up => up.User).ToListAsync(); // Pending to check if we really need the full user info when retrieving profiles. return await _context.Profiles .Include(up => up.GameExperiences) .Include(up => up.StreamingCategories) .Include(up => up.StreamerSponsors) .Include(up => up.TournamentExperiences) .Include(up => up.FavoriteGames) .Include(up => up.User) .ToListAsync(); } public async Task AddAsync(Profile profile) { await _context.Profiles.AddAsync(profile); } public async Task<Profile> FindByIdAsync(int id) { // return await _context.Profiles.Include(up => up.User).FirstOrDefaultAsync(up => up.Id == id); // Pending to check if we really need the full user info when retrieving profiles. return await _context.Profiles .Include(up => up.GameExperiences) .Include(up => up.StreamingCategories) .Include(up => up.StreamerSponsors) .Include(up => up.TournamentExperiences) .Include(up => up.FavoriteGames) .FirstOrDefaultAsync(up => up.Id == id); } public async Task<Profile> FindByUserId(int userId) { //return await _context.Profiles.Include(up => up.User).FirstOrDefaultAsync(up => up.UserId == userId); // Pending to check if we really need the full user info when retrieving profiles. return await _context.Profiles .Include(up => up.GameExperiences) .Include(up => up.StreamingCategories) .Include(up => up.StreamerSponsors) .Include(up => up.TournamentExperiences) .Include(up => up.FavoriteGames) .FirstOrDefaultAsync(up => up.UserId == userId); } public void Update(Profile profile) { _context.Profiles.Update(profile); } public void Remove(Profile profile) { _context.Profiles.Remove(profile); } } }
100546a07b285309f6817de258ff4021889d459d
[ "C#" ]
76
C#
maxwellpv/gamingworldbackend
6d101c73f7afcf3b6c1bfbca9abb75c0ad0f2c3e
ff467eeb1b77f917f198349d57ce252d37987e8c
refs/heads/master
<repo_name>jebroberts2/Test-Driven-Katas<file_sep>/wrap.js function wrap(string, number) { let splitArray = []; let remainingString = string; while (remainingString.length > number) { let backwardsCounter = number; while (remainingString[backwardsCounter] !== " ") { backwardsCounter--; } splitArray.push(remainingString.slice(0, backwardsCounter + 1)); // console.log(splitArray); // console.log("remaining string before slice:", remainingString); remainingString = remainingString.slice(backwardsCounter + 1); // console.log("remaining string after slice:", remainingString); } splitArray.push(remainingString); return splitArray.join("\n"); } // console.log(wrap("kirsten likes dogs", 10)); module.exports = wrap; // we have a string. we do our while loop, then we push the first section of our string // into the split array, and we keep doing that until there is no more string left
397b7041c57cc6aa9768e84c896ef42032ef0c0d
[ "JavaScript" ]
1
JavaScript
jebroberts2/Test-Driven-Katas
c323594a082015aaaff82474cfd88a74a8d4cc98
ea4f4a6afb8295930920e9910db3c3175bd73ea2
refs/heads/master
<repo_name>jimmyangarita/newGitTest<file_sep>/auction/common/xml/xml-discover/target/jaxws/wsimport/java/com/jdap/auction/common/xml/discover/JobPayload.java package com.jdap.auction.common.xml.discover; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for JobPayload complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="JobPayload"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TaskIdEBO" type="{http://xmlns.dcim.emerson.com/cps/scheduler/ebo}TaskIdEBOType"/> * &lt;element name="TaskActionIdEBO" type="{http://xmlns.dcim.emerson.com/cps/scheduler/ebo}TaskActionIdEBOType"/> * &lt;element name="TaskActionParameters" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/> * &lt;element name="JobStatusEBOType" type="{http://xmlns.dcim.emerson.com/cps/scheduler/ebo}StatusEBOType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "JobPayload", namespace = "http://xmlns.dcim.emerson.com/cps/scheduler/quartz-scheduler/ebo", propOrder = { "taskIdEBO", "taskActionIdEBO", "taskActionParameters", "jobStatusEBOType" }) @XmlSeeAlso({ ResumeTaskRequestEBM.class }) public class JobPayload { @XmlElement(name = "TaskIdEBO", required = true) protected TaskIdEBOType taskIdEBO; @XmlElement(name = "TaskActionIdEBO", required = true) protected TaskActionIdEBOType taskActionIdEBO; @XmlElement(name = "TaskActionParameters", required = true) protected byte[] taskActionParameters; @XmlElement(name = "JobStatusEBOType", required = true) protected StatusEBOType jobStatusEBOType; /** * Gets the value of the taskIdEBO property. * * @return * possible object is * {@link TaskIdEBOType } * */ public TaskIdEBOType getTaskIdEBO() { return taskIdEBO; } /** * Sets the value of the taskIdEBO property. * * @param value * allowed object is * {@link TaskIdEBOType } * */ public void setTaskIdEBO(TaskIdEBOType value) { this.taskIdEBO = value; } /** * Gets the value of the taskActionIdEBO property. * * @return * possible object is * {@link TaskActionIdEBOType } * */ public TaskActionIdEBOType getTaskActionIdEBO() { return taskActionIdEBO; } /** * Sets the value of the taskActionIdEBO property. * * @param value * allowed object is * {@link TaskActionIdEBOType } * */ public void setTaskActionIdEBO(TaskActionIdEBOType value) { this.taskActionIdEBO = value; } /** * Gets the value of the taskActionParameters property. * * @return * possible object is * byte[] */ public byte[] getTaskActionParameters() { return taskActionParameters; } /** * Sets the value of the taskActionParameters property. * * @param value * allowed object is * byte[] */ public void setTaskActionParameters(byte[] value) { this.taskActionParameters = ((byte[]) value); } /** * Gets the value of the jobStatusEBOType property. * * @return * possible object is * {@link StatusEBOType } * */ public StatusEBOType getJobStatusEBOType() { return jobStatusEBOType; } /** * Sets the value of the jobStatusEBOType property. * * @param value * allowed object is * {@link StatusEBOType } * */ public void setJobStatusEBOType(StatusEBOType value) { this.jobStatusEBOType = value; } } <file_sep>/auction/sql/Categoryes with-out Items.sql select * from category ca where (select count(*) from item_category ic , item it where ic.itemid = it.oid and ic.categoryid = ca.oid) = 0 order by ca.name; select ca.* from category ca, item_category ic where ca.oid = ic.categoryid (+) minus select ca.* from category ca, item_category ic where ca.oid = ic.categoryid; select ca.* from category ca, item_category ic, item it where ic.itemid = it.oid and ic.categoryid = ca.oid; select b.* from bid b where b.itemid = 'b9e3330a-4339-44cc-aba8-761995890423'; @NamedQuery(name = "Bids.getHighBids", query = "Select bid from Bid bid where bid.bidAmount > :amount") <file_sep>/auction/domain-module/model/pom.xml <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> <parent> <artifactId>auction-domain</artifactId> <groupId>com.jdap.auction.domain-model</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>com.jdap.auction.domain-model</groupId> <artifactId>auction-domain-model</artifactId> <version>0.0.1-SNAPSHOT</version> <pluginRepositories> <pluginRepository> <id>maven-annotation-plugin</id> <url>http://maven-annotation-plugin.googlecode.com/svn/trunk/mavenrepo</url> </pluginRepository> </pluginRepositories> <dependencies> <dependency> <groupId>javaee</groupId> <artifactId>javaee-api</artifactId> <version>5</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>${javax.persistence.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>${eclipselink.version}</version> <classifier>${eclipselink.classifier}</classifier> <scope>provided</scope> </dependency> <!-- <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>2.5.0</version> </dependency> --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-dao</artifactId> <version>2.0.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.3.RELEASE</version> </dependency> <!-- <dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.core</artifactId> <version>${spring.version}</version> <scope>provided</scope> <exclusions> <exclusion> <groupId>org.apache.commons</groupId> <artifactId>com.springsource.org.apache.commons.logging</artifactId> </exclusion> </exclusions> </dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.beans</artifactId> <version>${spring.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.context</artifactId> <version>${spring.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.aop</artifactId> <version>${spring.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.oxm</artifactId> <version>${spring.version}</version> </dependency> --> <dependency> <groupId>com.jdap.auction.domain-model</groupId> <artifactId>auction-domain-model-pu</artifactId> <version>${project.version}</version> <type>jar</type> </dependency> <dependency> <groupId>com.jdap.auction</groupId> <artifactId>auction-exceptions</artifactId> <version>${project.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>1.0</version> </dependency> </dependencies> </project><file_sep>/auction/sql/Worksheet 5.sql select * from item where oid ='b9e3330a-4339-44cc-aba8-761995890423'; describe item; select * from category; select * from item_category; select * from bid; select * from users; select * from bid where itemid = 'b9e3330a-4339-44cc-aba8-761995890423' order by biddate desc; select * from users; <file_sep>/auction/wlst/jmsmodule.py """ This script starts an edit session, creates a JMS Servers, targets the jms servers to the ADF server Creates a jms topics, two jms queues and two connections factories. The ms queues and topics are targeted using sub-deployments. """ import sys from java.lang import System print "Starting the script ..." connect('weblogic','Passw0rd','t3://localhost:7001') edit() startEdit() servermb=getMBean("Servers/AdminServer") if servermb is None: print 'Value is Null' else: jMSServer1mb = create('TESTJMSServer','JMSServer') jMSServer1mb.addTarget(servermb) jmsMySystemResource = create("TESTJMSSystemModule","JMSSystemResource") jmsMySystemResource.addTarget(servermb) subDep1mb = jmsMySystemResource.createSubDeployment('TESTJMSSystemModuleSub') subDep1mb.addTarget(jMSServer1mb) theJMSResource = jmsMySystemResource.getJMSResource() connfact1 = theJMSResource.createConnectionFactory('ApiFaultQueueConnectionFactory') connfact1.setJNDIName('jms.ApiFaultQueueConnectionFactory') connfact1.setSubDeploymentName('TESTJMSSystemModuleSub') connfact1.transactionParams.setXAConnectionFactoryEnabled(1) jmsqueue1 = theJMSResource.createQueue('ApiFaultQueue') jmsqueue1.setJNDIName('jms.ApiFaultQueue') jmsqueue1.setSubDeploymentName('TESTJMSSystemModuleSub') connfact2 = theJMSResource.createConnectionFactory('OrderBillingQueueConnectionFactory') connfact2.setJNDIName('jms.OrderBillingQueueConnectionFactory') connfact2.setSubDeploymentName('TESTJMSSystemModuleSub') connfact2.transactionParams.setXAConnectionFactoryEnabled(1) jmsqueue2 = theJMSResource.createQueue('OrderBillingQueue') jmsqueue2.setJNDIName('jms.OrderBillingQueue') jmsqueue2.setSubDeploymentName('TESTJMSSystemModuleSub') try: save() activate(block="true") print "script returns SUCCESS" except: print "Error while trying to save and/or activate!!!" dumpStack()<file_sep>/auction/domain-module/model/src/main/java/com/jdap/auction/model/Category.java package com.jdap.auction.model; //~--- non-JDK imports --------------------------------------------------------- import com.jdap.auction.patterns.persistence.AbstractPersistentObject; //~--- JDK imports ------------------------------------------------------------- import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; /** * Class description * * * @version 9.0, 2013.February.27 11:39 AM * @author JDAP Corporation */ @Entity @NamedQueries( { @NamedQuery( name = "category.getRootCategories", query = "SELECT c FROM Category c where c.parentCategory is null" ) , @NamedQuery( name = "category.getCategoriesByParent", query = "SELECT c FROM Category c where c.parentCategory = :parentcategory" ) } ) public class Category extends AbstractPersistentObject { /** Field description */ private String name; /** Field description */ private String description; /** Field description */ @ManyToMany( mappedBy = "categories", cascade = CascadeType.REMOVE ) private List<Item> items; /* * @JoinTable( * name = "category_items", * joinColumns = @JoinColumn( name = "categoryid", * referencedColumnName = "oid" ) , * inverseJoinColumns = @JoinColumn( name = "itemid", * referencedColumnName = "oid" ) * ) */ /** Field description */ @ManyToMany( mappedBy = "categories" ) private List<User> users; /** Field description */ @ManyToOne( cascade = CascadeType.ALL ) @JoinColumn( name = "parentCategoryid", referencedColumnName = "oid" ) private Category parentCategory; /** Field description */ @OneToMany( mappedBy = "parentCategory", cascade = CascadeType.ALL ) private List<Category> subCategories; /** * Constructs ... * */ public Category() { //String id = parentCategory.getId(); } /** * Method description * * * @return */ public String getName() { return name; } /** * Method description * * * @param name */ public void setName( String name ) { this.name = name; } /** * Method description * * * @return */ public String getDescription() { return description; } /** * Method description * * * @param description */ public void setDescription( String description ) { this.description = description; } /** * Method description * * * @return */ public List<Item> getItems() { if( items == null ) { items = new ArrayList<Item>(); } return items; } /** * Method description * * * @param items * * @return */ /* * public void setItems( List<Item> items ) * { * this.items = items; * } */ /** * Method description * * * @return */ public Category getParentCategory() { return parentCategory; } /** * Method description * * * @param parentCategory */ public void setParentCategory( Category parentCategory ) { this.parentCategory = parentCategory; } /** * Method description * * * @return */ public List<Category> getSubCategories() { if( subCategories == null ) { subCategories = new ArrayList<Category>(); } return this.subCategories; } /** * Method description * * * @param subCategories * * @return */ /* * public void setSubCategories( List<Category> subCategories ) * { * this.subCategories = subCategories; * } */ public List<User> getUsers() { return users; } /** * Method description * * * @param users */ public void setUsers( List<User> users ) { this.users = users; } } <file_sep>/auction/domain-module/model/src/main/java/com/jdap/auction/model/Bid.java package com.jdap.auction.model; // ~--- non-JDK imports --------------------------------------------------------- import com.jdap.auction.patterns.persistence.AbstractPersistentObject; // ~--- JDK imports ------------------------------------------------------------- import java.sql.Timestamp; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; /** * Class description * * * @version 9.0, 2013.February.26 05:07 PM * @author JDAP Corporation */ @Entity // @Table( name = "BIDS" ) @NamedQueries ( {@NamedQuery ( name = "Bids.getHighBids" , query = "Select bid from Bid bid where bid.bidAmount > :amount" ), @NamedQuery ( name = "Bids.getItemBids" , query = "SELECT b FROM Bid b WHERE b.item = :item ORDER BY b.bidAmount ASC" ) } ) public class Bid extends AbstractPersistentObject { /** Field description */ /** Field description */ @ManyToOne ( ) // cascade = CascadeType.PERSIST) has to change not cascade, in the one to many side to delete or update @JoinColumn ( name = "itemid" , referencedColumnName = "oid" ) private Item item; /** Field description */ @ManyToOne ( /* cascade = CascadeType.PERSIST */) // has to change not cascade, MERGE is better @JoinColumn ( name = "bidderid" , referencedColumnName = "oid" ) private Bidder bidder; /** Field description */ private Double bidAmount; /** Field description */ private Double maxAmount; /** Field description */ private Timestamp bidDate; /** * Method description * * * * @param bidID * @return */ /* @Id * @GeneratedValue( strategy = GenerationType.AUTO ) * @Column( name = "BID_ID" ) public Long getBidID() { return bidID; } */ /** * Method description * * * @param bidID */ /* public void setBidID( Long bidID ) { this.bidID = bidID; } */ /** * Method description * * * @return */ // @Column( name = "BID_AMOUNT" ) public Double getBidAmount() { return bidAmount; } /** * Method description * * * @return */ public Item getItem() { return item; } /** * Method description * * * @param item */ public void setItem(Item item) { this.item = item; } /** * Method description * * * @param bidAmount */ public void setBidAmount(Double bidAmount) { this.bidAmount = bidAmount; } public Double getMaxAmount() { return maxAmount; } public void setMaxAmount(Double maxAmount) { this.maxAmount = maxAmount; } /** * Method description * * * @return */ // @Column( name = "BID_DATE" ) public Timestamp getBidDate() { return bidDate; } /** * Method description * * * @param bidDate */ public void setBidDate(Timestamp bidDate) { this.bidDate = bidDate; } /** * Method description * * * @return */ public Bidder getBidder() { return bidder; } /** * Method description * * * @param bidder */ public void setBidder(Bidder bidder) { this.bidder = bidder; } } <file_sep>/Starting Project/Source Code/app/index.ts export {environment} from './environment'; export {ServicesDiAppComponent} from './services-di.component'; <file_sep>/auction/common/xml/xml-user/target/generated-sources/jaxb/com/jdap/auction/common/xml/user/ObjectFactory.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:57 PM EST // package com.jdap.auction.common.xml.user; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.jdap.auction.common.xml.user package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _ProblemIRI_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ProblemIRI"); private final static QName _DeleteSellerRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "DeleteSellerRequestMessage"); private final static QName _EndpointReference_QNAME = new QName("http://www.w3.org/2005/08/addressing", "EndpointReference"); private final static QName _ProblemHeaderQName_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ProblemHeaderQName"); private final static QName _DeleteBidderRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "DeleteBidderRequestMessage"); private final static QName _ReferenceParameters_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ReferenceParameters"); private final static QName _From_QNAME = new QName("http://www.w3.org/2005/08/addressing", "From"); private final static QName _CreateBidderResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "CreateBidderResponseMessage"); private final static QName _ReplyTo_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ReplyTo"); private final static QName _UpdateSellerResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "UpdateSellerResponseMessage"); private final static QName _MessageHeader_QNAME = new QName("http://xmlns.jdap.com/Common/MessageHeader/v2", "MessageHeader"); private final static QName _Action_QNAME = new QName("http://www.w3.org/2005/08/addressing", "Action"); private final static QName _FaultTo_QNAME = new QName("http://www.w3.org/2005/08/addressing", "FaultTo"); private final static QName _QuerySellerRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "QuerySellerRequestMessage"); private final static QName _UpdateBidderRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "UpdateBidderRequestMessage"); private final static QName _UpdateSellerRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "UpdateSellerRequestMessage"); private final static QName _User_QNAME = new QName("http://xmlns.jdap.com/auction/User/Objects/v2", "user"); private final static QName _RetryAfter_QNAME = new QName("http://www.w3.org/2005/08/addressing", "RetryAfter"); private final static QName _CreateBidderRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "CreateBidderRequestMessage"); private final static QName _CreateSellerRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "CreateSellerRequestMessage"); private final static QName _DeleteBidderResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "DeleteBidderResponseMessage"); private final static QName _DeleteSellerResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "DeleteSellerResponseMessage"); private final static QName _To_QNAME = new QName("http://www.w3.org/2005/08/addressing", "To"); private final static QName _Address_QNAME = new QName("http://xmlns.jdap.com/auction/Address/Objects/v2", "address"); private final static QName _Bidder_QNAME = new QName("http://xmlns.jdap.com/auction/Bidder/Objects/v2", "bidder"); private final static QName _ProblemAction_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ProblemAction"); private final static QName _UpdateBidderResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "UpdateBidderResponseMessage"); private final static QName _RelatesTo_QNAME = new QName("http://www.w3.org/2005/08/addressing", "RelatesTo"); private final static QName _Seller_QNAME = new QName("http://xmlns.jdap.com/auction/Seller/Objects/v2", "seller"); private final static QName _QueryBidderResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "QueryBidderResponseMessage"); private final static QName _Metadata_QNAME = new QName("http://www.w3.org/2005/08/addressing", "Metadata"); private final static QName _QuerySellerResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "QuerySellerResponseMessage"); private final static QName _CreateSellerResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "CreateSellerResponseMessage"); private final static QName _MessageID_QNAME = new QName("http://www.w3.org/2005/08/addressing", "MessageID"); private final static QName _QueryBidderRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/User/Messages/v2", "QueryBidderRequestMessage"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.jdap.auction.common.xml.user * */ public ObjectFactory() { } /** * Create an instance of {@link DeleteBidderRequestMessageType } * */ public DeleteBidderRequestMessageType createDeleteBidderRequestMessageType() { return new DeleteBidderRequestMessageType(); } /** * Create an instance of {@link DeleteSellerResponseMessageType } * */ public DeleteSellerResponseMessageType createDeleteSellerResponseMessageType() { return new DeleteSellerResponseMessageType(); } /** * Create an instance of {@link CreateSellerRequestMessageType } * */ public CreateSellerRequestMessageType createCreateSellerRequestMessageType() { return new CreateSellerRequestMessageType(); } /** * Create an instance of {@link CreateBidderRequestMessageType } * */ public CreateBidderRequestMessageType createCreateBidderRequestMessageType() { return new CreateBidderRequestMessageType(); } /** * Create an instance of {@link DeleteBidderResponseMessageType } * */ public DeleteBidderResponseMessageType createDeleteBidderResponseMessageType() { return new DeleteBidderResponseMessageType(); } /** * Create an instance of {@link DeleteSellerRequestMessageType } * */ public DeleteSellerRequestMessageType createDeleteSellerRequestMessageType() { return new DeleteSellerRequestMessageType(); } /** * Create an instance of {@link UpdateSellerRequestMessageType } * */ public UpdateSellerRequestMessageType createUpdateSellerRequestMessageType() { return new UpdateSellerRequestMessageType(); } /** * Create an instance of {@link QueryBidderRequestMessageType } * */ public QueryBidderRequestMessageType createQueryBidderRequestMessageType() { return new QueryBidderRequestMessageType(); } /** * Create an instance of {@link QuerySellerRequestMessageType } * */ public QuerySellerRequestMessageType createQuerySellerRequestMessageType() { return new QuerySellerRequestMessageType(); } /** * Create an instance of {@link UpdateBidderRequestMessageType } * */ public UpdateBidderRequestMessageType createUpdateBidderRequestMessageType() { return new UpdateBidderRequestMessageType(); } /** * Create an instance of {@link CreateSellerResponseMessageType } * */ public CreateSellerResponseMessageType createCreateSellerResponseMessageType() { return new CreateSellerResponseMessageType(); } /** * Create an instance of {@link QuerySellerResponseMessageType } * */ public QuerySellerResponseMessageType createQuerySellerResponseMessageType() { return new QuerySellerResponseMessageType(); } /** * Create an instance of {@link UpdateSellerResponseMessageType } * */ public UpdateSellerResponseMessageType createUpdateSellerResponseMessageType() { return new UpdateSellerResponseMessageType(); } /** * Create an instance of {@link QueryBidderResponseMessageType } * */ public QueryBidderResponseMessageType createQueryBidderResponseMessageType() { return new QueryBidderResponseMessageType(); } /** * Create an instance of {@link CreateBidderResponseMessageType } * */ public CreateBidderResponseMessageType createCreateBidderResponseMessageType() { return new CreateBidderResponseMessageType(); } /** * Create an instance of {@link UpdateBidderResponseMessageType } * */ public UpdateBidderResponseMessageType createUpdateBidderResponseMessageType() { return new UpdateBidderResponseMessageType(); } /** * Create an instance of {@link ListOfValuesType } * */ public ListOfValuesType createListOfValuesType() { return new ListOfValuesType(); } /** * Create an instance of {@link CategoryType } * */ public CategoryType createCategoryType() { return new CategoryType(); } /** * Create an instance of {@link UserIDType } * */ public UserIDType createUserIDType() { return new UserIDType(); } /** * Create an instance of {@link ValueHolderType } * */ public ValueHolderType createValueHolderType() { return new ValueHolderType(); } /** * Create an instance of {@link NameValuePairDataType } * */ public NameValuePairDataType createNameValuePairDataType() { return new NameValuePairDataType(); } /** * Create an instance of {@link RangeOfDatesType } * */ public RangeOfDatesType createRangeOfDatesType() { return new RangeOfDatesType(); } /** * Create an instance of {@link ExtensionUserType } * */ public ExtensionUserType createExtensionUserType() { return new ExtensionUserType(); } /** * Create an instance of {@link AddressType } * */ public AddressType createAddressType() { return new AddressType(); } /** * Create an instance of {@link ExtensionAddressType } * */ public ExtensionAddressType createExtensionAddressType() { return new ExtensionAddressType(); } /** * Create an instance of {@link SellerType } * */ public SellerType createSellerType() { return new SellerType(); } /** * Create an instance of {@link ExtensionSellerType } * */ public ExtensionSellerType createExtensionSellerType() { return new ExtensionSellerType(); } /** * Create an instance of {@link BidderType } * */ public BidderType createBidderType() { return new BidderType(); } /** * Create an instance of {@link ExtensionBidderType } * */ public ExtensionBidderType createExtensionBidderType() { return new ExtensionBidderType(); } /** * Create an instance of {@link MessageHeaderType } * */ public MessageHeaderType createMessageHeaderType() { return new MessageHeaderType(); } /** * Create an instance of {@link SenderType } * */ public SenderType createSenderType() { return new SenderType(); } /** * Create an instance of {@link WSAddressType } * */ public WSAddressType createWSAddressType() { return new WSAddressType(); } /** * Create an instance of {@link NameValuePairType } * */ public NameValuePairType createNameValuePairType() { return new NameValuePairType(); } /** * Create an instance of {@link ProblemActionType } * */ public ProblemActionType createProblemActionType() { return new ProblemActionType(); } /** * Create an instance of {@link AttributedURIType } * */ public AttributedURIType createAttributedURIType() { return new AttributedURIType(); } /** * Create an instance of {@link AttributedQNameType } * */ public AttributedQNameType createAttributedQNameType() { return new AttributedQNameType(); } /** * Create an instance of {@link EndpointReferenceType } * */ public EndpointReferenceType createEndpointReferenceType() { return new EndpointReferenceType(); } /** * Create an instance of {@link AttributedUnsignedLongType } * */ public AttributedUnsignedLongType createAttributedUnsignedLongType() { return new AttributedUnsignedLongType(); } /** * Create an instance of {@link MetadataType } * */ public MetadataType createMetadataType() { return new MetadataType(); } /** * Create an instance of {@link ReferenceParametersType } * */ public ReferenceParametersType createReferenceParametersType() { return new ReferenceParametersType(); } /** * Create an instance of {@link RelatesToType } * */ public RelatesToType createRelatesToType() { return new RelatesToType(); } /** * Create an instance of {@link ExtensionMessageHeaderType } * */ public ExtensionMessageHeaderType createExtensionMessageHeaderType() { return new ExtensionMessageHeaderType(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ProblemIRI") public JAXBElement<AttributedURIType> createProblemIRI(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_ProblemIRI_QNAME, AttributedURIType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteSellerRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "DeleteSellerRequestMessage") public JAXBElement<DeleteSellerRequestMessageType> createDeleteSellerRequestMessage(DeleteSellerRequestMessageType value) { return new JAXBElement<DeleteSellerRequestMessageType>(_DeleteSellerRequestMessage_QNAME, DeleteSellerRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "EndpointReference") public JAXBElement<EndpointReferenceType> createEndpointReference(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_EndpointReference_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedQNameType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ProblemHeaderQName") public JAXBElement<AttributedQNameType> createProblemHeaderQName(AttributedQNameType value) { return new JAXBElement<AttributedQNameType>(_ProblemHeaderQName_QNAME, AttributedQNameType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteBidderRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "DeleteBidderRequestMessage") public JAXBElement<DeleteBidderRequestMessageType> createDeleteBidderRequestMessage(DeleteBidderRequestMessageType value) { return new JAXBElement<DeleteBidderRequestMessageType>(_DeleteBidderRequestMessage_QNAME, DeleteBidderRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ReferenceParametersType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ReferenceParameters") public JAXBElement<ReferenceParametersType> createReferenceParameters(ReferenceParametersType value) { return new JAXBElement<ReferenceParametersType>(_ReferenceParameters_QNAME, ReferenceParametersType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "From") public JAXBElement<EndpointReferenceType> createFrom(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_From_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateBidderResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "CreateBidderResponseMessage") public JAXBElement<CreateBidderResponseMessageType> createCreateBidderResponseMessage(CreateBidderResponseMessageType value) { return new JAXBElement<CreateBidderResponseMessageType>(_CreateBidderResponseMessage_QNAME, CreateBidderResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ReplyTo") public JAXBElement<EndpointReferenceType> createReplyTo(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_ReplyTo_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UpdateSellerResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "UpdateSellerResponseMessage") public JAXBElement<UpdateSellerResponseMessageType> createUpdateSellerResponseMessage(UpdateSellerResponseMessageType value) { return new JAXBElement<UpdateSellerResponseMessageType>(_UpdateSellerResponseMessage_QNAME, UpdateSellerResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MessageHeaderType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/Common/MessageHeader/v2", name = "MessageHeader") public JAXBElement<MessageHeaderType> createMessageHeader(MessageHeaderType value) { return new JAXBElement<MessageHeaderType>(_MessageHeader_QNAME, MessageHeaderType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "Action") public JAXBElement<AttributedURIType> createAction(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_Action_QNAME, AttributedURIType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "FaultTo") public JAXBElement<EndpointReferenceType> createFaultTo(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_FaultTo_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QuerySellerRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "QuerySellerRequestMessage") public JAXBElement<QuerySellerRequestMessageType> createQuerySellerRequestMessage(QuerySellerRequestMessageType value) { return new JAXBElement<QuerySellerRequestMessageType>(_QuerySellerRequestMessage_QNAME, QuerySellerRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UpdateBidderRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "UpdateBidderRequestMessage") public JAXBElement<UpdateBidderRequestMessageType> createUpdateBidderRequestMessage(UpdateBidderRequestMessageType value) { return new JAXBElement<UpdateBidderRequestMessageType>(_UpdateBidderRequestMessage_QNAME, UpdateBidderRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UpdateSellerRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "UpdateSellerRequestMessage") public JAXBElement<UpdateSellerRequestMessageType> createUpdateSellerRequestMessage(UpdateSellerRequestMessageType value) { return new JAXBElement<UpdateSellerRequestMessageType>(_UpdateSellerRequestMessage_QNAME, UpdateSellerRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UserType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Objects/v2", name = "user") public JAXBElement<UserType> createUser(UserType value) { return new JAXBElement<UserType>(_User_QNAME, UserType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedUnsignedLongType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "RetryAfter") public JAXBElement<AttributedUnsignedLongType> createRetryAfter(AttributedUnsignedLongType value) { return new JAXBElement<AttributedUnsignedLongType>(_RetryAfter_QNAME, AttributedUnsignedLongType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateBidderRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "CreateBidderRequestMessage") public JAXBElement<CreateBidderRequestMessageType> createCreateBidderRequestMessage(CreateBidderRequestMessageType value) { return new JAXBElement<CreateBidderRequestMessageType>(_CreateBidderRequestMessage_QNAME, CreateBidderRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateSellerRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "CreateSellerRequestMessage") public JAXBElement<CreateSellerRequestMessageType> createCreateSellerRequestMessage(CreateSellerRequestMessageType value) { return new JAXBElement<CreateSellerRequestMessageType>(_CreateSellerRequestMessage_QNAME, CreateSellerRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteBidderResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "DeleteBidderResponseMessage") public JAXBElement<DeleteBidderResponseMessageType> createDeleteBidderResponseMessage(DeleteBidderResponseMessageType value) { return new JAXBElement<DeleteBidderResponseMessageType>(_DeleteBidderResponseMessage_QNAME, DeleteBidderResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteSellerResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "DeleteSellerResponseMessage") public JAXBElement<DeleteSellerResponseMessageType> createDeleteSellerResponseMessage(DeleteSellerResponseMessageType value) { return new JAXBElement<DeleteSellerResponseMessageType>(_DeleteSellerResponseMessage_QNAME, DeleteSellerResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "To") public JAXBElement<AttributedURIType> createTo(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_To_QNAME, AttributedURIType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AddressType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Address/Objects/v2", name = "address") public JAXBElement<AddressType> createAddress(AddressType value) { return new JAXBElement<AddressType>(_Address_QNAME, AddressType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BidderType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bidder/Objects/v2", name = "bidder") public JAXBElement<BidderType> createBidder(BidderType value) { return new JAXBElement<BidderType>(_Bidder_QNAME, BidderType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ProblemActionType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ProblemAction") public JAXBElement<ProblemActionType> createProblemAction(ProblemActionType value) { return new JAXBElement<ProblemActionType>(_ProblemAction_QNAME, ProblemActionType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UpdateBidderResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "UpdateBidderResponseMessage") public JAXBElement<UpdateBidderResponseMessageType> createUpdateBidderResponseMessage(UpdateBidderResponseMessageType value) { return new JAXBElement<UpdateBidderResponseMessageType>(_UpdateBidderResponseMessage_QNAME, UpdateBidderResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RelatesToType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "RelatesTo") public JAXBElement<RelatesToType> createRelatesTo(RelatesToType value) { return new JAXBElement<RelatesToType>(_RelatesTo_QNAME, RelatesToType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SellerType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Seller/Objects/v2", name = "seller") public JAXBElement<SellerType> createSeller(SellerType value) { return new JAXBElement<SellerType>(_Seller_QNAME, SellerType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QueryBidderResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "QueryBidderResponseMessage") public JAXBElement<QueryBidderResponseMessageType> createQueryBidderResponseMessage(QueryBidderResponseMessageType value) { return new JAXBElement<QueryBidderResponseMessageType>(_QueryBidderResponseMessage_QNAME, QueryBidderResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MetadataType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "Metadata") public JAXBElement<MetadataType> createMetadata(MetadataType value) { return new JAXBElement<MetadataType>(_Metadata_QNAME, MetadataType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QuerySellerResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "QuerySellerResponseMessage") public JAXBElement<QuerySellerResponseMessageType> createQuerySellerResponseMessage(QuerySellerResponseMessageType value) { return new JAXBElement<QuerySellerResponseMessageType>(_QuerySellerResponseMessage_QNAME, QuerySellerResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateSellerResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "CreateSellerResponseMessage") public JAXBElement<CreateSellerResponseMessageType> createCreateSellerResponseMessage(CreateSellerResponseMessageType value) { return new JAXBElement<CreateSellerResponseMessageType>(_CreateSellerResponseMessage_QNAME, CreateSellerResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "MessageID") public JAXBElement<AttributedURIType> createMessageID(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_MessageID_QNAME, AttributedURIType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QueryBidderRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/User/Messages/v2", name = "QueryBidderRequestMessage") public JAXBElement<QueryBidderRequestMessageType> createQueryBidderRequestMessage(QueryBidderRequestMessageType value) { return new JAXBElement<QueryBidderRequestMessageType>(_QueryBidderRequestMessage_QNAME, QueryBidderRequestMessageType.class, null, value); } } <file_sep>/auction/common/xml/xml-user/target/generated-sources/jaxb/com/jdap/auction/common/xml/user/LoggingLevelType.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:57 PM EST // package com.jdap.auction.common.xml.user; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for LoggingLevelType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="LoggingLevelType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Fatal"/> * &lt;enumeration value="Error"/> * &lt;enumeration value="Warning"/> * &lt;enumeration value="Notification"/> * &lt;enumeration value="Trace"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "LoggingLevelType", namespace = "http://xmlns.jdap.com/Common/MessageHeader/v2") @XmlEnum public enum LoggingLevelType { /** * Highest severity level. Unexpected errors that occur during normal execution. Fatal exceptions or any other serious problems that require immediate attention from the System Administrator. * */ @XmlEnumValue("Fatal") FATAL("Fatal"), /** * The Error level designates error events that might still allow the application to continue running. Administrator action can be delayed in this severity. * */ @XmlEnumValue("Error") ERROR("Error"), /** * The Warning level designates potentially harmful situations. Any potential problem that should be reviewed by the System Administrator. * */ @XmlEnumValue("Warning") WARNING("Warning"), /** * Key flow steps; high-level functional progress messages. A major life cycle event such as the activation or deactivation of a primary sub-component or feature. * */ @XmlEnumValue("Notification") NOTIFICATION("Notification"), /** * Configuration properties and environment settings. This is a finer level of granularity for reporting normal events. * */ @XmlEnumValue("Trace") TRACE("Trace"); private final String value; LoggingLevelType(String v) { value = v; } public String value() { return value; } public static LoggingLevelType fromValue(String v) { for (LoggingLevelType c: LoggingLevelType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } } <file_sep>/auction/sql/Worksheet 2.sql select * from users; update users u set u.phone = 7760759 where u.phone = 'string';<file_sep>/auction/sql/dropDDL_action_backup.sql ALTER TABLE BID DROP CONSTRAINT FK_BID_itemid; ALTER TABLE BID DROP CONSTRAINT FK_BID_bidderid; ALTER TABLE USERS DROP CONSTRAINT FK_USERS_billingInfoid; ALTER TABLE USERSPICTURE DROP CONSTRAINT FK_USERSPICTURE_OID; ALTER TABLE BIDDER DROP CONSTRAINT FK_BIDDER_OID; ALTER TABLE CATEGORY DROP CONSTRAINT FK_CATEGORY_parentCategoryid; ALTER TABLE CONTACTINFO DROP CONSTRAINT FK_CONTACTINFO_userid; ALTER TABLE ITEM DROP CONSTRAINT FK_ITEM_sellerid; ALTER TABLE ITEM DROP CONSTRAINT FK_ITEM_orderid; ALTER TABLE ORDERS DROP CONSTRAINT FK_ORDERS_bidderid; ALTER TABLE SELLER DROP CONSTRAINT FK_SELLER_OID; ALTER TABLE category_items DROP CONSTRAINT FK_category_items_itemid; ALTER TABLE category_items DROP CONSTRAINT FK_category_items_categoryid; DROP TABLE BID; DROP TABLE USERSPICTURE; DROP TABLE USERS; DROP TABLE BIDDER; DROP TABLE BILLINGINFO; DROP TABLE CATEGORY; DROP TABLE CONTACTINFO; DROP TABLE ITEM; DROP TABLE ORDERS; DROP TABLE SELLER; DROP TABLE category_items; <file_sep>/auction/domain-module/model/sql/model.sql CREATE TABLE ORDERS (CREATEDATE TIMESTAMP NULL, LASTMODIFIED TIMESTAMP NULL, VERSION NUMBER(19) NULL, OID VARCHAR(36), bidderid VARCHAR(36), PRIMARY KEY (OID)); CREATE TABLE USERS (USERTYPE VARCHAR2(1) NULL, OID VARCHAR(36), EMAIL VARCHAR2(255) NULL, FISRTNAME VARCHAR2(255) NOT NULL, LASTMODIFIED TIMESTAMP NULL, LASTNAME VARCHAR2(255) NOT NULL, PASSWORD VARCHAR2(255) NOT NULL, PHONE VARCHAR2(255) NULL, USERNAME VARCHAR2(255) NOT NULL, VERSION NUMBER(19) NULL, CITY VARCHAR2(255) NULL, COUNTRY VARCHAR2(255) NULL, STATE VARCHAR2(255) NULL, STREELINE2 VARCHAR2(255) NULL, STREETLINE1 VARCHAR2(255) NULL, ZIPCODE VARCHAR2(255) NULL, billingInfoid VARCHAR(36), PRIMARY KEY (OID)); CREATE TABLE USERSPICTURE (OID VARCHAR(36), PICTURE BLOB NULL, PRIMARY KEY (OID)); CREATE TABLE BIDDER (OID VARCHAR(36), BIDFRECUENCY NUMBER(19,4) NULL, PRIMARY KEY (OID)); CREATE TABLE CATEGORY (DESCRIPTION VARCHAR2(255) NULL, LASTMODIFIED TIMESTAMP NULL, NAME VARCHAR2(255) NULL, VERSION NUMBER(19) NULL, OID VARCHAR(36), parentCategoryid VARCHAR(36), PRIMARY KEY (OID)); CREATE TABLE CONTACTINFO (EMAIL VARCHAR2(255) NULL, FIRSTNAME VARCHAR2(255) NOT NULL, LASTMODIFIED TIMESTAMP NULL, LASTNAME VARCHAR2(255) NULL, PHONE VARCHAR2(255) NULL, VERSION NUMBER(19) NULL, CITY VARCHAR2(255) NULL, COUNTRY VARCHAR2(255) NULL, STATE VARCHAR2(255) NULL, STREELINE2 VARCHAR2(255) NULL, STREETLINE1 VARCHAR2(255) NULL, ZIPCODE VARCHAR2(255) NULL, OID VARCHAR(36), userid VARCHAR(36), PRIMARY KEY (OID)); CREATE TABLE BID (BIDAMOUNT NUMBER(19,4) NULL, BIDDATE TIMESTAMP NULL, LASTMODIFIED TIMESTAMP NULL, VERSION NUMBER(19) NULL, OID VARCHAR(36), bidderid VARCHAR(36), itemid VARCHAR(36), PRIMARY KEY (OID)); CREATE TABLE SELLER (OID VARCHAR(36), CREDITWORTH NUMBER(19,4) NULL, PRIMARY KEY (OID)); CREATE TABLE BILLINGINFO (BANKACCOUNTNUMBER VARCHAR2(255) NULL, BANKNAME VARCHAR2(255) NULL, CREDITCARDEXPIRATION DATE NULL, CREDITCARDNAMBER VARCHAR2(255) NULL, CREDITCARDTYPE VARCHAR2(255) NULL, LASTMODIFIED TIMESTAMP NULL, NAMEONCREDITCARD VARCHAR2(255) NULL, ROUTINGNUMBER VARCHAR2(255) NULL, VERSION NUMBER(19) NULL, OID VARCHAR(36), PRIMARY KEY (OID)); CREATE TABLE ITEM (BIDENDDATE TIMESTAMP NULL, BIDSTARTDATE TIMESTAMP NULL, DESCRIPTION CLOB NULL, INITIALPRICE NUMBER(19,4) NULL, LASTMODIFIED TIMESTAMP NULL, PICTURE BLOB NULL, POSTDATE TIMESTAMP NULL, TITLE VARCHAR2(255) NULL, VERSION NUMBER(19) NULL, OID VARCHAR(36), orderid VARCHAR(36), sellerid VARCHAR(36), PRIMARY KEY (OID)); CREATE TABLE category_items (categoryid VARCHAR(36), itemid VARCHAR(36), PRIMARY KEY (categoryid, itemid)); CREATE TABLE users_category (categoryid VARCHAR(36), userid VARCHAR(36), PRIMARY KEY (categoryid, userid)); ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_bidderid FOREIGN KEY (bidderid) REFERENCES USERS (OID); ALTER TABLE USERS ADD CONSTRAINT FK_USERS_billingInfoid FOREIGN KEY (billingInfoid) REFERENCES BILLINGINFO (OID); ALTER TABLE USERSPICTURE ADD CONSTRAINT FK_USERSPICTURE_OID FOREIGN KEY (OID) REFERENCES USERS (OID); ALTER TABLE BIDDER ADD CONSTRAINT FK_BIDDER_OID FOREIGN KEY (OID) REFERENCES USERS (OID); ALTER TABLE CATEGORY ADD CONSTRAINT FK_CATEGORY_parentCategoryid FOREIGN KEY (parentCategoryid) REFERENCES CATEGORY (OID); ALTER TABLE CONTACTINFO ADD CONSTRAINT FK_CONTACTINFO_userid FOREIGN KEY (userid) REFERENCES USERS (OID); ALTER TABLE BID ADD CONSTRAINT FK_BID_itemid FOREIGN KEY (itemid) REFERENCES ITEM (OID); ALTER TABLE BID ADD CONSTRAINT FK_BID_bidderid FOREIGN KEY (bidderid) REFERENCES USERS (OID); ALTER TABLE SELLER ADD CONSTRAINT FK_SELLER_OID FOREIGN KEY (OID) REFERENCES USERS (OID); ALTER TABLE ITEM ADD CONSTRAINT FK_ITEM_sellerid FOREIGN KEY (sellerid) REFERENCES USERS (OID); ALTER TABLE ITEM ADD CONSTRAINT FK_ITEM_orderid FOREIGN KEY (orderid) REFERENCES ORDERS (OID); ALTER TABLE category_items ADD CONSTRAINT FK_category_items_itemid FOREIGN KEY (itemid) REFERENCES ITEM (OID); ALTER TABLE category_items ADD CONSTRAINT FK_category_items_categoryid FOREIGN KEY (categoryid) REFERENCES CATEGORY (OID); ALTER TABLE users_category ADD CONSTRAINT FK_users_category_userid FOREIGN KEY (userid) REFERENCES USERS (OID); ALTER TABLE users_category ADD CONSTRAINT FK_users_category_categoryid FOREIGN KEY (categoryid) REFERENCES CATEGORY (OID); select * from USERSPICTURE; truncate table USERSPICTURE; select * from users; delete from users; truncate table users; select * from BIDDER; truncate table bidder; select * from CATEGORY; select * from CONTACTINFO; select * from BID; truncate table BID; select * from SELLER; select * from BILLINGINFO; select * from ITEM; delete from item; truncate table Item; select * from category_items; truncate table category_items; select * from users_category; select * from orders; ALTER TABLE ORDERS DROP CONSTRAINT FK_ORDERS_bidderid; ALTER TABLE USERS DROP CONSTRAINT FK_USERS_billingInfoid; ALTER TABLE USERSPICTURE DROP CONSTRAINT FK_USERSPICTURE_OID; ALTER TABLE BIDDER DROP CONSTRAINT FK_BIDDER_OID; ALTER TABLE CATEGORY DROP CONSTRAINT FK_CATEGORY_parentCategoryid; ALTER TABLE CONTACTINFO DROP CONSTRAINT FK_CONTACTINFO_userid; ALTER TABLE BID DROP CONSTRAINT FK_BID_itemid; ALTER TABLE BID DROP CONSTRAINT FK_BID_bidderid; ALTER TABLE SELLER DROP CONSTRAINT FK_SELLER_OID; ALTER TABLE ITEM DROP CONSTRAINT FK_ITEM_sellerid; ALTER TABLE ITEM DROP CONSTRAINT FK_ITEM_orderid; ALTER TABLE category_items DROP CONSTRAINT FK_category_items_itemid; ALTER TABLE category_items DROP CONSTRAINT FK_category_items_categoryid; ALTER TABLE users_category DROP CONSTRAINT FK_users_category_userid; ALTER TABLE users_category DROP CONSTRAINT FK_users_category_categoryid; DROP TABLE ORDERS; DROP TABLE USERS; DROP TABLE USERSPICTURE; DROP TABLE BIDDER; DROP TABLE CATEGORY; DROP TABLE CONTACTINFO; DROP TABLE BID; DROP TABLE SELLER; DROP TABLE BILLINGINFO; DROP TABLE ITEM; DROP TABLE category_items; DROP TABLE users_category; <file_sep>/auction/common/xml/xml-bid/target/generated-sources/jaxb/com/jdap/auction/common/xml/bid/ObjectFactory.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:56 PM EST // package com.jdap.auction.common.xml.bid; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.jdap.auction.common.xml.bid package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _ProblemIRI_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ProblemIRI"); private final static QName _EndpointReference_QNAME = new QName("http://www.w3.org/2005/08/addressing", "EndpointReference"); private final static QName _ProblemHeaderQName_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ProblemHeaderQName"); private final static QName _ReferenceParameters_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ReferenceParameters"); private final static QName _From_QNAME = new QName("http://www.w3.org/2005/08/addressing", "From"); private final static QName _ReplyTo_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ReplyTo"); private final static QName _MessageHeader_QNAME = new QName("http://xmlns.jdap.com/Common/MessageHeader/v2", "MessageHeader"); private final static QName _Action_QNAME = new QName("http://www.w3.org/2005/08/addressing", "Action"); private final static QName _UpdateBidRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "UpdateBidRequestMessage"); private final static QName _QueryBidResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "QueryBidResponseMessage"); private final static QName _FaultTo_QNAME = new QName("http://www.w3.org/2005/08/addressing", "FaultTo"); private final static QName _RetryAfter_QNAME = new QName("http://www.w3.org/2005/08/addressing", "RetryAfter"); private final static QName _CreateBidRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "CreateBidRequestMessage"); private final static QName _QueryBidDetailsRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "QueryBidDetailsRequestMessage"); private final static QName _To_QNAME = new QName("http://www.w3.org/2005/08/addressing", "To"); private final static QName _CreateBidResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "CreateBidResponseMessage"); private final static QName _ProblemAction_QNAME = new QName("http://www.w3.org/2005/08/addressing", "ProblemAction"); private final static QName _Bid_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Objects/v2", "bid"); private final static QName _CreateBidDetailsResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "CreateBidDetailsResponseMessage"); private final static QName _DeleteBidResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "DeleteBidResponseMessage"); private final static QName _RelatesTo_QNAME = new QName("http://www.w3.org/2005/08/addressing", "RelatesTo"); private final static QName _DeleteBidRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "DeleteBidRequestMessage"); private final static QName _Metadata_QNAME = new QName("http://www.w3.org/2005/08/addressing", "Metadata"); private final static QName _QueryBidDetailsResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "QueryBidDetailsResponseMessage"); private final static QName _CreateBidDetailsRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "CreateBidDetailsRequestMessage"); private final static QName _QueryBidRequestMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "QueryBidRequestMessage"); private final static QName _UpdateBidResponseMessage_QNAME = new QName("http://xmlns.jdap.com/auction/Bid/Messages/v2", "UpdateBidResponseMessage"); private final static QName _MessageID_QNAME = new QName("http://www.w3.org/2005/08/addressing", "MessageID"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.jdap.auction.common.xml.bid * */ public ObjectFactory() { } /** * Create an instance of {@link CreateBidDetailsRequestMessageType } * */ public CreateBidDetailsRequestMessageType createCreateBidDetailsRequestMessageType() { return new CreateBidDetailsRequestMessageType(); } /** * Create an instance of {@link QueryBidDetailsResponseMessageType } * */ public QueryBidDetailsResponseMessageType createQueryBidDetailsResponseMessageType() { return new QueryBidDetailsResponseMessageType(); } /** * Create an instance of {@link QueryBidRequestMessageType } * */ public QueryBidRequestMessageType createQueryBidRequestMessageType() { return new QueryBidRequestMessageType(); } /** * Create an instance of {@link UpdateBidRequestMessageType } * */ public UpdateBidRequestMessageType createUpdateBidRequestMessageType() { return new UpdateBidRequestMessageType(); } /** * Create an instance of {@link QueryBidResponseMessageType } * */ public QueryBidResponseMessageType createQueryBidResponseMessageType() { return new QueryBidResponseMessageType(); } /** * Create an instance of {@link UpdateBidResponseMessageType } * */ public UpdateBidResponseMessageType createUpdateBidResponseMessageType() { return new UpdateBidResponseMessageType(); } /** * Create an instance of {@link CreateBidResponseMessageType } * */ public CreateBidResponseMessageType createCreateBidResponseMessageType() { return new CreateBidResponseMessageType(); } /** * Create an instance of {@link CreateBidDetailsResponseMessageType } * */ public CreateBidDetailsResponseMessageType createCreateBidDetailsResponseMessageType() { return new CreateBidDetailsResponseMessageType(); } /** * Create an instance of {@link DeleteBidResponseMessageType } * */ public DeleteBidResponseMessageType createDeleteBidResponseMessageType() { return new DeleteBidResponseMessageType(); } /** * Create an instance of {@link CreateBidRequestMessageType } * */ public CreateBidRequestMessageType createCreateBidRequestMessageType() { return new CreateBidRequestMessageType(); } /** * Create an instance of {@link QueryBidDetailsRequestMessageType } * */ public QueryBidDetailsRequestMessageType createQueryBidDetailsRequestMessageType() { return new QueryBidDetailsRequestMessageType(); } /** * Create an instance of {@link DeleteBidRequestMessageType } * */ public DeleteBidRequestMessageType createDeleteBidRequestMessageType() { return new DeleteBidRequestMessageType(); } /** * Create an instance of {@link BidType } * */ public BidType createBidType() { return new BidType(); } /** * Create an instance of {@link ListOfValuesType } * */ public ListOfValuesType createListOfValuesType() { return new ListOfValuesType(); } /** * Create an instance of {@link CategoryType } * */ public CategoryType createCategoryType() { return new CategoryType(); } /** * Create an instance of {@link UserIDType } * */ public UserIDType createUserIDType() { return new UserIDType(); } /** * Create an instance of {@link ValueHolderType } * */ public ValueHolderType createValueHolderType() { return new ValueHolderType(); } /** * Create an instance of {@link NameValuePairDataType } * */ public NameValuePairDataType createNameValuePairDataType() { return new NameValuePairDataType(); } /** * Create an instance of {@link RangeOfDatesType } * */ public RangeOfDatesType createRangeOfDatesType() { return new RangeOfDatesType(); } /** * Create an instance of {@link ExtensionBidType } * */ public ExtensionBidType createExtensionBidType() { return new ExtensionBidType(); } /** * Create an instance of {@link MessageHeaderType } * */ public MessageHeaderType createMessageHeaderType() { return new MessageHeaderType(); } /** * Create an instance of {@link SenderType } * */ public SenderType createSenderType() { return new SenderType(); } /** * Create an instance of {@link WSAddressType } * */ public WSAddressType createWSAddressType() { return new WSAddressType(); } /** * Create an instance of {@link NameValuePairType } * */ public NameValuePairType createNameValuePairType() { return new NameValuePairType(); } /** * Create an instance of {@link ProblemActionType } * */ public ProblemActionType createProblemActionType() { return new ProblemActionType(); } /** * Create an instance of {@link AttributedURIType } * */ public AttributedURIType createAttributedURIType() { return new AttributedURIType(); } /** * Create an instance of {@link AttributedQNameType } * */ public AttributedQNameType createAttributedQNameType() { return new AttributedQNameType(); } /** * Create an instance of {@link EndpointReferenceType } * */ public EndpointReferenceType createEndpointReferenceType() { return new EndpointReferenceType(); } /** * Create an instance of {@link AttributedUnsignedLongType } * */ public AttributedUnsignedLongType createAttributedUnsignedLongType() { return new AttributedUnsignedLongType(); } /** * Create an instance of {@link MetadataType } * */ public MetadataType createMetadataType() { return new MetadataType(); } /** * Create an instance of {@link ReferenceParametersType } * */ public ReferenceParametersType createReferenceParametersType() { return new ReferenceParametersType(); } /** * Create an instance of {@link RelatesToType } * */ public RelatesToType createRelatesToType() { return new RelatesToType(); } /** * Create an instance of {@link ExtensionMessageHeaderType } * */ public ExtensionMessageHeaderType createExtensionMessageHeaderType() { return new ExtensionMessageHeaderType(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ProblemIRI") public JAXBElement<AttributedURIType> createProblemIRI(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_ProblemIRI_QNAME, AttributedURIType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "EndpointReference") public JAXBElement<EndpointReferenceType> createEndpointReference(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_EndpointReference_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedQNameType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ProblemHeaderQName") public JAXBElement<AttributedQNameType> createProblemHeaderQName(AttributedQNameType value) { return new JAXBElement<AttributedQNameType>(_ProblemHeaderQName_QNAME, AttributedQNameType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ReferenceParametersType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ReferenceParameters") public JAXBElement<ReferenceParametersType> createReferenceParameters(ReferenceParametersType value) { return new JAXBElement<ReferenceParametersType>(_ReferenceParameters_QNAME, ReferenceParametersType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "From") public JAXBElement<EndpointReferenceType> createFrom(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_From_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ReplyTo") public JAXBElement<EndpointReferenceType> createReplyTo(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_ReplyTo_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MessageHeaderType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/Common/MessageHeader/v2", name = "MessageHeader") public JAXBElement<MessageHeaderType> createMessageHeader(MessageHeaderType value) { return new JAXBElement<MessageHeaderType>(_MessageHeader_QNAME, MessageHeaderType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "Action") public JAXBElement<AttributedURIType> createAction(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_Action_QNAME, AttributedURIType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UpdateBidRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "UpdateBidRequestMessage") public JAXBElement<UpdateBidRequestMessageType> createUpdateBidRequestMessage(UpdateBidRequestMessageType value) { return new JAXBElement<UpdateBidRequestMessageType>(_UpdateBidRequestMessage_QNAME, UpdateBidRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QueryBidResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "QueryBidResponseMessage") public JAXBElement<QueryBidResponseMessageType> createQueryBidResponseMessage(QueryBidResponseMessageType value) { return new JAXBElement<QueryBidResponseMessageType>(_QueryBidResponseMessage_QNAME, QueryBidResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "FaultTo") public JAXBElement<EndpointReferenceType> createFaultTo(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_FaultTo_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedUnsignedLongType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "RetryAfter") public JAXBElement<AttributedUnsignedLongType> createRetryAfter(AttributedUnsignedLongType value) { return new JAXBElement<AttributedUnsignedLongType>(_RetryAfter_QNAME, AttributedUnsignedLongType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateBidRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "CreateBidRequestMessage") public JAXBElement<CreateBidRequestMessageType> createCreateBidRequestMessage(CreateBidRequestMessageType value) { return new JAXBElement<CreateBidRequestMessageType>(_CreateBidRequestMessage_QNAME, CreateBidRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QueryBidDetailsRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "QueryBidDetailsRequestMessage") public JAXBElement<QueryBidDetailsRequestMessageType> createQueryBidDetailsRequestMessage(QueryBidDetailsRequestMessageType value) { return new JAXBElement<QueryBidDetailsRequestMessageType>(_QueryBidDetailsRequestMessage_QNAME, QueryBidDetailsRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "To") public JAXBElement<AttributedURIType> createTo(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_To_QNAME, AttributedURIType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateBidResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "CreateBidResponseMessage") public JAXBElement<CreateBidResponseMessageType> createCreateBidResponseMessage(CreateBidResponseMessageType value) { return new JAXBElement<CreateBidResponseMessageType>(_CreateBidResponseMessage_QNAME, CreateBidResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ProblemActionType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "ProblemAction") public JAXBElement<ProblemActionType> createProblemAction(ProblemActionType value) { return new JAXBElement<ProblemActionType>(_ProblemAction_QNAME, ProblemActionType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BidType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Objects/v2", name = "bid") public JAXBElement<BidType> createBid(BidType value) { return new JAXBElement<BidType>(_Bid_QNAME, BidType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateBidDetailsResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "CreateBidDetailsResponseMessage") public JAXBElement<CreateBidDetailsResponseMessageType> createCreateBidDetailsResponseMessage(CreateBidDetailsResponseMessageType value) { return new JAXBElement<CreateBidDetailsResponseMessageType>(_CreateBidDetailsResponseMessage_QNAME, CreateBidDetailsResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteBidResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "DeleteBidResponseMessage") public JAXBElement<DeleteBidResponseMessageType> createDeleteBidResponseMessage(DeleteBidResponseMessageType value) { return new JAXBElement<DeleteBidResponseMessageType>(_DeleteBidResponseMessage_QNAME, DeleteBidResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RelatesToType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "RelatesTo") public JAXBElement<RelatesToType> createRelatesTo(RelatesToType value) { return new JAXBElement<RelatesToType>(_RelatesTo_QNAME, RelatesToType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteBidRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "DeleteBidRequestMessage") public JAXBElement<DeleteBidRequestMessageType> createDeleteBidRequestMessage(DeleteBidRequestMessageType value) { return new JAXBElement<DeleteBidRequestMessageType>(_DeleteBidRequestMessage_QNAME, DeleteBidRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MetadataType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "Metadata") public JAXBElement<MetadataType> createMetadata(MetadataType value) { return new JAXBElement<MetadataType>(_Metadata_QNAME, MetadataType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QueryBidDetailsResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "QueryBidDetailsResponseMessage") public JAXBElement<QueryBidDetailsResponseMessageType> createQueryBidDetailsResponseMessage(QueryBidDetailsResponseMessageType value) { return new JAXBElement<QueryBidDetailsResponseMessageType>(_QueryBidDetailsResponseMessage_QNAME, QueryBidDetailsResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CreateBidDetailsRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "CreateBidDetailsRequestMessage") public JAXBElement<CreateBidDetailsRequestMessageType> createCreateBidDetailsRequestMessage(CreateBidDetailsRequestMessageType value) { return new JAXBElement<CreateBidDetailsRequestMessageType>(_CreateBidDetailsRequestMessage_QNAME, CreateBidDetailsRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link QueryBidRequestMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "QueryBidRequestMessage") public JAXBElement<QueryBidRequestMessageType> createQueryBidRequestMessage(QueryBidRequestMessageType value) { return new JAXBElement<QueryBidRequestMessageType>(_QueryBidRequestMessage_QNAME, QueryBidRequestMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UpdateBidResponseMessageType }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.jdap.com/auction/Bid/Messages/v2", name = "UpdateBidResponseMessage") public JAXBElement<UpdateBidResponseMessageType> createUpdateBidResponseMessage(UpdateBidResponseMessageType value) { return new JAXBElement<UpdateBidResponseMessageType>(_UpdateBidResponseMessage_QNAME, UpdateBidResponseMessageType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AttributedURIType }{@code >}} * */ @XmlElementDecl(namespace = "http://www.w3.org/2005/08/addressing", name = "MessageID") public JAXBElement<AttributedURIType> createMessageID(AttributedURIType value) { return new JAXBElement<AttributedURIType>(_MessageID_QNAME, AttributedURIType.class, null, value); } } <file_sep>/auction/common/xml/xml-user/target/generated-sources/jaxb/com/jdap/auction/common/xml/user/SellerType.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:57 PM EST // package com.jdap.auction.common.xml.user; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for sellerType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="sellerType"> * &lt;complexContent> * &lt;extension base="{http://xmlns.jdap.com/auction/User/Objects/v2}userType"> * &lt;sequence> * &lt;element name="creditWorth" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="commissionRate" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="sellerExtension" type="{http://xmlns.jdap.com/auction/Seller/Objects/Extension/v2}ExtensionSellerType" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "sellerType", namespace = "http://xmlns.jdap.com/auction/Seller/Objects/v2", propOrder = { "creditWorth", "commissionRate", "sellerExtension" }) public class SellerType extends UserType { protected double creditWorth; protected double commissionRate; protected ExtensionSellerType sellerExtension; /** * Gets the value of the creditWorth property. * */ public double getCreditWorth() { return creditWorth; } /** * Sets the value of the creditWorth property. * */ public void setCreditWorth(double value) { this.creditWorth = value; } /** * Gets the value of the commissionRate property. * */ public double getCommissionRate() { return commissionRate; } /** * Sets the value of the commissionRate property. * */ public void setCommissionRate(double value) { this.commissionRate = value; } /** * Gets the value of the sellerExtension property. * * @return * possible object is * {@link ExtensionSellerType } * */ public ExtensionSellerType getSellerExtension() { return sellerExtension; } /** * Sets the value of the sellerExtension property. * * @param value * allowed object is * {@link ExtensionSellerType } * */ public void setSellerExtension(ExtensionSellerType value) { this.sellerExtension = value; } } <file_sep>/auction/sql/slq scripts.sql select count(6) from bids; select * from bids; SELECT * FROM bidders; delete bids; drop table bids; CREATE TABLE "CDMR"."BIDS" ( "BID_ID" NUMBER(19,0) NOT NULL ENABLE, "BID_AMOUNT" NUMBER(19,4), "BID_DATE" TIMESTAMP (6), "BIDDER_ID" NUMBER(19,0), "ITEM_ID" NUMBER(19,0), PRIMARY KEY ("BID_ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) TABLESPACE "CDMR_TABLESPACE" ENABLE ) SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT ) CREATE TABLE "CDMR"."BID" ( "BIDAMOUNT" NUMBER(19,4), "BIDDATE" TIMESTAMP (6), "BIDDERID" NUMBER(19,0), "ITEMID" NUMBER(19,0), "LASTMODIFIED" TIMESTAMP (6), "VERSION" NUMBER(19,0), "OID" VARCHAR2(36 BYTE), PRIMARY KEY ("OID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) TABLESPACE "CDMR_TABLESPACE" ENABLE ) SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT ) CREATE TABLE "CDMR"."SEQUENCE" ( "SEQ_COUNT" NUMBER(38,0), "SEQ_NAME" VARCHAR2(50 BYTE) NOT NULL ENABLE, PRIMARY KEY ("SEQ_NAME") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) TABLESPACE "CDMR_TABLESPACE" ENABLE ) SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT ) TABLESPACE "CDMR_TABLESPACE" ; <file_sep>/auction/common/xml/xml-user/target/generated-sources/jaxb/com/jdap/auction/common/xml/user/UserKind.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:57 PM EST // package com.jdap.auction.common.xml.user; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for UserKind. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="UserKind"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="SELLER"/> * &lt;enumeration value="BIDDER"/> * &lt;enumeration value="CSM"/> * &lt;enumeration value="ADMIN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "UserKind", namespace = "http://xmlns.jdap.com/auction/Common/v2") @XmlEnum public enum UserKind { SELLER, BIDDER, CSM, ADMIN; public String value() { return name(); } public static UserKind fromValue(String v) { return valueOf(v); } } <file_sep>/auction/sql/Worksheet 51.sql select * from category; select * from Item; delete from item where title = '?'; delete from item_category ic where ic.itemid = any (select oid from item where title = '?'); <file_sep>/auction/sql/dropDDL_action.sql ALTER TABLE ORDERS DROP CONSTRAINT FK_ORDERS_bidderid; ALTER TABLE USERS DROP CONSTRAINT FK_USERS_billingInfoid; ALTER TABLE USERSPICTURE DROP CONSTRAINT FK_USERSPICTURE_OID; ALTER TABLE BIDDER DROP CONSTRAINT FK_BIDDER_OID; ALTER TABLE CATEGORY DROP CONSTRAINT FK_CATEGORY_parentCategoryid; ALTER TABLE CONTACTINFO DROP CONSTRAINT FK_CONTACTINFO_userid; ALTER TABLE BID DROP CONSTRAINT FK_BID_itemid; ALTER TABLE BID DROP CONSTRAINT FK_BID_bidderid; ALTER TABLE SELLER DROP CONSTRAINT FK_SELLER_OID; ALTER TABLE ITEM DROP CONSTRAINT FK_ITEM_sellerid; ALTER TABLE ITEM DROP CONSTRAINT FK_ITEM_orderid; ALTER TABLE category_items DROP CONSTRAINT FK_category_items_itemid; ALTER TABLE category_items DROP CONSTRAINT FK_category_items_categoryid; ALTER TABLE users_category DROP CONSTRAINT FK_users_category_userid; ALTER TABLE users_category DROP CONSTRAINT FK_users_category_categoryid; DROP TABLE ORDERS; DROP TABLE USERS; DROP TABLE USERSPICTURE; DROP TABLE BIDDER; DROP TABLE CATEGORY; DROP TABLE CONTACTINFO; DROP TABLE BID; DROP TABLE SELLER; DROP TABLE BILLINGINFO; DROP TABLE ITEM; DROP TABLE category_items; DROP TABLE users_category; <file_sep>/auction/common/xml/xml-user/target/generated-sources/jaxb/com/jdap/auction/common/xml/user/UserType.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:57 PM EST // package com.jdap.auction.common.xml.user; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for userType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="userType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="usertype" type="{http://xmlns.jdap.com/auction/Common/v2}UserKind"/> * &lt;element name="username" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="password"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="5"/> * &lt;maxLength value="8"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="firstName" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="lastName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="email" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="phone" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="creationDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="picture" type="{http://www.w3.org/2001/XMLSchema}byte" minOccurs="0"/> * &lt;element ref="{http://xmlns.jdap.com/auction/Address/Objects/v2}address"/> * &lt;element name="category" type="{http://xmlns.jdap.com/auction/Common/v2}categoryType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Extension" type="{http://xmlns.jdap.com/auction/User/Objects/Extension/v2}ExtensionUserType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "userType", namespace = "http://xmlns.jdap.com/auction/User/Objects/v2", propOrder = { "id", "usertype", "username", "<PASSWORD>", "firstName", "lastName", "email", "phone", "creationDate", "picture", "address", "category", "extension" }) @XmlSeeAlso({ SellerType.class, BidderType.class }) public abstract class UserType { protected String id; @XmlElement(required = true) protected UserKind usertype; @XmlElement(required = true) protected String username; @XmlElement(required = true) protected String password; @XmlElement(required = true) protected String firstName; protected String lastName; @XmlElement(required = true) protected String email; protected String phone; @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationDate; protected Byte picture; @XmlElement(namespace = "http://xmlns.jdap.com/auction/Address/Objects/v2", required = true) protected AddressType address; @XmlElement(type = CategoryType.class) protected List<CategoryType> category; @XmlElement(name = "Extension") protected ExtensionUserType extension; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the usertype property. * * @return * possible object is * {@link UserKind } * */ public UserKind getUsertype() { return usertype; } /** * Sets the value of the usertype property. * * @param value * allowed object is * {@link UserKind } * */ public void setUsertype(UserKind value) { this.usertype = value; } /** * Gets the value of the username property. * * @return * possible object is * {@link String } * */ public String getUsername() { return username; } /** * Sets the value of the username property. * * @param value * allowed object is * {@link String } * */ public void setUsername(String value) { this.username = value; } /** * Gets the value of the password property. * * @return * possible object is * {@link String } * */ public String getPassword() { return password; } /** * Sets the value of the password property. * * @param value * allowed object is * {@link String } * */ public void setPassword(String value) { this.password = value; } /** * Gets the value of the firstName property. * * @return * possible object is * {@link String } * */ public String getFirstName() { return firstName; } /** * Sets the value of the firstName property. * * @param value * allowed object is * {@link String } * */ public void setFirstName(String value) { this.firstName = value; } /** * Gets the value of the lastName property. * * @return * possible object is * {@link String } * */ public String getLastName() { return lastName; } /** * Sets the value of the lastName property. * * @param value * allowed object is * {@link String } * */ public void setLastName(String value) { this.lastName = value; } /** * Gets the value of the email property. * * @return * possible object is * {@link String } * */ public String getEmail() { return email; } /** * Sets the value of the email property. * * @param value * allowed object is * {@link String } * */ public void setEmail(String value) { this.email = value; } /** * Gets the value of the phone property. * * @return * possible object is * {@link String } * */ public String getPhone() { return phone; } /** * Sets the value of the phone property. * * @param value * allowed object is * {@link String } * */ public void setPhone(String value) { this.phone = value; } /** * Gets the value of the creationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreationDate() { return creationDate; } /** * Sets the value of the creationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreationDate(XMLGregorianCalendar value) { this.creationDate = value; } /** * Gets the value of the picture property. * * @return * possible object is * {@link Byte } * */ public Byte getPicture() { return picture; } /** * Sets the value of the picture property. * * @param value * allowed object is * {@link Byte } * */ public void setPicture(Byte value) { this.picture = value; } /** * User Address * * @return * possible object is * {@link AddressType } * */ public AddressType getAddress() { return address; } /** * Sets the value of the address property. * * @param value * allowed object is * {@link AddressType } * */ public void setAddress(AddressType value) { this.address = value; } /** * Gets the value of the category property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the category property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCategory().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CategoryType } * * */ public List<CategoryType> getCategory() { if (category == null) { category = new ArrayList<CategoryType>(); } return this.category; } /** * Gets the value of the extension property. * * @return * possible object is * {@link ExtensionUserType } * */ public ExtensionUserType getExtension() { return extension; } /** * Sets the value of the extension property. * * @param value * allowed object is * {@link ExtensionUserType } * */ public void setExtension(ExtensionUserType value) { this.extension = value; } } <file_sep>/auction/domain-module/model-pu/target/classes/META-INF/maven/com.jdap.auction.domain-model/auction-domain-model-pu/pom.xml <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> <parent> <artifactId>auction-domain</artifactId> <groupId>com.jdap.auction.domain-model</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>com.jdap.auction.domain-model</groupId> <artifactId>auction-domain-model-pu</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.6</version> <executions> <execution> <configuration> <target> <replace file="./target/classes/META-INF/persistence.xml"> <replacetoken><![CDATA[lib/auction-domain-model-XXX.jar]]></replacetoken> <replacevalue>lib/auction-domain-model-${project.version}.jar</replacevalue> </replace> </target> </configuration> <phase>compile</phase> <goals> <goal>run</goal> </goals> </execution> <execution> <id>clean</id> <phase>clean</phase> <configuration> <target> <delete dir="target" /> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/auction/common/xml/xml-user/target/generated-sources/jaxb/com/jdap/auction/common/xml/user/CategoryType.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:57 PM EST // package com.jdap.auction.common.xml.user; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for categoryType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="categoryType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="category" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="subcategory" type="{http://xmlns.jdap.com/auction/Common/v2}categoryType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "categoryType", namespace = "http://xmlns.jdap.com/auction/Common/v2", propOrder = { "id", "category", "name", "description", "subcategory" }) public class CategoryType { protected String id; protected boolean category; @XmlElement(required = true) protected String name; @XmlElement(required = true) protected String description; @XmlElement(type = CategoryType.class) protected List<CategoryType> subcategory; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the category property. * */ public boolean isCategory() { return category; } /** * Sets the value of the category property. * */ public void setCategory(boolean value) { this.category = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the subcategory property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the subcategory property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSubcategory().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CategoryType } * * */ public List<CategoryType> getSubcategory() { if (subcategory == null) { subcategory = new ArrayList<CategoryType>(); } return this.subcategory; } } <file_sep>/auction/sql/Worksheet 3.sql select distinct se.*, us.* from users us, seller se where us.oid = se.oid order by us.lastmodified desc; select distinct bi.*, us.* from users us, bidder bi where us.oid = bi.oid order by us.lastmodified desc; select * from users; select * from seller; select * from bidder; select * from users_category; select * from billinginfo; select * from Item order by 2 desc; select * from item_category where itemid = 'a36eedb1-664e-46c6-8333-70215fdc910c'; select * from category; Category Test 03/21/2014 09:55:02 Category 1 5 61b646b8-8258-4e09-b9bc-14ab83c1a44b {null}<file_sep>/auction/domain-module/model/src/main/java/com/jdap/auction/model/ContactInfo.java package com.jdap.auction.model; //~--- JDK imports ------------------------------------------------------------- import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import com.jdap.auction.patterns.persistence.AbstractPersistentObject; /** * Class description * * * @version 9.0, 2013.February.28 04:44 PM * @author JDAP Corporation */ @Entity public class ContactInfo extends AbstractPersistentObject { /** * */ private static final long serialVersionUID = 1L; /** Field description */ @Column( name = "FIRSTNAME", nullable = false ) private String firstName; /** Field description */ @Column( name = "LASTNAME" ) private String lastName; /** Field description */ @Embedded private Address address; /** Field description */ private String email; /** Field description */ private String phone; /** Field description */ @ManyToOne @JoinColumn( name = "userid", referencedColumnName = "oid" ) private User user; /** * Method description * * * @return */ public String getFirstName() { return firstName; } /** * Method description * * * @param firstName */ public void setFirstName( String firstName ) { this.firstName = firstName; } /** * Method description * * * @return */ public String getLastName() { return lastName; } /** * Method description * * * @param lastName */ public void setLastName( String lastName ) { this.lastName = lastName; } /** * Method description * * * @return */ public Address getAddress() { return address; } /** * Method description * * * @param address */ public void setAddress( Address address ) { this.address = address; } /** * Method description * * * @return */ public String getEmail() { return email; } /** * Method description * * * @param email */ public void setEmail( String email ) { this.email = email; } /** * Method description * * * @return */ public String getPhone() { return phone; } /** * Method description * * * @param phone */ public void setPhone( String phone ) { this.phone = phone; } /** * Method description * * * @return */ public User getUser() { return user; } /** * Method description * * * @param user */ public void setUser( User user ) { this.user = user; } } <file_sep>/auction/sql/get tha referend tables.sql select a.table_name , a.constraint_name , a.constraint_type , b.table_name , b.column_name , b.position from user_constraints a , user_cons_columns b where a.owner = b.owner and a.constraint_name = b.constraint_name and a.constraint_type = 'P' and a.table_name = 'USERS' union all select a.table_name , a.constraint_name , a.constraint_type , b.table_name , b.column_name , b.position from user_constraints a , user_cons_columns b where a.owner = b.owner and a.r_constraint_name = b.constraint_name and a.constraint_type = 'R' and a.table_name = 'USERS' order by 1, 2, 3, 4, 5 / select table_name, constraint_name, status, owner from all_constraints where r_owner = 'CDMR' and constraint_type = 'R' and r_constraint_name in ( select constraint_name from all_constraints where constraint_type in ('P', 'U') and table_name = 'USERS' and owner = 'CDMR' ) order by table_name, constraint_name; <file_sep>/auction/common/xml/xml-bid/target/generated-sources/jaxb/com/jdap/auction/common/xml/bid/WSAddressType.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.11 at 02:45:56 PM EST // package com.jdap.auction.common.xml.bid; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for WSAddressType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="WSAddressType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.w3.org/2005/08/addressing}From" minOccurs="0"/> * &lt;element ref="{http://www.w3.org/2005/08/addressing}To" minOccurs="0"/> * &lt;element ref="{http://www.w3.org/2005/08/addressing}ReplyTo" minOccurs="0"/> * &lt;element ref="{http://www.w3.org/2005/08/addressing}FaultTo" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "WSAddressType", namespace = "http://xmlns.jdap.com/Common/MessageHeader/v2", propOrder = { "from", "to", "replyTo", "faultTo" }) public class WSAddressType { @XmlElement(name = "From", namespace = "http://www.w3.org/2005/08/addressing") protected EndpointReferenceType from; @XmlElement(name = "To", namespace = "http://www.w3.org/2005/08/addressing") protected AttributedURIType to; @XmlElement(name = "ReplyTo", namespace = "http://www.w3.org/2005/08/addressing") protected EndpointReferenceType replyTo; @XmlElement(name = "FaultTo", namespace = "http://www.w3.org/2005/08/addressing") protected EndpointReferenceType faultTo; /** * Gets the value of the from property. * * @return * possible object is * {@link EndpointReferenceType } * */ public EndpointReferenceType getFrom() { return from; } /** * Sets the value of the from property. * * @param value * allowed object is * {@link EndpointReferenceType } * */ public void setFrom(EndpointReferenceType value) { this.from = value; } /** * Gets the value of the to property. * * @return * possible object is * {@link AttributedURIType } * */ public AttributedURIType getTo() { return to; } /** * Sets the value of the to property. * * @param value * allowed object is * {@link AttributedURIType } * */ public void setTo(AttributedURIType value) { this.to = value; } /** * Gets the value of the replyTo property. * * @return * possible object is * {@link EndpointReferenceType } * */ public EndpointReferenceType getReplyTo() { return replyTo; } /** * Sets the value of the replyTo property. * * @param value * allowed object is * {@link EndpointReferenceType } * */ public void setReplyTo(EndpointReferenceType value) { this.replyTo = value; } /** * Gets the value of the faultTo property. * * @return * possible object is * {@link EndpointReferenceType } * */ public EndpointReferenceType getFaultTo() { return faultTo; } /** * Sets the value of the faultTo property. * * @param value * allowed object is * {@link EndpointReferenceType } * */ public void setFaultTo(EndpointReferenceType value) { this.faultTo = value; } } <file_sep>/auction/sql/Worksheet 4.sql select * from item order by 2 desc; select * from category; select * from item_category ic ; where ic.categoryid = any ('851e69f9-b43c-4ebd-b96d-ed7e5d69b8bf', '61b646b8-8258-4e09-b9bc-14ab83c1a44b') and ic.itemid = any ('8123fde8-4b42-43eb-a35d-0bbdb55ee655'); <file_sep>/auction/domain-module/model/src/main/java/com/jdap/auction/model/BillingInfo.java package com.jdap.auction.model; //~--- non-JDK imports --------------------------------------------------------- import com.jdap.auction.patterns.persistence.AbstractPersistentObject; //~--- JDK imports ------------------------------------------------------------- import java.sql.Date; import javax.persistence.Entity; import javax.persistence.OneToOne; /** * Class description * * * @version 9.0, 2013.February.27 11:22 AM * @author JDAP Corporation */ @Entity public class BillingInfo extends AbstractPersistentObject { /** Field description */ private String creditCardType; /** Field description */ private String creditCardNamber; /** Field description */ private String nameOnCreditCard; /** Field description */ private Date creditCardExpiration; /** Field description */ private String bankAccountNumber; /** Field description */ private String bankName; /** Field description */ private String routingNumber; /** Field description */ @OneToOne( mappedBy = "billingInfo", optional = false ) private User user; /** * Method description * * * @return */ public String getCreditCardType() { return creditCardType; } /** * Method description * * * @param creditCardType */ public void setCreditCardType( String creditCardType ) { this.creditCardType = creditCardType; } /** * Method description * * * @return */ public String getCreditCardNamber() { return creditCardNamber; } /** * Method description * * * @param creditCardNamber */ public void setCreditCardNamber( String creditCardNamber ) { this.creditCardNamber = creditCardNamber; } /** * Method description * * * @return */ public String getNameOnCreditCard() { return nameOnCreditCard; } /** * Method description * * * @param nameOnCreditCard */ public void setNameOnCreditCard( String nameOnCreditCard ) { this.nameOnCreditCard = nameOnCreditCard; } /** * Method description * * * @return */ public Date getCreditCardExpiration() { return creditCardExpiration; } /** * Method description * * * @param creditCardExpiration */ public void setCreditCardExpiration( Date creditCardExpiration ) { this.creditCardExpiration = creditCardExpiration; } /** * Method description * * * @return */ public String getBankAccountNumber() { return bankAccountNumber; } /** * Method description * * * @param bankAccountNumber */ public void setBankAccountNumber( String bankAccountNumber ) { this.bankAccountNumber = bankAccountNumber; } /** * Method description * * * @return */ public String getBankName() { return bankName; } /** * Method description * * * @param bankName */ public void setBankName( String bankName ) { this.bankName = bankName; } /** * Method description * * * @return */ public String getRoutingNumber() { return routingNumber; } /** * Method description * * * @param routingNumber */ public void setRoutingNumber( String routingNumber ) { this.routingNumber = routingNumber; } /** * Method description * * * @return */ public User getUser() { return user; } /** * Method description * * * @param user */ public void setUser( User user ) { this.user = user; } } <file_sep>/auction/sql/Worksheet0 1.sql select * from item; select * from category; select * from item_categorie; delete from item_categorie; delete from item; delete from category; <file_sep>/auction/common/xml/xml-fault/pom.xml <?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>common-xml</artifactId> <groupId>com.jdap.auction.common.xml</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>com.jdap.auction.common.xml</groupId> <artifactId>xml-fault</artifactId> <version>0.0.1-SNAPSHOT</version> <name>xml-fault</name> <packaging>jar</packaging> <dependencies> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2.5</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <executions> <execution> <!-- <id>template</id> --> <goals> <goal>xjc</goal> </goals> <configuration> <schemaDirectory>../SOAMetaData/Components/EnterpriseObjectLibrary/Common/Fault/v2</schemaDirectory> <includes> <include>ApiFault-v2.xsd</include> </includes> <packageName>com.jdap.auction.common.xml.fault</packageName> <xmlschema>true</xmlschema> <explicitAnnotation>true</explicitAnnotation> <extension>true</extension> <arguments>-Xifins</arguments> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>com.sun.jaxb.commons</groupId> <artifactId>interface-insert</artifactId> <version>${jaxb.commons.interface.insert.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>com.springsource.bundlor</groupId> <artifactId>com.springsource.bundlor.maven</artifactId> <version>${spring-bundlor-version}</version> <executions> <execution> <id>bundlor</id> <goals> <goal>bundlor</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>asm</groupId> <artifactId>asm-all</artifactId> <version>3.1</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifestFile>target/classes/META-INF/MANIFEST.MF</manifestFile> </archive> </configuration> </plugin> </plugins> </build> </project>
fd99746ba26641f5474479ccd2eeb4e67dfdf1ae
[ "SQL", "Maven POM", "Java", "Python", "TypeScript" ]
30
Java
jimmyangarita/newGitTest
254258675e783ae826c3c21c21f10c037edfe608
9e85d1c0875190913676b50453c4b0a7f655f393
refs/heads/master
<file_sep>from tkinter import * class Block: lis = ['+', '-', '*', '/'] def __init__(self, master): self.f_top = Frame() self.f_bot = Frame() self.e = Entry(master, width=20) self.g = Entry(master, width=20) self.but_sum = Button(self.f_top, text=self.lis[0], width=5) self.but_minus = Button(self.f_top, text=self.lis[1], width=5) self.but_umnoz = Button(self.f_bot, text=self.lis[2], width=5) self.but_delen = Button(self.f_bot, text=self.lis[3], width=5) self.but_sum['command'] = self.sum self.but_minus['command'] = self.minus self.but_umnoz['command'] = self.umnozhenie self.but_delen['command'] = self.delenie self.l = Label(master, bg='white', fg='black', width=20) self.e.pack(pady = 3) self.g.pack(pady = 3) self.f_top.pack(pady = 3) self.f_bot.pack(pady = 3) self.but_sum.pack(side = LEFT) self.but_minus.pack(side = LEFT) self.but_umnoz.pack(side = LEFT) self.but_delen.pack(side = LEFT) self.l.pack(pady = 3) def proverka(self, numb1, numb2, t): try: a = float(numb1) b = float(numb2) c = eval('%f %s %f' % (a, self.lis[t], b)) self.l['text'] = '%.2f %s %.2f = %.2f' % (a, self.lis[t], b, c) self.e.delete(0, END) self.g.delete(0, END) except ValueError: self.l['text'] = 'Ошибка' def sum(self): s = self.e.get() g = self.g.get() self.proverka(s, g, 0) def minus(self): s = self.e.get() g = self.g.get() self.proverka(s, g, 1) def umnozhenie(self): s = self.e.get() g = self.g.get() self.proverka(s, g, 2) def delenie(self): s = self.e.get() g = self.g.get() self.proverka(s, g, 3) root = Tk() root.minsize(width = 300, height = 100) first_block = Block(root) root.mainloop()
95b368a8e23fed2bf8b602fb4f896a95a1f039a1
[ "Python" ]
1
Python
Bitr0y/Courses
15843f40f307e18f0c7ebcb54abdbc65fb83aad5
1d727dd612dd9a235abd9adc80ed38ade7ffda72
refs/heads/master
<repo_name>yenertuz/app_academy_ruby<file_sep>/29_hash_map_lru_cache/lib/p02_hashing.rb class Fixnum # Fixnum#hash already implemented for you end class Array def hash return 0.hash if self.length == 0 sub_result = self.reduce { |sum, num| (sum << 5) + num } to_hash = self.length ^ sub_result sub_result.hash end end class String def hash return 0.hash if self.length == 0 sub_result = self.chars.reduce(0) { |sum, num| (sum << 5) + num.bytes[0] } to_hash = self.length ^ sub_result sub_result.hash end end class Hash # This returns 0 because rspec will break if it returns nil # Make sure to implement an actual Hash#hash method def hash return 0.hash if self.length == 0 arr = self.to_a.sort.flatten arr.map! { |x| x.is_a?(Symbol) ? x.to_s.hash : x.hash } arr.hash end end <file_sep>/13_diy_adts/map.rb class Map def initialize @map = [] end def set(key, value) a = nil @map.each_with_index {|(k, v), i| a = i if k == key } if a == nil @map << [key, value] else @map[i][1] = value end end def get(key) @map.each { |(k, v)| return v if k == key } nil end def delete(key) @map.delete_if { |(k, v)| k == key } end def show puts "{" @map.each { |(k, v)| print k.to_s + " => " + v.to_s; puts } end end<file_sep>/21_chess/chess.rb require "./tile.rb" require "./move.rb" require "./player.rb" require "io/console" class String def black; "\e[30m#{self}\e[0m" end def red; "\e[31m#{self}\e[0m" end def green; "\e[32m#{self}\e[0m" end def brown; "\e[33m#{self}\e[0m" end def blue; "\e[34m#{self}\e[0m" end def magenta; "\e[35m#{self}\e[0m" end def cyan; "\e[36m#{self}\e[0m" end def gray; "\e[37m#{self}\e[0m" end def yellow; "\e[33m#{self}\e[0m" end def pink; "\e[35m#{self}\e[0m" end def bg_black; "\e[40m#{self}\e[0m" end def bg_red; "\e[41m#{self}\e[0m" end def bg_green; "\e[42m#{self}\e[0m" end def bg_brown; "\e[43m#{self}\e[0m" end def bg_blue; "\e[44m#{self}\e[0m" end def bg_magenta; "\e[45m#{self}\e[0m" end def bg_cyan; "\e[46m#{self}\e[0m" end def bg_gray; "\e[47m#{self}\e[0m" end def bg_white; "\e[47;1m#{self}\e[0m" end def bold; "\e[1m#{self}\e[22m" end def italic; "\e[3m#{self}\e[23m" end def underline; "\e[4m#{self}\e[24m" end def blink; "\e[5m#{self}\e[25m" end def reverse_color; "\e[7m#{self}\e[27m" end def no_colors self.gsub /\e\[\d+m/, "" end end class Chess KEYMAP = { " " => :space, "h" => :left, "j" => :down, "k" => :up, "l" => :right, "w" => :up, "a" => :left, "s" => :down, "d" => :right, "\t" => :tab, "\r" => :return, "\n" => :newline, "\e" => :escape, "\e[A" => :up, "\e[B" => :down, "\e[C" => :right, "\e[D" => :left, "\177" => :backspace, "\004" => :delete, "\u0003" => :ctrl_c, } def self.start_game system "clear" @player1 = Player.from_input @player2 = Player.from_input @turn = @player1 @selection = false @cursor = [0, 0] @board = Array.new(8) do |row| Array.new(8) do |column| type = "" case column when 0, 7 type = :rook when 1, 6 type = :knight when 2, 5 type = :bishop when 3 type = :king when 4 type = :queen end poz = [row, column] case row when 0 Tile.new(poz, type, @player1) when 1 Tile.new(poz, :pawn, @player1) when 6 Tile.new(poz, :pawn, @player2) when 7 Tile.new(poz, type, @player2) else Tile.new(poz, :nil) end end end @is_over = false @board[@cursor[0]][@cursor[1]].place_cursor @check = false play end def self.read_char STDIN.echo = false # stops the console from printing return values STDIN.raw! # in raw mode data is given as is to the program--the system # doesn't preprocess special characters such as control-c input = STDIN.getc.chr # STDIN.getc reads a one-character string as a # numeric keycode. chr returns a string of the # character represented by the keycode. # (e.g. 65.chr => "A") if input == "\e" then input << STDIN.read_nonblock(3) rescue nil # read_nonblock(maxlen) reads # at most maxlen bytes from a # data stream; it's nonblocking, # meaning the method executes # asynchronously; it raises an # error if no data is available, # hence the need for rescue input << STDIN.read_nonblock(2) rescue nil end STDIN.echo = true # the console prints return values again STDIN.cooked! # the opposite of raw mode :) return input end def self.print_board(board) system "clear" board.each do |row| row.each do |tile| print tile.output + " " end puts; puts end end def self.play while @is_over == false print_board(@board) print "\nCHECK!" if @check == true move = KEYMAP[read_char] temp = @turn process_move(move) end end def self.valid_move?(move) new_cursor = [@cursor[0], @cursor[1]] case move when :left new_cursor[1] -= 1 when :right new_cursor[1] += 1 when :up new_cursor[0] -= 1 when :down new_cursor[0] += 1 end new_cursor.all? { |x| (0..7).include?(x) } end def self.update_cursor(move) new_cursor = [@cursor[0], @cursor[1]] case move when :left new_cursor[1] -= 1 when :right new_cursor[1] += 1 when :up new_cursor[0] -= 1 when :down new_cursor[0] += 1 end @board[@cursor[0]][@cursor[1]].remove_cursor @cursor = new_cursor @board[@cursor[0]][@cursor[1]].place_cursor end def self.process_selection if @selection == false && @board[@cursor[0]][@cursor[1]].player == @turn @selection = [@cursor[0], @cursor[1]] @board[@selection[0]][@selection[1]].place_select elsif @selection != false && @cursor == @selection remove_selection @board[@cursor[0]][@cursor[1]].place_cursor elsif @selection != false && moves(@selection).include?(@cursor) @board[@selection[0]][@selection[1]].remove_select @board[@selection[0]][@selection[1]].place_cursor @board[@cursor[0]][@cursor[1]] = @board[@selection[0]][@selection[1]] @board[@selection[0]][@selection[1]] = Tile.new(0, :nil) @selection = false @check = is_check(@turn) @turn == @player1 ? @turn = @player2 : @turn = @player1 end end def self.remove_selection if @selection @board[@selection[0]][@selection[1]].remove_select @selection = false end end def self.process_move(move) case move when :up, :down, :left, :right update_cursor(move) if valid_move?(move) when :return, :newline, :space process_selection when :escape remove_selection when :ctrl_c Process.exit(0) end end def self.is_check(turn) r = [] @board.each_with_index do |row, idx| row.each_with_index do |tile, idx2| if tile.type == :king && tile.player != turn r = [idx, idx2] end end end @board.each_with_index do |x, x_i| x.each_with_index do |y, y_i| return true if y.player == turn && moves([x_i, y_i]).include?(r) end end false end # MOVES def self.moves_rook(start) r = [] temp = [start[0], start[1] + 1] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[1] += 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn temp = [start[0], start[1] - 1] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[1] -= 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn temp = [start[0] + 1, start[1]] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[0] += 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn temp = [start[0] - 1, start[1]] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[0] -= 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn r end def self.moves_bishop(start) r = [] temp = [start[0] + 1, start[1] + 1] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[0] += 1 temp[1] += 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn temp = [start[0] + 1, start[1] - 1] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[0] += 1 temp[1] -= 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn temp = [start[0] - 1, start[1] + 1] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[0] -= 1 temp[1] += 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn temp = [start[0] - 1, start[1] - 1] while (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].type == :nil r << temp.dup temp[0] -= 1 temp[1] -= 1 end r << temp.dup if (temp.all? { |x| (0..7).include?(x) }) && @board[temp[0]][temp[1]].player != @turn r end def self.moves_king(start) a = start[0] b = start[1] r = [ [a, b + 1], [a, b - 1], [a + 1, b], [a + 1, b + 1], [a + 1, b - 1], [a - 1, b], [a - 1, b + 1], [a - 1, b - 1] ] r.select! { |x| (0..7).include?(x[0]) && (0..7).include?(x[1]) } r.reject { |x| @board[x[0]][x[1]].player == @turn } end def self.moves_knight(start) a = start[0] b = start[1] r = [ [a - 1, b + 2], [a + 1, b + 2], [a + 2, b + 1], [a + 2, b - 1], [a + 1, b - 2], [a - 1, b - 2], [a - 2, b - 1], [a - 2, b + 1] ] r.select! { |x| (0..7).include?(x[0]) && (0..7).include?(x[1]) } r.reject {|x| @board[x[0]][x[1]].player == @turn } end def self.moves_pawn(start) r = [] a = start[0] b = start[1] @turn == @player1 ? to_add = 1 : to_add = -1 return [] if (0..7).include?(a) == false r << [a + to_add, b] if @board[a + to_add][b].type == :nil r << [a + to_add, b + 1] if (0..7).include?(b + 1) && @board[a + to_add][b + 1].player != @turn r << [a + to_add, b - 1] if (0..7).include?(b - 1) && @board[a + to_add][b - 1].player != @turn r end def self.moves(start) type = @board[start[0]][start[1]].type case type when :rook moves_rook(start) when :bishop moves_bishop(start) when :king moves_king(start) when :pawn moves_pawn(start) when :queen moves_rook(start) + moves_bishop(start) when :knight moves_knight(start) end end # END MOVES end Chess.start_game<file_sep>/04_sudoku/sudoku.rb class Sudoku def initialize(sudoku_path) @board = File.read(sudoku_path) @board = @board.split("\n") @lines = (0...9).map { |x| (0...9).map {|y| [x, y] } } @columns = (0...9).map { |x| (0...9).map {|y| [y, x] } } all_poz = [] (0..9).each { |x| (0...9).each { |y| all_poz << [x, y] } } @squares = [] @squares = self.get_squares(all_poz) end def win? !(@board.join.include?("0")) end def get_squares(all_poz) row_counter = 0 column_counter = 0 temp_array = [] while row_counter < 3 column_counter = 0 while column_counter < 3 row_min = row_counter * 3 row_max = row_min + 3 column_min = column_counter * 3 column_max = column_min + 3 temp_array = all_poz.select { |(row, column)| row_min <= row && row < row_max && column_min <= column && column < column_max } @squares << temp_array column_counter += 1 end row_counter += 1 end @squares end def print_board puts " " + (0...9).map {|x| "[" + x.to_s + "]" } .join(" ") puts @board.each_with_index do |x, i| print "[" + i.to_s + "] " puts x.chars.map {|x| " " + x + " " }.join(" ") puts end end def check_poz_array(poz_array, board_array) focus_array = poz_array.map { |(row, column)| board_array[row][column] } (1...9).all? {|x| focus_array.count(x.to_s) <= 1 } end def check_if_valid(new_board) return false if @lines.any? {|x| self.check_poz_array(x, new_board) == false } return false if @columns.any? {|x| self.check_poz_array(x, new_board) == false } return false if @squares.any? {|x| self.check_poz_array(x, new_board) == false } true end def ask_for_input print "Enter a row, columnd and number like \"1 5 3\" (without the quoation marks, separated by spaces): " input = gets.chomp input = input.split (0...3).each { |x| input[x] = input[x].to_i } input[2] = input[2].to_s input end def next_move system("clear") self.print_board input = self.ask_for_input new_board = @board.join(" ").split new_board[input[0]][input[1]] = input[2] if self.check_if_valid(new_board) && input[2] != 0 @board = new_board else puts puts "Invalid move!" sleep(1) end end def play while self.win? == false self.next_move end system("clear") self.print_board puts "You win! :-)" puts end end<file_sep>/15_poly_tree_node/lib/00_tree_node.rb class PolyTreeNode attr_reader :parent, :children, :value def initialize(value) @parent = nil @children = [] @value = value end def parent=(new_parent) self.parent.children.delete(self) if @parent @parent = new_parent if new_parent != nil new_parent.children << self if new_parent.children.include?(self) == false end end def add_child(child_node) raise "Child node is not a Poly Tree Node object!" if child_node.is_a?(PolyTreeNode) == false child_node.parent = self @children << child_node if @children.include?(child_node) == false end def remove_child(child_node) raise "Child node is not a Poly Tree Node object!" if child_node.is_a?(PolyTreeNode) == false raise "Child node is not a child of this node" if @children.include?(child_node) == false child_node.parent = nil @children.delete(child_node) end def dfs(target_value) return self if @value == target_value @children.each do |x| if x != self result = x.dfs(target_value) return result if result end end return nil end def bfs(target_value) queue = [] queue.push(self) while queue.length != 0 current = queue.pop return current if current.value == target_value current.children.each { |x| queue.unshift(x) } end nil end end<file_sep>/29_hash_map_lru_cache/lib/p04_linked_list.rb class Node attr_reader :key attr_accessor :val, :next, :prev def initialize(key = nil, val = nil) @key = key @val = val @next = nil @prev = nil end def to_s "#{@key}: #{@val}" end def remove # optional but useful, connects previous link to next link # and removes self from list. @prev.next = @next @next.prev = @prev end end class LinkedList include Enumerable attr_reader :length def initialize @head = Node.new @tail = @head @head.next = @tail @tail.prev = @head @length = 0 end def [](i) each_with_index { |link, j| return link if i == j } nil end def first @head end def last @tail end def empty? @head.next == @tail && @head.key == nil end def get(key) self.each {|node| return node.val if node.key == key } return nil end def include?(key) self.each {|node| return true if node.key == key } false end def append(key, val) new_node = Node.new(key, val) if @head.key == nil @head = new_node @tail = @head @head.next = @tail @tail.prev = @head @length = 1 else @tail.next = new_node @tail.next.prev = @tail @tail = @tail.next @length += 1 end new_node end def update(key, val) self.each { |node| node.val = val if node.key == key } end def remove(key) if @length == 1 && @head.key == key @head = Node.new @tail = @head @head.next = @tail @tail.prev = @head @length = 0 else self.each do |node| next if node.key != key if node == @head @head = @head.next @head.prev = nil elsif node == @tail @tail = @tail.prev @tail.next = nil else node.prev.next = node.next node.next.prev = node.prev end end @length -= 1 end end def each pointer = @head while pointer != nil yield pointer break if pointer == pointer.next pointer = pointer.next end end #uncomment when you have `each` working and `Enumerable` included def to_s inject([]) { |acc, link| acc << "[#{link.key}, #{link.val}]" }.join(", ") end end <file_sep>/25_poker/deck.rb require_relative "./card.rb" class Deck def initialize @deck = Card.all_cards @deck.shuffle! @deck.shuffle! end def draw return @deck.pop end def start_over @deck = Card.all_cards @deck.shuffle! @deck.shuffle! end end<file_sep>/08_recursion_exercises/recursion.rb def range(start, end_) return Array.new(start) if end_ <= start return Array.new(end_) + range(end_ - 1) end def exp1(b, n) return 1 if n <= 0 return b * exp1(b, n - 1) end def exp2(b, n) return 1 if n <= 0 return b if n == 1 return exp2(b, n / 2) ** 2 if n.even? return b * exp2(b, ( (n - 1) / 2 ) ** 2) end def deep_dup(input) return Array.new(1, input) if input.is_a?(Array) == false return deep_dup(input[0]) if input.length <= 1 return deep_dup(input[0]) + deep_dup(input[1..-1]) end def r_fib(n) return nil if n < 1 return 1 if n == 1 return n * r_fib(n - 1) end def i_fib(n) return nil if n < 1 (1..n).reduce(:*) end def b_search(array, target) l = n.length return nil if l == 0 m = l / 2 return m if array[m] == target if target < array[m] return b_search(array[0...m], target) else return m + b_search(array[(m + 1)..-1]) end end def merge_helper(arr1, arr2) r = [] while arr1.length > 0 && arr2.length > 0 if arr1[0] > arr2[0] r.push(arr2.shift) else r.push(arr1.shift) end end r.push(arr1.shift) if arr1.length > 0 r.push(arr2.shift) if arr2.legnth > 0 r end def merge_sort(array) return array if array.length <= 1 l = array.length m = l / 2 merge_helper(merge_sort(array[0..m], merge_sort(array[(m + 1)..-1]))) end def array_subsets(array) return [[]] if array.length == 0 return array_subsets(array[1..-1]) + array_subsets(array[1..-1]).map {|x| x << array[0] } end def greedy_make_change(total, changes=[25, 10, 5, 1]) changes.sort! r = [] while total > 0 while total < changes[-1] changes.pop end r << changes[-1] total -= changes[-1] end r end<file_sep>/13_diy_adts/stack.rb class Stack def initialize @stack = [] end def push(el) @stack.push(el) end def pop(el) @stack.pop end def peek() @stack[-1] end end<file_sep>/21_chess/tile.rb require "./player.rb" class Tile attr_reader :char, :output, :type, :player CHAR_MAP = { king: "♚", queen: "♛", rook: "♜", bishop: "♝", knight: "♞", pawn: "♟", nil: "*" } def initialize(poz, type=:nil, player=nil) @row = poz[0] @column = poz[1] @type = type @char = CHAR_MAP[@type] @output = @char @player = player self.get_char end def get_char @char = CHAR_MAP[@type] return if @player == nil if @player.number == 1 @char = @char.red elsif @player.number == 2 @char = @char.blue end @output = @char end def place_cursor @output = @char.reverse_color if @output == @char end def place_select @output = @char.no_colors.yellow end def remove_select @output = @char end def remove_cursor @output = @char if @output == @char.reverse_color end end<file_sep>/04_sudoku/play.rb require "./sudoku.rb" print "enter the path of sudoku file to solve: " path = gets.chomp Sudoku.new(path).play<file_sep>/21_chess/cursor.rb require "io/console" class String def black; "\e[30m#{self}\e[0m" end def red; "\e[31m#{self}\e[0m" end def green; "\e[32m#{self}\e[0m" end def brown; "\e[33m#{self}\e[0m" end def blue; "\e[34m#{self}\e[0m" end def magenta; "\e[35m#{self}\e[0m" end def cyan; "\e[36m#{self}\e[0m" end def gray; "\e[37m#{self}\e[0m" end def yellow; "\e[33m#{self}\e[0m" end def pink; "\e[35m#{self}\e[0m" end def bg_black; "\e[40m#{self}\e[0m" end def bg_red; "\e[41m#{self}\e[0m" end def bg_green; "\e[42m#{self}\e[0m" end def bg_brown; "\e[43m#{self}\e[0m" end def bg_blue; "\e[44m#{self}\e[0m" end def bg_magenta; "\e[45m#{self}\e[0m" end def bg_cyan; "\e[46m#{self}\e[0m" end def bg_gray; "\e[47m#{self}\e[0m" end def bg_white; "\e[47;1m#{self}\e[0m" end def bold; "\e[1m#{self}\e[22m" end def italic; "\e[3m#{self}\e[23m" end def underline; "\e[4m#{self}\e[24m" end def blink; "\e[5m#{self}\e[25m" end def reverse_color; "\e[7m#{self}\e[27m" end def no_colors self.gsub /\e\[\d+m/, "" end end KEYMAP = { " " => :space, "h" => :left, "j" => :down, "k" => :up, "l" => :right, "w" => :up, "a" => :left, "s" => :down, "d" => :right, "\t" => :tab, "\r" => :return, "\n" => :newline, "\e" => :escape, "\e[A" => :up, "\e[B" => :down, "\e[C" => :right, "\e[D" => :left, "\177" => :backspace, "\004" => :delete, "\u0003" => :ctrl_c, } def read_char STDIN.echo = false # stops the console from printing return values STDIN.raw! # in raw mode data is given as is to the program--the system # doesn't preprocess special characters such as control-c input = STDIN.getc.chr # STDIN.getc reads a one-character string as a # numeric keycode. chr returns a string of the # character represented by the keycode. # (e.g. 65.chr => "A") if input == "\e" then input << STDIN.read_nonblock(3) rescue nil # read_nonblock(maxlen) reads # at most maxlen bytes from a # data stream; it's nonblocking, # meaning the method executes # asynchronously; it raises an # error if no data is available, # hence the need for rescue input << STDIN.read_nonblock(2) rescue nil end STDIN.echo = true # the console prints return values again STDIN.cooked! # the opposite of raw mode :) return input end<file_sep>/12_minesweeper/board.rb class Board def initialize @board = Array.new(9) { Array.new(9) { Tile.new } } end end<file_sep>/29_hash_map_lru_cache/lib/p05_hash_map.rb require_relative 'p04_linked_list' class HashMap attr_accessor :count include Enumerable def initialize(num_buckets = 8) @store = Array.new(num_buckets) { LinkedList.new } @max = num_buckets @count = 0 end def include?(key) bucket(key).include?(key) end def set(key, val) resize! if @count == @max if self.include?(key) == false bucket(key).append(key, val) @count += 1 return true else bucket(key).update(key, val) end false end def get(key) bucket(key).get(key) end def delete(key) if self.include?(key) == true bucket(key).remove(key) @count -= 1 return true end false end def each @store.each do |bucket2| bucket2.each do |node| yield [node.key, node.val] if node.key != nil end end end # uncomment when you have Enumerable included def to_s pairs = inject([]) do |strs, (k, v)| strs << "#{k.to_s} => #{v.to_s}" end "{\n" + pairs.join(",\n") + "\n}" end alias_method :[], :get alias_method :[]=, :set private def num_buckets @store.length end def resize! @max *= 2 new_store = Array.new(@max) { LinkedList.new } self.each do |(key, val)| new_store[key.hash % @max].append(key, val) end @store = new_store end def bucket(key) # optional but useful; return the bucket corresponding to `key` @store[key.hash % @max] end end <file_sep>/03_memory_puzzle/game.rb class Game def initialize @cards = Array.new(5) { ("A".."Z").to_a.sample(1) } @cards += @cards @cards.shuffle! @remaining = 10 @index = nil @index2 = nil end def first_pick system("clear") self.line_cards puts "Pick a card by entering a number between 0 and " + (@remaining - 1).to_s + " :" @index = gets.chomp while ("0".."9").include?(@index) == false || @index.to_i >= @remaining puts "\nInvalid input! Try again: " @index = gets.chomp end @index = @index.to_i end def second_pick system("clear") self.line_cards puts "Pick another card by entering a number between 0 and " + (@remaining - 1).to_s + " :" @index2 = gets.chomp while ("0".."9").include?(@index2) == false || @index2.to_i >= @remaining || @index2 == @index puts "\nInvalid input! Try again: " @index2 = gets.chomp end @index2 = @index2.to_i end def line_cards indices = [@index, @index2].reject { |x| x == nil } to_display = @cards.map.with_index { |x, i| indices.include?(i) ? x : "*" } puts to_display.join(" ") puts (0...@remaining).to_a.map {|x| x.to_s }.join(" ") end def process system("clear") self.line_cards sleep(1) if @cards[@index] == @cards[@index2] to_del = @cards[@index] @cards.delete(to_del) @remaining -= 2 end @index = nil @index2 = nil end def next_turn self.first_pick self.second_pick self.process end def play puts "\nStarting Game!" while @remaining > 0 self.next_turn end puts "\nGame Over!" end end<file_sep>/20_class_inheritance/test.rb require "./manager.rb" david = Employee.new("David", 10000, "TA", "Darren") shawna = Employee.new("Shawna", 12000, "TA", "Darren") darren = Manager.new("Darren", 78000, "TA Manager", "Ned", [david, shawna]) ned = Manager.new("Ned", 1000000, "Founder", nil, [darren]) p ned.bonus(5) p darren.bonus(4) p david.bonus(3)<file_sep>/22_rspec_homework/spec/dessert_spec.rb require 'rspec' require 'dessert' =begin Instructions: implement all of the pending specs (the `it` statements without blocks)! Be sure to look over the solutions when you're done. =end describe Dessert do let(:chef) { double("chef", :bake => 21, :titleize => "Yener") } subject { Dessert.new("type", 40, chef) } describe "#initialize" do it "sets a type" do expect(subject.type).to eq("type") end it "sets a quantity" do expect(subject.quantity).to eq(40) end it "starts ingredients as an empty array" do expect(subject.ingredients).to eq([]) end it "raises an argument error when given a non-integer quantity" do expect {Dessert.new("type2", "ss", "yener")}.to raise_error(ArgumentError) end end describe "#add_ingredient" do it "adds an ingredient to the ingredients array" do subject.add_ingredient("ingredient1") expect(subject.ingredients).to include("ingredient1") end end describe "#mix!" do it "shuffles the ingredient array" do (0..20).each { |n| subject.add_ingredient(n) } subject.mix! expect(subject.ingredients).to_not eq((0..20).to_a) end end describe "#eat" do it "subtracts an amount from the quantity" do subject.eat(20) expect(subject.quantity).to eq(20) end it "raises an error if the amount is greater than the quantity" do expect { subject.eat(200) }.to raise_error end end describe "#serve" do it "contains the titleized version of the chef's name" do expect(subject.serve).to include("Yener") end end describe "#make_more" do it "calls bake on the dessert's chef with the dessert passed in" do expect(subject.make_more).to eq(21) end end end <file_sep>/21_chess/player.rb class Player @@counter = 1 attr_reader :number, :name def initialize(name) @name = name @number = @@counter @@counter += 1 end def self.from_input print "Enter name for Player #{@@counter}: " name = gets.chomp.split[0] puts return self.new(name) end end<file_sep>/01_ghost/game.rb class Game def initialize(p1, p2) @fragment = "" @players = [p1, p2].shuffle @dictionary = Hash.new(0) File.read("dictionary.txt").split("\n").each { |x| @dictionary[x] = 1 } @losses = Hash.new(0) end def round_over? if @fragment.length > 2 && @dictionary[@fragment] == 1 return true end false end def check_guess(guess) return false if guess.length != 1 return false if ("a"..."z").include?(guess.downcase) == 0 return false if @dictionary.keys.none? { |key| key.index(@fragment + guess) == 0 } true end def next_turn current_player = @players[0] current_player.announce_turn puts "current fragment is: " + @fragment guess = current_player.get_guess while self.check_guess(guess) == false current_player.invalid_guess guess = current_player.get_guess end @fragment += guess @players.rotate! puts current_player.lose_round if self.round_over? end def play_round @fragment = "" puts "starting round" puts "" while self.round_over? == false self.next_turn end puts puts "end of round" end def play while @players.none? {|player| player.lost? } self.play_round end puts "game over!" @players.select {|player| player.lost? }[0].lose_game end end<file_sep>/13_diy_adts/queue.rb class Queue def initialize @queue = [] end def enqueue(el) @queue.unshift(el) end def dequeue @queue.pop end def peek @queue[-1] end end<file_sep>/16_knights_travails/path_finder.rb require "./tree_node.rb" class KnightPathFinder def initialize(start_poz) @start_node = PolyTreeNode(start_poz) @visited_positions = [start_poz] self.build_move_tree end def self.valid_moves_helper(pos, x_add, y_add) ret = pos.dup ret[0] += x_add ret[1] += y_add ret end def self.valid_moves(pos) r = [] r << self.class.valid_moves_helper(pos, 1, 2) r << self.class.valid_moves_helper(pos, -1, 2) r << self.class.valid_moves_helper(pos, 1, -2) r << self.class.valid_moves_helper(pos, -1, -2) r << self.class.valid_moves_helper(pos, 2, 1) r << self.class.valid_moves_helper(pos, -2, 1) r << self.class.valid_moves_helper(pos, 2, -1) r << self.class.valid_moves_helper(pos, -2, -1) r.select {|x| 0 <= x[0] && x[0] < 8 && 0 <= x[1] && x[1] < 8 } end def new_move_positions(pos_node) new_moves = self.class.valid_moves(pos_node) new_moves.each end def build_move_tree ; end end<file_sep>/29_hash_map_lru_cache/lib/p03_hash_set.rb class HashSet attr_reader :count def initialize(num_buckets = 8) @store = Array.new(num_buckets) { Array.new } @count = 0 @max = num_buckets end def insert(key) resize! if @count == @max if self[key].include?(key) == false self[key].push(key) @count += 1 return true end false end def include?(key) self[key].include?(key) end def remove(key) if self[key].include?(key) self[key].delete(key) @count -= 1 return true end false end private def [](num) # optional but useful; return the bucket corresponding to `num` @store[num.hash % @max] end def num_buckets @store.length end def resize! @max *= 2 new_store = Array.new(@max) { Array.new } @store.each do |bucket| bucket.each do |element| new_store[element.hash % @max].push(element) end end @store = new_store end end <file_sep>/21_chess/move.rb def Move def initialize(start_tile, end_tile) @start = start_tile @end_ = end_tile end end<file_sep>/20_class_inheritance/manager.rb require "./employee.rb" class Manager < Employee def initialize(name, title, salary, boss, team=[]) super(name, title, salary, boss) @team = team end def bonus(multiplier) @team.reduce(0) { |sum, num| sum + num.bonus(multiplier) + (num.is_a?(Manager) ? num.salary * multiplier : 0 ) } end end<file_sep>/17_simon/lib/simon.rb require "colorize" class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @sequence_length = 1 @game_over = false @seq = [] end def play self.take_turn while @game_over == false self.game_over_message self.reset_game end def take_turn self.show_sequence self.require_sequence if @game_over == false self.round_success_message @sequence_length += 1 end end def show_sequence self.add_random_color end def require_sequence seq = gets.chomp.split @game_over == 1 if seq != @seq end def add_random_color @seq += COLORS.sample(1) end def round_success_message end def game_over_message puts "GAME OVER :( ".red end def reset_game @sequence_length = 1 @seq = [] @game_over = false end end Simon.new.play<file_sep>/24_tdd/lib/tdd.rb class Array def my_uniq r = [] self.each { |x| r << x if r.include?(x) == false} r end def two_sum r = [] self.each_with_index do |x1, i1| self.each_with_index do |x2, i2| if x1 != 0 && x1 + x2 == 0 r << [i1, i2].sort end end end r.uniq end end def my_transpose(array) raise ArgumentError.new("Argument not an array") if array.is_a?(Array) == false r = Array.new(array.length) { Array.new(array.length) } (0...array.length).each do |i1| (0...array.length).each do |i2| r[i1][i2] = array[i2][i1] end end r end def stock_picker(stocks) raise ArgumentError.new("Argument not an array") if stocks.is_a?(Array) == false t = [] profit = -1 (0...stocks.length).each do |i1| ((i1 + 1)...stocks.length).each do |i2| new_profit = stocks[i2][1] - stocks[i1][0] if new_profit > profit t = [i1, i2] profit = new_profit end end end t end class Toh attr_reader :stacks def initialize @stacks = [ [5, 3], [4, 1], [2] ] end def move(start, end_) if (@stacks[start][-1] < @stacks[end_][-1]) @stacks[end_].push(@stacks[start].pop) return true end return false end def end? return true if @stacks.count { |x| x.empty? } == 2 false end end<file_sep>/25_poker/player.rb class Player def initialize(name, money) @name = name @money = money @hand = [] @pot = 1000 end end<file_sep>/09_word_chains/word_chains.rb class WordChainer def initialize(first_word, second_word) @first_word = first_word @second_word = second_word raise "First word and second word cannot be of different length" if first_word.length != second_word.length raise "First word and second word are the same ..." if first_word == second_word @dictionary = Hash.new(0) File.read("dictionary.txt").split("\n").each { |x| @dictionary[x] = 1 } raise "First word does not exist!" if @dictionary[@first_word] != 1 raise "Second word does not exist!" if @dictionary[@second_word] != 1 l = first_word.length @dictionary = @dictionary.keys.select { |x| x.length == l } @is_solved = 0 self.try end def try @stack = [[@first_word.dup, []]] while @stack.length > 0 && @dictionary.length > 0 && @is_solved == 0 self.next_word end if @is_solved == 1 puts @solution else puts "Cannot find a word chain between #{@first_word} and #{@second_word}" end end def char_diffs(word1, word2) word1_chars = word1.chars word2_chars = word2.chars matches = 0 (0...word1_chars.length).each { |i| matches += 1 if word1_chars[i] == word2_chars[i] } return word2_chars.length - matches end def is_match?(p1, p2) return false if p1.length != p2.length return false if self.char_diffs(p1, p2) != 1 true end def get_matches(word) r = [] @dictionary.each_with_index {|x, i| (r << x ; @dictionary.delete(x)) if self.is_match?(word, x) } r end def next_word current = @stack[0] current_word = current[0] current_history = current[1] matches = self.get_matches(current_word) if matches.length != 0 if matches.include?(@second_word) @is_solved = 1 @solution = current_history + [current_word] + [@second_word] return end @stack += matches.map { |x| [x, current_history + [current_word]] } end @stack.delete_at(0) end end if __FILE__ == $PROGRAM_NAME WordChainer.new(ARGV[0].to_s, ARGV[1]) end<file_sep>/01_ghost/play.rb require "./game.rb" require "./player.rb" print "Enter name for player1: " p1_name = gets.chomp puts print "Enter name for player2: " p2_name = gets.chomp puts puts "Starting game" puts game = Game.new(Player.new(p1_name), Player.new(p2_name)) game.play<file_sep>/18_mancala/mancala.rb require "colorize" require "./board.rb" class Mancala def initialize system("clear") print "Enter player1 name (single word): " @player1_name = gets.chomp.split[0] print "Enter player2 name (single word): " @player2_name = gets.chomp.split[0] @board = [0, 4, 4, 4, 4, 0, 4, 4, 4, 4] @turn = 1 @winner = 0 self.play end def self.get_board_string(board, tur=0, turn=-1) str = "%2s %2s %2s %2s" % [board[0], board[1], board[2], board[3]] str = str.light_blue if tur == turn str = str.yellow if tur == 0 str end def is_over? if p1_board.all?(0) || p2_board.all?(0) if @board[0] > @board[5] @winner = @player1_name elsif @board[5] > @board[0] @winner = @player2_name else @winner = "" end return true end false end def play while self.is_over? == false self.next_turn end puts if @winner == "" puts "TIE!" else puts "#{@winner} WINS!" end end def get_input puts print "Enter a number 0, 1, 2 or 3: " input = gets.chomp if ("0".."3").include?(input) == false puts "Invalid input! Try again" return get_input end input.to_i end def get_next_current(current) return current - 1 if (1..5).include?(current) return 6 if current == 0 return current + 1 if (5..8).include?(current) return 5 if current == 9 end def process_input(input) current = input stones = @board[current] @board[current] = 0 self.render @turn == 1 ? special = 0 : special = 5 @turn == 1 ? counter = 5 : counter = 0 while stones > 0 current = get_next_current(current) if current != counter @board[current] += 1 stones -= 1 end end if @board[current] != 1 && [0, 5].include?(current) == false return process_input(current) elsif current != special @turn = (@turn % 2) + 1 end end def next_turn self.render input = get_input input += 1 input += 5 if @turn == 2 self.process_input(input) end def render system("clear") puts "%4s%s" % ["", self.class.get_board_string([0, 1, 2, 3])] puts puts "%4s%s" % ["", self.class.get_board_string(p1_board, 1, @turn)] puts "%2s%13s%3s" % ["P1", "", "P2"] puts "%2s%13s%3s" % [@board[0].to_s, "", @board[5].to_s] puts "%4s%s" % ["", self.class.get_board_string(p2_board, 2, @turn)] end private def p1_board @board[1..4] end def p2_board @board[6..-1] end end if __FILE__ == $PROGRAM_NAME Mancala.new end<file_sep>/24_tdd/spec/tdd_spec.rb require "rspec" require "tdd" describe Array do describe ".my_uniq" do subject { [1, 1, 2, 2, 3] } it "removes dupes" do expect(subject.my_uniq).to eq([1, 2, 3]) end end describe ".two_sum" do it "finds all pairs of positions where elements at those positions sum to zero" do expect([-1, 0, 2, -2, 1].two_sum).to eq([[0, 4], [2, 3]]) end end describe "my_transpose()" do subject { [[0, 1, 2], [3, 4, 5], [6, 7, 8]] } it "converts between the row oriented and column oriented representations of an array" do expect(my_transpose(subject)).to eq([[0, 3, 6], [1, 4, 7], [2, 5, 8]]) end it "raises error when argumetn is not an array" do expect{ my_transpose("test")}.to raise_error(ArgumentError, "Argument not an array") end end describe "stock picker" do subject { [[1, 2], [3, 4], [5, 6]] } it "returns an array (of 2 elements) with the number (not index, but index + 1) of day to buy and sell" do expect(stock_picker(subject)).to eq([0, 2]) end end end describe Toh do subject { Toh.new } describe "#move" do it "moves when valid" do expect(subject.move(1, 2)).to eq(true) end it "does not move when invalid" do expect(subject.move(0, 2)).to eq(false) end end describe "#end?" do it "return false when game is not over" do expect(subject.end?).to eq(false) end end end<file_sep>/README.md # App Academy - Ruby Gif of the Chess project ![Gif of Chess](chess_demo.gif?raw=true "Chess") Image of the Mine Sweeper project ![Screen Shot of Mine Sweeper](screen_show.png?raw=true "Mine Sweeper") <file_sep>/06_recursion_homework/recursion.rb def sum_to(n) return 1 if n == 1 return n + sum_to(n - 1) end def add_numbers(nums_array) return nums_array[0] if nums_array.length == 1 return nil if nums_array.length == 0 return nums_array[0] + add_numbers(nums_array[1..-1]) end def factorial(n) return nil if n < 0 return 1 if n == 0 return n * factorial(n - 1) end def gamma(n) factorial(n - 1) end def ice_cream_shop(flavors, favorite) return false if flavors.length == 0 return flavors[0] == favorite if flavors.length == 1 return flavors[0] == favorite || ice_cream_shop(flavors[1..-1], favorite) end def reverse(str) return str if str.length <= 1 return str[-1] + reverse(str[0...-1]) end<file_sep>/12_minesweeper/game.rb require "./tile.rb" require "colorize" class Minesweeper def initialize @board = Array.new(10) { Array.new(10) { Tile.new } } @is_loss = 0 end def render system("clear") puts " 0 1 2 3 4 5 6 7 8 9".yellow (0..9).each do |i| puts print i.to_s.yellow + " " @board[i].each { |tile| print tile.render; print " " } puts end puts end def game_over? return true if @is_loss == 1 return false if @board.any? do |row| row.any? do |tile| tile.is_unrevealed_bomb? end end true end def is_valid_input?(input) return false if "rf".include?(input[0]) == false return false if (0..9).include?(input[1]) == false return false if (0..9).include?(input[2]) == false return true end def get_input print "Enter an action (r for reveal or f for flag lowercase) and two digits (ex: r05 or f36): " input = gets.chomp while self.is_valid_input?(input) == 0 print "Invalid input! Try again: " input = gets.chomp end input end def get_neighbors(coors) r = [] [-1, 0, 1].each do |add_to_x| [-1, 0, 1].each do |add_to_y| new_x = coors[0] + add_to_x new_y = coors[1] + add_to_y if new_x.to_s.length == 1 && new_y.to_s.length == 1 r << [new_x, new_y] end end end r end def count_neighbors(coor_arr) coor_arr.reduce(0) { |sum, num| sum + @board[num[0]][num[1]].is_mine } end def reveal_recursively(coors) neighbors = self.get_neighbors(coors) neighbor_count = self.count_neighbors(neighbors) @board[coors[0]][coors[1]].reveal(neighbor_count) if neighbor_count == 0 neighbors.each do |target| self.reveal_recursively(target) if @board[target[0]][target[1]].render == "*" end end end def process_input(input) x_coor = input[1].to_i y_coor = input[2].to_i action = input[0] if action == "r" coors = [x_coor, y_coor] target = @board[x_coor][y_coor] break if target.is_revealed == 1 if target.is_mine == 1 target.reveal @is_loss = 1 else self.reveal_recursively(coors) end elsif action == "f" @board[x_coor][y_coor].flag end end def next_turn self.render input = self.get_input self.process_input(input) end def play while self.game_over? == false self.next_turn end self.render puts "You win, this time ..." if @is_loss != 1 #self.announce_result end end Minesweeper.new.play<file_sep>/27_lru_cache/lru_cache.rb class LRUCache def initialize(num=0) @cache = Array.new(num) @num = num end def add(element) @cache.delete(element) @cache.push(element) if @cache.length > @num @cache.shift end end def show p @cache end def count @cache.length end end <file_sep>/05_stack_trace/stack_trace.rb MAX_STACK_SIZE = 200 tracer = proc do |event| if event == 'call' && caller_locations.length > MAX_STACK_SIZE fail "Probable Stack Overflow" end end set_trace_func(tracer)<file_sep>/25_poker/card.rb require "./libft.rb" class Card RANKS = [ :A, :K, :Q, :J, 10, 9, 8, 7, 6, 5, 4, 3, 2 ] SUITS = [ :heart, :diamond, :club, :spade ] attr_reader :suit, :rank def initialize(suit, rank) raise ArgumentError.new("#{suit} is not a valid suit") if SUITS.include?(suit) == false raise ArgumentError.new("#{rank} is not a valid rank") if RANKS.include?(rank) == false @suit = suit @rank = rank end def self.all_cards r = [] RANKS.each do |rank| SUITS.each do |suit| r << self.class.new(suit, rank) end end r end def same_suit?(other_card) self.suit == other_card.suit end def same_rank?(other_card) self.rank == other_card.rank end def >(other_card) RANKS.index(self.rank) < RANKS.index(other_card.rank) end def <(other_card) RANKS.index(self.rank) < RANKS.index(other_card.rank) end end<file_sep>/12_minesweeper/tile.rb class Tile attr_reader :is_mine, :is_revealed def initialize rand(0..5) == 0 ? @is_mine = 1 : @is_mine = 0 @is_mine = @is_mine.to_i @is_revealed = 0 @is_flagged = 0 @render_character = "*" end def is_unrevealed_bomb? return true if @is_mine == 1 && @is_flagged == 0 false end def render @render_character end def flag if @is_flagged == 0 && @is_revealed == 0 @is_flagged = 1 @render_character = "F".light_blue elsif @is_flagged == 1 && @is_revealed == 0 @is_flagged = 0 @render_character = "*" end return @render_Character end def reveal(neighbor_bomb_count=0) if @is_revealed == 0 if @is_mine == 1 @render_character = "B".red else @render_character = neighbor_bomb_count.to_s @render_character = "_" if neighbor_bomb_count == 0 end @is_revealed = 1 end @render_character end end<file_sep>/01_ghost/player.rb class Player def initialize(name) @name = name @losses = 0 end def announce_turn puts "current player: " + @name end def get_guess print "enter a letter: " gets.chomp end def invalid_guess puts puts "invalid guess! try again" puts end def lose_round puts @name + " lost this round :( " @losses += 1 end def lost? @losses >= 5 end def lose_game puts @name + " lost the game :( " end end<file_sep>/00_enumerables/enumerables.rb class Array def my_each i = 0 while i < self.length yield self[i] i += 1 end end def my_select(&prc) r = [] self.my_each { |n| r << n if prc.(n) } r end def my_reject(&prc) r = [] self.my_each { |n| r << n unless prc.(n) } r end def my_any?(&prc) self.my_each { |n| return true if prc.(n) } false end def my_flatten self.map { |x| x.is_a?(Array) ? x.flatten : x } end def my_zip(*arg) r = Array.new([]) self.each_with_index { |x, i| r[i] << self[i] } args.each_with_index { |x, i| r[i] << x[i] } r end def my_rotate(p1 = 1) r = self.dup p1.times { r.push(r.shift) } r end def my_join(p1 = "") self.reduce() { |sum, num| sum.to_s + p1 + num.to_s } end def my_reverse (0...l).map { |i| } end end <file_sep>/20_class_inheritance/employee.rb class Employee attr_reader :name, :title, :boss, :salary def initialize(name, salary, title, boss) @name = name @title = title @boss = boss @salary = salary end def bonus(multiplier) @salary * multiplier end end<file_sep>/12_minesweeper/README.md # App_Academy_Ruby Image of the Mine Sweeper project ![Screen Shot of Mine Sweeper](../screen_show.png?raw=true "Mine Sweeper") <file_sep>/29_hash_map_lru_cache/lib/p01_int_set.rb class MaxIntSet def initialize(max) @store = Array.new(max) {false} @max = max end def insert(num) #raise ArgumentError.new("Can only accept integers") if num.is_a? FixNum == false raise ArgumentError.new("Out of bounds") if num < 0 raise ArgumentError.new("Out of bounds") if num >= @max if @store[num] == false @store[num] = true return true else return false end end def remove(num) #raise ArgumentError.new("Can only accept integers") if num.is_a? FixNum == false raise ArgumentError.new("Out of bounds") if num < 0 raise ArgumentError.new("Out of bounds") if num >= @max @store[num] = false end def include?(num) #raise ArgumentError.new("Can only accept integers") if num.is_a? FixNum == false raise ArgumentError.new("Can only accept non-negative numbers") if num < 0 raise ArgumentError.new("Invalid argument: #{num} is greater than #{@max}") if num >= @max return @store[num] end private def is_valid?(num) return true if 0 <= num && num < max false end def validate!(num) end end class IntSet def initialize(num_buckets = 20) @store = Array.new(num_buckets) { Array.new } @size = num_buckets end def insert(num) if self[num].include?(num) == false self[num].push num return true end false end def remove(num) if self[num].include?(num) == true self[num].delete num return true end false end def include?(num) return self[num].include?(num) end private def [](num) # optional but useful; return the bucket corresponding to `num` @store[num % @size] end def num_buckets @size end end class ResizingIntSet attr_reader :count, :max, :store def initialize(num_buckets = 20) @store = Array.new(num_buckets) { Array.new } @count = 0 @max = num_buckets end def insert(num) resize! if @count == @max if self[num].include?(num) == false self[num].push(num) @count += 1 return true end false end def remove(num) if self[num].include?(num) == true self[num].delete(num) @count -= 1 return true end false end def include?(num) self[num].include?(num) end private def [](num) # optional but useful; return the bucket corresponding to `num` @store[num % @max] end def num_buckets @max end def resize! @max *= 2 new_store = Array.new(@max) {Array.new} @store.each do |bucket| bucket.each do |number| new_store[number % @max].push(number) end end @store = new_store end end
24c7e7e7b3a5e37d2d8563ce47eb26e72113fe20
[ "Markdown", "Ruby" ]
43
Ruby
yenertuz/app_academy_ruby
44957a5c30cffafd8fc66a645d1d86debb780f60
37dae2bf9af1845b7ef020adefe643265647b106
refs/heads/master
<file_sep><?php use Carbon\Carbon; use Arkade\Bronto\RestClient; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Handler\MockHandler; use Arkade\Bronto\RestAuthentication; use PHPUnit\Framework\TestCase; class RestClientTest extends TestCase { public function testRequest() { $auth = new RestAuthentication( HandlerStack::create(new MockHandler([ new Response( 200, [], json_encode( [ 'access_token' => 'aRandom<PASSWORD>', 'refresh_token' => '<PASSWORD>', 'expires_in' => 3600, ] ) ), ])) ); $auth->setAuthUrl('https://auth.bronto.com/oauth2/token'); $auth->setClientId('arkade'); $auth->setClientSecret('secret'); $auth->setEndpoint('https://rest.bronto.com'); // Set up our request(s) history $container = []; $history = Middleware::history($container); // Set up our mock handler for the auth response(s) $mock = new MockHandler( [new Response(200, [], json_encode([]))] ); // Set up our Guzzle Handler Stack History (for requests) $stack = HandlerStack::create($mock); $stack->push($history); // Let's make the client with our mock responses and history container $client = new RestClient($auth, $stack); // Let's test! $client->request('GET', 'some-endpoint', ['query' => ['foo' => 'bar']]); // Check the correct outgoing call was made $this->assertEquals('GET', $container[0]['request']->getMethod()); $this->assertEquals('/some-endpoint?foo=bar', $container[0]['request']->getRequestTarget()); } }<file_sep><?php namespace Omneo\Bronto\Modules; use Omneo\Bronto\Entities\Order; use Omneo\Bronto\Parsers\OrderParser; use Omneo\Bronto\Serializers\OrderSerializer; use Illuminate\Support\Collection; class OrderService extends AbstractRestModule { /** * Order find. * Uses Bronto order ID * * @param $id * @return Order */ public function find($id) { return (new OrderParser)->parse( $this->client->get('orders/'.$id,['debug' => env('APP_DEBUG')]) ); } /** * Order search. * Uses customer order ID * * @param $id * @return Collection */ public function findById($id) { $data = $this->client->get('orders?customerOrderId='.$id,['debug' => env('APP_DEBUG')]); $collection = new Collection; if(!count($data)) return $collection; foreach($data as $item){ $collection->push( (new OrderParser)->parse($item) ); } return $collection; } /** * Order add. * * @param Order $order * @param boolean $createContact * @param boolean $triggerEvents * @return \Psr\Http\Message\ResponseInterface */ public function add(Order $order, $createContact = false, $triggerEvents = false) { $query = 'createContact='.$createContact; $query .= 'triggerEvents='.$createContact; return (new OrderParser)->parse( $this->client->post( 'orders?'.$query, [ 'headers' => ['Content-Type' => 'application/json'], 'body' => (new OrderSerializer)->serialize($order), 'debug' => env('APP_DEBUG') ] ) ); } /** * Order update. * Uses Bronto order ID * * @param Order $order * @param boolean $createContact * @param boolean $triggerEvents * @return \Psr\Http\Message\ResponseInterface */ public function update(Order $order, $createContact = false, $triggerEvents = false) { $query = 'createContact='.$createContact; $query .= 'triggerEvents='.$createContact; return (new OrderParser)->parse( $this->client->post( 'orders/'.$order->getOrderId().'?'.$query, [ 'headers' => ['Content-Type' => 'application/json'], 'body' => (new OrderSerializer)->serialize($order), 'debug' => env('APP_DEBUG') ] ) ); } /** * Order update. * Uses customer order ID * * @param Order $order * @param boolean $createContact * @param boolean $triggerEvents * @return \Psr\Http\Message\ResponseInterface */ public function updateById(Order $order, $createContact = false, $triggerEvents = false) { $query = 'createContact='.$createContact; $query .= 'triggerEvents='.$createContact; return (new OrderParser)->parse( $this->client->post( 'orders/customerOrderId/'.$order->getCustomerOrderId().'?'.$query, [ 'headers' => ['Content-Type' => 'application/json'], 'body' => (new OrderSerializer)->serialize($order), 'debug' => env('APP_DEBUG') ] ) ); } /** * Order delete. * Uses Bronto order ID * * @param string $id * @return \Psr\Http\Message\ResponseInterface */ public function delete($id) { return $this->client->delete('orders/'.$id, ['debug' => env('APP_DEBUG')]); } /** * Order delete. * Uses customer order ID * * @param string $id * @return \Psr\Http\Message\ResponseInterface */ public function deleteById($id) { return $this->client->delete('orders/customerOrderId/'.$id,['debug' => env('APP_DEBUG')]); } }<file_sep><?php namespace Omneo\Bronto; use Bronto_Api; use Illuminate\Support\Collection; class SoapClient { /** * @var Bronto_Api */ protected $client; /** * @var string */ protected $token; /** * @var string */ protected $listId; /** * @var Collection */ protected $contactMappings; /** * Client constructor. * */ public function __construct() { $this->client = new \Bronto_Api(); } /** * @return Bronto_Api */ public function getClient() { return $this->client; } /** * @param Bronto_Api $client * @return SoapClient */ public function setClient($client) { $this->client = $client; return $this; } /** * @return string */ public function getToken() { return $this->token; } /** * @param string $token * @return SoapClient */ public function setToken($token) { $this->token = $token; $this->client->setToken($token); $this->client->login(); return $this; } /** * @return string */ public function getListId() { return $this->listId; } /** * @param string $listId * @return SoapClient */ public function setListId($listId) { $this->listId = $listId; return $this; } /** * @return Collection */ public function getContactMappings() { return $this->contactMappings; } /** * @param Collection $contactMappings * @return SoapClient */ public function setContactMappings($contactMappings) { $this->contactMappings = $contactMappings; return $this; } /** * Contact service module. * * @return Modules\ContactService */ public function contactService() { return new Modules\ContactService($this, $this->contactMappings); } /** * Delivery service module. * * @return Modules\DeliveryService */ public function deliveryService() { return new Modules\DeliveryService($this); } } <file_sep><?php namespace Omneo\Bronto\Exceptions; use Exception; class NotFoundException extends Exception { // } <file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; use Illuminate\Support\Collection; class DeliveryField extends AbstractEntity { /** * @var string */ protected $name; /** * @var string */ protected $type; /** * @var string */ protected $content; /** * @return string */ public function getName() { return $this->name; } /** * The name of the API message tag. API message tags can be placed in the body or subject line of an email message * with a prepended ‘#’, as in “%%#tag_name%%“). When you reference the name of an API message tag via the API, * be sure to leave off the “%%# %%” portion of the API message tag. * For example, name => tag_name, rather than name => %%#tag_name%%. * Loop tags use a slightly different syntax (%%#tagname_#%%) and can only be added to the body of an email message. * When you reference the the name of a Loop tag via the API, * be sure to leave off the “%%# %%” portion of the Loop tag, * and replace the underscore “_#” with an underscore followed by a number. * @param string $name * @return DeliveryField */ public function setName($name) { $this->name = $name; return $this; } /** * @return string */ public function getType() { return $this->type; } /** * The version of the message into which API message tag content should be inserted {text or html}. * @param string $type * @return DeliveryField */ public function setType($type) { $this->type = $type; return $this; } /** * @return string */ public function getContent() { return $this->content; } /** * @param string $content * @return DeliveryField */ public function setContent($content) { $this->content = $content; return $this; } /** * @return Array */ public function jsonSerialize() { $result = get_object_vars($this); return $result; } } <file_sep><?php use Carbon\Carbon; use Arkade\Bronto\RestAuthentication; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Handler\MockHandler; use PHPUnit\Framework\TestCase; class AuthenticationTest extends TestCase { public function testAuthUrlSetterGetter() { $auth = new RestAuthentication; $auth->setAuthUrl('https://auth.bronto.com/oauth2/token'); $this->assertEquals('https://auth.bronto.com/oauth2/token', $auth->getAuthUrl()); } public function testClientIdGetterSetter() { $auth = new RestAuthentication; $auth->setClientId('arkade'); $this->assertEquals('arkade', $auth->getClientId()); } public function testPasswordGetterSetter() { $auth = new RestAuthentication; $auth->setClientSecret('secret'); $this->assertEquals('secret', $auth->getClientSecret()); } public function testEndpointGetterSetter() { $auth = new RestAuthentication; $auth->setEndpoint('https://rest.bronto.com'); $this->assertEquals('https://rest.bronto.com', $auth->getEndpoint()); } public function testTokenExpiryGetterSetter() { $auth = new RestAuthentication; $auth->setTokenExpiry(Carbon::createFromTimestamp('3600')); $this->assertEquals(Carbon::createFromTimestamp('3600'), $auth->getTokenExpiry()); } public function testTokenIsExpired() { $auth = new RestAuthentication; $auth->setTokenExpiry(Carbon::now()->addHour()); $this->assertEquals(false, $auth->isTokenExpired()); $auth->setTokenExpiry(Carbon::now()->subHour()); $this->assertEquals(true, $auth->isTokenExpired()); } public function testTokenSetter() { $auth = new RestAuthentication; $auth->setToken('my<PASSWORD>'); $auth->setTokenExpiry(Carbon::now()->addHour()); $this->assertEquals('mytoken', $auth->getToken()); } public function testTokenGetter() { $auth = new RestAuthentication( HandlerStack::create(new MockHandler([ new Response( 200, [], json_encode( [ 'access_token' => '<PASSWORD>', 'refresh_token' => '<PASSWORD>', 'expires_in' => 3600, ] ) ), ])) ); $this->assertEquals('aRandomToken', $auth->getToken()); $this->assertEquals('aRandomRefreshToken', $auth->getRefreshToken()); $this->assertEquals(Carbon::now()->addSeconds(3600)->toDateTimeString(), $auth->getTokenExpiry()->toDateTimeString()); } public function testCreateToken(){ // Set up our request(s) history $container = []; $history = Middleware::history($container); // Set up our mock handler for the auth response(s) $mock = new MockHandler( [ new Response( 200, [], json_encode( [ 'access_token' => '<PASSWORD>', 'refresh_token' => '<PASSWORD>', 'expires_in' => 3600, ] ) ), ] ); // Set up our Guzzle Handler Stack History (for requests) $stack = HandlerStack::create($mock); $stack->push($history); // Let's make the client with our mock responses and history container $auth = new RestAuthentication($stack); $auth->setAuthUrl('https://auth.bronto.com/oauth2/token'); $auth->setClientId('arkade'); $auth->setClientSecret('secret'); // Let's call create token $auth->createOauthToken(); // Check that only one call was made to get q new token $this->assertCount(1, $container); // Check that it was a POST request $this->assertEquals('POST', $container[0]['request']->getMethod()); // Ensure that it went to the Auth URL specified $this->assertEquals('/oauth2/token', $container[0]['request']->getRequestTarget()); // Lastly, make sure the body has the correct form params $this->assertEquals( "grant_type=client_credentials&client_id=arkade&client_secret=secret", (string)$container[0]['request']->getBody() ); $this->assertEquals('aRandomToken', $auth->getToken()); $this->assertEquals('aRandomRefreshToken', $auth->getRefreshToken()); } public function testRefreshToken(){ // Set up our request(s) history $container = []; $history = Middleware::history($container); // Set up our mock handler for the auth response(s) $mock = new MockHandler( [ new Response( 200, [], json_encode( [ 'access_token' => 'aRandomToken', 'refresh_token' => '<PASSWORD>', 'expires_in' => 3600, ] ) ) ] ); // Set up our Guzzle Handler Stack History (for requests) $stack = HandlerStack::create($mock); $stack->push($history); // Let's make the client with our mock responses and history container $auth = new RestAuthentication($stack); $auth->setAuthUrl('https://auth.bronto.com/oauth2/token'); $auth->setClientId('arkade'); $auth->setClientSecret('secret'); $auth->setRefreshToken('<PASSWORD>'); // Let's call create token $auth->refreshOauthToken(); // Check that only one call was made to get q new token $this->assertCount(1, $container); // Check that it was a POST request $this->assertEquals('POST', $container[0]['request']->getMethod()); // Ensure that it went to the Auth URL specified in the setClientConfig $this->assertEquals('/oauth2/token', $container[0]['request']->getRequestTarget()); // Lastly, make sure the body has the correct form params $this->assertEquals( "grant_type=refresh_token&client_id=arkade&client_secret=secret&refresh_token=aRandom<PASSWORD>", (string)$container[0]['request']->getBody() ); $this->assertEquals('aRandomToken', $auth->getToken()); $this->assertEquals('anotherRandomRefreshToken', $auth->getRefreshToken()); } }<file_sep><?php namespace Omneo\Bronto\Parsers; use Carbon\Carbon; use Omneo\Bronto\Entities; use Illuminate\Support\Collection; class LineItemParser { /** * Parse the given array to a LineItem entity. * * @param array $payload * @return Entities\LineItem */ public function parse($payload) { $lineItem = (new Entities\LineItem()) ->setCategory($payload->category) ->setDescription($payload->description) ->setImageUrl($payload->imageUrl) ->setName($payload->name) ->setOther($payload->other) ->setProductUrl($payload->productUrl) ->setQuantity($payload->quantity) ->setSalePrice($payload->salePrice) ->setSku($payload->sku) ->setTotalPrice($payload->totalPrice) ->setUnitPrice($payload->unitPrice); return $lineItem; } }<file_sep><?php namespace Omneo\Bronto\Parsers; use Omneo\Bronto\Entities; use Illuminate\Support\Collection; class ContactUnsubscribeParser { /** * Parse the given array to a Contact entity. * * @param array $payload * @return Collection */ public function parse($payload) { $result = collect([]); foreach($payload as $item){ $contact = (new Entities\Contact) ->setId($item->id) ->setEmail($item->email) ->setMobileNumber($item->mobileNumber) ->setStatus($item->status); $result->push($contact); } return $result; } }<file_sep><?php namespace Arkade\Bronto\Factories; use Arkade\Bronto\Entities\Product; use Carbon\Carbon; class ProductsFactory { /** * Make an array of product entities. * * @return array */ public function make() { $products = []; $product = new Product(); $product->setProductId('9330947716452'); $product->setTitle('SPARKLE CARDI CHEESE'); $product->setColor('REBLK001'); $product->setUpc('9330947716452'); $product->setBrand('TEST'); $product->setAvailabilityDate(Carbon::parse('2017-05-12')); $products[] = $product; $product = new Product(); $product->setProductId('9330947716315'); $product->setTitle('AMITY LACE DRESS'); $product->setColor('REBLK001'); $product->setUpc('9330947716315'); $product->setBrand('TEST'); $product->setAvailabilityDate(Carbon::parse('2017-06-12')); $products[] = $product; $product = new Product(); $product->setProductId('9330947716179'); $product->setTitle('PEARLY QUEEN JUMPER'); $product->setColor('REBLK001'); $product->setUpc('9330947716179'); $product->setBrand('TEST'); $product->setAvailabilityDate(Carbon::parse('2017-07-12')); $products[] = $product; return $products; } }<file_sep><?php namespace Arkade\Bronto\Serializers; use PHPUnit\Framework\TestCase; use Arkade\Bronto\Factories; class ProductSerializerTest extends TestCase { /** * @test */ public function returns_populated_json() { $json = (new ProductSerializer)->serialize( (new Factories\ProductFactory)->make() ); $this->assertEquals(file_get_contents(__DIR__.'/../Stubs/Products/serialized_product.json'), $json); } }<file_sep><?php namespace Omneo\Bronto\Modules; use Omneo\Bronto; abstract class AbstractSoapModule { /** * @var Bronto\SoapClient */ protected $client; /** * Abstract Module constructor. * * @param Bronto\SoapClient|null $client */ public function __construct(Bronto\SoapClient $client) { $this->client = $client; } } <file_sep><?php namespace Arkade\Bronto\Factories; use Arkade\Bronto\Entities\Product; use Carbon\Carbon; class ProductFactory { /** * Make an product entity. * * @return Entities\Product */ public function make() { $product = new Product(); $product->setProductId('9330947716452'); $product->setTitle('SPARKLE CARDI CHEESE'); $product->setColor('REBLK001'); $product->setUpc('9330947716452'); $product->setBrand('TEST'); $product->setAvailabilityDate(Carbon::parse('2017-05-12')); return $product; } }<file_sep><?php namespace Arkade\Bronto\Modules; use GuzzleHttp\Psr7\Response; use Arkade\Bronto\Factories; use PHPUnit\Framework\TestCase; use Arkade\Bronto\InteractsWithClient; use Arkade\Bronto\Entities\Product; use Illuminate\Support\Collection; class ProductServiceTest extends TestCase { use InteractsWithClient; /** * @test */ public function product_find() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, ['Content-Type' => 'application/json'], file_get_contents(__DIR__.'../../Stubs/Products/product.json') ) ], $history); $response = $client->productService()->find('9330947716452'); $this->assertInstanceOf(Product::class, $response); } /** * @test */ public function product_feed_import() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, [], null ) ], $history); $products = (new Factories\ProductsFactory)->make(); $response = $client->productService()->feedImport($products); $this->assertNull($response); } /** * @test */ public function product_update() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, [], null ) ], $history); $product = (new Factories\ProductFactory)->make(); $response = $client->productService()->update($product); $this->assertNull($response); } }<file_sep><?php namespace Omneo\Bronto\Serializers; use Omneo\Bronto\Entities; class DeliverySerializer { /** * Serialize. * * @param Entities\Delivery $delivery * @return string */ public function serialize(Entities\Delivery $delivery) { // trigger the entities jsonSerialize method $serialized = json_decode(json_encode($delivery)); $serialized->start = $delivery->getStart()->toIso8601String(); return json_encode($serialized); } }<file_sep><?php namespace Omneo\Bronto\Modules; use Omneo\Bronto\Entities\Product; use Omneo\Bronto\Parsers\ProductParser; use Omneo\Bronto\Serializers\ProductSerializer; use Illuminate\Support\Collection; use League\Csv\Writer; class ProductService extends AbstractRestModule { /** * Product find. * Uses product ID * * @param $id * @return Product */ public function find($id) { return (new ProductParser)->parse( $this->client->get( 'products/public/catalogs/' . $this->client->getProductsApiId() . '/products/' . $id, ['debug' => env('APP_DEBUG')] ) ); } /** * Product feed import. * * @param array $products * @return \Psr\Http\Message\ResponseInterface */ public function feedImport($products) { $csv = Writer::createFromFileObject(new \SplTempFileObject()); $csv->insertOne(array_keys(json_decode((new ProductSerializer())->serialize($products[0]), true))); foreach ($products as $product) { $csv->insertOne(array_values(json_decode((new ProductSerializer())->serialize($product), true))); } return $this->client->post('products/public/feed_import/', [ 'debug' => env('APP_DEBUG'), 'multipart' => [ [ 'name' => 'catalogId', 'contents' => $this->client->getProductsApiId() ], [ 'name' => 'feed', 'contents' => $csv->__toString() ] ] ]); } /** * Product update. * * @param $product * @return Product */ public function update(Product $product) { $payload = new \stdClass(); $payload->fields = json_decode((new ProductSerializer)->serialize($product)); $payload = json_encode([$payload]); $this->client->put( 'products/public/catalogs/' . $this->client->getProductsApiId() . '/products', [ 'headers' => ['Content-Type' => 'application/json'], 'body' => $payload, 'debug' => env('APP_DEBUG') ] ); } }<file_sep><?php namespace Arkade\Bronto\Factories; use Arkade\Bronto\Entities\OrderState; use Arkade\Bronto\Entities\LineItem; use Arkade\Bronto\Entities\Order; use Carbon\Carbon; class OrderFactory { /** * Make an order entity. * * @return Entities\Order */ public function make() { $orderState = new OrderState(); $orderState->setProcessed(true); $orderState->setShipped(false); $orderItem1 = new LineItem(); $orderItem1->setName('someItemName1'); $orderItem1->setDescription('item description'); $orderItem1->setQuantity(1); $orderItem1->setSku('AS1210000'); $orderItem1->setSalePrice('90.00'); $orderItem1->setTotalPrice('100.00'); $orderItem2 = new LineItem(); $orderItem2->setName('someItemName2'); $orderItem2->setDescription('item description'); $orderItem2->setQuantity(1); $orderItem2->setSku('AS3420000'); $orderItem2->setSalePrice('40.00'); $orderItem2->setTotalPrice('50.00'); $order = new Order(); $order->setGrandTotal('160.00'); $order->setOrderDate(Carbon::parse('2017-05-12T00:00:00.000Z')); $order->setTaxAmount('15.00'); $order->setCurrency('AUD'); $order->setCustomerOrderId('ORDER-123456789'); $order->setLineItems(collect([$orderItem1,$orderItem2])); $order->setStates($orderState); return $order; } }<file_sep><?php namespace Omneo\Bronto\Modules; use Omneo\Bronto\SoapClient; use Omneo\Bronto\Entities\Contact; use Omneo\Bronto\Parsers\ContactUnsubscribeParser; use Omneo\Bronto\Serializers\ContactSerializer; use Omneo\Bronto\Parsers\ContactParser; use Omneo\Bronto\Exceptions; use Carbon\Carbon; use Illuminate\Support\Collection; class ContactService extends AbstractSoapModule { /** * @var Collection */ protected $mappings; /** * constructor. * * @param SoapClient|null $client * @param Collection $mappings */ public function __construct(SoapClient $client, Collection $mappings) { $this->mappings = $mappings; parent::__construct($client); } /** * Create a contact in Bronto * * @param Contact $contact * @return Contact * @throws Exceptions\BrontoException */ public function create(Contact $contact) { $contactRow = $this->buildContactRow($contact); // Save try { return (new ContactParser)->parse($contactRow->save(), $this->mappings); } catch (\Exception $e) { throw new Exceptions\BrontoException((string)$e->getMessage(), $e->getCode()); } } /** * @param Contact $contact * @return \Bronto_Api_Rowset * @throws Exceptions\BrontoException */ public function update(Contact $contact) { $contactRow = $this->buildContactRow($contact); // Update try { return $contactRow->getApiObject()->update($contactRow->getData()); } catch (\Exception $e) { throw new Exceptions\BrontoException((string)$e->getMessage(), $e->getCode()); } } /** * @param Contact $contact * @return \Bronto_Api_Contact_Row */ public function buildContactRow(Contact $contact){ $contactObject = $this->client->getClient()->getContactObject(); $contactRow = $contactObject->createRow(); $contactRow->id = $contact->getId(); $contactRow->email = $contact->getEmail(); $contactRow->status = $contact->getStatus(); $contactRow->mobileNumber = $contact->getMobileNumber(); // Add Contact to List $contactRow->addToList($this->client->getListId()); // Transform the Contact entity to a flattened array $contactArray = array_filter(json_decode((new ContactSerializer())->serialize($contact),true)); // Map the fields to Bronto field ID's and set the fields on the contact row foreach ($contactArray as $key => $value){ if($key === 'email' || $key === 'id' || $key === 'status' || $key === 'mobileNumber') continue; $this->mappings->each(function($mapping) use($key, $value, &$contactRow){ if($key === $mapping['bronto_name']){ $contactRow->setField($mapping['bronto_id'], (string)$value); } }); } return $contactRow; } /** * Find contact by ID * * @param string ID * @return Contact * @throws Exceptions\BrontoException */ public function findById($id) { $contactObject = $this->client->getClient()->getContactObject(); $contactsFilter['id'] = [$id]; //$contactsFilter['listId'] = [$this->client->getListId()]; $fields = []; $this->mappings->each(function($mapping) use(&$fields){ $fields[] = $mapping['bronto_id']; }); try { $contacts = $contactObject->readAll($contactsFilter, $fields, false); if (!$contacts->count()) return null; return (new ContactParser)->parse($contacts[0], $this->mappings); } catch (\Exception $e) { throw new Exceptions\BrontoException((string)$e->getResponse()->getBody(), $e->getResponse()->getStatusCode()); } } /** * Find contact by Email * * @param string $email * @return Contact */ public function findByEmail($email) { $contactObject = $this->client->getClient()->getContactObject(); $contactsFilter['email'] = ['value' => $email, 'operator' => 'EqualTo']; $contactsFilter['listId'] = [$this->client->getListId()]; $fields = []; $this->mappings->each(function($mapping) use(&$fields){ $fields[] = $mapping['bronto_id']; }); $contacts = $contactObject->readAll($contactsFilter, $fields, false); if (!$contacts->count()) return null; return (new ContactParser)->parse($contacts[0], $this->mappings); } /** * Get contacts updated since * * @param Carbon $date * @param int $page * @return Collection */ public function getContactsUpdatedSince($date, $page = 1) { $contactObject = $this->client->getClient()->getContactObject(); $value = $date->format('Y-m-d\Th:m:s.BP'); $contactsFilter['modified'] = ['value' => $value, 'operator' => 'After']; $contactsFilter['listId'] = [$this->client->getListId()]; $fields = []; $this->mappings->each(function($mapping) use(&$fields){ $fields[] = $mapping['bronto_id']; }); $contacts = $contactObject->readAll($contactsFilter, $fields, false, $page); $parseContacts = collect([]); foreach($contacts as $contact) { $parseContacts->push( (new ContactParser)->parse($contact, $this->mappings) ); } return $parseContacts; } /** * Get contacts by status * * @param string $status * @param Carbon $date * @param int $page * @return Collection */ public function getContactsByStatus($status, $date, $page = 1) { $contactObject = $this->client->getClient()->getContactObject(); $value = $date->format('Y-m-d\Th:m:s.BP'); $contactsFilter['status'] = [$status]; $contactsFilter['created'] = ['value' => $value, 'operator' => 'After']; $contactsFilter['listId'] = [$this->client->getListId()]; $fields = []; $this->mappings->each(function($mapping) use(&$fields){ $fields[] = $mapping['bronto_id']; }); $contacts = $contactObject->readAll($contactsFilter, $fields, false, $page); $parseContacts = collect([]); foreach($contacts as $contact) { $parseContacts->push( (new ContactParser)->parse($contact, $this->mappings) ); } return $parseContacts; } /** * Get unsubscribes * * @param Carbon $date * @param int $page * @return Collection */ public function getUnsubscribes($date, $page = 1) { $contactObject = $this->client->getClient()->getContactObject(); $value = $date->format('Y-m-d\Th:m:s.BP'); $contactsFilter['status'] = ['unsub']; $contactsFilter['modified'] = ['value' => $value, 'operator' => 'After']; $fields = []; $contacts = $contactObject->readAll($contactsFilter, $fields, false, $page); return (new ContactUnsubscribeParser())->parse($contacts); } /** * Get bounces * * @param Carbon $date * @param int $page * @return Collection */ public function getBounces($date, $page = 1) { $contactObject = $this->client->getClient()->getContactObject(); $value = $date->format('Y-m-d\Th:m:s.BP'); $contactsFilter['status'] = ['bounce']; $contactsFilter['modified'] = ['value' => $value, 'operator' => 'After']; $fields = []; $contacts = $contactObject->readAll($contactsFilter, $fields, false, $page); return (new ContactUnsubscribeParser())->parse($contacts); } /** * Get fields * * @return Collection * @throws Exceptions\BrontoException */ public function getFields() { $fieldObject = $this->client->getClient()->getFieldObject(); try { $fields = $fieldObject->readAll(); $result = collect([]); foreach($fields as $field){ $field = $field->toArray(); $result->push($field); } return $result; } catch (\Exception $e) { throw new Exceptions\BrontoException((string)$e->getResponse()->getBody(), $e->getResponse()->getStatusCode()); } } /** * Output fields for bronto config file * * @return void * @throws Exceptions\BrontoException */ public function outputFields() { $fieldObject = $this->client->getClient()->getFieldObject(); try { $fields = $fieldObject->readAll(); foreach($fields as $field){ $field = $field->toArray(); echo "'" . $field['name'] . "' => " . "'" . $field['id'] . "',\r\n"; } } catch (\Exception $e) { throw new Exceptions\BrontoException((string)$e->getResponse()->getBody(), $e->getResponse()->getStatusCode()); } } } <file_sep><?php namespace Omneo\Bronto\Serializers; use Omneo\Bronto\Entities; class OrderSerializer { /** * Serialize. * * @param Entities\Order $order * @return string */ public function serialize(Entities\Order $order) { // trigger the entities jsonSerialize method $serialized = json_decode(json_encode($order)); // these can never be set when sending to bronto // only populated with a parsed response from bronto unset($serialized->orderId); unset($serialized->createdDate); unset($serialized->updatedDate); // tracking cookie params cannot be null if(is_null($serialized->trackingCookieName)) unset($serialized->trackingCookieName); if(is_null($serialized->trackingCookieValue)) unset($serialized->trackingCookieValue); return json_encode($serialized); } }<file_sep><?php namespace Omneo\Bronto\Entities; class AbstractEntity implements \JsonSerializable { /** * @return Array */ public function jsonSerialize() { return get_object_vars($this); } } <file_sep># Bronto PHP SDK This SDK provides simple access to the Bronto API. It handles most Bronto associated complexities including authentication, entity abstraction, errors and more. <file_sep><?php namespace Omneo\Bronto\Parsers; use Omneo\Bronto\Entities; class OrderStateParser { /** * Parse the given array to a OrderState entity. * * @param array $payload * @return Entities\OrderState */ public function parse($payload) { $orderState = (new Entities\OrderState()) ->setProcessed($payload->processed) ->setShipped($payload->shipped); return $orderState; } }<file_sep><?php namespace Arkade\Bronto\Parsers; use Carbon\Carbon; use Arkade\Bronto\Entities\Product; use PHPUnit\Framework\TestCase; use Illuminate\Support\Collection; class ProductParserTest extends TestCase { /** * @test */ public function returns_populated_product() { $product = (new ProductParser)->parse( json_decode(file_get_contents(__DIR__.'/../Stubs/Products/product.json')) ); $this->assertInstanceOf(Product::class, $product); $this->assertEquals(null, $product->getAgeGroup()); $this->assertEquals(null, $product->getAvailability()); $this->assertEquals(null, $product->getAvailabilityDate()); $this->assertEquals(null, $product->getAverageRating()); $this->assertEquals('TEST', $product->getBrand()); $this->assertEquals('REBLK001', $product->getColor()); $this->assertEquals(null, $product->getCondition()); $this->assertEquals(null, $product->getDescription()); $this->assertEquals(null, $product->getGender()); $this->assertEquals(null, $product->getGtin()); $this->assertEquals(null, $product->getImageUrl()); $this->assertEquals(null, $product->getInventoryThreshold()); $this->assertEquals(null, $product->getIsbn()); $this->assertEquals(null, $product->getMpn()); $this->assertEquals(null, $product->getMargin()); $this->assertEquals(null, $product->getMobileUrl()); $this->assertEquals(null, $product->getParentProductId()); $this->assertEquals(null, $product->getPrice()); $this->assertEquals(null, $product->getPrice()); $this->assertEquals(null, $product->getProductCategory()); $this->assertEquals('9330947716452', $product->getProductId()); $this->assertEquals(null, $product->getProductTypeMulti()); $this->assertEquals(null, $product->getProductUrl()); $this->assertEquals(null, $product->getQuantity()); $this->assertEquals(null, $product->getReviewCount()); $this->assertEquals(null, $product->getSalePrice()); $this->assertEquals(null, $product->getSalePriceEffectiveStartDate()); $this->assertEquals(null, $product->getSalePriceEffectiveEndDate()); $this->assertEquals(null, $product->getSize()); $this->assertEquals('SPARKLE CARDI CHEESE', $product->getTitle()); $this->assertEquals('9330947716452', $product->getUpc()); $this->assertEquals(Carbon::parse('2017-12-05T22:00:42.236Z'), $product->getUpdatedDate()); $this->assertEquals(Carbon::parse('2017-12-05T00:39:47.618Z'), $product->getCreatedDate()); } } <file_sep><?php namespace Omneo\Bronto; use GuzzleHttp; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Log; use Omneo\Bronto; class LaravelServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { // Publish the config. $this->publishes([ __DIR__ . '/Config/bronto.php' => config_path('bronto.php'), ]); } /** * Register bindings in the container. * * @return void */ public function register() { // Setup the rest client auth. $this->app->singleton(Bronto\RestAuthentication::class, function(){ return (new Bronto\RestAuthentication) ->setAuthUrl(config('services.bronto.auth_url')) ->setEndpoint(config('services.bronto.endpoint')) ->setClientId(config('services.bronto.client_id')) ->setClientSecret(config('services.bronto.client_secret')); }); // Setup the rest client. $this->app->singleton(Bronto\RestClient::class, function () { $client = (new Bronto\RestClient(resolve(Bronto\RestAuthentication::class))) ->setProductsApiId(config('services.bronto.products_api_id')) ->setLogging(config('services.bronto.logging')) ->setVerifyPeer(config('app.env') === 'production') ->setLogger(Log::getMonolog()); $this->setupRecorder($client); return $client; }); // Setup the soap client $this->app->singleton(Bronto\SoapClient::class, function () { return (new Bronto\SoapClient()) ->setToken(config('services.bronto.soap_token')) ->setListId(config('services.bronto.list_id')); }); } /** * Setup recorder middleware if the HttpRecorder package is bound. * * @param Client $client * @return Client */ protected function setupRecorder(RestClient $client) { if (! $this->app->bound('Omneo\Plugins\HttpRecorder\Recorder')) { return $client->setupClient(); } $stack = GuzzleHttp\HandlerStack::create(); $stack->push( $this->app ->make('Omneo\Plugins\HttpRecorder\GuzzleIntegration') ->getMiddleware(['bronto', 'outgoing']) ); return $client->setupClient($stack); } } <file_sep><?php namespace Omneo\Bronto\Serializers; use Omneo\Bronto\Entities; use Carbon\Carbon; class ProductSerializer { /** * Serialize. * * @param Entities\Product $product * @return string */ public function serialize(Entities\Product $product) { // trigger the entities jsonSerialize method $serialized = json_decode(json_encode($product)); // dates to bronto need to be in ISO 8601 if(!is_null($serialized->salePriceEffectiveStartDate)) $serialized->salePriceEffectiveStartDate = (new Carbon($serialized->salePriceEffectiveStartDate))->toIso8601String(); if(!is_null($serialized->salePriceEffectiveEndDate)) $serialized->salePriceEffectiveEndDate = (new Carbon($serialized->salePriceEffectiveEndDate))->toIso8601String(); if(!is_null($serialized->availabilityDate)) $serialized->availabilityDate = (new Carbon($serialized->availabilityDate))->toIso8601String(); // bronto product fields are stored in snake case $vars = get_object_vars($serialized); $serialized = []; foreach ($vars as $key => $value){ $serialized[snake_case($key)] = $value; } return json_encode($serialized); } }<file_sep><?php namespace Omneo\Bronto\Parsers; use Omneo\Bronto\Entities\Contact; use Carbon\Carbon; use Omneo\Bronto\Entities; use Illuminate\Support\Collection; class ContactParser { /** * Parse the given array to a Contact entity. * * @param array $payload * @param Collection $mappings * @return Contact */ public function parse($payload, $mappings) { $contact = (new Entities\Contact) ->setId($payload->id) ->setEmail($payload->email) ->setMobileNumber($payload->mobileNumber) ->setStatus($payload->status); $attributes = []; foreach($payload->fields as $field){ $mappings->each(function($mapping) use(&$attributes, $field){ if($field['fieldId'] === $mapping['bronto_id']){ $attributes[$mapping['bronto_name']] = $field['content']; } }); } $contact->setAttributes(new Collection($attributes)); return $contact; } }<file_sep><?php namespace Omneo\Bronto\Parsers; use Carbon\Carbon; use Omneo\Bronto\Entities; class ProductParser { /** * Parse the given array to a Product entity. * * @param mixed $payload * @return Entities\Product */ public function parse($payload) { $product = new Entities\Product(); if (!empty($payload->fields)) { foreach ($payload->fields as $field) { $value = (null !== $field->value && $field->type === 'date') ? Carbon::parse((string)$field->value) : $field->value; $setterName = camel_case('set_' . $field->name); if (method_exists($product, $setterName)) { $product->{$setterName}($value); } } } return $product; } }<file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; use Illuminate\Support\Collection; class DeliveryRemail extends AbstractEntity { /** * @var int */ protected $days; /** * @var Carbon */ protected $time; /** * @var string */ protected $subject; /** * @var string */ protected $messageId; /** * @var string */ protected $activity; /** * @return int */ public function getDays() { return $this->days; } /** * The number of days until the remail will trigger. * @param int $days * @return DeliveryRemail */ public function setDays($days) { $this->days = $days; return $this; } /** * @return Carbon */ public function getTime() { return $this->time; } /** * The time at which the remail will trigger. The time should be in 24 hour format: HH:MM:SS * Note: Do not add a time zone offset for the remail time. * The time for the remail will use the time zone specified for the delivery object. * @param Carbon $time * @return DeliveryRemail */ public function setTime(Carbon $time = null) { $this->time = $time; return $this; } /** * @return string */ public function getSubject() { return $this->subject; } /** * @param string $subject * @return DeliveryRemail */ public function setSubject($subject) { $this->subject = $subject; return $this; } /** * @return string */ public function getMessageId() { return $this->messageId; } /** * @param string $messageId * @return DeliveryRemail */ public function setMessageId($messageId) { $this->messageId = $messageId; return $this; } /** * The activity that will trigger the remail. Valid values are: noopen, opennoclick, or clicknoconvert * @return string */ public function getActivity() { return $this->activity; } /** * @param string $activity * @return DeliveryRemail */ public function setActivity($activity) { $this->activity = $activity; return $this; } /** * @return Array */ public function jsonSerialize() { $result = get_object_vars($this); return $result; } } <file_sep><?php namespace Omneo\Bronto\Serializers; use Omneo\Bronto\Entities; class ContactSerializer { /** * Serialize. * * @param Entities\Contact $contact * @return string */ public function serialize(Entities\Contact $contact) { // trigger the entities jsonSerialize method $serialized = json_decode(json_encode($contact)); // flatten attributes if(isset($serialized->attributes)){ foreach ($serialized->attributes as $attribute){ $vars = get_object_vars($attribute); foreach($vars as $key=>$value){ $serialized->$key = $value; } } unset($serialized->attributes); } return json_encode($serialized); } }<file_sep><?php namespace Omneo\Bronto; use GuzzleHttp; use Carbon\Carbon; class RestAuthentication { /** * Guzzle client. * * @var GuzzleHttp\Client */ protected $guzzle; /** * Auth URL. * * @var string */ protected $authUrl; /** * Client ID. * * @var string */ protected $clientId; /** * Client Secret. * * @var string */ protected $clientSecret; /** * Endpoint. * * @var string */ protected $endpoint; /** * Token. * * @var string */ protected $token; /** * Token expiry. * * @var string */ protected $tokenExpiry; /** * Refresh Token. * * @var string */ protected $refreshToken; /** * Authentication constructor. * * @param GuzzleHttp\HandlerStack $handler */ public function __construct(GuzzleHttp\HandlerStack $handler = null) { $this->guzzle = new GuzzleHttp\Client([ 'handler' => $handler ? $handler : GuzzleHttp\HandlerStack::create(), ]); } /** * Set the auth URL. * * @param string $authUrl * @return $this */ public function setAuthUrl($authUrl) { $this->authUrl = $authUrl; return $this; } /** * Get the auth URL. * * @return string */ public function getAuthUrl() { return $this->authUrl; } /** * Set the client ID. * * @param string $clientId * @return $this */ public function setClientId($clientId) { $this->clientId = $clientId; return $this; } /** * Get the client ID. * * @return string */ public function getClientId() { return $this->clientId; } /** * Set the client secret. * * @param string $clientSecret * @return $this */ public function setClientSecret($clientSecret) { $this->clientSecret = $clientSecret; return $this; } /** * Get the client secret. * * @return string */ public function getClientSecret() { return $this->clientSecret; } /** * Set the endpoint. * * @param string $url * @return $this */ public function setEndpoint($url) { $this->endpoint = $url; return $this; } /** * Get the endpoint. * * @return string */ public function getEndpoint() { return $this->endpoint; } /** * Get a token. * * @return string */ public function getToken() { if ($this->token) return $this->isTokenExpired() ? $this->refreshOauthToken() : $this->token; return $this->createOauthToken(); } /** * Set the token. * * @param $token * @return $this */ public function setToken($token) { $this->token = $token; return $this; } /** * Get the token expiry. * * @return mixed */ public function getTokenExpiry() { return $this->tokenExpiry; } /** * Set token expiry. * * @param $tokenExpiry * @return $this */ public function setTokenExpiry($tokenExpiry) { $this->tokenExpiry = $tokenExpiry; return $this; } /** * Get the refresh token. * * @return string */ public function getRefreshToken() { return $this->refreshToken; } /** * Set the refresh token. * * @param $refreshToken * @return $this */ public function setRefreshToken($refreshToken) { $this->refreshToken = $refreshToken; return $this; } /** * Create oauth token. * * @return string */ public function createOauthToken() { $params = [ 'form_params' => [ 'grant_type' => 'client_credentials', 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, ], ]; // Make the Request and process the response $response = $this->guzzle->request('POST', $this->getAuthUrl(), $params); $result = json_decode((string) $response->getBody()); $this->setToken($result->access_token) ->setTokenExpiry( Carbon::now() ->addSeconds($result->expires_in) ) ->setRefreshToken($result->refresh_token); return $this->token; } /** * Refresh oauth token. * * @return string */ public function refreshOauthToken() { // Setup our auth parameters $params = [ 'form_params' => [ 'grant_type' => 'refresh_token', 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'refresh_token' => $this->refreshToken, ], ]; // Make the Request and process the response $response = $this->guzzle->request('POST', $this->getAuthUrl(), $params); $result = json_decode((string) $response->getBody()); $this->setToken($result->access_token) ->setTokenExpiry( Carbon::now() ->addSeconds($result->expires_in) ) ->setRefreshToken($result->refresh_token); return $this->token; } /** * Determine if a token has expired. * * @return bool */ public function isTokenExpired() { return Carbon::now()->greaterThanOrEqualTo($this->getTokenExpiry()->subMinutes(5)); } } <file_sep><?php namespace Arkade\Bronto; use Arkade\Bronto\RestAuthentication; use Arkade\Bronto\RestClient; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; trait InteractsWithClient { /** * Create a history stack. * * @param $container * @return HandlerStack */ protected function createHistoryMiddleware(&$container) { return Middleware::history($container); } /** * Create a Responsys mock client. * * @param array $responses * @param $history * @return Client */ private function createClient(array $responses, &$history) { // Add the auth response. $responses = array_prepend($responses, new Response(200, [], json_encode([ 'access_token' => '<PASSWORD>', 'refresh_token' => '<PASSWORD>', 'expires_in' => 3600, ]))); $stack = HandlerStack::create(new MockHandler($responses)); $stack->push($this->createHistoryMiddleware($history)); $auth = new RestAuthentication($stack); $auth->setAuthUrl('https://auth.bronto.com/oauth2/token'); $auth->setClientId('arkade'); $auth->setClientSecret('secret'); $auth->setEndpoint('https://rest.bronto.com'); $client = new RestClient($auth, $stack); return $client; } /** * Get the request body. * * @param Request $request * @return mixed */ protected function getRequestBody(Request $request) { return json_decode((string) $request->getBody()); } }<file_sep><?php namespace Arkade\Bronto\Modules; use GuzzleHttp\Psr7\Response; use Arkade\Bronto\Factories; use PHPUnit\Framework\TestCase; use Arkade\Bronto\InteractsWithClient; use Arkade\Bronto\Entities\Order; use Illuminate\Support\Collection; class OrderServiceTest extends TestCase { use InteractsWithClient; /** * @test */ public function order_find() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, ['Content-Type' => 'application/json'], file_get_contents(__DIR__.'../../Stubs/Orders/order.json') ) ], $history); $response = $client->orderService()->find('52e2ba9d-b339-4859-aeec-43a79cf6bfd7'); $this->assertInstanceOf(Order::class, $response); } /** * @test */ public function order_find_by_id() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, ['Content-Type' => 'application/json'], '[' . file_get_contents(__DIR__.'../../Stubs/Orders/order.json') . ']' ) ], $history); $response = $client->orderService()->findById('ORDER-123456789'); $this->assertInstanceOf(Collection::class, $response); } /** * @test */ public function order_add() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, ['Content-Type' => 'application/json'], file_get_contents(__DIR__.'../../Stubs/Orders/order.json') ) ], $history); $order = (new Factories\OrderFactory)->make(); $response = $client->orderService()->add($order); $this->assertInstanceOf(Order::class, $response); } /** * @test */ public function order_update() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, ['Content-Type' => 'application/json'], file_get_contents(__DIR__.'../../Stubs/Orders/order.json') ) ], $history); $order = (new Factories\OrderFactory)->make(); $response = $client->orderService()->update($order); $this->assertInstanceOf(Order::class, $response); } /** * @test */ public function order_update_by_id() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(200, ['Content-Type' => 'application/json'], file_get_contents(__DIR__.'../../Stubs/Orders/order.json') ) ], $history); $order = (new Factories\OrderFactory)->make(); $response = $client->orderService()->updateById($order); $this->assertInstanceOf(Order::class, $response); } /** * @test */ public function order_delete() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(204, [], null ) ], $history); $response = $client->orderService()->delete('52e2ba9d-b339-4859-aeec-43a79cf6bfd7'); $this->assertNull($response); } /** * @test */ public function order_delete_by_id() { // Create the container. $history = []; // Create a mock response object. $client = $this->createClient([ new Response(204, [], null ) ], $history); $response = $client->orderService()->deleteById('ORDER-123456789'); $this->assertNull($response); } }<file_sep><?php namespace Omneo\Bronto\Entities; class OrderState extends AbstractEntity { /** * @var boolean */ protected $processed = false; /** * @var boolean */ protected $shipped = false; /** * @return bool */ public function getProcessed() { return $this->processed; } /** * @param bool $processed * @return OrderState */ public function setProcessed($processed) { $this->processed = $processed; return $this; } /** * @return string */ public function getShipped() { return $this->shipped; } /** * @param string $shipped * @return OrderState */ public function setShipped($shipped) { $this->shipped = $shipped; return $this; } } <file_sep><?php namespace Omneo\Bronto\Exceptions; use Exception; class BrontoException extends Exception { // } <file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; use Illuminate\Support\Collection; class DeliveryProduct extends AbstractEntity { /** * @var string */ protected $placeholder; /** * @var string */ protected $productId; /** * @return string */ public function getPlaceholder() { return $this->placeholder; } /** * Placeholder text used in a product tag. Maximum of 50 characters. * @param string $placeholder * @return DeliveryProduct */ public function setPlaceholder($placeholder) { $this->placeholder = $placeholder; return $this; } /** * @return string */ public function getProductId() { return $this->productId; } /** * A valid Product ID that will replace the placeholder on message send. Maximum of 50 characters. * @param string $productId * @return DeliveryProduct */ public function setProductId($productId) { $this->productId = $productId; return $this; } /** * @return Array */ public function jsonSerialize() { $result = get_object_vars($this); return $result; } } <file_sep><?php namespace Omneo\Bronto\Entities; class LineItem extends AbstractEntity { /** * @var string */ protected $name; /** * @var string */ protected $description; /** * @var string */ protected $sku; /** * @var string */ protected $other; /** * @var string */ protected $imageUrl; /** * @var string */ protected $category; /** * @var string */ protected $productUrl; /** * @var integer */ protected $quantity; /** * @var float */ protected $salePrice; /** * @var float */ protected $totalPrice; /** * @var float */ protected $unitPrice; /** * @return string */ public function getName() { return $this->name; } /** * @param string $name * @return LineItem */ public function setName($name) { $this->name = $name; return $this; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description * @return LineItem */ public function setDescription($description) { $this->description = $description; return $this; } /** * @return string */ public function getSku() { return $this->sku; } /** * @param string $sku * @return LineItem */ public function setSku($sku) { $this->sku = $sku; return $this; } /** * @return string */ public function getOther() { return $this->other; } /** * @param string $other * @return LineItem */ public function setOther($other) { $this->other = $other; return $this; } /** * @return string */ public function getImageUrl() { return $this->imageUrl; } /** * @param string $imageUrl * @return LineItem */ public function setImageUrl($imageUrl) { $this->imageUrl = $imageUrl; return $this; } /** * @return string */ public function getCategory() { return $this->category; } /** * @param string $category * @return LineItem */ public function setCategory($category) { $this->category = $category; return $this; } /** * @return string */ public function getProductUrl() { return $this->productUrl; } /** * @param string $productUrl * @return LineItem */ public function setProductUrl($productUrl) { $this->productUrl = $productUrl; return $this; } /** * @return int */ public function getQuantity() { return $this->quantity; } /** * @param int $quantity * @return LineItem */ public function setQuantity($quantity) { $this->quantity = $quantity; return $this; } /** * @return float */ public function getSalePrice() { return $this->salePrice; } /** * @param float $salePrice * @return LineItem */ public function setSalePrice($salePrice) { $this->salePrice = $salePrice; return $this; } /** * @return float */ public function getTotalPrice() { return $this->totalPrice; } /** * @param float $totalPrice * @return LineItem */ public function setTotalPrice($totalPrice) { $this->totalPrice = $totalPrice; return $this; } /** * @return float */ public function getUnitPrice() { return $this->unitPrice; } /** * @param float $unitPrice * @return LineItem */ public function setUnitPrice($unitPrice) { $this->unitPrice = $unitPrice; return $this; } } <file_sep><?php namespace Omneo\Bronto\Parsers; use Carbon\Carbon; use Omneo\Bronto\Entities; class OrderParser { /** * Parse the given array to a Order entity. * * @param array $payload * @return Order */ public function parse($payload) { $order = (new Entities\Order) ->setCartId($payload->cartId) ->setCreatedDate(Carbon::parse((string) $payload->createdDate)) ->setCurrency($payload->currency) ->setCustomerOrderId($payload->customerOrderId) ->setDiscountAmount($payload->discountAmount) ->setEmailAddress($payload->emailAddress) ->setGrandTotal($payload->grandTotal) ->setOrderId($payload->orderId) ->setOriginIp($payload->originIp) ->setOriginUserAgent($payload->originUserAgent) ->setShippingAmount($payload->shippingAmount) ->setShippingDate(null) ->setShippingDetails($payload->shippingDetails) ->setShippingTrackingUrl($payload->shippingTrackingUrl) ->setSubtotal($payload->subtotal) ->setTaxAmount($payload->taxAmount) ->setTrackingCookieName($payload->trackingCookieName) ->setTrackingCookieValue($payload->trackingCookieValue) ->setUpdatedDate(Carbon::parse((string) $payload->updatedDate)) ->setStates( (new OrderStateParser)->parse($payload->states) ); if(!is_null($payload->shippingDate)){ $order->setShippingDate(Carbon::parse((string) $payload->shippingDate)); } if(!is_null($payload->orderDate)){ $order->setOrderDate(Carbon::parse((string) $payload->orderDate)); } foreach($payload->lineItems as $item){ $order->getLineItems()->push( (new LineItemParser)->parse($item) ); } return $order; } }<file_sep><?php namespace Arkade\Bronto\Parsers; use Carbon\Carbon; use Arkade\Bronto\Entities\Order; use Arkade\Bronto\Entities\LineItem; use Arkade\Bronto\Entities\OrderState; use PHPUnit\Framework\TestCase; use Illuminate\Support\Collection; class OrderParserTest extends TestCase { /** * @test */ public function returns_populated_order() { $order = (new OrderParser)->parse( json_decode(file_get_contents(__DIR__.'/../Stubs/Orders/order.json')) ); $this->assertInstanceOf(Order::class, $order); $this->assertEquals(0, $order->getDiscountAmount()); $this->assertEquals(null, $order->getEmailAddress()); $this->assertEquals('160.00', $order->getGrandTotal()); $this->assertEquals(null, $order->getOriginIp()); $this->assertEquals(0, $order->getShippingAmount()); $this->assertEquals(null, $order->getShippingDate()); $this->assertEquals(null, $order->getShippingDetails()); $this->assertEquals(null, $order->getShippingTrackingUrl()); $this->assertEquals(0, $order->getSubtotal()); $this->assertEquals('15.00', $order->getTaxAmount()); $this->assertEquals(null, $order->getTrackingCookieName()); $this->assertEquals(null, $order->getTrackingCookieValue()); $this->assertEquals(null, $order->getTid()); $this->assertEquals(null, $order->getCartId()); $this->assertEquals('ORDER-123456789', $order->getCustomerOrderId()); $this->assertEquals(Carbon::parse('2017-05-12T00:00:00.000Z'), $order->getOrderDate()); $this->assertEquals('AUD', $order->getCurrency()); $this->assertEquals('52e2ba9d-b339-4859-aeec-43a79cf6bfd7', $order->getOrderId()); $this->assertEquals(Carbon::parse('2017-11-28T03:53:14.322Z'), $order->getCreatedDate()); $this->assertEquals(Carbon::parse('2017-11-28T03:53:14.322Z'), $order->getUpdatedDate()); } /** * @test */ public function returns_populated_order_line_items() { $order = (new OrderParser)->parse( json_decode(file_get_contents(__DIR__.'/../Stubs/Orders/order.json')) ); $this->assertInstanceOf(Collection::class, $order->getLineItems()); $this->assertEquals(2, $order->getLineItems()->count()); $lineItem = $order->getLineItems()->first(); $this->assertInstanceOf(LineItem::class, $lineItem); $this->assertEquals('someItemName1', $lineItem->getName()); $this->assertEquals('item description', $lineItem->getDescription()); $this->assertEquals('AS1210000', $lineItem->getSku()); $this->assertEquals(null, $lineItem->getOther()); $this->assertEquals(null, $lineItem->getImageUrl()); $this->assertEquals(null, $lineItem->getCategory()); $this->assertEquals(null, $lineItem->getProductUrl()); $this->assertEquals(1, $lineItem->getQuantity()); $this->assertEquals('90.00', $lineItem->getSalePrice()); $this->assertEquals('100.00', $lineItem->getTotalPrice()); $this->assertEquals(0, $lineItem->getUnitPrice()); } /** * @test */ public function returns_populated_order_states() { $order = (new OrderParser)->parse( json_decode(file_get_contents(__DIR__.'/../Stubs/Orders/order.json')) ); $states = $order->getStates(); $this->assertInstanceOf(OrderState::class, $states); $this->assertEquals(true, $states->getProcessed()); $this->assertEquals(false, $states->getShipped()); } } <file_sep><?php namespace Omneo\Bronto\Modules; use Omneo\Bronto; abstract class AbstractRestModule { /** * @var Bronto\RestClient */ protected $client; /** * Abstract Module constructor. * * @param Bronto\RestClient|null $client */ public function __construct(Bronto\RestClient $client) { $this->client = $client; } } <file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; use Illuminate\Support\Collection; class Contact extends AbstractEntity { /** * @var string */ protected $id; /** * @var string */ protected $email; /** * @var string */ protected $mobileNumber; /** * @var string */ protected $status; /** * @var Collection */ protected $attributes; /** * @return string */ public function getId() { return $this->id; } /** * @param string $id * @return Contact */ public function setId($id) { $this->id = $id; return $this; } /** * @return string */ public function getEmail() { return $this->email; } /** * @param string $email * @return Contact */ public function setEmail($email) { $this->email = $email; return $this; } /** * @return string */ public function getMobileNumber() { return $this->mobileNumber; } /** * @param string $mobile * @return Contact */ public function setMobileNumber($mobileNumber) { $this->mobileNumber = $mobileNumber; return $this; } /** * @return string */ public function getStatus() { return $this->status ?: \Bronto_Api_Contact::STATUS_ONBOARDING; } /** * @param string $status * @return Contact */ public function setStatus( $status) { $this->status = $status; return $this; } /** * Return collection of attributes. * * @return Collection */ public function getAttributes() { return $this->attributes ?: $this->attributes = new Collection; } /** * Set collection of attributes. * * @param Collection $attributes * @return Contact */ public function setAttributes(Collection $attributes) { $this->attributes = $attributes; return $this; } /** * @return array */ public function jsonSerialize() { return get_object_vars($this); } }<file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; use Illuminate\Support\Collection; class Order extends AbstractEntity { /** * @var float */ protected $discountAmount; /** * @var string */ protected $emailAddress; /** * @var float */ protected $grandTotal; /** * @var Collection */ protected $lineItems; /** * @var string */ protected $originIp; /** * @var string */ protected $originUserAgent; /** * @var float */ protected $shippingAmount; /** * @var Carbon */ protected $shippingDate; /** * @var string */ protected $shippingDetails; /** * @var string */ protected $shippingTrackingUrl; /** * @var float */ protected $subtotal; /** * @var float */ protected $taxAmount; /** * @var string */ protected $trackingCookieName; /** * @var string */ protected $trackingCookieValue; /** * @var string */ protected $tid; /** * @var string */ protected $cartId; /** * @var string */ protected $customerOrderId; /** * @var string */ protected $orderDate; /** * @var string */ protected $currency; /** * @var OrderState */ protected $states; /** * @var string */ protected $orderId; /** * @var Carbon */ protected $createdDate; /** * @var Carbon */ protected $updatedDate; /** * @return float */ public function getDiscountAmount() { return $this->discountAmount; } /** * @param float $discountAmount * @return Order */ public function setDiscountAmount($discountAmount) { $this->discountAmount = $discountAmount; return $this; } /** * @return string */ public function getEmailAddress() { return $this->emailAddress; } /** * @param string $emailAddress * @return Order */ public function setEmailAddress($emailAddress) { $this->emailAddress = $emailAddress; return $this; } /** * @return float */ public function getGrandTotal() { return $this->grandTotal; } /** * @param float $grandTotal * @return Order */ public function setGrandTotal($grandTotal) { $this->grandTotal = $grandTotal; return $this; } /** * @return Collection */ public function getLineItems() { return $this->lineItems ?: $this->lineItems = new Collection; } /** * @param Collection $lineItems * @return Order */ public function setLineItems($lineItems) { $this->lineItems = $lineItems; return $this; } /** * @return string */ public function getOriginIp() { return $this->originIp; } /** * @param string $originIp * @return Order */ public function setOriginIp($originIp) { $this->originIp = $originIp; return $this; } /** * @return string */ public function getOriginUserAgent() { return $this->originUserAgent; } /** * @param string $originUserAgent * @return Order */ public function setOriginUserAgent($originUserAgent) { $this->originUserAgent = $originUserAgent; return $this; } /** * @return float */ public function getShippingAmount() { return $this->shippingAmount; } /** * @param float $shippingAmount * @return Order */ public function setShippingAmount($shippingAmount) { $this->shippingAmount = $shippingAmount; return $this; } /** * @return Carbon|null */ public function getShippingDate() { return $this->shippingDate; } /** * @param Carbon $shippingDate * @return Order */ public function setShippingDate(Carbon $shippingDate = null) { $this->shippingDate = $shippingDate; return $this; } /** * @return string */ public function getShippingDetails() { return $this->shippingDetails; } /** * @param string $shippingDetails * @return Order */ public function setShippingDetails($shippingDetails) { $this->shippingDetails = $shippingDetails; return $this; } /** * @return string */ public function getShippingTrackingUrl() { return $this->shippingTrackingUrl; } /** * @param string $shippingTrackingUrl * @return Order */ public function setShippingTrackingUrl($shippingTrackingUrl) { $this->shippingTrackingUrl = $shippingTrackingUrl; return $this; } /** * @return float */ public function getSubtotal() { return $this->subtotal; } /** * @param float $subtotal * @return Order */ public function setSubtotal($subtotal) { $this->subtotal = $subtotal; return $this; } /** * @return float */ public function getTaxAmount() { return $this->taxAmount; } /** * @param float $taxAmount * @return Order */ public function setTaxAmount($taxAmount) { $this->taxAmount = $taxAmount; return $this; } /** * @return string */ public function getTrackingCookieName() { return $this->trackingCookieName; } /** * @param string $trackingCookieName * @return Order */ public function setTrackingCookieName($trackingCookieName) { $this->trackingCookieName = $trackingCookieName; return $this; } /** * @return string */ public function getTrackingCookieValue() { return $this->trackingCookieValue; } /** * @param string $trackingCookieValue * @return Order */ public function setTrackingCookieValue($trackingCookieValue) { $this->trackingCookieValue = $trackingCookieValue; return $this; } /** * @return string */ public function getTid() { return $this->tid; } /** * @param string $tid * @return Order */ public function setTid($tid) { $this->tid = $tid; return $this; } /** * @return string */ public function getCartId() { return $this->cartId; } /** * @param string $cartId * @return Order */ public function setCartId($cartId) { $this->cartId = $cartId; return $this; } /** * @return string */ public function getCustomerOrderId() { return $this->customerOrderId; } /** * @param string $customerOrderId * @return Order */ public function setCustomerOrderId($customerOrderId) { $this->customerOrderId = $customerOrderId; return $this; } /** * @return Carbon|null */ public function getOrderDate() { return $this->orderDate; } /** * @param Carbon $orderDate * @return Order */ public function setOrderDate(Carbon $orderDate = null) { $this->orderDate = $orderDate; return $this; } /** * @return string */ public function getCurrency() { return $this->currency; } /** * @param string $currency * @return Order */ public function setCurrency($currency) { $this->currency = $currency; return $this; } /** * @return OrderState */ public function getStates() { return $this->states; } /** * @param OrderState $states * @return Order */ public function setStates(OrderState $states) { $this->states = $states; return $this; } /** * @return string */ public function getOrderId() { return $this->orderId; } /** * @param string $orderId * @return Order */ public function setOrderId($orderId) { $this->orderId = $orderId; return $this; } /** * @return Carbon */ public function getCreatedDate() { return $this->createdDate; } /** * @param Carbon $createdDate * @return Order */ public function setCreatedDate($createdDate) { $this->createdDate = $createdDate; return $this; } /** * @return Carbon */ public function getUpdatedDate() { return $this->updatedDate; } /** * @param Carbon $updatedDate * @return Order */ public function setUpdatedDate($updatedDate) { $this->updatedDate = $updatedDate; return $this; } /** * @return Array */ public function jsonSerialize() { $result = get_object_vars($this); if(!is_null($result['orderDate'])) $result['orderDate'] = $result['orderDate']->toDateString(); if(!is_null($result['shippingDate'])) $result['shippingDate'] = $result['shippingDate']->toDateString(); return $result; } } <file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; use Illuminate\Support\Collection; class Delivery extends AbstractEntity { /** * @var Carbon */ protected $start; /** * @var string */ protected $messageId; /** * @var string */ protected $type; /** * @var string */ protected $fromEmail; /** * @var string */ protected $fromName; /** * @var string */ protected $replyEmail; /** * @var bool */ protected $authentication; /** * @var string */ protected $messageRuleId; /** * @var bool */ protected $optin; /** * @var int */ protected $throttle; /** * @var int */ protected $fatigueOverride; /** * @var DeliveryRemail */ protected $remail; /** * @var DeliveryRecipient */ protected $recipients; /** * @var DeliveryField */ protected $fields; /** * @var DeliveryProduct */ protected $products; /** * @var string */ protected $cartId; /** * @var string */ protected $orderId; /** * @return Carbon */ public function getStart() { return $this->start; } /** * The date the delivery was scheduled to be sent. * You can (and should) specify a timezone offset if you do not want the system to assume you are providing a time in * UTC (Universal Coordinated Time / Greenwich Mean Time). For the Eastern Time Zone on Daylight Savings Time, * this would be YYYY-MM-DDTHH:MM:SS-04:00. * @param Carbon $start * @return Delivery */ public function setStart(Carbon $start = null) { $this->start = $start; return $this; } /** * @return string */ public function getMessageId() { return $this->messageId; } /** * @param string $messageId * @return Delivery */ public function setMessageId($messageId) { $this->messageId = $messageId; return $this; } /** * @return string */ public function getType() { return $this->type; } /** * The type of delivery. Valid values are: triggered, test, or transactional. * triggered is the default. Only use transactional when adding a delivery which uses a message that has * been approved for transactional sending. * Note: If you attempt to send a triggered or test delivery to a contact with a status of transactional, * the delivery will be set to skipped and the delivery will not be sent. * @param string $type * @return Delivery */ public function setType($type) { $this->type = $type; return $this; } /** * @return string */ public function getFromEmail() { return $this->fromEmail; } /** * @param string $fromEmail * @return Delivery */ public function setFromEmail($fromEmail) { $this->fromEmail = $fromEmail; return $this; } /** * @return string */ public function getFromName() { return $this->fromName; } /** * @param string $fromName * @return Delivery */ public function setFromName($fromName) { $this->fromName = $fromName; return $this; } /** * @return string */ public function getReplyEmail() { return $this->replyEmail; } /** * @param string $replyEmail * @return Delivery */ public function setReplyEmail($replyEmail) { $this->replyEmail = $replyEmail; return $this; } /** * @return bool */ public function getAuthentication() { return $this->authentication; } /** * Enables sender authentication for the delivery if set to true. * Sender authentication will sign your message with DomainKeys/DKIM * (an authentication method that can optimize your message delivery to Hotmail, MSN, and Yahoo! email addresses). * If you are associating this delivery with an automated message rule, * these parameters will only be accepted if you clicked the Allow API to select sending options * checkbox via the application UI on step 2 of creating an API triggered automated message rule. * @param bool $authentication * @return Delivery */ public function setAuthentication($authentication) { $this->authentication = $authentication; return $this; } /** * @return string */ public function getMessageRuleId() { return $this->messageRuleId; } /** * The ID of an automated message rule to associate with this delivery. * Used to include this delivery in the reporting for the automator you specify. * @param string $messageRuleId * @return Delivery */ public function setMessageRuleId($messageRuleId) { $this->messageRuleId = $messageRuleId; return $this; } /** * @return bool */ public function getOptin() { return $this->optin; } /** * Whether or not this delivery is an opt-in confirmation email. If set to true, contacts who have not yet confirmed * their opt-in status with the account will still receive the message. * @param bool $optin * @return Delivery */ public function setOptin($optin) { $this->optin = $optin; return $this; } /** * @return int */ public function getThrottle() { return $this->throttle; } /** * Allows you to specify a throttle rate for the delivery. * Throttle rate must be in range [0, 720] (minutes). * For example you could specify 60 for the throttle range. * @param int $throttle * @return Delivery */ public function setThrottle($throttle) { $this->throttle = $throttle; return $this; } /** * @return int */ public function getFatigueOverride() { return $this->fatigueOverride; } /** * If set to true, the delivery can be sent even if it exceeds frequency cap settings for a contact. * @param int $fatigueOverride * @return Delivery */ public function setFatigueOverride($fatigueOverride) { $this->fatigueOverride = $fatigueOverride; return $this; } /** * @return DeliveryRemail */ public function getRemail() { return $this->remail; } /** * A remail object. Remails allow you to send another email to contacts based on actions they did not take. * The goal is to persuade them to continue along the conversion process. * @param DeliveryRemail $remail * @return Delivery */ public function setRemail($remail) { $this->remail = $remail; return $this; } /** * @return DeliveryRecipient[]|Collection */ public function getRecipients() { return $this->recipients ?: $this->recipients = new Collection; } /** * A collection of the recipients who were or are scheduled to receive the delivery. * Recipients can include lists, segments, or individual contacts. * @param DeliveryRecipient[]|Collection $recipients * @return Delivery */ public function setRecipients($recipients) { $this->recipients = $recipients; return $this; } /** * @return DeliveryField[]|Collection */ public function getFields() { return $this->fields ?: $this->fields = new Collection; } /** * An array of the API fields and data to substitute into the message being sent by this delivery. * @param DeliveryField[]|Collection $fields * @return Delivery */ public function setFields($fields) { $this->fields = $fields; return $this; } /** * @return Product[]|Collection */ public function getProducts() { return $this->products ?: $this->products = new Collection; } /** * Specifies Product IDs to substitute for placeholders in product tags upon message send. Limit: 100 products * @param Product[]|Collection $products * @return Delivery */ public function setProducts($products) { $this->products = $products; return $this; } /** * @return string */ public function getCartId() { return $this->cartId; } /** * @param string $cartId * @return Delivery */ public function setCartId($cartId) { $this->cartId = $cartId; return $this; } /** * @return string */ public function getOrderId() { return $this->orderId; } /** * @param string $orderId * @return Delivery */ public function setOrderId($orderId) { $this->orderId = $orderId; return $this; } /** * @return Array */ public function jsonSerialize() { $result = get_object_vars($this); return $result; } } <file_sep><?php namespace Omneo\Responsys\Exceptions; use Exception; class UnexpectedException extends Exception { // } <file_sep><?php namespace Omneo\Bronto; use Psr\Http; use GuzzleHttp; use GuzzleHttp\Middleware; use GuzzleHttp\MessageFormatter; use Omneo\Bronto; use Psr\Log\LoggerInterface; class RestClient { /** * @var GuzzleHttp\Client */ protected $client; /** * @var Bronto\RestAuthentication */ protected $auth; /** * Products API ID * This ID can be found on the Products Overview page in the BMP, * located on the bottom-right part of the page. It is titled 'Products API ID' * * @var string */ protected $productsApiId; /** * Enable logging of guzzle requests / responses * * @var bool */ protected $logging = false; /** * PSR-3 logger * * @var LoggerInterface */ protected $logger; /** * Verify peer SSL * * @var bool */ protected $verifyPeer = true; /** * Set connection timeout * * @var int */ protected $timeout = 900; /** * Client constructor. * * @param RestAuthentication $auth * @param GuzzleHttp\HandlerStack|null $handler */ public function __construct(Bronto\RestAuthentication $auth, GuzzleHttp\HandlerStack $handler = null) { $this->auth = $auth; $this->setupClient($handler); } /** * Set the product API ID. * * @param string $id * @return $this */ public function setProductsApiId($id) { $this->productsApiId = $id; return $this; } /** * Get the product API ID. * * @return string */ public function getProductsApiId() { return $this->productsApiId; } /** * @return bool */ public function getLogging() { return $this->logging; } /** * @param bool $logging * @return Client */ public function setLogging($logging) { $this->logging = $logging; return $this; } /** * @return LoggerInterface */ public function getLogger() { return $this->logger; } /** * @param LoggerInterface $logger * @return Client */ public function setLogger($logger) { $this->logger = $logger; return $this; } /** * @return bool */ public function getVerifyPeer() { return $this->verifyPeer; } /** * @param bool $verifyPeer * @return RestClient */ public function setVerifyPeer($verifyPeer) { $this->verifyPeer = $verifyPeer; return $this; } /** * @return int */ public function getTimeout() { return $this->timeout; } /** * @param int $timeout * @return RestClient */ public function setTimeout($timeout) { $this->timeout = $timeout; return $this; } /** * Setup Guzzle client with optional provided handler stack. * * @param GuzzleHttp\HandlerStack|null $stack * @param array $options * @return Client */ public function setupClient(GuzzleHttp\HandlerStack $stack = null, $options = []) { $stack = $stack ?: GuzzleHttp\HandlerStack::create(); if($this->logging) $this->bindLoggingMiddleware($stack); $this->client = new GuzzleHttp\Client(array_merge([ 'handler' => $stack, 'verify' => $this->getVerifyPeer(), 'timeout' => $this->getTimeout(), ], $options)); return $this; } /** * Make a request. * * @param $method * @param $endpoint * @param array $params * @return Http\Message\ResponseInterface * @throws Exceptions\BrontoException * @throws Exceptions\NotFoundException */ public function request($method, $endpoint, array $params = []) { $clientHandler = $this->client->getConfig('handler'); $oauthMiddleware = Middleware::mapRequest(function ($request) { return $request->withHeader('Authorization','Bearer ' . $this->auth->getToken()); }); $params['handler'] = $oauthMiddleware($clientHandler); try { $response = $this->client->request( $method, $this->auth->getEndpoint() . '/' . $endpoint, $params ); } catch (\Exception $e) { throw $this->convertException($e); } return json_decode((string) $response->getBody()); } /** * Convert the provided exception. * * @param Exception $e * @return Exceptions\NotFoundException|Exceptions\BrontoException|Exception */ protected function convertException(\Exception $e) { if ($e instanceof GuzzleHttp\Exception\ClientException && $e->getResponse()->getStatusCode() == 404) { return new Exceptions\NotFoundException('not found'); } if ($e instanceof GuzzleHttp\Exception\BadResponseException) { $message = (string) $e->getResponse()->getBody(); if(count($e->getResponse()->getHeader('X-Reason'))){ $message = (string) $e->getResponse()->getHeader('X-Reason')[0]; } return new Exceptions\BrontoException($message, $e->getResponse()->getStatusCode()); } return $e; } /** * Perform a GET request. * * @param $endpoint * @param array $params * @return Http\Message\ResponseInterface */ public function get($endpoint, array $params = []) { return $this->request('GET', $endpoint, $params); } /** * Perform a POST request. * * @param $endpoint * @param array $params * @return Http\Message\ResponseInterface */ public function post($endpoint, array $params = []) { return $this->request('POST', $endpoint, $params); } /** * Perform a PUT request. * * @param $endpoint * @param array $params * @return Http\Message\ResponseInterface */ public function put($endpoint, array $params = []) { return $this->request('PUT', $endpoint, $params); } /** * Perform a DELETE request. * * @param $endpoint * @param array $params * @return Http\Message\ResponseInterface */ public function delete($endpoint, array $params = []) { return $this->request('DELETE', $endpoint, $params); } /** * Order service module. * * @return Modules\OrderService */ public function orderService() { return new Modules\OrderService($this); } /** * Product service module. * * @return Modules\ProductService */ public function productService() { return new Modules\ProductService($this); } /** * Bind logging middleware. * * @param GuzzleHttp\HandlerStack $stack * @return void */ protected function bindLoggingMiddleware(GuzzleHttp\HandlerStack $stack) { $stack->push(Middleware::log( $this->logger, new MessageFormatter('{request} - {response}') )); } } <file_sep><?php namespace Arkade\Bronto\Serializers; use PHPUnit\Framework\TestCase; use Arkade\Bronto\Factories; class OrderSerializerTest extends TestCase { /** * @test */ public function returns_populated_json() { $json = (new OrderSerializer)->serialize( (new Factories\OrderFactory)->make() ); $this->assertEquals(file_get_contents(__DIR__.'/../Stubs/Orders/create_order_request.json'), $json); } }<file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; use Illuminate\Support\Collection; class DeliveryRecipient extends AbstractEntity { /** * @var string */ protected $deliveryType; /** * @var string */ protected $id; /** * @var string */ protected $type; /** * @return string */ public function getDeliveryType() { return $this->deliveryType; } /** * Valid values are: * eligible - Indicates that the contact, list, keyword, or segment specified in this object are eligible to receive the message being sent to it. * ineligible - Indicates that the contact, list, keyword, or segment specified in this object are not eligible to receive the message being sent to it. * uselected - (Default) * @param string $deliveryType * @return DeliveryRecipient */ public function setDeliveryType($deliveryType) { $this->deliveryType = $deliveryType; return $this; } /** * @return string */ public function getId() { return $this->id; } /** * The unique id of the recipient receiving the delivery. Depending on the type specified, * the id will be for a contact, a list, an smsKeyword, or a segment. * @param string $id * @return DeliveryRecipient */ public function setId($id) { $this->id = $id; return $this; } /** * @return string */ public function getType() { return $this->type; } /** * Whether the contact is receiving the message as part of a list, segment, SMS keyword, or as an individual contact. * Valid values are: contact, list, segment or keyword (SMS Only – Use with addSMSDeliveries) * @param string $type * @return DeliveryRecipient */ public function setType($type) { $this->type = $type; return $this; } /** * @return Array */ public function jsonSerialize() { $result = get_object_vars($this); return $result; } } <file_sep><?php namespace Omneo\Bronto\Entities; use Carbon\Carbon; /* * @see https://helpdocs.bronto.com/bmp/reference/r_bmp_product_fields_descriptions.html */ class Product extends AbstractEntity { /** * @var string */ protected $ageGroup; /** * @var string */ protected $availability; /** * @var Carbon */ protected $availabilityDate; /** * @var float */ protected $averageRating; /** * @var string */ protected $brand; /** * @var string */ protected $color; /** * @var string */ protected $condition; /** * @var string */ protected $description; /** * @var string */ protected $gender; /** * @var string */ protected $gtin; /** * @var string */ protected $imageUrl; /** * @var int */ protected $inventoryThreshold; /** * @var string */ protected $isbn; /** * @var string */ protected $mpn; /** * @var float */ protected $margin; /** * @var string */ protected $mobileUrl; /** * @var string */ protected $parentProductId; /** * @var string */ protected $price; /** * @var string */ protected $productCategory; /** * @var string */ protected $productId; /** * @var string */ protected $productTypeMulti; /** * @var string */ protected $productUrl; /** * @var int */ protected $quantity; /** * @var int */ protected $reviewCount; /** * @var string */ protected $salePrice; /** * @var Carbon */ protected $salePriceEffectiveStartDate; /** * @var Carbon */ protected $salePriceEffectiveEndDate; /** * @var string */ protected $size; /** * @var string */ protected $title; /** * @var string */ protected $upc; /** * @var Carbon */ protected $createdDate; /** * @var Carbon */ protected $updatedDate; /** * @return string */ public function getAgeGroup() { return $this->ageGroup; } /** * @param string $ageGroup * @return Product */ public function setAgeGroup($ageGroup) { $this->ageGroup = $ageGroup; return $this; } /** * @return string */ public function getAvailability() { return $this->availability; } /** * @param string $availability * @return Product */ public function setAvailability($availability) { $this->availability = $availability; return $this; } /** * @return Carbon|null */ public function getAvailabilityDate() { return $this->availabilityDate; } /** * @param Carbon $availabilityDate * @return Product */ public function setAvailabilityDate(Carbon $availabilityDate = null) { $this->availabilityDate = $availabilityDate; return $this; } /** * @return float */ public function getAverageRating() { return $this->averageRating; } /** * @param float $averageRating * @return Product */ public function setAverageRating($averageRating) { $this->averageRating = $averageRating; return $this; } /** * @return string */ public function getBrand() { return $this->brand; } /** * @param string $brand * @return Product */ public function setBrand($brand) { $this->brand = $brand; return $this; } /** * @return string */ public function getColor() { return $this->color; } /** * @param string $color * @return Product */ public function setColor($color) { $this->color = $color; return $this; } /** * @return string */ public function getCondition() { return $this->condition; } /** * @param string $condition * @return Product */ public function setCondition($condition) { $this->condition = $condition; return $this; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description * @return Product */ public function setDescription($description) { $this->description = $description; return $this; } /** * @return string */ public function getGender() { return $this->gender; } /** * @param string $gender * @return Product */ public function setGender($gender) { $this->gender = $gender; return $this; } /** * @return string */ public function getGtin() { return $this->gtin; } /** * @param string $gtin * @return Product */ public function setGtin($gtin) { $this->gtin = $gtin; return $this; } /** * @return string */ public function getImageUrl() { return $this->imageUrl; } /** * @param string $imageUrl * @return Product */ public function setImageUrl($imageUrl) { $this->imageUrl = $imageUrl; return $this; } /** * @return int */ public function getInventoryThreshold() { return $this->inventoryThreshold; } /** * @param int $inventoryThreshold * @return Product */ public function setInventoryThreshold($inventoryThreshold) { $this->inventoryThreshold = $inventoryThreshold; return $this; } /** * @return string */ public function getIsbn() { return $this->isbn; } /** * @param string $isbn * @return Product */ public function setIsbn($isbn) { $this->isbn = $isbn; return $this; } /** * @return string */ public function getMpn() { return $this->mpn; } /** * @param string $mpn * @return Product */ public function setMpn($mpn) { $this->mpn = $mpn; return $this; } /** * @return float */ public function getMargin() { return $this->margin; } /** * @param float $margin * @return Product */ public function setMargin($margin) { $this->margin = $margin; return $this; } /** * @return string */ public function getMobileUrl() { return $this->mobileUrl; } /** * @param string $mobileUrl * @return Product */ public function setMobileUrl($mobileUrl) { $this->mobileUrl = $mobileUrl; return $this; } /** * @return string */ public function getParentProductId() { return $this->parentProductId; } /** * @param string $parentProductId * @return Product */ public function setParentProductId($parentProductId) { $this->parentProductId = $parentProductId; return $this; } /** * @return string */ public function getPrice() { return $this->price; } /** * @param string $price * @return Product */ public function setPrice($price) { $this->price = $price; return $this; } /** * @return string */ public function getProductCategory() { return $this->productCategory; } /** * @param string $productCategory * @return Product */ public function setProductCategory($productCategory) { $this->productCategory = $productCategory; return $this; } /** * @return string */ public function getProductId() { return $this->productId; } /** * @param string $productId * @return Product */ public function setProductId($productId) { $this->productId = $productId; return $this; } /** * @return string */ public function getProductTypeMulti() { return $this->productTypeMulti; } /** * @param string $productTypeMulti * @return Product */ public function setProductTypeMulti($productTypeMulti) { $this->productTypeMulti = $productTypeMulti; return $this; } /** * @return string */ public function getProductUrl() { return $this->productUrl; } /** * @param string $productUrl * @return Product */ public function setProductUrl($productUrl) { $this->productUrl = $productUrl; return $this; } /** * @return int */ public function getQuantity() { return $this->quantity; } /** * @param int $quantity * @return Product */ public function setQuantity($quantity) { $this->quantity = $quantity; return $this; } /** * @return int */ public function getReviewCount() { return $this->reviewCount; } /** * @param int $reviewCount * @return Product */ public function setReviewCount($reviewCount) { $this->reviewCount = $reviewCount; return $this; } /** * @return string */ public function getSalePrice() { return $this->salePrice; } /** * @param string $salePrice * @return Product */ public function setSalePrice($salePrice) { $this->salePrice = $salePrice; return $this; } /** * @return Carbon|null */ public function getSalePriceEffectiveStartDate() { return $this->salePriceEffectiveStartDate; } /** * @param Carbon $salePriceEffectiveStartDate * @return Product */ public function setSalePriceEffectiveStartDate(Carbon $salePriceEffectiveStartDate = null) { $this->salePriceEffectiveStartDate = $salePriceEffectiveStartDate; return $this; } /** * @return Carbon|null */ public function getSalePriceEffectiveEndDate() { return $this->salePriceEffectiveEndDate; } /** * @param Carbon $salePriceEffectiveEndDate * @return Product */ public function setSalePriceEffectiveEndDate(Carbon $salePriceEffectiveEndDate = null) { $this->salePriceEffectiveEndDate = $salePriceEffectiveEndDate; return $this; } /** * @return string */ public function getSize() { return $this->size; } /** * @param string $size * @return Product */ public function setSize($size) { $this->size = $size; return $this; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param string $title * @return Product */ public function setTitle($title) { $this->title = $title; return $this; } /** * @return string */ public function getUpc() { return $this->upc; } /** * @param string $upc * @return Product */ public function setUpc($upc) { $this->upc = $upc; return $this; } /** * @return Carbon */ public function getCreatedDate() { return $this->createdDate; } /** * @param Carbon $createdDate * @return Order */ public function setCreatedDate(Carbon $createdDate = null) { $this->createdDate = $createdDate; return $this; } /** * @return Carbon */ public function getUpdatedDate() { return $this->updatedDate; } /** * @param Carbon $updatedDate * @return Order */ public function setUpdatedDate(Carbon $updatedDate = null) { $this->updatedDate = $updatedDate; return $this; } /** * @return Array */ public function jsonSerialize() { $result = get_object_vars($this); if(!is_null($result['salePriceEffectiveStartDate'])) $result['salePriceEffectiveStartDate'] = $result['salePriceEffectiveStartDate']->toDateString(); if(!is_null($result['salePriceEffectiveEndDate'])) $result['salePriceEffectiveEndDate'] = $result['salePriceEffectiveEndDate']->toDateString(); if(!is_null($result['availabilityDate'])) $result['availabilityDate'] = $result['availabilityDate']->toDateString(); return $result; } } <file_sep><?php namespace Omneo\Bronto\Modules; use Omneo\Bronto\Entities\Delivery; use Omneo\Bronto\Serializers\DeliverySerializer; use Omneo\Bronto\Exceptions; use Carbon\Carbon; class DeliveryService extends AbstractSoapModule { /** * Send an email delivery * * @param Delivery * @return Delivery */ public function send(Delivery $delivery) { $deliveryObject = $this->client->getClient()->getDeliveryObject(); $deliveryRow = $deliveryObject->createRow(); $deliveryArray = array_filter(json_decode((new DeliverySerializer())->serialize($delivery),true)); if(isset($deliveryArray['start'])) $deliveryRow->start = $deliveryArray['start']; if(isset($deliveryArray['type'])) $deliveryRow->type = $deliveryArray['type']; if(isset($deliveryArray['messageId'])) $deliveryRow->messageId = $deliveryArray['messageId']; if(isset($deliveryArray['fromEmail'])) $deliveryRow->fromEmail = $deliveryArray['fromEmail']; if(isset($deliveryArray['fromName'])) $deliveryRow->fromName = $deliveryArray['fromName']; if(isset($deliveryArray['recipients'])) $deliveryRow->recipients = $deliveryArray['recipients']; if(isset($deliveryArray['optin'])) $deliveryRow->optin = $deliveryArray['optin']; if(isset($deliveryArray['throttle'])) $deliveryRow->throttle = $deliveryArray['throttle']; if(isset($deliveryArray['replyEmail'])) $deliveryRow->replyEmail = $deliveryArray['replyEmail']; if(isset($deliveryArray['authentication'])) $deliveryRow->authentication = $deliveryArray['authentication']; if(isset($deliveryArray['messageRuleId'])) $deliveryRow->messageRuleId = $deliveryArray['messageRuleId']; $delivery->getFields()->each(function($field) use($deliveryRow){ $deliveryRow->setField($field->getName(), $field->getContent(), $field->getType()); }); // Save try { $deliveryRow->save(); return $delivery; } catch (Exception $e) { throw new Exceptions\BrontoException((string)$e->getResponse()->getBody(), $e->getResponse()->getStatusCode()); } } }<file_sep><?php return [ /* |-------------------------------------------------------------------------- | Bronto Contact Field Mappings |-------------------------------------------------------------------------- | | Because Bronto uses a custom identifier for accessing and updating fields, | you need to run the contact service's outputFields method first and past the output in here. | Example below. | */ 'field_mappings' => [ 'firstName' => '0bce03e9000000000000000000<KEY>', 'lastName' => '0bce03e9000000000000000000<KEY>' ], /* |-------------------------------------------------------------------------- | Bronto Contact Field to Bronto Contact Object Mappings |-------------------------------------------------------------------------- | | Now we map the properties of the SDK's Contact object to the field mappings | above. The values on the right should match the mapping names above. The values | here are from the MJ Bale Bronto contact fields, and are just an example. | */ 'contact_mappings' => [ 'id' => 'id', 'firstName' => 'firstname', 'lastName' => 'lastname', 'gender' => 'gender', 'birthday' => 'birthday', 'companyName' => 'Company', 'jobTitle' => 'Job_Title', 'phoneHome' => 'Phone_number', 'phoneMobile' => 'phone_mobile', 'salutation' => 'salutation', 'address1' => 'address1', 'address2' => 'address2', 'city' => 'city', 'suburb' => 'suburb', 'state' => 'state_province', 'postCode' => 'postal_code', 'creationDate' => 'Person_created_date', ], ];
c8bb208e14623c4af24d9e23a514248b019fbceb
[ "Markdown", "PHP" ]
48
PHP
omneo/bronto-sdk
f79dd9cf7c4c9510ef2e034d3ab639f04930958e
34fbf64bbbb7f89d5f4fb562e60b2757c1c8dbed
refs/heads/master
<file_sep>import React from "react" // components import VideoItem from "./VideoItem" const VideoList = ({ videos, onSelectVideo }) => { const videoItems = videos.map((video) => ( <VideoItem key={video.id.videoId} video={video} onSelectVideo={onSelectVideo} /> )) return <div className="ui relaxed divided list">{videoItems}</div> } export default VideoList <file_sep>import React from "react" const Spinner = ({ msg }) => { return ( <div className="ui active inverted dimmer"> <div className="ui text big loader">{msg}</div> </div> ) } Spinner.defaultProps = { msg: "Application is Loading...", } export default Spinner <file_sep>import React, { useState, useEffect } from "react" // components import Footer from "./Footer" import SearchBar from "./SearchBar" import Spinner from "./Spinner" import VideoDetails from "./VideoDetails" import VideoList from "./VideoList" // styles import "./App.css" // hooks import useVideo from "../hooks/useVideos" const App = () => { const [isLoading, videos, setVideos] = useVideo("python") const [selectedVideo, setSelectedVideo] = useState(null) useEffect(() => { setSelectedVideo(videos[0]) }, [videos]) if (selectedVideo) { return ( <> <div className="ui container"> <SearchBar onSearchSubmit={setVideos} isLoading={isLoading} /> <div className="ui grid"> <div className="ui row"> <div className="eleven wide column"> <VideoDetails video={selectedVideo} /> </div> <div className="five wide column"> <VideoList videos={videos} onSelectVideo={setSelectedVideo} /> </div> </div> </div> </div> <Footer /> </> ) } return <Spinner /> } export default App <file_sep># Screenshots A live version of this project is available at [search-youtube-videos-with-reactjs.netlify.app](https://search-youtube-videos-with-reactjs.netlify.app/) ![application preview](https://raw.githubusercontent.com/StephenRoille/project-428016a805-part-1/master/screenshots/preview.png) # Usage Clone this repo to your computer. ```shell git clone https://github.com/StephenRoille/project-428016a805-part-1.git youtube-search ``` Create a `.env` file and set a private Youtube token to allow your application to query the Youtube API, ```ini REACT_APP_YOUTUBE_TOKEN='<...>' ``` Install all the dependencies, ```shell npm install ``` Start the development server, ```shell npm run start ``` Your Youtube token is automatically loaded by `React`. To create a production build simply run, ```shell npm run build ``` This command creates a `build` directory that you can serve from a web server ([Apache](https://www.apache.org/), [nginx](https://www.nginx.com/)) or using a CDN platform ([Netlify](https://www.netlify.com/)) # Dependencies This project has the following dependencies, 1. `axios` (Youtube API requests) 2. `react` (user interface) # Reference Based on the [Modern React with Redux](https://www.udemy.com/course/react-redux/) course by <NAME>.
5d47861deb615df1e4c953c5f307ffac94927628
[ "JavaScript", "Markdown" ]
4
JavaScript
StephenRoille/project-428016a805-part-1
066968e1b596536104f109d3b187de53ab856573
98694a1f49abba209ca3aaefab5fa547afdc527a
refs/heads/master
<repo_name>dca-araujo/lib-SNRHos<file_sep>/src/libSNRHos.class.php <?php /** * Biblioteca mínima para atender envios de ficha eletrônica, checkin e checkout * de hóspedes * @author Airton (about.me/airton <EMAIL>) */ class libSNRHos { const FalhaCriarSoapClient = 1; const FalhaInserirFicha = 2; const FalhaAtualizarFicha = 3; const FalhaCheckin = 4; const FalhaCheckout = 5; private $chave; private $wsld_url = 'http://fnrhws.hospedagen.turismo.gov.br/FnrhWs/FnrhWs?wsdl'; private function getSoapClient() { try{ $soapClient = new SoapClient($this->wsld_url); }catch(Exception $e){ throw new Exception('falha ao criar SoapClient msg:'.$e->getMessage(), libSNRHos::FalhaCriarSoapClient); } return $soapClient; } public function __construct($sandbox = false) { if($sandbox == true){ $this->wsld_url = 'http://localhost:8088/mockwebservice?WSDL'; } } public function setCredenciais($chave) { $this->chave = $chave; } public function inserirFicha($ficha) { try{ $soapClient = $this->getSoapClient(); $soapClient->fnrhInserir($ficha); }catch(Exception $e){ throw new Exception('falha ao inserir ficha msg:' . $e->getMessage(), libSNRHos::FalhaInserirFicha); } } public function atualizarFicha($ficha) { try{ $soapClient = $this->getSoapClient(); $soapClient->fnrhAtualizar($ficha); }catch(Exception $e){ throw new Exception('falha ao atualizar ficha msg:' . $e->getMessage(), libSNRHos::FalhaAtualizarFicha); } } public function checkin($hospede) { try{ $soapClient = $this->getSoapClient(); return $soapClient->fnrhCheckin($hospede); }catch(Exception $e){ throw new Exception('falha ao informar checkin msg:' . $e->getMessage(), libSNRHos::FalhaCheckin); } } public function checkout($hospede) { try{ $soapClient = $this->getSoapClient(); $soapClient->fnrhCheckout($hospede); }catch(Exception $e){ throw new Exception('falha ao informar checkout msg:' . $e->getMessage(), libSNRHos::FalhaCheckout); } } } <file_sep>/src/msgCheckin.class.php <?php /** * Mensagem para informar checkin * * @author Airton (about.me/airton <EMAIL>) */ namespace libSNRHos; class msgCheckin implements Mensagem{ private $msg; public function __construct() { } public function setChaveAcesso($chave){ $this->msg['chaveAcesso'] = $chave; } /** identificação da ficha de registro de hóspede para realizar checkin * @param string $numeroficha */ public function setFicha($numeroFicha) { $this->msg['snNum'] = $numeroFicha; } /** * Data hora em formato americano do checkin * @param Data aaaa-MM-ddTHH:mm:ss $dataHora */ public function setDataCheckin($dataHora) { $this->msg['dataCheckin']=$dataHora; } /** * Retorna mensagem para envio em array * @return array */ public function getMensagem() { return $this->msg; } } <file_sep>/src/msgFicha.class.php <?php /** * Mesagem de Entrada, ficha de registro do hóspede * @author Airton (about.me/airton <EMAIL>) */ namespace libSNRHos; class msgFicha implements Mensagem{ const MotivoLazerFerias =1; const MotivoNegocios =2; const MotivoCongressoFeira =3; const MotivoParentesAmigos =4; const MotivoEstudosCursos =5; const MotivoReligiao =6; const MotivoSaude =7; const MotivoCompras =8; const MotivoOutro =9; const TransporteAviao =1; const TransporteAutomovel =2; const TransporteOnibus =3; const TransporteMoto =4; const TransporteNavio =5; const TransporteTrem =6; const TransporteOutro =7; private $msg; public function __construct() { } public function setChaveAcesso($chave) { $this->msg['chaveAcesso'] = $chave; } public function setCpf($cpf) { $this->msg['fnrh']['snnumcpf'] = $cpf; } public function setTipoDocumento($tipo) { } public function setNumeroDocumento($numero) { } public function getMensagem(){ return $this->msg; } } <file_sep>/README.md lib-SNRHos ========== Biblioteca php para integração com webservice do Sistema Nacional de Registro de Hóspedes (SNRHos) do Ministério do Turismo, que é uma exigência o envio de ficha do hóspede, checkin e checkout. Site oficial: http://hospedagem.turismo.gov.br/ WSDL de PRODUÇÃO: http://fnrhws.hospedagem.turismo.gov.br/FnrhWs/FnrhWs?wsdl <file_sep>/src/mensagem.class.php <?php /** * Interface básica de mensagem * @author Airton (about.me/airton <EMAIL>) */ namespace libSNRHos; interface Mensagem { public function setChaveAcesso($chave); public function getMensagem(); }
07cf5caaaeba879ee5f8982ed7d2f322f60cb1d2
[ "Markdown", "PHP" ]
5
PHP
dca-araujo/lib-SNRHos
6d0fabd2e424e8b82aae4d7457f1a0f8e8b40c4c
914b5b24f64c931aa778d88e4755d6e5ce0eb1cd
refs/heads/master
<repo_name>AppetizerDessert/P05Quiz<file_sep>/app/src/main/java/c346/rp/edu/p05_quiz/MainActivity.java package c346.rp.edu.p05_quiz; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; public class MainActivity extends AppCompatActivity { CheckBox cbOneWay; CheckBox cbRoundTrip; Button btnMinus; Button btnPlus; Button btnSubmit; TextView tvPaxAmt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cbOneWay = findViewById(R.id.OneWay); cbRoundTrip = findViewById(R.id.RoundTrip); btnMinus = findViewById(R.id.minus); btnPlus = findViewById(R.id.plus); btnSubmit = findViewById(R.id.button3); tvPaxAmt = findViewById(R.id.PaxAmt); btnMinus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int amt = 0; tvPaxAmt.setText(amt - 1); } }); btnPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int amt = 0; tvPaxAmt.setText(amt + 1); } }); if (cbOneWay.isChecked() == true && cbRoundTrip.isChecked() == false){ String option1 = "One Way Trip"; } else if (cbRoundTrip.isChecked() == true && cbOneWay.isChecked() == false){ String option1 = "Round Trip"; } btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getBaseContext(), SecondActivity.class); intent.putExtra("trip", option1); intent.putExtra("cost", amount); startActivity(intent); } }); } }
45f62d05963c82c08980aa3a04801af25eedd847
[ "Java" ]
1
Java
AppetizerDessert/P05Quiz
9d686cb7db90f335d8ea1a7e805f7d87d35724ae
64942b33610e3f1ce9bfaf8549c7fa5e09a58db5
refs/heads/master
<repo_name>ettiennegous/ESP-MQTT-JSON-Multisensor<file_sep>/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino /* .______ .______ __ __ __ __ ___ __ __ .___________. ______ .___ ___. ___ .___________. __ ______ .__ __. | _ \ | _ \ | | | | | | | | / \ | | | | | | / __ \ | \/ | / \ | || | / __ \ | \ | | | |_) | | |_) | | | | | | |__| | / ^ \ | | | | `---| |----`| | | | | \ / | / ^ \ `---| |----`| | | | | | | \| | | _ < | / | | | | | __ | / /_\ \ | | | | | | | | | | | |\/| | / /_\ \ | | | | | | | | | . ` | | |_) | | |\ \-.| `--' | | | | | / _____ \ | `--' | | | | `--' | | | | | / _____ \ | | | | | `--' | | |\ | |______/ | _| `.__| \______/ |__| |__| /__/ \__\ \______/ |__| \______/ |__| |__| /__/ \__\ |__| |__| \______/ |__| \__| Thanks much to @corbanmailloux for providing a great framework for implementing flash/fade with HomeAssistant https://github.com/corbanmailloux/esp-mqtt-rgb-led To use this code you will need the following dependancies: - Support for the ESP8266 boards. - You can add it to the board manager by going to File -> Preference and pasting http://arduino.esp8266.com/stable/package_esp8266com_index.json into the Additional Board Managers URL field. - Next, download the ESP8266 dependancies by going to Tools -> Board -> Board Manager and searching for ESP8266 and installing it. - You will also need to download the follow libraries by going to Sketch -> Include Libraries -> Manage Libraries - DHT sensor library - Adafruit unified sensor - PubSubClient - ArduinoJSON UPDATE 16 MAY 2017 by Knutella - Fixed MQTT disconnects when wifi drops by moving around Reconnect and adding a software reset of MCU UPDATE 23 MAY 2017 - The MQTT_MAX_PACKET_SIZE parameter may not be setting appropriately do to a bug in the PubSub library. If the MQTT messages are not being transmitted as expected please you may need to change the MQTT_MAX_PACKET_SIZE parameter in "PubSubClient.h" directly. */ #include <ESP8266WiFi.h> #include <DHT.h> #include <PubSubClient.h> #include <ESP8266mDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h> #include <ArduinoJson.h> /************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/ #define wifi_ssid "YourSSID" //type your WIFI information inside the quotes #define wifi_password "<PASSWORD>" #define mqtt_server "your.mqtt.server.ip" #define mqtt_user "yourMQTTusername" #define mqtt_password "<PASSWORD>" #define mqtt_port 1883 /************* MQTT TOPICS (change these topics as you wish) **************************/ #define light_state_topic "bruh/sensornode1" #define light_set_topic "bruh/sensornode1/set" const char* on_cmd = "ON"; const char* off_cmd = "OFF"; /**************************** FOR OTA **************************************************/ #define SENSORNAME "sensornode1" #define OTApassword "<PASSWORD>" // change this to whatever password you want to use when you upload OTA int OTAport = 8266; /**************************** PIN DEFINITIONS ********************************************/ const int redPin = D1; const int greenPin = D2; const int bluePin = D3; #define PIRPIN D5 #define DHTPIN D7 #define DHTTYPE DHT22 #define LDRPIN A0 #define TRIGGER 2 #define ECHO 15 /**************************** SENSOR DEFINITIONS *******************************************/ float ldrValue; int LDR; float calcLDR; float diffLDR = 25; float diffTEMP = 0.2; float tempValue; long distanceValue = 0.0; long durationValue = 0.0; float diffHUM = 1; float humValue; int pirValue; int pirStatus; String motionStatus; char message_buff[100]; int calibrationTime = 0; const int BUFFER_SIZE = 300; #define MQTT_MAX_PACKET_SIZE 512 /******************************** GLOBALS for fade/flash *******************************/ byte red = 255; byte green = 255; byte blue = 255; byte brightness = 255; byte realRed = 0; byte realGreen = 0; byte realBlue = 0; bool stateOn = false; bool startFade = false; unsigned long lastLoop = 0; int transitionTime = 0; bool inFade = false; int loopCount = 0; int stepR, stepG, stepB; int redVal, grnVal, bluVal; bool flash = false; bool startFlash = false; int flashLength = 0; unsigned long flashStartTime = 0; byte flashRed = red; byte flashGreen = green; byte flashBlue = blue; byte flashBrightness = brightness; WiFiClient espClient; PubSubClient client(espClient); DHT dht(DHTPIN, DHTTYPE); /********************************** START SETUP*****************************************/ void setup() { Serial.begin(115200); pinMode(PIRPIN, INPUT); pinMode(DHTPIN, INPUT); pinMode(LDRPIN, INPUT); pinMode(TRIGGER, OUTPUT); pinMode(ECHO, INPUT); pinMode(TRIGGER, OUTPUT); pinMode(ECHO, INPUT); Serial.begin(115200); delay(10); ArduinoOTA.setPort(OTAport); ArduinoOTA.setHostname(SENSORNAME); ArduinoOTA.setPassword((const char *)OTApassword); Serial.print("calibrating sensor "); for (int i = 0; i < calibrationTime; i++) { Serial.print("."); delay(1000); } Serial.println("Starting Node named " + String(SENSORNAME)); setup_wifi(); client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); ArduinoOTA.onStart([]() { Serial.println("Starting"); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println("Ready"); Serial.print("IPess: "); Serial.println(WiFi.localIP()); reconnect(); } /********************************** START SETUP WIFI*****************************************/ void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(wifi_ssid); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } /********************************** START CALLBACK*****************************************/ void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); char message[length + 1]; for (int i = 0; i < length; i++) { message[i] = (char)payload[i]; } message[length] = '\0'; Serial.println(message); if (!processJson(message)) { return; } if (stateOn) { // Update lights realRed = map(red, 0, 255, 0, brightness); realGreen = map(green, 0, 255, 0, brightness); realBlue = map(blue, 0, 255, 0, brightness); } else { realRed = 0; realGreen = 0; realBlue = 0; } startFade = true; inFade = false; // Kill the current fade sendState(); } /********************************** START PROCESS JSON*****************************************/ bool processJson(char* message) { StaticJsonBuffer<BUFFER_SIZE> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(message); if (!root.success()) { Serial.println("parseObject() failed"); return false; } if (root.containsKey("state")) { if (strcmp(root["state"], on_cmd) == 0) { stateOn = true; } else if (strcmp(root["state"], off_cmd) == 0) { stateOn = false; } } // If "flash" is included, treat RGB and brightness differently if (root.containsKey("flash")) { flashLength = (int)root["flash"] * 1000; if (root.containsKey("brightness")) { flashBrightness = root["brightness"]; } else { flashBrightness = brightness; } if (root.containsKey("color")) { flashRed = root["color"]["r"]; flashGreen = root["color"]["g"]; flashBlue = root["color"]["b"]; } else { flashRed = red; flashGreen = green; flashBlue = blue; } flashRed = map(flashRed, 0, 255, 0, flashBrightness); flashGreen = map(flashGreen, 0, 255, 0, flashBrightness); flashBlue = map(flashBlue, 0, 255, 0, flashBrightness); flash = true; startFlash = true; } else { // Not flashing flash = false; if (root.containsKey("color")) { red = root["color"]["r"]; green = root["color"]["g"]; blue = root["color"]["b"]; } if (root.containsKey("brightness")) { brightness = root["brightness"]; } if (root.containsKey("transition")) { transitionTime = root["transition"]; } else { transitionTime = 0; } } return true; } /********************************** START SEND STATE*****************************************/ void sendState() { StaticJsonBuffer<BUFFER_SIZE> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); root["state"] = (stateOn) ? on_cmd : off_cmd; JsonObject& color = root.createNestedObject("color"); color["r"] = red; color["g"] = green; color["b"] = blue; root["brightness"] = brightness; root["humidity"] = (String)humValue; root["motion"] = (String)motionStatus; root["ldr"] = (String)LDR; root["distance"] = (String)distanceValue; root["temperature"] = (String)tempValue; root["heatIndex"] = (String)calculateHeatIndex(humValue, tempValue); char buffer[root.measureLength() + 1]; root.printTo(buffer, sizeof(buffer)); Serial.println(buffer); client.publish(light_state_topic, buffer, true); } /* * Calculate Heat Index value AKA "Real Feel" * NOAA heat index calculations taken from * http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml */ float calculateHeatIndex(float humidity, float temp) { float heatIndex= 0; if (temp >= 80) { heatIndex = -42.379 + 2.04901523*temp + 10.14333127*humidity; heatIndex = heatIndex - .22475541*temp*humidity - .00683783*temp*temp; heatIndex = heatIndex - .05481717*humidity*humidity + .00122874*temp*temp*humidity; heatIndex = heatIndex + .00085282*temp*humidity*humidity - .00000199*temp*temp*humidity*humidity; } else { heatIndex = 0.5 * (temp + 61.0 + ((temp - 68.0)*1.2) + (humidity * 0.094)); } if (humidity < 13 && 80 <= temp <= 112) { float adjustment = ((13-humidity)/4) * sqrt((17-abs(temp-95.))/17); heatIndex = heatIndex - adjustment; } return heatIndex; } /********************************** START SET COLOR *****************************************/ void setColor(int inR, int inG, int inB) { analogWrite(redPin, inR); analogWrite(greenPin, inG); analogWrite(bluePin, inB); Serial.println("Setting LEDs:"); Serial.print("r: "); Serial.print(inR); Serial.print(", g: "); Serial.print(inG); Serial.print(", b: "); Serial.println(inB); } /********************************** START RECONNECT*****************************************/ void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect(SENSORNAME, mqtt_user, mqtt_password)) { Serial.println("connected"); client.subscribe(light_set_topic); setColor(0, 0, 0); sendState(); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } /********************************** START CHECK SENSOR **********************************/ bool checkBoundSensor(float newValue, float prevValue, float maxDiff) { return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff; } /********************************** START MAIN LOOP***************************************/ void loop() { ArduinoOTA.handle(); if (!client.connected()) { // reconnect(); software_Reset(); } client.loop(); if (!inFade) { float newTempValue = dht.readTemperature(true); //to use celsius remove the true text inside the parentheses float newHumValue = dht.readHumidity(); digitalWrite(TRIGGER, LOW); delayMicroseconds(2); digitalWrite(TRIGGER, HIGH); delayMicroseconds(10); digitalWrite(TRIGGER, LOW); durationValue = pulseIn(ECHO, HIGH); long newDistanceValue = (durationValue/2) / 29.1; if(newDistanceValue != distanceValue) { distanceValue = newDistanceValue; sendState(); } //PIR CODE pirValue = digitalRead(PIRPIN); //read state of the if (pirValue == LOW && pirStatus != 1) { motionStatus = "standby"; sendState(); pirStatus = 1; } else if (pirValue == HIGH && pirStatus != 2) { motionStatus = "motion detected"; sendState(); pirStatus = 2; } delay(100); if (checkBoundSensor(newTempValue, tempValue, diffTEMP)) { tempValue = newTempValue; sendState(); } if (checkBoundSensor(newHumValue, humValue, diffHUM)) { humValue = newHumValue; sendState(); } int newLDR = analogRead(LDRPIN); if (checkBoundSensor(newLDR, LDR, diffLDR)) { LDR = newLDR; sendState(); } } if (flash) { if (startFlash) { startFlash = false; flashStartTime = millis(); } if ((millis() - flashStartTime) <= flashLength) { if ((millis() - flashStartTime) % 1000 <= 500) { setColor(flashRed, flashGreen, flashBlue); } else { setColor(0, 0, 0); // If you'd prefer the flashing to happen "on top of" // the current color, uncomment the next line. // setColor(realRed, realGreen, realBlue); } } else { flash = false; setColor(realRed, realGreen, realBlue); } } if (startFade) { // If we don't want to fade, skip it. if (transitionTime == 0) { setColor(realRed, realGreen, realBlue); redVal = realRed; grnVal = realGreen; bluVal = realBlue; startFade = false; } else { loopCount = 0; stepR = calculateStep(redVal, realRed); stepG = calculateStep(grnVal, realGreen); stepB = calculateStep(bluVal, realBlue); inFade = true; } } if (inFade) { startFade = false; unsigned long now = millis(); if (now - lastLoop > transitionTime) { if (loopCount <= 1020) { lastLoop = now; redVal = calculateVal(stepR, redVal, loopCount); grnVal = calculateVal(stepG, grnVal, loopCount); bluVal = calculateVal(stepB, bluVal, loopCount); setColor(redVal, grnVal, bluVal); // Write current values to LED pins Serial.print("Loop count: "); Serial.println(loopCount); loopCount++; } else { inFade = false; } } } } /**************************** START TRANSITION FADER *****************************************/ // From https://www.arduino.cc/en/Tutorial/ColorCrossfader /* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS The program works like this: Imagine a crossfade that moves the red LED from 0-10, the green from 0-5, and the blue from 10 to 7, in ten steps. We'd want to count the 10 steps and increase or decrease color values in evenly stepped increments. Imagine a + indicates raising a value by 1, and a - equals lowering it. Our 10 step fade would look like: 1 2 3 4 5 6 7 8 9 10 R + + + + + + + + + + G + + + + + B - - - The red rises from 0 to 10 in ten steps, the green from 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps. In the real program, the color percentages are converted to 0-255 values, and there are 1020 steps (255*4). To figure out how big a step there should be between one up- or down-tick of one of the LED values, we call calculateStep(), which calculates the absolute gap between the start and end values, and then divides that gap by 1020 to determine the size of the step between adjustments in the value. */ int calculateStep(int prevValue, int endValue) { int step = endValue - prevValue; // What's the overall gap? if (step) { // If its non-zero, step = 1020 / step; // divide by 1020 } return step; } /* The next function is calculateVal. When the loop value, i, reaches the step size appropriate for one of the colors, it increases or decreases the value of that color by 1. (R, G, and B are each calculated separately.) */ int calculateVal(int step, int val, int i) { if ((step) && i % step == 0) { // If step is non-zero and its time to change a value, if (step > 0) { // increment the value if step is positive... val += 1; } else if (step < 0) { // ...or decrement it if step is negative val -= 1; } } // Defensive driving: make sure val stays in the range 0-255 if (val > 255) { val = 255; } else if (val < 0) { val = 0; } return val; } /****reset***/ void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers { Serial.print("resetting"); ESP.reset(); } <file_sep>/README.md # ESP MQTT JSON Multisensor This project shows a super easy way to get started with your own DIY Multisensor to use with [Home Assistant](https://home-assistant.io/), a sick, open-source Home Automation platform that can do just about anything. Bonus, this project requires **no soldering** and **no breadboards** - just header wires and the development board! Video Tutorial - https://youtu.be/jpjfVc-9IrQ The code covered in this repository utilizies Home Assistant's [MQTT JSON Light Component](https://home-assistant.io/components/light.mqtt_json/), [MQTT Sensor Component](https://home-assistant.io/components/sensor.mqtt/), and a [NodeMCU ESP8266](http://geni.us/cpmi) development board. ### Supported Features Include - **DHT22** temperature sensor - **DHT22** humidity sensor - **AM312** PIR motion sensor - **photoresistor** or **TEMT600** light sensor - **RGB led** with support for color, flash, fade, and transition - **Over-the-Air (OTA)** upload from the ArduinoIDE #### OTA Uploading This code also supports remote uploading to the ESP8266 using Arduino's OTA library. To utilize this, you'll need to first upload the sketch using the traditional USB method. However, if you need to update your code after that, your WIFI-connected ESP chip should show up as an option under Tools -> Port -> Porch at your.ip.address.xxx. More information on OTA uploading can be found [here](http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html). Note: You cannot access the serial monitor over WIFI at this point. ### Parts List **Amazon Prime (fast shipping)** - [NodeMCU 1.0](http://geni.us/cpmi) - [DHT22 Module](http://geni.us/vAJWMXo) - [LDR Photoresistor Module](http://geni.us/O0AO0) OR - [TEMT6000](http://geni.us/aRYe) - [Power Supply](http://geni.us/ZZ1r) - [Common Cathode RGB Led](http://geni.us/nFcB) - [Header Wires](http://geni.us/pvFNG) - [AM312 Mini PIR Sensor](http://geni.us/dbGQ) **Aliexpress (long shipping = cheap prices)** - [NodeMCU 1.0](http://geni.us/EfYA) - [DHT22 Module](http://geni.us/35Np8H) - [LDR Photoresistor Module](http://geni.us/O5iv) OR - [TEMT6000](http://geni.us/xAuLoy) - [Power Supply](http://geni.us/NSYjvb) - [Common Cathode RGB Led](http://geni.us/OfHbhZb) - [Header Wires](http://geni.us/Iv6p9) - [AM312 Mini PIR Sensor](http://geni.us/WBKyxhx) ### Wiring Diagram ![alt text](https://github.com/bruhautomation/ESP-MQTT-JSON-Multisensor/blob/master/wiring_diagram_v2.png?raw=true "Wiring Diagram") ### 3D Printed Enclosure In an effort to make the sensor less ugly, I designed an enclosure in 123D Design and uploaded the [STL file](https://github.com/bruhautomation/ESP-MQTT-JSON-Multisensor/blob/master/BRUH%20Multisensor%20V1.stl) in case you want to print your own. It's also availible on [Thingiverse](http://www.thingiverse.com/thing:2239142). I printed mine on a [Prusa I3 clone](https://www.youtube.com/watch?v=PLRdMtZVQfQ) with a layer height of 0.2 mm, 40% infill, and no supports in [ESUN PLA](http://geni.us/GS3U) and it turned out great. Alternatively, you can also make your own enclosure by hand using something like [Instamorph](http://geni.us/BtidLG3). It's themoplastic that melts in hot water and then solidifies to hard plastic at room temperature. You can even get [pigment packs](http://geni.us/dNTi) and take it next level. I, personally, suck at using it, but it's cheap and functional. Of course, you can use a project box, tupperware, a card board box, or skip the enclosure all together. ![alt text](https://github.com/bruhautomation/ESP-MQTT-JSON-Multisensor/blob/master/BRUH%20Multisensor%20V1.PNG?raw=true "Enclosure") ### UPDATED 10 JUN 2017 I added a second version of my enclosure that moves the DHT22 sensor outside the case, removes the standoff for the LDR sensor, and adds a pocket for the LED. This should reduce most of the high temperatures being reported by the board and the removal of the standoff allows you to use either the TEMT600 sensor or photoresistor module. A dab of hot glue can help hold everything in place until you can snap the case together. A few people have reported that the floating PIR sensor issue is back. If it happens, wrap the PIR module in electrical tape, then aluminum foil, and then electrical tape again. Using the tape will make sure you don't short anything out with the foil on either the module or other components in the system. ### Home Assistant Service Examples Besides using the card in Home Assistant's user interface, you can also use the Services tool to control the light using the light.turn_on and light.turn_off services. This will let you play with the parameters you can call later in automations or scripts. Fade the Light On Over 5 Seconds - light.turn_on ``` {"entity_id":"light.sn1_led", "brightness":150, "color_name":"blue", "transition":"5" } ``` Flash The Light - light.turn_on ``` {"entity_id":"light.sn1_led", "color_name":"green", "brightness":255, "flash":"short" } ``` Fade the Light Off Over 5 Seconds - light.turn_off ``` {"entity_id":"light.sn1_led", "transition":"5" } ```
8fc626e6dd7a6e7fc616bfba508f789d76a2118a
[ "Markdown", "C++" ]
2
C++
ettiennegous/ESP-MQTT-JSON-Multisensor
06f7d14ee7248be5b14e48c7b65efe7936aa6d34
e9c3cb82cb7d03c58e90a16df3d212e9c3d0f9f0
refs/heads/master
<repo_name>omgitspradeep/TheSpiceLounge<file_sep>/app/src/main/java/com/sujan/info/thespicelounge/CashierActivity.java package com.sujan.info.thespicelounge; import android.content.Intent; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.Toolbar; import com.sujan.info.thespicelounge.Adapters.OrderedListAdapterCashier; import com.sujan.info.thespicelounge.Adapters.TableAdapter; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.MyPreferences; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.fragments.CashierOrderFragment; import com.sujan.info.thespicelounge.fragments.CashierTableFragment; import com.sujan.info.thespicelounge.interfaceT.orderListWithTableListener; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.models.TableInformation; import com.sujan.info.thespicelounge.webservices.GetOrderListWithTable; import java.util.ArrayList; public class CashierActivity extends BaseActivity implements TableAdapter.tableSelectionInterface,OrderedListAdapterCashier.onOrderedListInCashierUpdated,orderListWithTableListener { Toolbar tb; FrameLayout frameLayout; FloatingActionButton fabForBack,fabForRefresh; boolean doubleBackToExitPressedOnce = false; CashierOrderFragment cashierOrderFragment; ProgressBar progressBar; @Override public void onTableClick(int tableNum,ArrayList<OrderDetail> orderDetailArrayList) { cashierOrderFragment=new CashierOrderFragment(this,orderDetailArrayList,tableNum); getSupportFragmentManager().beginTransaction().replace(R.id.fragment_cashier_frame, cashierOrderFragment).commit(); fabForBack.setVisibility(View.VISIBLE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cashier); init(); } private void init() { tb = (Toolbar) findViewById(R.id.toolbar_cashier); tb.setTitle(MyPreferences.getStringPrefrences(Constants.EMPLOYEE_NAME_TITLE,this)); tb.inflateMenu(R.menu.toolbar); setActionBar(tb); progressBar=(ProgressBar)findViewById(R.id.progressBarRefresh); fabForBack=(FloatingActionButton)findViewById(R.id.fab_cashier_back_to_table); fabForRefresh=(FloatingActionButton)findViewById(R.id.fab_refresh_to_update); frameLayout=(FrameLayout)findViewById(R.id.fragment_cashier_frame); getSupportFragmentManager().beginTransaction().replace(R.id.fragment_cashier_frame, new CashierTableFragment(this)).commit(); fabForBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onFabForBackPressed(); } }); fabForRefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar.setVisibility(View.VISIBLE); new GetOrderListWithTable(CashierActivity.this,CashierActivity.this).execute(); } }); } public void onFabForBackPressed() { getSupportFragmentManager().beginTransaction().replace(R.id.fragment_cashier_frame, new CashierTableFragment(CashierActivity.this)).commit(); fabForBack.setVisibility(View.INVISIBLE); } @Override public boolean onCreateOptionsMenu(Menu menu) { tb.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { return onOptionsItemSelected(item); } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // action with ID action_refresh was selected case R.id.action_logout: MyPreferences.resetAllPreferences(getApplicationContext()); Utils.activityTransitionRemovingHistory(this,new Intent(this, MainActivity.class)); break; default: break; } return true; } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Utils.displayShortToastMessage(this, "Please click BACK again to exit"); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } @Override public void onCashierListUpdated(int totalAmt, boolean canBeCheckout) { cashierOrderFragment.updateTotalPriceAndCheckout(totalAmt,canBeCheckout); } public void setFabForRefreshInvisible(){ fabForRefresh.setVisibility(View.INVISIBLE); } public void progressBarVisibility(int id){ // id: 0->invisible, 1:visible if(id==0){ progressBar.setVisibility(View.INVISIBLE); }else{ progressBar.setVisibility(View.VISIBLE); } } @Override public void onOrdersForTableReceived(boolean isSuccess) { progressBar.setVisibility(View.INVISIBLE); if(isSuccess){ Utils.activityTransitionRemovingHistory(this,new Intent(this,CashierActivity.class)); Utils.displayLongToastMessage(this,"All table orders are updated."); } } public void setFabForRefreshVisible() { fabForRefresh.setVisibility(View.VISIBLE); } @Override public void onCustomerCheckoutSuccessfully(boolean isSuccess) { Utils.activityTransitionRemovingHistory(this,new Intent(this,CashierActivity.class)); Utils.displayShortToastMessage(this,"Successfully checkout"); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/Adapters/OrderedListAdapterChef.java package com.sujan.info.thespicelounge.Adapters; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.sujan.info.thespicelounge.ChefActivity; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.webservices.ChangeOrderStatus; import java.util.ArrayList; import java.util.HashMap; /** * Created by pradeep on 9/7/20. */ public class OrderedListAdapterChef extends RecyclerView.Adapter<OrderedListAdapterChef.ViewHolder> { ChefActivity context; private LayoutInflater mInflater; ArrayList<OrderDetail> orderDetailsList; public OrderedListAdapterChef(ChefActivity context,ArrayList<OrderDetail> orderDetailsList) { this.context = context; this.mInflater = LayoutInflater.from(context); this.orderDetailsList=orderDetailsList; } @Override public OrderedListAdapterChef.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.order_item_recycler_element_chef, parent, false); return new OrderedListAdapterChef.ViewHolder(view); } /* java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference*/ @Override public void onBindViewHolder(ViewHolder holder, int position) { init(holder,position); } @SuppressLint("SetTextI18n") private void init(ViewHolder holder, int position) { OrderDetail od=orderDetailsList.get(position); int foodId=od.getItemId(); FoodDetails fd= ResourceManager.getFoodDetails(foodId); int orderStatus=od.getFoodStatus(); String custRequest=od.getCustRequest(); holder.sNoChef.setText(position+1+""); holder.quantity.setText(od.getQuantity()+" "); holder.chefOrderItem.setText(fd.getFullItemName()); holder.chefOrderTime.setText(fd.getPrepareTimeinMins()+""); if(!custRequest.equals("")){ holder.custRequest.setText("Request: "+custRequest); } changeColor(orderStatus,holder.chefFoodStatus); holder.chefFoodStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Chef can click on waiting and cooking only if(orderStatus==0 || orderStatus == 1){ context.getProgressBarChef().setVisibility(View.VISIBLE); new ChangeOrderStatus(context,context,od.getOrderID(),orderStatus).execute(); } } }); } private void changeColor(int orderStatus, Button chefFoodStatus) { switch (orderStatus){ case 0: chefFoodStatus.setText("waiting"); chefFoodStatus.setTextColor(Color.parseColor("#4B0082")); chefFoodStatus.setClickable(true); break; case 1: chefFoodStatus.setText("cooking"); chefFoodStatus.setTextColor(Color.parseColor("#0000FF")); chefFoodStatus.setClickable(true); break; case 2: chefFoodStatus.setText("cooked"); chefFoodStatus.setTextColor(Color.parseColor("#FF7F00")); break; case 3: chefFoodStatus.setText("served"); chefFoodStatus.setTextColor(Color.parseColor("#006400")); break; } } @Override public int getItemCount() { return orderDetailsList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView sNoChef,quantity, chefOrderItem,chefOrderTime,custRequest; Button chefFoodStatus; public ViewHolder(View itemView) { super(itemView); sNoChef=(TextView)itemView.findViewById(R.id.sNo_chef); quantity=(TextView)itemView.findViewById(R.id.chef_order_qty); chefOrderItem=(TextView)itemView.findViewById(R.id.chef_ordered_item); chefOrderTime=(TextView)itemView.findViewById(R.id.chef_order_time); chefFoodStatus=(Button) itemView.findViewById(R.id.chef_status_button); custRequest=(TextView) itemView.findViewById(R.id.customer_request_message); } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/webservices/AddUpdateFoodItem.java package com.sujan.info.thespicelounge.webservices; import android.app.Activity; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import com.sujan.info.thespicelounge.Utils.AppConstants; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.interfaceT.deleteItemListener; import com.sujan.info.thespicelounge.interfaceT.menuItemAddUpdateListener; import com.sujan.info.thespicelounge.models.FoodDetails; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; /** * Created by pradeep on 5/8/20. */ public class AddUpdateFoodItem extends AsyncTask<String,Integer,Boolean> { private ArrayList<FoodDetails> foodDetailsArrayList; menuItemAddUpdateListener listener; FoodDetails foodDetails; Activity context; public AddUpdateFoodItem(Activity activity,menuItemAddUpdateListener listener, FoodDetails fd) { this.listener = listener; this.foodDetails = fd; this.context=activity; } @Override protected Boolean doInBackground(String... strings) { try{ URL url=new URL(AppConstants.BASE_ADMIN_URL+AppConstants.ADD_UPDATE_MENU_ITEM); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; utf-8"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); String jsonString=foodDetails.toJSON(); try(OutputStream os = conn.getOutputStream()) { byte[] input = jsonString.getBytes("utf-8"); os.write(input, 0, input.length); } String line; StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line); } String s = sb.toString(); JSONArray jsonArray = new JSONArray(s); Log.e("Hoooooooo",s); ResourceManager.writeToFile(s, Constants.MENU_FILE, context); // For offline uses foodDetailsArrayList = JSONParser.ParseMenuItems(jsonArray); ResourceManager.setGlobalFoodMenu(foodDetailsArrayList); // to store all foodMenu serially to inflate in foodMenu adapter ResourceManager.setFoodMenuHashMap(foodDetailsArrayList); // to get item detail using "foodId" return true; }catch (IOException |JSONException |ParseException e){ e.printStackTrace(); } return false; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); listener.onItemAddedOrUpdated(aBoolean); } }<file_sep>/app/src/main/java/com/sujan/info/thespicelounge/WaiterActivity.java package com.sujan.info.thespicelounge; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.Toolbar; import com.sujan.info.thespicelounge.Adapters.FoodMenuAdapter; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.MyPreferences; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.fragments.HomeFragment; import com.sujan.info.thespicelounge.fragments.WaiterOrderListFragment; import com.sujan.info.thespicelounge.interfaceT.orderStatusUpdateListener; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.models.OrderDetail; import java.util.ArrayList; public class WaiterActivity extends BaseActivity implements FoodMenuAdapter.ItemClickListener,orderStatusUpdateListener { FrameLayout displayFoodItemsFrame; FloatingActionButton fab; Toolbar tb=null; boolean doubleBackToExitPressedOnce = false; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_waiter); init(); } @Override public boolean onCreateOptionsMenu(Menu menu) { tb.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { return onOptionsItemSelected(item); } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // action with ID action_refresh was selected case R.id.action_logout: MyPreferences.resetAllPreferences(getApplicationContext()); Utils.activityTransitionRemovingHistory(this,new Intent(this, MainActivity.class)); break; default: break; } return true; } public FloatingActionButton getFab() { return fab; } private void init() { tb = (Toolbar)findViewById(R.id.toolbar_waiter_activity); tb.setTitle(MyPreferences.getStringPrefrences(Constants.EMPLOYEE_NAME_TITLE,this)); tb.inflateMenu(R.menu.toolbar); setActionBar(tb); displayFoodItemsFrame=(FrameLayout) findViewById(R.id.display_food_items_frame); progressBar=(ProgressBar)findViewById(R.id.waiter_activity_progressbar); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().beginTransaction().replace(R.id.display_food_items_frame, new HomeFragment(WaiterActivity.this)).commit(); fab.setVisibility(View.GONE); } }); getSupportFragmentManager().beginTransaction().replace(R.id.display_food_items_frame, new HomeFragment(WaiterActivity.this)).commit(); fab.setVisibility(View.GONE); } public ProgressBar getWaiterProgressBar(){ return progressBar; } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Utils.displayShortToastMessage(this, "Please click BACK again to exit"); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } @Override public void onItemClick(View view, int position) { Intent intent = new Intent(this, FoodOrderActivity.class); intent.putExtra("foodID",ResourceManager.getFoodDetailsInstance().getItemId()); startActivity(intent); // finish(); } public void inflateAdapter(){ getSupportFragmentManager().beginTransaction().replace(R.id.display_food_items_frame, new WaiterOrderListFragment(this)).commit(); ResourceManager.getWaiterActivityInstance().getFab().setVisibility(View.VISIBLE); } @Override public void onAllOrderedListReceiver(ArrayList<OrderDetail> orderDetailArrayList, boolean isSuccess) { progressBar.setVisibility(View.INVISIBLE); if (isSuccess){ ResourceManager.setAllOrders(orderDetailArrayList); inflateAdapter(); }else { Utils.displayShortToastMessage(this,"Try again"); } } @Override public void onOrderStatusUpdated(boolean isSuccessful) { progressBar.setVisibility(View.INVISIBLE); if (isSuccessful){ inflateAdapter(); } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/webservices/DeleteMenuItem.java package com.sujan.info.thespicelounge.webservices; import android.app.Activity; import android.net.Uri; import android.os.AsyncTask; import com.sujan.info.thespicelounge.Utils.AppConstants; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.interfaceT.deleteItemListener; import com.sujan.info.thespicelounge.models.FoodDetails; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; /** * Created by pradeep on 5/8/20. */ public class DeleteMenuItem extends AsyncTask<String,Integer,Boolean> { private ArrayList<FoodDetails> foodDetailsArrayList; deleteItemListener listener; int foodId; Activity context; public DeleteMenuItem(Activity activity,deleteItemListener listener, int foodId) { this.listener = listener; this.foodId = foodId; this.context=activity; } @Override protected Boolean doInBackground(String... strings) { try{ Uri.Builder builder = new Uri.Builder().appendQueryParameter("foodID",foodId+""); URL url=new URL(AppConstants.BASE_ADMIN_URL+AppConstants.DELETE_MENU_ITEM); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); String query = builder.build().getEncodedQuery(); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.connect(); //Send request DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ()); wr.writeBytes (query); wr.flush (); wr.close (); //Get Response InputStream isNew = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(isNew)); String line; StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line); } rd.close(); String s = sb.toString(); JSONArray jsonArray = new JSONArray(s); ResourceManager.writeToFile(s, Constants.MENU_FILE, context); // FOr offline uses foodDetailsArrayList = JSONParser.ParseMenuItems(jsonArray); ResourceManager.setGlobalFoodMenu(foodDetailsArrayList); // to store all foodMenu serially to inflate in foodMenu adapter ResourceManager.setFoodMenuHashMap(foodDetailsArrayList); // to get item detail using "foodId" return true; }catch (IOException |JSONException |ParseException e){ e.printStackTrace(); } return false; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); listener.onMenuItemDeleted(aBoolean); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/interfaceT/feedbackAddedListener.java package com.sujan.info.thespicelounge.interfaceT; import android.widget.ProgressBar; import com.sujan.info.thespicelounge.models.CustomerFeedback; import java.util.ArrayList; /** * Created by pradeep on 4/8/20. */ public interface feedbackAddedListener { public void onFBAddedMessage(boolean isSuccessful); } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/Adapters/OrderedListAdapterWaiter.java package com.sujan.info.thespicelounge.Adapters; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Color; import android.support.annotation.ColorRes; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.WaiterActivity; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.webservices.ChangeOrderStatus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by pradeep on 8/7/20. */ public class OrderedListAdapterWaiter extends RecyclerView.Adapter<OrderedListAdapterWaiter.ViewHolder> { ArrayList<OrderDetail> orderDetailList; WaiterActivity context; private LayoutInflater mInflater; HashMap<Integer,FoodDetails> foodDetailsHashMap; public OrderedListAdapterWaiter(WaiterActivity mContext, ArrayList<OrderDetail> orderDetailsList) { this.mInflater = LayoutInflater.from(mContext); this.context=mContext; this.orderDetailList=orderDetailsList; this.foodDetailsHashMap=ResourceManager.getGlobalFoodMenuMap(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.order_item_recycler_element_waiter, parent, false); return new OrderedListAdapterWaiter.ViewHolder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(ViewHolder holder, int position) { final OrderDetail orderDetail=orderDetailList.get(position); int foodId=orderDetail.getItemId(); FoodDetails foodDetails=foodDetailsHashMap.get(foodId); final int orderStatus=orderDetail.getFoodStatus(); holder.sNo.setText(position+1+""); holder.qty.setText(orderDetail.getQuantity()+""); holder.waiterOrderItem.setText(foodDetails.getFullItemName()); Log.e("HEHEHE",""+foodDetails.getFullItemName()); holder.waiterorderPrice.setText(foodDetails.getPrice()+""); changeColor(orderStatus,holder.waiterFoodStatus); holder.waiterFoodStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(orderStatus==2){ // context.getWaiterProgressBar().setVisibility(View.VISIBLE); new ChangeOrderStatus(context,context,orderDetail.getOrderID(),orderStatus).execute(); } } }); } @SuppressLint("SetTextI18n") private void changeColor(int orderStatus, Button waiterFoodStatus) { switch (orderStatus){ case 0: waiterFoodStatus.setText("waiting"); waiterFoodStatus.setTextColor(Color.parseColor("#4B0082")); break; case 1: waiterFoodStatus.setText("cooking"); waiterFoodStatus.setTextColor(Color.parseColor("#0000FF")); break; case 2: waiterFoodStatus.setText("cooked"); waiterFoodStatus.setTextColor(Color.parseColor("#FF7F00")); waiterFoodStatus.setClickable(true); break; case 3: waiterFoodStatus.setText("served"); waiterFoodStatus.setTextColor(Color.parseColor("#006400")); break; } } @Override public int getItemCount() { return orderDetailList.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ TextView sNo,qty, waiterOrderItem,waiterorderPrice; Button waiterFoodStatus; public ViewHolder(View itemView) { super(itemView); sNo=(TextView)itemView.findViewById(R.id.sNo_waiter); qty=(TextView)itemView.findViewById(R.id.waiter_order_qty); waiterOrderItem=(TextView)itemView.findViewById(R.id.waiter_ordered_item); waiterorderPrice=(TextView)itemView.findViewById(R.id.waiter_order_price); waiterFoodStatus=(Button) itemView.findViewById(R.id.waiter_status_button); } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/webservices/GetOrdersList.java package com.sujan.info.thespicelounge.webservices; import android.os.AsyncTask; import com.sujan.info.thespicelounge.Utils.AppConstants; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.interfaceT.allOrderedListListener; import com.sujan.info.thespicelounge.models.OrderDetail; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; /** * Created by pradeep on 3/8/20. */ public class GetOrdersList extends AsyncTask<String,Integer,Boolean>{ ArrayList<OrderDetail> orderDetailArrayList; allOrderedListListener listener; public GetOrdersList( allOrderedListListener orderedListListener) { this.listener = orderedListListener; } @Override protected Boolean doInBackground(String... strings) { try{ URL url=new URL(AppConstants.BASE_ADMIN_URL+AppConstants.GET_ALL_ORDERS); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); String line; StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line); } String s = sb.toString(); JSONArray jsonArray = new JSONArray(s); orderDetailArrayList = JSONParser.ParseAllOrders(jsonArray); System.out.println("Final Orders===="+jsonArray); System.out.println("Final Orders===="+orderDetailArrayList.size()); return true; }catch (JSONException | IOException e){ e.printStackTrace(); } return false; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); if(aBoolean){ listener.onAllOrderedListReceiver(orderDetailArrayList,true); }else{ listener.onAllOrderedListReceiver(orderDetailArrayList,false); } } // SAMPLE OF RECEIVED JSON /* [ { "orderID": "1", "foodID": "10", "tableNum": "1", "orderStatus": "2", "quantity": "2", "extraRequest": "Make it little spicy" }, { "orderID": "2", "foodID": "7", "tableNum": "2", "orderStatus": "1", "quantity": "3", "extraRequest": "with coke" }, { "orderID": "3", "foodID": "11", "tableNum": "1", "orderStatus": "3", "quantity": "3", "extraRequest": "Bring with tomato ketchup" }, { "orderID": "4", "foodID": "15", "tableNum": "6", "orderStatus": "3", "quantity": "3", "extraRequest": "Make it little crispy" } ]*/ } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/Adapters/FoodMenuAdapter.java package com.sujan.info.thespicelounge.Adapters; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.models.FoodDetails; import java.util.ArrayList; import java.util.List; /** * Created by pradeep on 3/7/20. */ public class FoodMenuAdapter extends RecyclerView.Adapter<FoodMenuAdapter.ViewHolder>{ private ArrayList<FoodDetails> mData; private LayoutInflater mInflater; Context mContext; public Drawable drawable; private ItemClickListener mClickListener; public FoodMenuAdapter(Context context) { this.mInflater = LayoutInflater.from(context); this.mContext=context; this.mData = ResourceManager.getGlobalFoodMenu(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.menu_item_adapter, parent, false); return new ViewHolder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(ViewHolder holder, int position) { FoodDetails foodDetails = mData.get(position); holder.foodImage.setImageResource(foodDetails.getImage()); holder.foodName.setText(ResourceManager.getFoodName(foodDetails)); holder.foodPrice.setText(foodDetails.getPrice()+""); holder.foodTime.setText("Time : "+foodDetails.getPrepareTimeinMins()+" Mins"); holder.foodRating.setNumStars(foodDetails.getRatingStar()); } @Override public int getItemCount() { return mData.size(); } public FoodDetails getItem(int id) { return mData.get(id); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ ImageView foodImage; TextView foodName,foodPrice,foodTime; RatingBar foodRating; public ViewHolder(View itemView) { super(itemView); foodImage = itemView.findViewById(R.id.food_image); foodName = itemView.findViewById(R.id.food_name); foodTime = itemView.findViewById(R.id.food_prepare_time); foodPrice=itemView.findViewById(R.id.food_price); foodRating = itemView.findViewById(R.id.food_rating); drawable = foodRating.getProgressDrawable(); drawable.setColorFilter(Color.parseColor("#F2BA49"), PorterDuff.Mode.SRC_ATOP); itemView.setOnClickListener(this); } @Override public void onClick(View v) { if (Utils.isConnected(mContext)){ ResourceManager.setFoodDetailsInstance(mData.get(getAdapterPosition())); // temporary setup to inflate data if (mClickListener != null) mClickListener.onItemClick(v, getAdapterPosition()); }else{ Utils.displayShortToastMessage(mContext,"No Internet"); } } } // allows clicks events to be caught public void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } // parent activity will implement this method to respond to click events public interface ItemClickListener { void onItemClick(View view, int position); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/Utils/MyPreferences.java package com.sujan.info.thespicelounge.Utils; import android.content.Context; import android.content.SharedPreferences; /** * Created by pradeep on 16/7/20. */ public class MyPreferences { private static String myPrefrences = "THESPICELOUNGE_APP_PREFERENCES"; public static void setStringPrefrences(String key,String value,Context context){ SharedPreferences preferences = context.getSharedPreferences(myPrefrences, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString(key, value); editor.commit(); } public static String getStringPrefrences(String key,Context context){ SharedPreferences preferences = context.getSharedPreferences(myPrefrences, Context.MODE_PRIVATE); return preferences.getString(key, ""); } public static void setBooleanPrefrences(String key,boolean value,Context context){ SharedPreferences preferences = context.getSharedPreferences(myPrefrences, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(key, value); editor.commit(); } public static boolean getBooleanPrefrences(String key,Context context){ SharedPreferences prefrences = context.getSharedPreferences(myPrefrences, Context.MODE_PRIVATE); return prefrences.getBoolean(key, false); } public static void setIntPrefrences(String key,int value,Context context){ SharedPreferences preferences = context.getSharedPreferences(myPrefrences, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt(key, value); editor.commit(); } public static int getIntPrefrences(String key,Context context){ SharedPreferences prefrences = context.getSharedPreferences(myPrefrences, Context.MODE_PRIVATE); return prefrences.getInt(key, -1); } public static void resetAllPreferences(Context mContext) { SharedPreferences preferences = mContext.getSharedPreferences(myPrefrences, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/fragments/Login.java package com.sujan.info.thespicelounge.fragments; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import com.sujan.info.thespicelounge.MainActivity; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.webservices.StaffLogin; /** * A simple {@link Fragment} subclass. */ @SuppressLint("ValidFragment") public class Login extends Fragment { EditText userText,passwordText; Button login; MainActivity context; String userName,userPass; public Login() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_login, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); context= (MainActivity) getActivity(); userText=(EditText)context.findViewById(R.id.input_email); passwordText=(EditText)context.findViewById(R.id.input_password); login=(Button)context.findViewById(R.id.btn_login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utils.isConnected(context)){ userName = userText.getText().toString(); userPass= passwordText.getText().toString(); if(validate(userName,userPass)){ new StaffLogin(context,context,userName,userPass).execute(); context.getProgressBarMain().setVisibility(View.VISIBLE); } }else { Utils.displayShortToastMessage(context,"No Internet."); } } }); } public boolean validate(String userName,String password) { boolean valid = true; if (userName.isEmpty()) { userText.setError("Username field is empty"); valid = false; } else { userText.setError(null); } if (password.isEmpty()) { passwordText.setError("Password Field is empty"); valid = false; } else { passwordText.setError(null); } return valid; } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/interfaceT/orderStatusUpdateListener.java package com.sujan.info.thespicelounge.interfaceT; /** * Created by pradeep on 5/8/20. */ public interface orderStatusUpdateListener { public void onOrderStatusUpdated(boolean isSuccessful); } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/models/MyTasks.java package com.sujan.info.thespicelounge.models; /** * Created by pradeep on 1/8/20. */ public class MyTasks { /* * * 1. make feedback for waiter activity (Done) * 2. Get and display all the food orders for waiter * 2. Get and display all the food orders for Chef except served ones * 2. * 3. * 4. * * * * * * * * ISSUES: * 1. When api is hit to bring feedbacks from orderedListAdapterCust , feedback icon can be click multiple times as progressbar is visible. * * * * * * */ } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/ChefActivity.java package com.sujan.info.thespicelounge; import android.content.Intent; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.Toolbar; import com.sujan.info.thespicelounge.Adapters.OrderedListAdapterChef; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.MyPreferences; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.fragments.WaiterOrderListFragment; import com.sujan.info.thespicelounge.interfaceT.orderStatusUpdateListener; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.webservices.GetOrdersList; import java.util.ArrayList; import java.util.Collections; import static junit.framework.Assert.assertTrue; public class ChefActivity extends BaseActivity implements orderStatusUpdateListener { FloatingActionButton modifyFoodItemFab; RecyclerView chefRecyclerViewOrders; ArrayList<OrderDetail> orderDetailsListChef; OrderedListAdapterChef orderedListAdapterChef; Toolbar tb; ProgressBar progressBarChef; boolean doubleBackToExitPressedOnce = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chef); init(); } @Override public boolean onCreateOptionsMenu(Menu menu) { tb.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { return onOptionsItemSelected(item); } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // action with ID action_refresh was selected case R.id.action_logout: Utils.activityTransitionRemovingHistory(this,new Intent(this, MainActivity.class)); MyPreferences.resetAllPreferences(getApplicationContext()); break; default: break; } return true; } private void init() { tb = (Toolbar) findViewById(R.id.toolbar_chef_activity); tb.setTitle(MyPreferences.getStringPrefrences(Constants.EMPLOYEE_NAME_TITLE,this)); tb.inflateMenu(R.menu.toolbar); setActionBar(tb); orderDetailsListChef=new ArrayList<OrderDetail>(); progressBarChef=(ProgressBar)findViewById(R.id.progress_bar_chef); modifyFoodItemFab=(FloatingActionButton)findViewById(R.id.fab_chef_itemview); chefRecyclerViewOrders=(RecyclerView)findViewById(R.id.ordered_items_recycler_chef); chefRecyclerViewOrders.setLayoutManager(new LinearLayoutManager(this)); modifyFoodItemFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ChefActivity.this, ChefMenuModifyActivity.class); startActivity(intent); finish(); } }); if(ResourceManager.isAllFoodOrdersAvailable()){ inflateAdapter(); }else{ new GetOrdersList(this).execute(); } } public void inflateAdapter(){ orderedListAdapterChef = new OrderedListAdapterChef(this,ResourceManager.getAllOrders()); chefRecyclerViewOrders.setAdapter(orderedListAdapterChef); } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Utils.displayShortToastMessage(this, "Please click BACK again to exit"); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } public ProgressBar getProgressBarChef(){ return progressBarChef; } @Override public void onAllOrderedListReceiver(ArrayList<OrderDetail> orderDetailArrayList, boolean isSuccess) { ResourceManager.setAllOrders(orderDetailArrayList); if (isSuccess){ Collections.sort(ResourceManager.allOrders, OrderDetail.statusComparator); }else { Utils.displayShortToastMessage(this,"Something went wrong.Try again"); } inflateAdapter(); } @Override public void onOrderStatusUpdated(boolean isSuccessful) { progressBarChef.setVisibility(View.INVISIBLE); if (isSuccessful){ inflateAdapter(); }else{ Utils.displayShortToastMessage(this,"Try again"); } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/Adapters/MenuAdapter.java package com.sujan.info.thespicelounge.Adapters; import android.content.Context; import android.support.annotation.NonNull; import android.widget.ArrayAdapter; import android.widget.ImageView; import com.sujan.info.thespicelounge.interfaceT.MenuItemsListener; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.webservices.GetMenuItems; import java.util.ArrayList; /** * Created by pradeep on 2/7/20. */ public class MenuAdapter extends ArrayAdapter<FoodDetails> implements MenuItemsListener { public MenuAdapter(@NonNull Context context, int resource) { super(context, resource); } @Override public void MenuItemsReceived(ArrayList<FoodDetails> foodDetails, boolean fileExists) { // place all the received data here /* if(fileExists){ this.bookings = bookings; if (!showCanceled.isChecked()) { removeCanceled(); } if (bookings.size()==0){ placeHolder.setVisibility(View.VISIBLE); placeHolder.setText(Utils.getLanguageMessage("booking_err")); }else{ placeHolder.setVisibility(View.INVISIBLE); } adapter = new BookingsAdapter(getActivity(), R.layout.booking_list_item, bookings); adapter.setListener(listener); listView.setAdapter(adapter); progressBar.setVisibility(View.INVISIBLE); }else { Utils.displayConnectivityStatus(getContext()); progressBar.setVisibility(View.INVISIBLE); }*/ } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/BaseActivity.java package com.sujan.info.thespicelounge; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.interfaceT.MenuItemsListener; import com.sujan.info.thespicelounge.interfaceT.allOrderedListListener; import com.sujan.info.thespicelounge.interfaceT.cashierCheckoutListener; import com.sujan.info.thespicelounge.interfaceT.menuItemAddUpdateListener; import com.sujan.info.thespicelounge.interfaceT.orderListWithTableListener; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.models.TableInformation; import com.sujan.info.thespicelounge.webservices.GetMenuItems; import com.sujan.info.thespicelounge.webservices.GetOrderListWithTable; import org.json.JSONArray; import java.util.ArrayList; public class BaseActivity extends AppCompatActivity implements MenuItemsListener,allOrderedListListener,orderListWithTableListener,menuItemAddUpdateListener,cashierCheckoutListener { JSONArray jsonArray; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*// Download menuitems from internet only when chef makes changes in menu or when there is no local file that have menu items. if(ResourceManager.isMenuFileExists("MenuItems.obj",this)){ Utils.displayLongToastMessage(this,"This file does exists."); jsonArray=ResourceManager.getFileToJSON("MenuItems.obj",this); }else{ getMenuItems(); }*/ ResourceManager.setBaseActivityInstance(this); } public void runApi(){ } public void getMenuItems() { new GetMenuItems(this,this).execute("Url address here"); } public void getOrderItems(){ new GetOrderListWithTable(this,this).execute("get order items"); } public void getTableInformation(){} @Override public void MenuItemsReceived(ArrayList<FoodDetails> foodDetails, boolean fileExists) { } @Override public void onOrdersForTableReceived( boolean fileExists) { } @Override public void onAllOrderedListReceiver(ArrayList<OrderDetail> orderDetailArrayList, boolean isSuccess) { } @Override public void onItemAddedOrUpdated(boolean isSuccessful) { } @Override public void onCustomerCheckoutSuccessfully(boolean isSuccess) { } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/FoodOrderActivity.java package com.sujan.info.thespicelounge; import android.annotation.SuppressLint; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.MyPreferences; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.interfaceT.feedbackListener; import com.sujan.info.thespicelounge.interfaceT.takeOrderListener; import com.sujan.info.thespicelounge.models.CustomerFeedback; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.webservices.GetCustomerFeedbacks; import com.sujan.info.thespicelounge.webservices.PushFoodOrder; import java.util.ArrayList; public class FoodOrderActivity extends AppCompatActivity implements feedbackListener,takeOrderListener { Button placeOrder,feedbacks; FoodDetails foodDetails; ImageView foodImage; TextView foodName, timePreparation, foodDesc, foodPrice; Spinner tableNumSpinner; CheckBox verifyEntries; int tableNumber; ArrayAdapter<Integer> adapter; boolean isItWaiter=false; ProgressBar receivingFeedbacksPB; boolean feedbackIsNotClickedOnce=true; // to stop user from clicking feedback option multiple times OrderDetail newOrder; int selectedFoodID; EditText foodQuantity,custumerRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_food_order); Intent intent = getIntent(); selectedFoodID= intent.getIntExtra("foodID",0); init(); dataInflate(); } @SuppressLint("SetTextI18n") private void dataInflate() { // foodImage.setImageResource(foodDetails.getImage()); foodImage.setImageResource(R.drawable.momos); foodName.setText(foodDetails.getItemName()); timePreparation.setText(foodDetails.getPrepareTimeinMins()+""); foodDesc.setText(foodDetails.getDescription()); foodPrice.setText(foodDetails.getPrice()+""); feedbacks.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utils.isConnected(FoodOrderActivity.this)){ if(feedbackIsNotClickedOnce){ feedbackIsNotClickedOnce=false; receivingFeedbacksPB.setVisibility(View.VISIBLE); new GetCustomerFeedbacks(FoodOrderActivity.this,foodDetails.getItemId(),receivingFeedbacksPB).execute(); } }else{ Utils.displayShortToastMessage(FoodOrderActivity.this,"No Internet."); } } }); tableNumSpinner.setAdapter(adapter); placeOrder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String orderQuant=foodQuantity.getText().toString(); if(verifyEntries.isChecked() && !orderQuant.equals("")){ tableNumber=Integer.parseInt(tableNumSpinner.getSelectedItem().toString()); String customerRequestStr=custumerRequest.getText().toString(); Log.d("SIZEy","Quantity of orders are: "+orderQuant); // Here orderId and foodStatus doesnot matter since we place "null" and "0" in php file newOrder=new OrderDetail(0,selectedFoodID,tableNumber,Integer.parseInt(orderQuant),0,customerRequestStr); new PushFoodOrder(newOrder,FoodOrderActivity.this).execute(); /*if(MyPreferences.getBooleanPrefrences(Constants.IS_USER_LOGGED_IN,getApplicationContext())){ // Waiter orders from here }else { //Customer orders from here }*/ }else{ Utils.displayLongToastMessage(FoodOrderActivity.this, "Please verify the details "); } } }); } private void init() { isItWaiter=MyPreferences.getBooleanPrefrences(Constants.IS_USER_LOGGED_IN,this); foodDetails= ResourceManager.getFoodDetailsInstance(); adapter = new ArrayAdapter<Integer>(this,R.layout.customized_spinner,ResourceManager.getListOfTableNumber()); foodImage=(ImageView)findViewById(R.id.food_image); foodName=(TextView)findViewById(R.id.order_fullName); foodQuantity=(EditText) findViewById(R.id.order_quantity); timePreparation=(TextView)findViewById(R.id.prepare_time_order); foodDesc=(TextView)findViewById(R.id.desc_order); foodPrice=(TextView)findViewById(R.id.order_price); tableNumSpinner=(Spinner) findViewById(R.id.table_num_spinner_order); custumerRequest=(EditText) findViewById(R.id.customer_request_order); verifyEntries=(CheckBox)findViewById(R.id.verify_order_details); placeOrder=(Button)findViewById(R.id.place_order); feedbacks=(Button)findViewById(R.id.view_item_feedback_customer); receivingFeedbacksPB=(ProgressBar)findViewById(R.id.feedback_pb_placeorder); } @Override public void onBackPressed() { super.onBackPressed(); if(isItWaiter){ Utils.activityTransitionRemovingHistory(this,new Intent(this,WaiterActivity.class)); }else{ Utils.activityTransitionRemovingHistory(this,new Intent(this,MainActivity.class)); } } @Override public void onFeedbackReceived(ArrayList<CustomerFeedback> customerFeedbacks, int foodID, ProgressBar progressBar,boolean isSuccess) { progressBar.setVisibility(View.GONE); feedbackIsNotClickedOnce=true; if(isSuccess){ ResourceManager.setCustomerFeedbackArrayList(customerFeedbacks); Intent intent=new Intent(FoodOrderActivity.this, CustomerFeedbackActivity.class); intent.putExtra("foodID",foodDetails.getItemId()); intent.putExtra("toComment",false); startActivity(intent); }else { Utils.displayShortToastMessage(this,"Try again."); } } @Override public void onOrderReceived(boolean isSuccess) { if(isSuccess){ Utils.displayLongToastMessage(getApplication(),"Your order has been successfully placed for table number "+tableNumber); // if user is logged in go to waiterActivity else go to Home page since it must be customer who placed order. if(isItWaiter){ startActivity(new Intent(FoodOrderActivity.this, WaiterActivity.class)); }else { startActivity(new Intent(FoodOrderActivity.this, MainActivity.class)); ResourceManager.setActiveTableForCurrentCustomer(tableNumber+""); } }else { Utils.displayLongToastMessage(this,"Something went wrong.Please try again "); } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/webservices/GetCustomerFeedbacks.java package com.sujan.info.thespicelounge.webservices; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.view.View; import android.widget.ProgressBar; import com.sujan.info.thespicelounge.MainActivity; import com.sujan.info.thespicelounge.Utils.AppConstants; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.interfaceT.feedbackListener; import com.sujan.info.thespicelounge.models.CustomerFeedback; import com.sujan.info.thespicelounge.models.FoodDetails; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; /** * Created by pradeep on 2/8/20. */ public class GetCustomerFeedbacks extends AsyncTask<String,Integer,Boolean> { feedbackListener fbListener; private ArrayList<CustomerFeedback> customerFeedbacks; int foodID; @SuppressLint("StaticFieldLeak") ProgressBar pb; public GetCustomerFeedbacks(feedbackListener fbListener, int foodId, ProgressBar pb) { this.fbListener = fbListener; this.foodID=foodId; this.pb=pb; } @Override protected Boolean doInBackground(String... strings) { try{ Uri.Builder builder = new Uri.Builder().appendQueryParameter("foodID",foodID+""); URL url=new URL(AppConstants.BASE_ADMIN_URL+AppConstants.GET_CUSTOMER_FEEDBACKS); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); String query = builder.build().getEncodedQuery(); System.out.println("REQUEST PARAMETERS ARE===" + query); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.connect(); //Send request DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ()); wr.writeBytes (query); wr.flush (); wr.close (); //Get Response InputStream isNew = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(isNew)); String line; StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line); } rd.close(); String s = sb.toString(); JSONArray jsonArray = new JSONArray(s); customerFeedbacks=JSONParser.ParseFeedbackItems(jsonArray); System.out.println("Final response===="+jsonArray); return true; }catch (JSONException | IOException | ParseException e){ e.printStackTrace(); pb.setVisibility(View.GONE); fbListener.onFeedbackReceived(customerFeedbacks,foodID,pb,false); } return false; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); fbListener.onFeedbackReceived(customerFeedbacks,foodID,pb,true); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/interfaceT/cashierCheckoutListener.java package com.sujan.info.thespicelounge.interfaceT; /** * Created by pradeep on 5/8/20. */ public interface cashierCheckoutListener { public void onCustomerCheckoutSuccessfully(boolean isSuccess); } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/ChefItemAddAndModifyActivity.java package com.sujan.info.thespicelounge; import android.annotation.SuppressLint; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.webservices.AddUpdateFoodItem; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.sujan.info.thespicelounge.Utils.Constants.PICK_IMAGE; public class ChefItemAddAndModifyActivity extends BaseActivity { Button addModifyItem; ImageView foodImage; boolean isItForItemEdit=false; FoodDetails foodDetailsInstanceForEdit,foodDetailsForUpdate; EditText foodCategoryChef,foodNameChef,foodServeTypeChef,foodPriceChef,foodTimePrepChef,foodDescChef; CheckBox verifyDetails; String foodC,foodN,foodST,foodD,foodP,foodT; int foodImg,foodPri,foodTim; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chef_item_add_and_modify); isItForItemEdit= getIntent().getBooleanExtra("isItForItemEdit",false); init(); } @SuppressLint("SetTextI18n") private void init() { addModifyItem=(Button)findViewById(R.id.push_button_chef_modify); foodImage=(ImageView)findViewById(R.id.food_image_chef_modify); foodImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageSelection(); } }); foodCategoryChef=(EditText)findViewById(R.id.food_catgory_chef_modify); foodNameChef=(EditText)findViewById(R.id.food_name_chef_modify); foodServeTypeChef=(EditText)findViewById(R.id.serve_type_chef_modify); foodPriceChef=(EditText)findViewById(R.id.food_price_chef_modify); foodTimePrepChef=(EditText)findViewById(R.id.food_time_chef_modify); foodDescChef=(EditText)findViewById(R.id.food_desc_chef_modify); verifyDetails=(CheckBox)findViewById(R.id.terms_conditions_chef_modify); verifyDetails.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(areFieldsEmpty()){ verifyDetails.setChecked(false); Utils.displayLongToastMessage(ChefItemAddAndModifyActivity.this,"Please verify the details first."); } } }); if(isItForItemEdit){ foodDetailsInstanceForEdit=ResourceManager.getFoodDetailsInstance(); Utils.displayShortToastMessage(ChefItemAddAndModifyActivity.this,"This item will be edited"); addModifyItem.setText("Modify Item"); foodImage.setImageResource(foodDetailsInstanceForEdit.getImage()); foodCategoryChef.setText(foodDetailsInstanceForEdit.getItemCategory()); foodNameChef.setText(foodDetailsInstanceForEdit.getItemName()); foodServeTypeChef.setText(foodDetailsInstanceForEdit.getServeType()); foodPriceChef.setText(foodDetailsInstanceForEdit.getPrice()+""); foodTimePrepChef.setText(foodDetailsInstanceForEdit.getPrepareTimeinMins()+""); foodDescChef.setText(foodDetailsInstanceForEdit.getDescription()); addModifyItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // tO MODIFY THE MENU ITEM. if (verifyDetails.isChecked()) { ResourceManager.getBaseActivityInstance().getMenuItems(); foodDetailsForUpdate=getFoodObject(foodDetailsInstanceForEdit.getRatingStar(),foodDetailsInstanceForEdit.getItemId()); new AddUpdateFoodItem(ChefItemAddAndModifyActivity.this,ChefItemAddAndModifyActivity.this,foodDetailsForUpdate).execute(); }else{ Utils.displayLongToastMessage(ChefItemAddAndModifyActivity.this,"Please verify the details first."); } } }); }else{ // to ADD A NEW ITEM IN MENU Utils.displayShortToastMessage(ChefItemAddAndModifyActivity.this,"New item will be added here."); addModifyItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (verifyDetails.isChecked()) { foodDetailsForUpdate=getFoodObject(5,0); new AddUpdateFoodItem(ChefItemAddAndModifyActivity.this,ChefItemAddAndModifyActivity.this,foodDetailsForUpdate).execute(); }else{ Utils.displayLongToastMessage(ChefItemAddAndModifyActivity.this,"Please verify the details first."); } } }); } } private boolean areFieldsEmpty() { boolean flag; extractFieldsData(); if (foodC.isEmpty() || foodN.isEmpty() || foodST.isEmpty() || foodD.isEmpty() || foodP.isEmpty()||foodT.isEmpty()){ flag=true; }else{ flag=false; } return flag; } private void extractFieldsData() { try { foodC = foodCategoryChef.getText().toString(); foodN = foodNameChef.getText().toString(); foodST = foodServeTypeChef.getText().toString(); foodD = foodDescChef.getText().toString(); foodT = foodTimePrepChef.getText().toString(); foodP = foodPriceChef.getText().toString(); foodPri = Integer.parseInt(foodP); foodTim = Integer.parseInt(foodT); foodImg = foodImage.getImageAlpha(); }catch (Exception e){ // Exception arises when INT fields doesnot parse empty string "" Utils.displayLongToastMessage(ChefItemAddAndModifyActivity.this,"Please verify the details first."); } } private FoodDetails getFoodObject(int rating,int foodID) { extractFieldsData(); return new FoodDetails(foodC,foodN,foodST,foodD,foodPri,foodImg,foodTim,rating,foodID); } private void imageSelection() { final CharSequence[] options = {"Choose from Gallery","Cancel" }; android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(ChefItemAddAndModifyActivity.this); builder.setTitle("Add Photo!"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if(options[item].equals("Choose from Gallery")) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); } else if (options[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data!=null) { if(requestCode == PICK_IMAGE ){ Uri uri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); Log.d(Constants.TAG, String.valueOf(bitmap)); foodImage.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } }else{ Utils.displayShortToastMessage(this,"Some thing went wrong."); } } @Override public void onItemAddedOrUpdated(boolean isSuccessful) { if(isSuccessful){ if(isItForItemEdit){ Utils.displayShortToastMessage(ChefItemAddAndModifyActivity.this,"Food details are modified sucessfully."); Intent intent = new Intent(ChefItemAddAndModifyActivity.this,ChefActivity.class); startActivity(intent); }else{ Utils.displayShortToastMessage(ChefItemAddAndModifyActivity.this,"New item is added in Menu sucessfully"); Intent intent = new Intent(ChefItemAddAndModifyActivity.this,ChefActivity.class); startActivity(intent); } } } }<file_sep>/README.md # TheSpiceLoungeAndroid application This is a android version of resturant app that was designed for college project. SOurce code for backend / web version is located at [web application](https://github.com/omgitspradeep/TheSpiceLoungeWeb). You are free to use this code for any purpose. Before you implement it in your business make sure to fix backend. Backend could be vunerable to lots of attacks. However, you can always visit the frontend of web app [hosted @ 000webhost](https://thespicelounge.000webhostapp.com/index.php ) [![Documentation Status](https://readthedocs.org/projects/thespiceloungeweb/badge/?version=latest)](https://thespiceloungeweb.readthedocs.io/en/latest/?badge=latest) Also, [Documentation](https://thespiceloungeweb.rtfd.io) is provided for further information. <file_sep>/app/src/androidTest/java/com/sujan/info/thespicelounge/TempTest.java package com.sujan.info.thespicelounge; import static org.junit.Assert.*; /** * Created by pradeep on 19/7/20. */ public class TempTest { }<file_sep>/app/src/main/java/com/sujan/info/thespicelounge/webservices/PushCustomerFeedbacks.java package com.sujan.info.thespicelounge.webservices; import android.net.Uri; import android.os.AsyncTask; import android.view.View; import android.widget.RelativeLayout; import com.sujan.info.thespicelounge.CustomerFeedbackActivity; import com.sujan.info.thespicelounge.Utils.AppConstants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.interfaceT.feedbackAddedListener; import com.sujan.info.thespicelounge.models.CustomerFeedback; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; /** * Created by pradeep on 4/8/20. */ public class PushCustomerFeedbacks extends AsyncTask<String,Integer,Boolean> { CustomerFeedback customerFeedback; feedbackAddedListener mListener; public PushCustomerFeedbacks(feedbackAddedListener listener, CustomerFeedback customerFeedback) { this.customerFeedback = customerFeedback; this.mListener=listener; } @Override protected Boolean doInBackground(String... strings) { try{ Uri.Builder builder = new Uri.Builder() .appendQueryParameter("foodID",customerFeedback.getFoodId()+"") .appendQueryParameter("custName",customerFeedback.getCustName()+"") .appendQueryParameter("feedbackMessage",customerFeedback.getFeedback()+"") .appendQueryParameter("ratingStarCust",customerFeedback.getRatingstar()+""); URL url=new URL(AppConstants.BASE_ADMIN_URL+AppConstants.PUSH_CUSTOMER_FEEDBACKS); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); String query = builder.build().getEncodedQuery(); System.out.println("REQUEST PARAMETERS ARE===" + query); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.connect(); //Send request DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ()); wr.writeBytes (query); wr.flush (); wr.close (); //Get Response InputStream isNew = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(isNew)); String line; StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line); } rd.close(); String s = sb.toString(); System.out.println("FEEDBACK ADDED RESUTLT:"+s); return true; }catch ( IOException e){ e.printStackTrace(); } return false; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); mListener.onFBAddedMessage(aBoolean); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/webservices/ChangeOrderStatus.java package com.sujan.info.thespicelounge.webservices; import android.app.Activity; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import com.sujan.info.thespicelounge.Utils.AppConstants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.interfaceT.cashierCheckoutListener; import com.sujan.info.thespicelounge.interfaceT.orderStatusUpdateListener; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.models.TableInformation; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; /** * Created by pradeep on 5/8/20. */ public class ChangeOrderStatus extends AsyncTask<String,Integer,Boolean> { orderStatusUpdateListener listener; int orderID; int orderStatus; private Activity context; public ChangeOrderStatus(Activity activity,orderStatusUpdateListener listener, int orderID,int orderStat) { this.listener = listener; this.orderID = orderID; // Since status must be incremented per click (0: waiting,1:cooking, 2:cooked, 3:served) this.orderStatus=orderStat+1; this.context=activity; } @Override protected Boolean doInBackground(String... strings) { try{ Log.e("QWERTY",orderID+":"+orderStatus); Uri.Builder builder = new Uri.Builder() .appendQueryParameter("orderID",orderID+"") .appendQueryParameter("orderStatus",orderStatus+""); URL url=new URL(AppConstants.BASE_ADMIN_URL+AppConstants.UPDATE_ORDER_STATUS); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); String query = builder.build().getEncodedQuery(); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.connect(); //Send request DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ()); wr.writeBytes (query); wr.flush (); wr.close (); //Get Response InputStream isNew = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(isNew)); String line; StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line); } rd.close(); String s = sb.toString(); JSONArray jsonArray = new JSONArray(s); Log.e("QWERTY",s); ArrayList<OrderDetail> orderDetailArrayList = JSONParser.ParseAllOrders(jsonArray); ResourceManager.setAllOrders(orderDetailArrayList); return true; }catch (IOException |JSONException e){ e.printStackTrace(); } return false; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); listener.onOrderStatusUpdated(aBoolean); } }<file_sep>/app/src/main/java/com/sujan/info/thespicelounge/interfaceT/orderListWithTableListener.java package com.sujan.info.thespicelounge.interfaceT; import com.sujan.info.thespicelounge.models.TableInformation; import java.util.ArrayList; /** * Created by pradeep on 3/8/20. */ public interface orderListWithTableListener { void onOrdersForTableReceived( boolean fileExists); } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/Adapters/OrderedListAdapterCust.java package com.sujan.info.thespicelounge.Adapters; import android.annotation.SuppressLint; import android.app.Activity; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.models.TableInformation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by pradeep on 3/7/20. */ public class OrderedListAdapterCust extends RecyclerView.Adapter<OrderedListAdapterCust.ViewHolder> { Activity context; private LayoutInflater mInflater; FeedbackClickListener mFeedbackClickListener; HashMap<Integer,TableInformation> tableInformationHashMap; // To get TableInformation with the help of "tableNum" as key TableInformation tableInformation; // TableInformation received from "tableInformationHashMap" ArrayList<OrderDetail> orderDetailArrayList; // List of ordered foods received from "tableInformation" HashMap<Integer,FoodDetails> foodDetailsHashMap; // To get FoodDetails with the help of "foodID " public interface FeedbackClickListener { void onFeedbackClick(View view, int position); } public OrderedListAdapterCust(Activity mContext) { this.mInflater = LayoutInflater.from(mContext); this.context=mContext; tableInformationHashMap=ResourceManager.getGlobalTableInformationMap(); tableInformation=tableInformationHashMap.get(ResourceManager.getSelectedTable()); orderDetailArrayList=tableInformation.getOrderedFoods(); foodDetailsHashMap=ResourceManager.getGlobalFoodMenuMap(); } @Override public OrderedListAdapterCust.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.order_item_recycler_element_cust, parent, false); return new OrderedListAdapterCust.ViewHolder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(OrderedListAdapterCust.ViewHolder holder, int position) { OrderDetail orderDetail=orderDetailArrayList.get(position); int foodID=orderDetail.getItemId(); FoodDetails foodDetails= (FoodDetails) foodDetailsHashMap.get(foodID); holder.custOrderItem.setText(foodDetails.getFullItemName()); holder.orderPrice.setText(foodDetails.getPrice()+""); holder.orderStatus.setText(ResourceManager.getOrderStatus(orderDetail.getFoodStatus())); int orderStatus=orderDetail.getFoodStatus(); holder.qty.setText(orderDetail.getQuantity()+""); if (displayFeedbackButton(orderStatus)){ holder.feedback.setVisibility(View.VISIBLE); holder.feedback.setClickable(true); }else { holder.feedback.setVisibility(View.INVISIBLE); // If food is still waiting user can cancel the order. if(orderStatus==0){ holder.feedback.setVisibility(View.VISIBLE); holder.feedback.setClickable(true); holder.feedback.setImageResource(R.drawable.delete); } } } private boolean displayFeedbackButton(int status) { boolean isServed=false; switch (status){ case 0: isServed= false; break; case 1: isServed= false; break; case 2: isServed= false; break; case 3: isServed= true; break; } return isServed; } @Override public int getItemCount() { return orderDetailArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ TextView qty, custOrderItem,orderStatus,orderPrice; ImageButton feedback; public ViewHolder(View itemView) { super(itemView); qty=(TextView)itemView.findViewById(R.id.qty); custOrderItem=(TextView)itemView.findViewById(R.id.cust_ordered_item); orderStatus=(TextView)itemView.findViewById(R.id.cust_order_status); orderPrice=(TextView)itemView.findViewById(R.id.cust_order_price); feedback=(ImageButton) itemView.findViewById(R.id.customer_feedback_button); feedback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utils.isConnected(context)){ if (mFeedbackClickListener != null) mFeedbackClickListener.onFeedbackClick(v, getAdapterPosition()); } } }); } @Override public void onClick(View v) { } } public void setFeedbackClickListener(FeedbackClickListener feedbackClickListener) { this.mFeedbackClickListener = feedbackClickListener; } public OrderDetail getItem(int id) { return orderDetailArrayList.get(id); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/interfaceT/deleteItemListener.java package com.sujan.info.thespicelounge.interfaceT; /** * Created by pradeep on 5/8/20. */ public interface deleteItemListener { public void onMenuItemDeleted(boolean isSuccessful); } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/webservices/PushFoodOrder.java package com.sujan.info.thespicelounge.webservices; import android.net.Uri; import android.os.AsyncTask; import android.view.View; import com.sujan.info.thespicelounge.Utils.AppConstants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.interfaceT.takeOrderListener; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.models.TableInformation; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; /** * Created by pradeep on 4/8/20. */ public class PushFoodOrder extends AsyncTask<String,Integer,Boolean> { private ArrayList<TableInformation> tableInformationArrayList; OrderDetail orderDetail; takeOrderListener listener; public PushFoodOrder(OrderDetail orderDetail,takeOrderListener mListener) { this.orderDetail = orderDetail; this.listener=mListener; } @Override protected Boolean doInBackground(String... strings) { try{ String foodID=orderDetail.getItemId()+""; String tableNum=orderDetail.getTableNum()+""; String quantity=orderDetail.getQuantity()+""; String custRequest=orderDetail.getCustRequest()+""; System.out.println("REQUEST PARAMETERS ARE===" + foodID+" "+tableNum+" "+quantity+" "+custRequest); Uri.Builder builder = new Uri.Builder().appendQueryParameter("foodID",foodID) .appendQueryParameter("tableNum",tableNum) .appendQueryParameter("quantity",quantity) .appendQueryParameter("extraRequest",custRequest); URL url=new URL(AppConstants.BASE_ADMIN_URL+AppConstants.PUSH_CUSTOMER_ORDER); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); String query = builder.build().getEncodedQuery(); System.out.println("REQUEST PARAMETERS ARE===" + query); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.connect(); //Send request DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ()); wr.writeBytes (query); wr.flush (); wr.close (); //Get Response InputStream isNew = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(isNew)); String line; StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line); } rd.close(); String s = sb.toString(); System.out.println("FEEDBACK ADDED RESUTLT:"+s); JSONArray jsonArray = new JSONArray(s); System.out.println("TESTING 2:"+jsonArray); // List of orders for each table is received here. tableInformationArrayList=JSONParser.ParseOrderItemsForTable(jsonArray); // It is set as global since customer have to see updated orders for his table. ResourceManager.setGlobalTableInfoArraylist(tableInformationArrayList); return true; }catch (IOException |JSONException |ParseException e){ e.printStackTrace(); } return false; } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); listener.onOrderReceived(aBoolean); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/fragments/HomeFragment.java package com.sujan.info.thespicelounge.fragments; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.media.Image; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.sujan.info.thespicelounge.Adapters.FoodMenuAdapter; import com.sujan.info.thespicelounge.Adapters.TableSelectionDialogAdapter; import com.sujan.info.thespicelounge.FoodOrderActivity; import com.sujan.info.thespicelounge.MainActivity; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.MyPreferences; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.WaiterActivity; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.webservices.GetOrdersList; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ @SuppressLint("ValidFragment") public class HomeFragment extends Fragment { MainActivity mainActivityInstance; WaiterActivity waiterActivityInstance; Activity activity; RecyclerView recyclerView; FloatingActionButton fab; FoodMenuAdapter menuFoodAdapter; boolean isItWaiter=false; @SuppressLint("ValidFragment") public HomeFragment(MainActivity mContext) { // Required empty public constructor mainActivityInstance=mContext; activity=mContext; } public HomeFragment(WaiterActivity waiterActivityInstance) { this.waiterActivityInstance = waiterActivityInstance; activity=waiterActivityInstance; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_home, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(); } private void init() { isItWaiter=MyPreferences.getBooleanPrefrences(Constants.IS_USER_LOGGED_IN,activity); //This fragment is used in both waiter and customer menu list. if(isItWaiter){ fab = (FloatingActionButton)waiterActivityInstance.findViewById(R.id.fab_order_view); recyclerView=(RecyclerView)waiterActivityInstance.findViewById(R.id.food_menu_recycler); recyclerView.setLayoutManager(new LinearLayoutManager(waiterActivityInstance)); menuFoodAdapter = new FoodMenuAdapter(waiterActivityInstance); recyclerView.setAdapter(menuFoodAdapter); menuFoodAdapter.setClickListener(waiterActivityInstance); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // GET ORDERS LIST if(Utils.isConnected(activity)){ waiterActivityInstance.getWaiterProgressBar().setVisibility(View.VISIBLE); new GetOrdersList(waiterActivityInstance).execute(); ResourceManager.setWaiterActivityInstance(waiterActivityInstance); }else{ Utils.displayShortToastMessage(activity,"No Internet."); } } }); }else { fab = (FloatingActionButton)mainActivityInstance.findViewById(R.id.fab_order_view); recyclerView=(RecyclerView)mainActivityInstance.findViewById(R.id.food_menu_recycler); recyclerView.setLayoutManager(new LinearLayoutManager(mainActivityInstance)); menuFoodAdapter = new FoodMenuAdapter(mainActivityInstance); recyclerView.setAdapter(menuFoodAdapter); menuFoodAdapter.setClickListener(mainActivityInstance); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(Utils.isConnected(mainActivityInstance)){ if(ResourceManager.listOfBusyTables!=null){ Utils.buildAskTableDialog(mainActivityInstance); }else { Utils.displayShortToastMessage(mainActivityInstance,"You have not order your food yet."); } } else{ Utils.displayShortToastMessage(mainActivityInstance,"No Internet"); } } }); } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/interfaceT/loginListener.java package com.sujan.info.thespicelounge.interfaceT; public interface loginListener { public void onLoginResponse(boolean isSuccess); } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/Adapters/FeedbackListAdapter.java package com.sujan.info.thespicelounge.Adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RatingBar; import android.widget.TextView; import com.sujan.info.thespicelounge.CustomerFeedbackActivity; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.models.CustomerFeedback; import java.util.ArrayList; /** * Created by pradeep on 6/7/20. */ public class FeedbackListAdapter extends RecyclerView.Adapter<FeedbackListAdapter.ViewHolder> { private LayoutInflater mInflater; ArrayList<CustomerFeedback> mCustomerFeedbackList; CustomerFeedbackActivity mContext; public FeedbackListAdapter(ArrayList<CustomerFeedback> customerFeedbackList, CustomerFeedbackActivity context) { this.mContext=context; this.mInflater = LayoutInflater.from(context); this.mCustomerFeedbackList=customerFeedbackList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.adapter_feedback_recycler, parent, false); return new FeedbackListAdapter.ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.feedback.setText(mCustomerFeedbackList.get(position).getFeedback()); holder.name.setText(mCustomerFeedbackList.get(position).getCustName()); holder.rating.setNumStars(mCustomerFeedbackList.get(position).getRatingstar()); } @Override public int getItemCount() { return mCustomerFeedbackList.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ TextView feedback,name; RatingBar rating; public ViewHolder(View itemView) { super(itemView); feedback=(TextView)itemView.findViewById(R.id.feedback_desc); name=(TextView)itemView.findViewById(R.id.customer_name); rating=(RatingBar) itemView.findViewById(R.id.customer_rating_bar_); } @Override public void onClick(View v) { } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/fragments/WaiterOrderListFragment.java package com.sujan.info.thespicelounge.fragments; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.sujan.info.thespicelounge.Adapters.OrderedListAdapterWaiter; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.WaiterActivity; /** * Created by pradeep on 8/7/20. */ @SuppressLint("ValidFragment") public class WaiterOrderListFragment extends android.support.v4.app.Fragment { WaiterActivity mContext; OrderedListAdapterWaiter orderedListAdapter; RecyclerView customerOrderRecyclerView; public WaiterOrderListFragment(WaiterActivity waiterActivity) { this.mContext=waiterActivity; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.waiter_frag_order_list, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(); } private void init() { customerOrderRecyclerView= (RecyclerView)mContext.findViewById(R.id.waiter_orders_list_recycler); customerOrderRecyclerView.setLayoutManager(new LinearLayoutManager(mContext)); orderedListAdapter = new OrderedListAdapterWaiter(mContext,ResourceManager.getAllOrders()); customerOrderRecyclerView.setAdapter(orderedListAdapter); } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/MainActivity.java package com.sujan.info.thespicelounge; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.ProgressBar; import com.sujan.info.thespicelounge.Adapters.FoodMenuAdapter; import com.sujan.info.thespicelounge.Utils.Constants; import com.sujan.info.thespicelounge.Utils.JSONParser; import com.sujan.info.thespicelounge.Utils.MyPreferences; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.fragments.AboutUs; import com.sujan.info.thespicelounge.fragments.CustomerOrderdListFragment; import com.sujan.info.thespicelounge.fragments.Entertainment; import com.sujan.info.thespicelounge.fragments.HomeFragment; import com.sujan.info.thespicelounge.fragments.Login; import com.sujan.info.thespicelounge.interfaceT.cancelFoodListener; import com.sujan.info.thespicelounge.interfaceT.feedbackListener; import com.sujan.info.thespicelounge.interfaceT.loginListener; import com.sujan.info.thespicelounge.models.CustomerFeedback; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.webservices.GetMenuItems; import org.json.JSONArray; import org.json.JSONException; import java.text.ParseException; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements FoodMenuAdapter.ItemClickListener,feedbackListener,cancelFoodListener, loginListener { BottomNavigationView navigation; FrameLayout frameLayout; boolean doubleBackToExitPressedOnce = false; ProgressBar progressBarMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { frameLayout=(FrameLayout)findViewById(R.id.fl_fragment); progressBarMain=(ProgressBar)findViewById(R.id.main_activity_progressbar); navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); getSupportFragmentManager().beginTransaction().replace(R.id.fl_fragment, new HomeFragment(this)).commit(); } private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: getSupportFragmentManager().beginTransaction().replace(R.id.fl_fragment,new HomeFragment(MainActivity.this)).commit(); break; case R.id.entertainment: getSupportFragmentManager().beginTransaction().replace(R.id.fl_fragment,new Entertainment()).commit(); break; case R.id.login: getSupportFragmentManager().beginTransaction().replace(R.id.fl_fragment,new Login()).commit(); break; case R.id.about_us: getSupportFragmentManager().beginTransaction().replace(R.id.fl_fragment,new AboutUs()).commit(); break; } return true; } }; public ProgressBar getProgressBarMain(){ return progressBarMain; } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Utils.displayShortToastMessage(this, "Please click BACK again to exit"); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } @Override public void onItemClick(View view, int position) { Intent intent = new Intent(this, FoodOrderActivity.class); intent.putExtra("foodID",ResourceManager.getFoodDetailsInstance().getItemId()); startActivity(intent); } @Override public void onFeedbackReceived(ArrayList<CustomerFeedback> customerFeedbacks, int foodID, ProgressBar progressBar,boolean isSuccess) { progressBar.setVisibility(View.GONE); if(isSuccess){ ResourceManager.setCustomerFeedbackArrayList(customerFeedbacks); // Once feebacks are received "CustomerFeedbackActivity" is proceed Intent intent = new Intent(this, CustomerFeedbackActivity.class); intent.putExtra("toComment", true); intent.putExtra("foodID",foodID); startActivity(intent); }else{ Utils.displayShortToastMessage(this,"Try again."); } } @Override public void onFoodCancelled(boolean isSuccess) { progressBarMain.setVisibility(View.INVISIBLE); Utils.displayLongToastMessage(this,"Food order is cancelled successfully."); getSupportFragmentManager().beginTransaction().replace(R.id.fl_fragment,new CustomerOrderdListFragment(this)).commit(); } @Override public void onLoginResponse(boolean isSuccess) { progressBarMain.setVisibility(View.INVISIBLE); if (isSuccess){ String staffPost=ResourceManager.getLoggedStaff().getPost(); MyPreferences.setBooleanPrefrences(Constants.IS_USER_LOGGED_IN,true,this); if(staffPost.equals("manager") ){ //login for admin or manager : It is supposed to be redirect to webview, MyPreferences.setIntPrefrences(Constants.LAST_LOGGED_USER,Constants.ADMIN_ID,this); Utils.activityTransitionRemovingHistory(this, new Intent(this, AdminActivity.class)); }else if(staffPost.equals("chef")){ //login for chef, MyPreferences.setIntPrefrences(Constants.LAST_LOGGED_USER,Constants.CHEF_ID,this); Utils.activityTransitionRemovingHistory(this, new Intent(this, ChefActivity.class)); }else if(staffPost.equals("waiter")){ //login for waiter MyPreferences.setIntPrefrences(Constants.LAST_LOGGED_USER,Constants.WAITER_ID,this); Utils.activityTransitionRemovingHistory(this, new Intent(this, WaiterActivity.class)); }else if(staffPost.equals("cashier")) { //login for cashier /*When user opens app without Internet then only foodmenu list is available as saved data but not food orders with table As cashier logs in and internet is available then app crashes since there is no data about tables. Therefore, we need to bring table data.*/ if (ResourceManager.isFoodOrdersWithTableDataAvailable()) { //login for cashier MyPreferences.setIntPrefrences(Constants.LAST_LOGGED_USER,Constants.CASHIER_ID,this); Utils.activityTransitionRemovingHistory(this, new Intent(this, CashierActivity.class)); } else { Utils.displayShortToastMessage(this, "Please restart app once again."); } } }else{ Utils.displayShortToastMessage(this, "You have entered wrong credentials."); } } } <file_sep>/app/src/main/java/com/sujan/info/thespicelounge/fragments/CustomerOrderdListFragment.java package com.sujan.info.thespicelounge.fragments; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.sujan.info.thespicelounge.Adapters.OrderedListAdapterCust; import com.sujan.info.thespicelounge.CustomerFeedbackActivity; import com.sujan.info.thespicelounge.MainActivity; import com.sujan.info.thespicelounge.R; import com.sujan.info.thespicelounge.Utils.ResourceManager; import com.sujan.info.thespicelounge.Utils.Utils; import com.sujan.info.thespicelounge.interfaceT.feedbackListener; import com.sujan.info.thespicelounge.models.FoodDetails; import com.sujan.info.thespicelounge.models.OrderDetail; import com.sujan.info.thespicelounge.webservices.GetCustomerFeedbacks; /** * A simple {@link Fragment} subclass. */ @SuppressLint("ValidFragment") public class CustomerOrderdListFragment extends Fragment implements OrderedListAdapterCust.FeedbackClickListener{ MainActivity mContext; OrderedListAdapterCust orderedListAdapter; RecyclerView customerOrderRecyclerView; feedbackListener feedbackListener; ProgressBar progressBarFeedbacks; public CustomerOrderdListFragment(MainActivity context) { // Required empty public constructor mContext=context; feedbackListener=context; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.ordered_item_list_of_customer, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(); } private void init() { progressBarFeedbacks=(ProgressBar)mContext.findViewById(R.id.progressBarFeedbacks); customerOrderRecyclerView= (RecyclerView)mContext.findViewById(R.id.customer_orders_list_recycler); customerOrderRecyclerView.setLayoutManager(new LinearLayoutManager(mContext)); orderedListAdapter = new OrderedListAdapterCust(mContext); orderedListAdapter.setFeedbackClickListener(this); customerOrderRecyclerView.setAdapter(orderedListAdapter); } @Override public void onFeedbackClick(View view, int position) { OrderDetail orderDetail=orderedListAdapter.getItem(position); if(orderDetail.getFoodStatus()==0){ Utils.showAlertDialogBeforeCancelOrder(mContext,mContext,orderDetail.getTableNum(),orderDetail.getOrderID()); }else { // Run api to get feedbacks progressBarFeedbacks.setVisibility(View.VISIBLE); new GetCustomerFeedbacks(mContext,orderedListAdapter.getItem(position).getItemId(),progressBarFeedbacks).execute(); } } }
ed6ce31bcc9a4adfdca6f358e735f847def25595
[ "Markdown", "Java" ]
34
Java
omgitspradeep/TheSpiceLounge
01dc5c46ce369337ca0e935dfeb5b57050500694
fc00de9098d90564116daa01a5369ee93446b6f8
refs/heads/master
<repo_name>gezi666/tableDesigner<file_sep>/README.md # tableDesign 表单设计器 ## 基于Vue开发的可视化拖拽表单设计器 <file_sep>/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { canSelect: true, currentID: "", selectCompList: [], screenProps: { width: 1920, height: 1080, bkcolor: "#fff" } }, getters: { curComp(state) { let currentID = state.currentID; if (currentID) { let currentComp = state.selectCompList.filter(item => { return item.uid === currentID })[0] return currentComp; } return {} }, curStyle(state) { let currentID = state.currentID; if (currentID) { let currentComp = state.selectCompList.filter(item => { return item.uid === currentID })[0] return currentComp.info.style; } return {} } }, mutations: { changeSelectFlag(state, payload) { state.canSelect = payload }, addComp(state, payload) { state.selectCompList.push(payload) state.currentID = payload.uid }, setSelect(state, payload) { state.currentID = payload }, changeStyle(state, payload) { let newStyle = {} for (let item of state.selectCompList) { if (item.uid === state.currentID) { newStyle = { ...item.info.style, ...payload } item.info.style = Object.assign({}, newStyle) break } } }, changeScreenProp(state, payload) { state.screenProps = Object.assign(state.screenProps, payload) } } }) export default store<file_sep>/src/widgets/mix.js export default { name: "TextComp", props: { info: { type: Object, default() { return {}; } } }, computed: { style() { return this.info.style } }, methods: { selectComp() { this.$emit("selectComp"); } } };<file_sep>/vue.config.js // 详细配置参数请参考:https://cli.vuejs.org/zh/config/#%E5%85%A8%E5%B1%80-cli-%E9%85%8D%E7%BD%AE const webpack = require('webpack') const path = require('path') function resolve(dir) { return path.join(__dirname, './', dir) } // 请求后台地址 let api_url = "" // 动态获取命令行服务器地址 try { let url = JSON.parse(process.env.npm_config_argv).remain[0] api_url = url ? url : "" } catch (e) { api_url = "" console.log("获取process参数异常") } module.exports = { publicPath: "./", devServer: { // easymock模拟接口 proxy: 'http://10.10.50.190:7300/mock/5cbeb362abf86b3bdc64f106/example' }, productionSourceMap: false, // webpack相关 configureWebpack: config => { // 定义全局API请求地址 config.plugins.push( new webpack.DefinePlugin({ API_URL: JSON.stringify(api_url) }) ) config.resolve = Object.assign(config.resolve, { alias: { 'vue$': 'vue/dist/vue.runtime.esm.js', '@': resolve('src'), '@components': resolve('src/components'), '@widgets': resolve('src/widgets'), '@assets': resolve('src/assets'), '@api': resolve('src/api'), '@utils': resolve('src/utils') } }) if (process.env.NODE_ENV === 'production') { // 为生产环境修改配置... config.optimization.splitChunks = { chunks: 'all', maxInitialRequests: 5, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/](echarts|element-ui)[\\/]/, name(module) { const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1] return `vendors~${packageName.replace('@', '')}` } } } } } else { // 为开发环境修改配置... } } }
e0544e19f99fb7dcb8ebf2bf16198dbf72fea714
[ "Markdown", "JavaScript" ]
4
Markdown
gezi666/tableDesigner
ff3003acc3afbfa3956063a7bb27a7f546015432
28feed66ad3239ecf0c57be80620243309810eea
refs/heads/master
<file_sep>// // ImageURLView.swift // CryptoWorkshop // // Created by <NAME> on 8/31/18. // Copyright © 2018 TanookiLabs. All rights reserved. // import UIKit class ImageURLView: UIView { let imageUrl: URL let imageView: UIImageView let errorLabel: UILabel let activityIndicator: UIActivityIndicatorView private var task: URLSessionTask? // MARK: - Life Cycle init(imageUrl: URL, frame: CGRect = CGRect(x: 0, y: 0, width: 200, height: 200)) { self.imageUrl = imageUrl self.imageView = UIImageView(frame: .zero) self.errorLabel = UILabel(frame: .zero) self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initialize() { setupLayout() loadImage() } // MARK: - Configuration private func setupLayout() { imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false addSubview(imageView) errorLabel.numberOfLines = 1 errorLabel.font = UIFont.systemFont(ofSize: 10) errorLabel.textAlignment = .center errorLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(errorLabel) activityIndicator.translatesAutoresizingMaskIntoConstraints = false addSubview(activityIndicator) imageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true errorLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true errorLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: 10).isActive = true errorLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true heightAnchor.constraint(equalToConstant: 200).isActive = true setNeedsDisplay() layoutIfNeeded() } private func loadImage() { showSpinner() setError(message: "") let session = URLSession.shared let imageUrl = self.imageUrl.pathExtension == "svg" ? ZippySVG(imageUrl: self.imageUrl) : self.imageUrl task = session.dataTask(with: imageUrl, completionHandler: { [weak self] (data, response, error) in guard let `self` = self else { return } defer { self.hideSpinner() } if let error = error { self.setError(message: error.localizedDescription) return } if let response = response as? HTTPURLResponse, response.statusCode != 200 { self.setError(message: "Server response: \(response.statusCode)") return } if let data = data, let image = UIImage(data: data) { self.setImage(image) } else { self.setError(message: "Unable to decode image") } }) task?.resume() } // MARK: - UI Actions private func setError(message: String) { DispatchQueue.main.async { self.errorLabel.text = message } } private func setImage(_ image: UIImage) { DispatchQueue.main.async { self.imageView.image = image } } private func showSpinner() { DispatchQueue.main.async { self.activityIndicator.startAnimating() self.activityIndicator.isHidden = false } } private func hideSpinner() { DispatchQueue.main.async { self.activityIndicator.stopAnimating() self.activityIndicator.isHidden = true } } } // MARK: - ZippySVG fileprivate func ZippySVG(imageUrl: URL) -> URL { let baseURL = URL(string: "https://zippy-svg.herokuapp.com/svg")! var zippyURL = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)! zippyURL.queryItems = [URLQueryItem(name: "url", value: imageUrl.absoluteString)] return zippyURL.url! } <file_sep># Cryptocurrency Workshop @ try! Swift Materials for the Cryptocurrency Workshop at the [2018 try! Swift NYC](https://www.tryswift.co/events/2018/nyc/) conference. ## Getting started Please download this repository to get started: ``` git clone https://github.com/mseijas/crypto-workshop.git ``` ## Notes The completed version of the project can be found on the `final` branch <file_sep>// // TokenMetadata.swift // CryptoWorkshop // // Created by <NAME> on 8/31/18. // Copyright © 2018 TanookiLabs. All rights reserved. // import Foundation struct TokenMetada: Codable { let name: String let description: String let image: String } <file_sep>platform :ios, '11.4' inhibit_all_warnings! target 'CryptoWorkshop' do use_frameworks! # Pods for CryptoWorkshop pod 'web3swift' end <file_sep>// // ViewController.swift // CryptoWorkshop // // Created by <NAME> on 8/31/18. // Copyright © 2018 TanookiLabs. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var assetCountLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! let tokenMetadataProvider = TokenMetadaProvider() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let web3 = setupWeb3() // CryptoStrikers contract // Ethreum user account // Populate count label // Get Token metadata for each token // Render UI activityIndicator.stopAnimating() } // 1. Setup Ethereum node + web3 object func setupWeb3() -> web3 { } // 2. Setup contract with ABI func setupContract(with web3: web3, address: EthereumAddress) -> web3.web3contract { } // 3. Interact with the contract // 3a. Get token balance for an account func tokenBalance(for account: EthereumAddress, on contract: web3.web3contract) -> Int { } // 3b. Get token id by index func tokenId(for account: EthereumAddress, index: Int, on contract: web3.web3contract) -> Int { } // 3c. Get token metadata url by id func tokenMetadataURL(id: Int, on contract: web3.web3contract) -> URL { } } <file_sep>// // TokenMetadataProvider.swift // CryptoWorkshop // // Created by <NAME> on 8/31/18. // Copyright © 2018 TanookiLabs. All rights reserved. // import Foundation class TokenMetadaProvider { func getMetadata(with url: URL) -> TokenMetada? { let session = URLSession.shared let semaphore = DispatchSemaphore(value: 0) var tokenMetadata: TokenMetada? let task = session.dataTask(with: url) { (data, response, error) in if let error = error { print("Error: \(error)") tokenMetadata = nil } if let response = response as? HTTPURLResponse, response.statusCode != 200 { print("Error: Server responded with \(response.statusCode)") tokenMetadata = nil } let decoder = JSONDecoder() if let data = data { do { let response = try decoder.decode(TokenMetada.self, from: data) tokenMetadata = response } catch { print("Error: \(error.localizedDescription)") } } else { print("Error: JSON parsing error") tokenMetadata = nil } semaphore.signal() } task.resume() _ = semaphore.wait(timeout: DispatchTime.distantFuture) return tokenMetadata } }
bc5dad44f31cd27088b5469de97098d3da2fe0a7
[ "Swift", "Ruby", "Markdown" ]
6
Swift
mseijas/crypto-workshop
651d1bf85563ff25b81be83855f91824de518c91
64917136d626190182c74ddd9b4a9c139400da39
refs/heads/master
<file_sep># Map Marker Map Marker is a Laravel-based webapp which maps and displays the location of an incoming request in real-time. It's using Google Maps for the map library and has dropdown option to display coordinates in the last X hours (pre-defined). It requires the user to allow location permission on the browser. # Steps to run ### 1. Clone the repository ``` git clone https://github.com/robi-ng/map-marker.git ``` ### 2. Ensure that you have PHP, MySQL, and composer installed locally Tested on `PHP 7.1.23` and `MySQL 5.7.25`. ### 3. Run composer to install dependencies ``` cd map-marker composer install ``` ### 4. Copy .env.example into .env file ``` cp .env.example .env ``` ### 5. Generate app key ``` php artisan key:generate ``` ### 6. Fill in your local database details in .env file ``` DB_CONNECTION=mysql DB_HOST= DB_PORT= DB_DATABASE= DB_USERNAME= DB_PASSWORD= DB_SOCKET= ``` ### 7. Migrate database to create the defined table ``` php artisan migrate ``` ### 8. Fill in Google Map API key in .env file ``` GOOGLE_MAP_API_KEY= ``` ### 9. Run Laravel app ``` php artisan serve ``` ### 10. Load the app on browser Open http://localhost:8000 on browser and the app should load. <file_sep><?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 App\Models\Coordinate; use Illuminate\Http\Request; use Log; use Carbon\Carbon; class CoordinatesController extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function index(Request $request) { $minimumDateTime = Carbon::now()->setTimezone('Asia/Singapore')->subHour($request->filter); $coordinates = Coordinate::where('created_at', '>=', $minimumDateTime)->get(); return response()->json($coordinates); } public function store(Request $request) { Coordinate::firstOrCreate([ 'latitude' => round($request->latitude, 2), 'longitude' => round($request->longitude, 2) ]); return response()->json(['status' => 'OK']); } }
4059d6fdcfb6c120db8ac5e7ab2af67732a8ae4d
[ "Markdown", "PHP" ]
2
Markdown
robi-ng/map-marker
0b1157a702886fb5079adf329a5353720376feb5
0cafc82bb62b1750dee86ea420f078d0f5d214d3
refs/heads/master
<file_sep><h1>Week 1 Scrum Report</h1> <h2><NAME></h2> ### Finished Last Week - Task 1: Picked a Core XP value - Courage - Task 2: Decided on project - First commit of initial code and modified Readme ### Planned Next Week - Refactor into patterns - Create 2 user stories - Create UI Wireframes with team ### Problems - Due to exams and different schedules, we didn't get to meet until Friday this week ### Time Spend - Task1: 1 hrs - Task2: 3 hrs - decided during chatting and meeting - Task 3: 2 hours ### XP Core Value I was given courage. I made sure that we all give correct information regarding progress and estimates. I also made sure that we adapt our processes as needed and that we should not be afraid to speak up when needed. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Looked at several games online since our team decided for game option - Researched typical patterns used in games - Participated in wireframes and design of the game. ### Planned Next Week - Implementing initial framework for the world. - Technical story for a design pattern. Factory Pattern. Create lady bug and different types of lettuce (green and red). - Will be working on initial grounding work of observer pattern for Turtle kill. ### Problems - Problems hooking up with team. ### Time Spent - Task1: 5 hrs - Task2: 5 hrs ### XP Core Value I was given respect. I made sure this week that every teammember should be respectful to eachother by reminding them about this important aspect. It is one of the core values in XP. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Read Greenfoot Documentation and some code examples - Researched game ideas ### Planned Next Week - Technical story for a design pattern. Strategy Pattern for Game Level Difficulty (Low, Medium, High) - Write Story about a feature in the game - How to pick the game level and how to define it based on # of snakes and speed of snakes. - Technical story for a design pattern. Observer Pattern for snake count. - Write Story about a feature in the game. On every kill of snake, update snakes count so we can create more snakes. ### Problems - We had problems in finding a time to meet this week ### Time Spent - Task1: 5 hrs - Task2: 5 hrs ### XP Core Value As a team member responsible for feedback I have made sure that I give timely and correct feedback to my teammates about their ideas and implementation approaches. I also encourage my teammates to give feedback regularly amongst us. <h2></h2> <h2>Megha</h2> ### Finished Last Week - Googled online for game ideas - We decided on Greenfoot so I re-read the documentation ### Planned Next Week - Write technical story for a design pattern. Decorator Pattern (Decorate gun) - Write story about a feature in the game. When the turtle eats Lettuce or bug increment the points on Counter ### Problems - Due to exams and different schedules, we didn't get to meet until Friday this week ### Time Spent - Task1: 5 hrs - Task2: 5 hrs ### Core Value I picked simplicity and I have made sure that we only work on what is important and needed. I ensure that the team is creating just the basic functions first. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Task 1: Researched ideas for project - Task 2: Looked at Greenfoot examples ### Planned Next Week - Technical story for composite design pattern (Turtle and shield) - Story about a feature in the game. The shield given to turtle and what happens when snake hits the shield - Create and code the story when turtle dies (game over) ### Problems - We had some challenges finding time to meet this week ### Time Spent - Task1: 6 hrs - Task2: 4 hrs ### Core Value My responsibility is communication. I have ensured that the flow of communication is going well and the team is getting to know eachother and feel comfortable. We have also gotten to know about what each of us are good at.<file_sep>public class RedLettuceObserver implements IEatObserver { public RedLettuceObserver() { } public void invoke(String className) { System.out.println("In red lettuce observer"); if (RedLettuce.class.getName().equalsIgnoreCase(className)) { Turtle turtle = Turtle.getTurtle(); Shield shield = Turtle.getShield(); System.out.println("In red lettuce"); ShieldBoostDecorator booster = new ShieldBoostDecorator(shield); booster.attach(new ShotObserver()); shield.setDecorator(booster); } } } <file_sep>import greenfoot.*; public interface IEatSubject { void attach (IEatObserver obj); void removeObserver (IEatObserver obj); void notifyObservers(String clss); } <file_sep> public interface IScoreObserver { void scoreAction(int score); } <file_sep>public interface IShotObserver { void invoke(); }<file_sep><h1>Week 3 Scrum Report</h1> <h2><NAME></h2> ### Finished Last Week - Task 1: I finished coding the feature of advancing to next level - Task 2: I also finished that the lady bug will appear at random when turtle eats the lady bug - Task 3: Finetuned my wireframes, created draft class diagram, use case diagram, activity diagram, and sequence diagram for my features. - Task 4: Created initial ad video ### Planned Next Week - Finish ad video - Integrate with team on diagrams and code ### Problems - I had a blocker this week. I was blocked on review of UML diagram and task board items. After we had a meeting, this issue was resolved. ### Time Spent - Task1: 6 hrs - Task2: 2 hrs - Task 3: 5 hours - Task 4: 3 hour ### Ensuring my XP core value of Courage I reminded our team that noone works alone. Therefore, if we have issues, we need to speak up about them. Our team has been very good about that. As a result, we have had multiple meetings on zoom in addition to our standbots and weekly Saturday face-2-face meetings. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Completed the feature which is when snake interacts with Turtle, then game should end. Made some refactoring changes to the logic such that it can integrate with other feature such as shield. - Helped other team members in features such as Snake Movement and Snake attraction. - Fixed major merge conflicts in master due to which many team members were not able to merge. Pitched in to help teammates with a solution for these kind of git conflicts. Provided training on git cherry-pick. ### Planned Next Week - Reasearching on WOW factor (multiplayer, android application and how machine learning models can help in playing the game) - To create sequence diagrams and other UML diagrams from the source code. ### Problems ### Time Spent - Task1: 5 hrs - Task2: 3 hrs - Task3: 3 hrs ### XP Core Value So far all criteria for respect XP values were met. All team members reported no issues in terms of respect. Standups were conducted with respecting each other ideas, thoughts and suggestions. <h2></h2> <h2><NAME></h2> ### Accomplished Last Week - Task 1: I completed implementing Strategy pattern for Game Difficulty. - Task 2: I also created Startup screen to integrate Strategy pattern in it. - Task 3: Finetuned wireframes for my user stories ### Planned Next Week - Implement "Won the game" feature - Start creating sequence diagram for completed user stories ### Blockers - Due to urgent work issues, I was not able to spend as much time as I decided to work on the project. ### Time Spent - Task 1: 4 hours - Task 2: 4 hours - Task 3: 3 hours ### XP Value : Feedback In this week, I did peer review for many pull requests and I tested different features and reported my feedback to the team. <h2></h2> <h2>Megha</h2> ### Finished Last Week - Task 1: Finished implementation of Decorator pattern on Shield. - Task 2: Decided on the design of my feature - Points System - Task 3: Finished development of my feature. - Task 4: Integrated my code with the features developed by the team. - Task 5: Worked on Sequence diagrams of my user stories. ### Planned Next Week - Research on feasibility of Multiplayer game in greenfoot. - Research on feasibility of creating an Android app from greenfoot. - Finalize on a WoW factor and start working on the same ### Problems - Our team faced some issues in code integration. Together we fixed the issue and created a clean master branch with all features integrated. ### Time Spent - Task1: 4 hrs - Task2: 2 hrs - Task 3: 4 hours - Task 4: 2 hours - Task 5: 2 hours ### Ensuring my XP core value of Simplicity Most of our features required actors to have different images at different points based on the state of the game. We spent some time thinking about editing existing images to make them look a certain way. But eventually I encouraged the team to pick the simplest images for the actors and not spend too much time editing the same thereby not focusing too much on the look of actors. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Task 1: When snake gets killed, the count of snakes in the game needs to be adjusted - Task 2: Integrate Snake with different patterns to make sure snake features are validated - Task 3: Checked if composite pattern fits the story of shield for Turtle - Task 4: Implement composite pattern so that shield and turtle moves together and can be treated as a group or individually ### Planned Next Week - Implement shield power system when snake hits shield - Implement turtle kill when shield strength reaches zero - Create UML diagrams and documentation ### Problems - Had issues greenfoot initialising all the objects on game refresh ### Time Spent - Task1: 4 hrs - Task2: 6 hrs - Task 3: 2 hrs - Task 4: 4 hrs ### Ensuring my XP core value of Communication I have ensured that our team has regular meetings whenever needed. Also that team is comfortable with the meeting timings and duration. Made sure that the owners of the inter related features discuss and solve any integration that may arise. <file_sep>import greenfoot.*; public class TurtleWorld extends World { public TurtleWorld() { super(WorldConfig.getX(), WorldConfig.getY(), WorldConfig.getCellSize()); System.out.println("construc call"); loadInitScreen(); } public void loadPlayScreen() { Helper.resetAll(this); reinitialize(); } public void loadInitScreen() { Helper.resetAll(this); initScreen(); } private void initScreen() { // init function addObject(new ChooseDifficulty(), 380, 100); addObject(new DifficultyLow(this), 390, 200); addObject(new DifficultyMedium(this), 390, 305); addObject(new DifficultyHigh(this), 390, 410); } private void reinitialize() { int worldWidth = getWidth(); int worldHeight = getHeight(); ActorManager actorManager = new ActorManager(); ScoreManager scoreManager = new ScoreManager(actorManager); Level level = new Level(); addObject(level, 380,26); Counter counter = new Counter(); addObject(counter, 58, 26); counter.attach(scoreManager); counter.attach(level); Turtle turtle = Turtle.init(); Shield shield = Turtle.getShield(); addObject(shield,100,100); addObject(turtle, 100, 100); turtle.attach(new RedLettuceObserver()); turtle.attach(counter); turtle.attach(actorManager); actorManager.createLettuce(); actorManager.createSnakes(); actorManager.createBug(); } }<file_sep>import greenfoot.*; public class ActorGenerator implements ActorFactory { public Actor createActor(String type, int x, int y) { Actor actor = null; if (Bug.class.getName().equalsIgnoreCase(type)) { actor = createBug(x, y); } else if (Lettuce.class.getName().equalsIgnoreCase(type)) { actor = createLettuce(x, y); } else if (RedLettuce.class.getName().equalsIgnoreCase(type)) { actor = createRedLettuce(x, y); } else if (Snake.class.getName().equalsIgnoreCase(type)) { actor = createSnake(x, y); } return actor; } /** * on turtle eat -> * kill manager will observe to kill the actor * counter will observe to increase score * actor manager will observe to create actors */ private Actor createSnake(int x, int y) { Snake snake = new Snake(); Helper.createActor(snake,x,y); return snake; } private Actor createLettuce(int x, int y) { Lettuce lettuce = new Lettuce(); Helper.createActor(lettuce,x,y); return lettuce; } private Actor createRedLettuce(int x, int y) { RedLettuce rl = new RedLettuce(); Helper.createActor(rl,x,y); return rl; } private Actor createBug(int x, int y) { Bug bug = new Bug(); Helper.createActor(bug,x , y); return bug; } } <file_sep><h1>Week 4 Scrum Report</h1> <h2><NAME></h2> ### Finished Last Week - Task 1: Completed another draft of ad video - Task 2: Finetuned documentation - Task 3: Final integration of documentation on github and practice presentation ### Planned Next Week - N/A ### Problems - No problems ### Time Spent - Task1: 2 hrs - Task2: 4 hrs - Task 3: 8 hrs ### Ensuring my XP core value of Courage I reminded team that we need to adapt to changes when they happen. Like for example we adapted as a team for ad hoc meetings this week because one team member had a time conflict. We also all adapted to the change that we all, in addition to daily Standbots, that we also have to do weekly journals. Finally, our wireframes and uml diagrams constantly needs to be updated because of bug fixes, refactoring, and changed features. We are adapting as a team to get the best value out of each sprint. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Researched on WOW factor. Found Multiplayer is achievable but will require major design changes which is not feasible at this time. - Suggested team how to make changes for Android application WOW factor. - Worked on creating sequence diagrams. Finalizing the deliverables, ReadME. making sure we have everything to submit. ### Planned Next Week - DEMO (end of sprint) ### Problems ### Time Spent - Task1: 6 hrs - Task2: 1 hrs - Task3: 6 hrs ### XP Core Value Everyone were respectful. Team did a great job in the 4 week sprint. <h2></h2> <h2><NAME></h2> ### Accomplished Last Week - Task 1: I implemented Won the game feature - Task 2: Completed sequence diagrams for my user storie - Task 3: Finetuned README.md file - Task 4: Prepared presentation ### Blockers - I didn't have any blockers. ### Time Spent Task 1: 3 hours Task 2: 4 hours Task 3: 2 hours Task 4: 2 hours ### XP Value : Feedback This is the last week of sprint. I am happy that everyone considered my feedback and made changes accordingly. I provided my feedback for ad video and presentation to make it more presentable and polish. <h2></h2> <h2>Megha</h2> ### Finished Last Week - Task 1: Researched on Multiplayer game in greenfoot - Task 2: Researched on porting greenfoot application on Android. - Task 3: Modified greenfoot application code to make it compatible with Android - Task 4: Ported Turtle World application to Android. - Task 5: Redefined movement and key press events for Android application ### Planned Next Week - N/A ### Problems - None ### Time Spent - Task1: 2 hrs - Task2: 4 hrs - Task 3: 2 hours - Task 4: 4 hours - Task 5: 3 hours ### Ensuring my XP core value of Simplicity Researched on both Multiplayer game and Android game on Greenfoot. Porting to Android was the simpler choice so went ahead with it. Because of this choice we were able to get a WoW factor element. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Task 1: Implemented shield power system when snake hits shield - Task 2: Implemented turtle shield will decrease on intersection with snake - Task 3: Implemented turtle dies if shield strength is 0 and turtle intersects with snake - Task 4: Created UML diagrams for the two stories - Task 5: Final integration of documentation on github and practice presentation ### Planned Next Week - NA ### Problems - No Problems ### Time Spent - Task1: 2 hrs - Task2: 2 hrs - Task 3: 3 hrs - Task 4: 3 hrs - Task 5: 3 hrs ### Ensuring my XP core value of Communication I have ensured that our team has regular meetings whenever needed. Also that team is comfortable with the meeting timings and duration. Regular meetings were necessary to finalize project documentation and presentation. <file_sep> public interface IScoreSubject { void attach (IScoreObserver obj); void removeObserver (IScoreObserver obj); void notifyObservers(); } <file_sep>import greenfoot.*; public class Shield extends Animal implements IComponent, IShield { public int power; public boolean hitFlag; private IShield shieldBooster = null; public Shield(int p) { power = p; hitFlag = false; setImage("shield5.png"); } public Shield() { power = 5; hitFlag = false; setImage("shield5.png"); System.out.println("shield:" + power); } public void snakeHit() { power--; this.setImagePower(power); } public void setImagePower(int power) { switch (power) { case 1: setImage("shield1.png"); break; case 2: setImage("shield2.png"); break; case 3: setImage("shield3.png"); break; case 4: setImage("shield4.png"); break; case 5: setImage("shield5.png"); break; default: setImage("shield5.png"); break; } } public void act() { } public void moveactor() { move(WorldConfig.getInstance().TURTLE_SPEED); checkKeys(); Turtle t = Turtle.getTurtle(); try { setLocation(t.getX(), t.getY()); setRotation(t.getRotation()); if (canSee(Snake.class) && hitFlag == false) { System.out.println("hit"); hitFlag = true; snakeHit(); } if (hitFlag == true && !canSee(Snake.class)) { hitFlag = false; } } catch(Exception e) { } } public void checkKeys() { if (Greenfoot.isKeyDown("Left")) { turn(-WorldConfig.getInstance().TURTLE_DEGREE); } if (Greenfoot.isKeyDown("Right")) { turn(WorldConfig.getInstance().TURTLE_DEGREE); } if (Greenfoot.isKeyDown("Up")) { move(WorldConfig.getInstance().TURTLE_SPEED); } if (Greenfoot.isKeyDown("Down")) { move(-WorldConfig.getInstance().TURTLE_SPEED); } if ("space".equals(Greenfoot.getKey())) { attack(); } } public void setDecorator(IShield shieldBooster) { System.out.println("In booster decorator"); this.shieldBooster = shieldBooster; } public void removeDecorator() { this.shieldBooster = null; } public void attack() { if (this.shieldBooster != null) shieldBooster.attack(); } } <file_sep># Game Squad Table of contents ================= * [UI Wireframes](#ui-wireframes) * [Use Case](#use-case) * [Class Diagram](#class-diagram) * [Activity Diagram](#activity-diagram) * [Design Patterns](#design-patterns) * [Decorator](#decorator) * [Strategy](#strategy) * [Factory](#factory) * [Composite](#composite) * [Observer](#observer) * [Feature 1](#feature-1) * [Feature 2](#feature-2) * [Feature 3](#feature-3) * [Feature 4](#feature-4) * [Feature 5](#feature-5) ## UI Wireframes https://balsamiq.cloud/s41ht0j/pcfr87k ![Alt text](/docs/Wireframes/1_Game%20Options.png?raw=true "Story #1") ![Alt text](/docs/Wireframes/2_Startup.png?raw=true "Story #2") ![Alt text](/docs/Wireframes/3_Snake%20attracted.png?raw=true "Story #3") ![Alt text](/docs/Wireframes/4_Points.png?raw=true "Story #4") ![Alt text](/docs/Wireframes/5_Turtle%20dies.png?raw=true "Story #5") ![Alt text](/docs/Wireframes/6_Advancing%20to%20next%20level.png?raw=true "Story #6") ![Alt text](/docs/Wireframes/7_Shield.png?raw=true "Story #7") ![Alt text](/docs/Wireframes/8_Shooting%20power.png?raw=true "Story #8") ![Alt text](/docs/Wireframes/9_Lady%20Bug%20-%20Story%20%239.png?raw=true "Story #9") ![Alt text](/docs/Wireframes/10_Won%20the%20game.png?raw=true "Story #10") ## Use Case ![Alt text](/docs/UseCase_Diagram.png?raw=true "Use Case Diagram") ## Class Diagram ![Alt text](/docs/class_diagram.png?raw=true "Class Diagram") ## Activity Diagram ![Alt text](/docs/activity_diagram.png?raw=true "Activity Diagram") ## Design Patterns #### Decorator Shield class contains a decorator object which is initially set to Null. The ```attack()``` method of ```Shield``` invokes the decorator's attack method if it is not null. Initially Shield class does not perform any opertaion since the decorator object is Null. Once Turtle eats the ```RedLettuce```, ```RedLettuceObserver``` assigns ```ShieldBoostDecorator``` as the decorator. ```attack()``` method is invoked on clicking the shield. ShieldBoostDecorator's attack() method releases a Shot. It is assigned 10 Shots and once all Shots are used, the decorator is reset to null. ![Alt text](/docs/Story8-ShootingPower.png?raw=true "Decorator Pattern") <img src="/docs/Story8_use_case_specification.png" width="500" height="500"> #### Strategy We used strategy pattern for Game startup screen. When user wants to play the game, user will first see the game startup screen. Game startup screen has 3 difficulty button Low, Medium and High. User has to choose one of the difficulty to play the game. Each difficulty is different from each other in various attributes. So we have decided to use strategy pattern for this story. There are number of attributes such of number of snakes, speed of snakes, visibility of snakes etc which has different values in different difficulties. For Low difficulty, these attributes are set in such a way that it is easier to play the game. As user goes towards Medium and High, these attributes are set in such a way that the game would be harder to play. Strategy Interface: ```DifficultyStrategy``` Strategy Concrete Class: ```DifficultyLevelLow```, ```DifficultyLevelMedium```, ```DifficultyLevelHigh``` Actor: ```DifficultyLow```, ```DifficultyMedium```, ```DifficultyHigh``` ![Alt text](/docs/Story1-GameStartUpScreen.png?raw=true "Strategy Pattern") <img src="/docs/Story1-use_case_specification.png" width="500" height="500"> #### Factory We used factory pattern to create the actors on the world. Main actors in our game are : Red Lettuce, Lettuce, Snake, and Bug. All actors are being created using Factory pattern. We have an interface Actor Factory and its concrete class Actor Generator. When an actor dies (except Turtle), the observers or the world submits a request to create that specfic actor to the Actor Manager. Actor Manager then using a timer queue the request in the threadpool. When one of the background threads are free, thread using the Factory pattern, calls the ```ActorGenerator``` to create the specific actor. We have some time threshold to wait for few seconds before we see an actor in the world. Factory Interface : ```ActorFactory``` Factory Concrete: ```ActorGenerator``` Api : ```createSnakes(), createLettuce(), createRedLettuce(), createBug()``` ![Alt text](/docs/Story2-StartGame.png?raw=true "Factory Pattern") <img src="/docs/Story2_use_case_specification.png" width="500" height="500"> #### Composite We used Composite pattern to add shield to the Turtle. The shield and turtle share methods to move around, action on keypress and snake Hit. Shield and turtle move together and can be treated as a group. With composite we can add multiple accessories to Turtle and move them together. Also Implemented a feature of changing shield power. On intersection with a snake power of shield decreases by 1, which also results in changing the image of the shield to a smaller shield. Interface: ```IComponent``` Classes: ```Shield```, ```Turtle``` ![Alt text](/docs/Story7-Shield.png?raw=true "Composite Pattern") <img src="/docs/Story7_use_case_specification.png" width="500" height="500"> #### Observer Though we used observer patterns quite a bit in our game, but the main observer in focus is advancing level. Once Turtle eats lettuce or bug, the score counter gets updated (via observer) and level counter. Both ```ScoreCounter``` and ```Level``` implements ```IScoreObserver```. ```IScoreSubject``` is implemented by ```Counter```. The data flow is such, that on every eat, we update the counter via observer and once the counter is updated we update the level via another observer. Reason we implemented in such a way is because Level upgrade events are only emmited at a factor of 20 (when we change our next level). ![Alt text](/docs/Story6-AdvancingToNextLevel.png?raw=true "Observer Pattern") <img src="/docs/Story6_use_case_specification.png" width="500" height="500"> #### Feature 1 Game End: This feature is to end the game once snake eats a turtle. Since snake can move freely and in case turtle has 0 shield power, if snakes get in touch with Turtle, using the observer patterns we have in our game. On this special event, the world drops all its actors and displays Looser. This event only and can only happen when shield is not their on the turtle. ![Alt text](/docs/Story5-EatTurtle.png?raw=true "Game End") <img src="/docs/Story5_use_case_specification.png" width="500" height="500"> #### Feature 2 Bug Move Randomly: This feature enables our Lady bug to move randomly. When lady bug encounters the world's edge, it changes its position and make turns instead of getting stuck at the edge. The feature enables bug to move on top of turtles and lettuces. This is to avoid collisions between different actors in our game. ![Alt text](/docs/Story9-LadyBug.png?raw=true "Bug Move Randomly") <img src="/docs/Story9_use_case_specification.png" width="500" height="500"> #### Feature 3 Won the game When turtle is moving, turtle can eat many things and user gains points on the basis of what was eaten by the turtle. User also gets point when turtle has a gun power if turtle shoots down snake. Whenever turtle eats or kills anything, it will be notified to ```ScoreManager``` which will keep track of points. This is a notification type of calling. Therefore, we decided to use Observer pattern here. When ScoreManager adds score, it will also notify Level class to keep track of the levels. So if user is on the highest level and reaches to 2000 points, the game will be over and user will be declared as winner. Interface: ```IScoreObserver``` Class: ```ScoreManager```, ```Level``` ![Alt text](/docs/Story10-WonTheGame.png?raw=true "Won the game") <img src="/docs/Story10_use_case_specification.png" width="500" height="500"> #### Feature 4 Point System for Lettuce and Bug This feature is related to the Points System for Lettuce and Bug. When the turtle eats lettuce or bug, we notify the game counter to increase the score by either 5 (for lettuce) and 20 (for bug). Point system uses a combination of observer and ```ScoreManager```. Scoremanager tracks the score and creates Redlettuce after it reaches it threshold. Basically point system is the backbone of the game to keep all the subjects and observers go hand-in-hand. ![Alt text](/docs/Story4-EatLettuceAndBug(Point%20System).png?raw=true "Eat Lettuce And Bug") <img src="/docs/Story4_use_case_specification.png" width="500" height="500"> #### Feature 5 Snake Attraction For this we have used method ```getNeighbours()``` provided by Greenfoot. On every move snake keeps on checking if there is a turtle in its radius of effect (```getNeighbours()```). On finding a turtle in its neighborhood, snake’s changes its direction and starts moving in direction of the turtle. Also snake’s image changes to ‘RedSnakeImage’ on attraction. Classes: ```Snake```, ```Turtle``` ![Alt text](/docs/Story3-SnakeAttracted.png?raw=true "Snake Attraction") <img src="/docs/Story3_use_case_specification.png" width="500" height="500"> <file_sep>/** * * @author (Saumil) */ public class DifficultyLevelLow implements DifficultyStrategy { private int numberOfSnakes; private int speedOfSnake; private int snakeVisibilityRadius; public DifficultyLevelLow() { this.numberOfSnakes = 5; this.speedOfSnake = 1; this.snakeVisibilityRadius = 10; } public int getNumberOfSnakes() { return this.numberOfSnakes; } public int getSpeedOfSnake() { return this.speedOfSnake; } public int getSnakeVisibilityRadius() { return this.snakeVisibilityRadius; } } <file_sep>public class ShotObserver implements IShotObserver { public void invoke() { System.out.println("In shot observer"); Turtle turtle = Turtle.getTurtle(); Shield shield = turtle.getShield(); shield.removeDecorator(); } }<file_sep><h1>Team Project Repo</h1> <h2>Team</h2> <h3>Game Squad</h3> <h2>Team Members</h2> * <h3>[<NAME>](https://github.com/mariannepaulson/cmpe202)</h3> * <h3>[<NAME>](https://github.com/saumilnpatel17/cmpe202)</h3> * <h3>[<NAME>](https://github.com/Anjali-Deshmukh/cmpe202)</h3> * <h3>[<NAME>](https://github.com/megha-31/cmpe202)</h3> * <h3>[<NAME>](https://github.com/chiragarora1703/cmpe202)</h3> <h2>Project Name</h2> <h3>TurtleWorld</h3> <h2>Project Description</h2> We started with a cute turtle game one of us created based on watching <NAME>'s video series. https://blogs.kcl.ac.uk/proged/2012/01/14/joc-9/ The initial commit of code is from watching how to create this game and creating it from scratch. We then added counter, custom sounds, and experimented with the Greenfoot UI. We then refactored the code into patterns taught in class. Finally, we came up with 10 user stories and implemented all 10 features. We picked two features each. <h2>Project Progress</h2> <h3>Project Dashboard</h3> https://docs.google.com/spreadsheets/d/1mopQ8FHEn-voEusz9E8PlLg993NWcqjp-fM39Le03FU/edit <h3>Burndown Map</h3> <img src="docs/BurnDownChart.PNG" alt="Markdown Monster icon" style="float: left; margin-right: 10px;" /> <br/> <h3>Advertising our game</h3> https://www.youtube.com/watch?v=X-OZWBY9mkE <h3>Individual Contributions</h3> All team members contributed equally to create mocks, original features for the game, user specifications, accomodating sequence diagrams and presentation. We took turn acting as a scrum master during the project. - Megha - Worked on Decorator pattern for shield which decorates the shield with power to attack snakes - Worked on feature point system which controls the levels and scoring of the game - Implemented changes to make greenfoot application compatible in Android for wow factor - Marianne - Pitched the idea for this wonderfull game and also worked on our stunning advertisement - Worked on observer pattern to update the level in the game - Worked on lady bug movement feature which makes ladybug move randomly and over other actors - Anjali - Worked on Composite pattern to add shield with power on turtle. Due to this pattern turtle and shield act like one component and one can add multiple attributes to the turtle as a component - Worked on feature Snake Attraction. This enables snake to get attracted towards turtle. If turtle is in its vicinity the snake turns red - Converted the mocks from paper to balsamiq mocks - Chirag - Worked on factory pattern to create all actors using multithread and timer. After submitting the create actor request to the queue, the implementation creates actors dynamically - Worked on feature 'Game Over' when turtle dies. In this feature when snake eats turtle, game world state is changed to EndWorld state and all the objects are dropped from the world - Researched on multiplayer and android application for wow factor - Saumil - Worked on the strategy pattern to add difficulty levels to the game (LOW, MEDIUM, HIGH). These difficulty levels control the speed and count of the snakes in the world - Worked on the feature 'Won The Game' which keeps track of levels. Once points reach the maximum threshold, the world transitions to end of game - Worked on README enhancements <h2>Issues</h2> - We had some issues in editing README and ended up with multiple one liner commits from web - On merging the branch, the setting to auto delete the branch was used. Due to which branches were deleted. - We had setup automatic triggers to update the issues to change its status, but those didn't work. We had to manually close the issues. But pull requests are their if you want to look at each branches. - Due to github account getting flagged, Chirag was blocked. We ended up creating duplicate issues with same context. Now account has been reset. We see all the duplicate issues under issues section. - We were uncertain about project board. We interpreted project board as Google Task Sheet. <h2>Wow Factor</h2> https://github.com/nguyensjsu/sp19-202-game-squad/tree/wowtry References: https://github.com/rhildred/droidfoot <file_sep><h1>Week 2 Scrum Report</h1> <h2><NAME></h2> ### Finished Last Week - Task 1: Some more research on new features and how to refactor using patterns. - Task 2: I got my three features assigned (turtle dance, advance to next level and lady bug) and - created wireframes for these using Balsamic. I also created use case specifications for these. - Task 3: - I spent time on process - How to use Github issue tracking - How to create branching - Understanding how our team was going to work on github - Also learned how to effectively use Standbot on Slack for daily standups. - Took the first stab at project task board (actually twice) ### Planned Next Week - Code my two features (dropped turtle dance) - Create sequence diagrams for my two features - Finetune wireframes - Help team with process issues ### Problems - I was not able to get the turtle to make any nice moves. Also, as a team, we did not find this feature to be very valuable. Therefore, we removed this feature from the backlog. ### Time Spend - Task1: 4 hrs - Task2: 6 hrs - Task 3: 4 hours ### Ensuring my XP core value of Courage Our team is very honest so there is no issue there. However, I had to remind the team about improving on their estimates. When we say we will complete something by a certain date, we need to try our hardest to meet our estimate. Therefore, if we know we have a time conflict, we should be upfront about it and try and estimate correctly. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Wrapped up the factory pattern to create actors using multi-thread in the backgroun and using timer to control the creation of the actors - Started looking into Turtle kill feature story and how to update the counter score board. - Fixed some integration issues that arised in greenfoot when merging others code. ### Planned Next Week - Implementing initial framework for the world. - Technical story for a design pattern. Factory Pattern. Create lady bug and different types of lettuce (green and red). - Will be working on initial grounding work of observer pattern for Turtle kill. ### Problems - Got my Github account flagged. I emailed GitHub support but due to no response, creating a new account and transferring all commits under this new account. Waiting for access to our project. ### Time Spend - Task1: 7 hrs - Task2: 3 hrs - Task3: 3 hrs ### XP Core Value All the team members were respecting each other ideas. Though respect should also be regarded in terms of time. Most of the teammembers were on time for our meetings. Reminded them to be on time. <h2></h2> <h2><NAME></h2> ### Accomplished Last Week - Task 1: We did a research on what design patterns will be suitable for the game and what features will go in the game. - Task 2: As discussed in the team meeting, I got my 3 user stories that is Create Difficulty Levels, keep the count of snake so that we can create a new snake when snake gets killed and won the game. - Task 3: Started creating wireframes on paper and then later moved it to Balsamic. - Task 4: We switched from weekly standup to 3 times a week standup routine. We started using standbot in slack for standups. - Task 5: Learn more about github to make it easier for team to work in parallel environment ### Planned Next Week - Start working on my design pattern user story - Finetune wireframes ### Blockers - I didn't have any blockers. ### Time Spend Task 1: 2 hours Task 2: 2 hour Task 3: 3 hours Task 4: 3 hours Task 5: 2 hours ### XP Value : Feedback During this week, I gave feedback to the team based on wireframes and use case specifications. I also suggested them some modifications to make user stories much more efficient. <h2></h2> <h2>Megha</h2> ### Finished Last Week - Task 1: I got my two features assigned (Decorate Shield and Points System). Created User stories for both the assigned tasks. - Task 2: Re-read about the decorator pattern and it's implementation. Finalized the design of Decorator on Shield. - Task 3: Started implementation of Decorator pattern. Stubbed code for Red lettuce as it's development was in progress and I didn't want to block myself. - Task 4: Helped team with github issues - Task 5: Worked on implementation of turtle shooting gunshots in Greenfoot ### Planned Next Week - Finish the design pattern (Decorate Shield) - Start implementation on the feature (Points System). - Create sequence diagrams for my two features ### Problems - None ### Time Spend - Task1: 2 hrs - Task2: 4 hrs - Task 3: 4 hours - Task 4: 2 hours ### Ensuring my XP core value of Simplicity Since we have started development this week, a lot of features are dependent on each other and most of them are in development state. I made sure that we were stubbing dependent code and there were no blockers so that we can proceed with our development. Using this simple technique we were able to progress smoothly. <h2></h2> <h2><NAME></h2> ### Finished Last Week - Task 1: Some more research on new features and how to refactor using patterns. - Task 2: I got my two stories assigned (Snake Attracted to turtle in its vicinity, Shield for Turtle) and - created wireframes for these using Balsamic. I also created use case specifications for these. - Task 3: Implemented speed and movement of snake and logic so that Snakes don't get too close to each other. Snake tries to repel other Snake - I spent time on process - How to use Github issue tracking - How to create branching - Understanding how our team was going to work on github - Also learned how to effectively use Standbot on Slack for daily standups. ### Planned Next Week - Code my two stories - Create sequence diagrams for my two stories ### Problems N/A ### Time Spend - Task1: 4 hrs - Task2: 6 hrs - Task 3: 4 hours ### Ensuring my XP core value of Communication I have ensured that our team has regular meetings whenever needed. Also that team is comfortable with the meeting timings and duration. <file_sep>import java.util.List; import greenfoot.*; public class Snake extends Animal { /** * Act - do whatever the Snake wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { List<Snake> snakes = this.getNeighbours(30, false, Snake.class); if (!snakes.isEmpty()) { this.turn(WorldConfig.getInstance().TURTLE_DEGREE); move(WorldConfig.getInstance().SPEED_OF_SNAKES * 5); } List<Turtle> turtles = this.getNeighbours(WorldConfig.getInstance().SNAKES_ATTRACTION, true, Turtle.class); if (!turtles.isEmpty()) { this.setImage("snake2_red.png"); Turtle turtle = turtles.get(0); this.turnTowards(turtle.getX(), turtle.getY()); move(0); } else { move(WorldConfig.getInstance().SPEED_OF_SNAKES); this.setImage("snake2.png"); randomTurn(); } worldEdge(); eatTurtle(); } /** * Check if lettuce there and then eat */ public void eatTurtle() { if (canSee(Turtle.class) && (Turtle.getShield().power == 1)) { World world = Turtle.getTurtle().getWorld(); eat(Turtle.class); eat(Shield.class); Helper.loadEndScreen("Looser", world); } } } <file_sep>import greenfoot.*; public interface ActorFactory { public Actor createActor(String type, int x, int y); } <file_sep>public interface IShield { void attack(); }<file_sep>/** * Write a description of class WorldConfig here. * * @author (your name) * @version (a version number or a date) */ public class WorldConfig { private static WorldConfig worldConfig; public DifficultyStrategy ds; private static int x = 800; private static int y = 800; private static int cellSize = 1; // Turtle configuration public int TURTLE_SPEED = 2; public int TURTLE_DEGREE = 3; // Ammo configuration public int SHOTS = 5; // Level configuration public int MAX_LEVEL=10; public int LEVEL_FACTOR=20; // level increment in // Lettuce configuration public int NUM_OF_LETTUCE = 5; public int RED_LETTUCE_CREATION_ON_SCORE = 40; public int NUM_OF_RED_LETTUCE = 1; public int LETTUCE_CREATION_DELAY = 30; // Snake configuration // these will come from strategy pattern, defaults public int NUM_OF_SNAKES = 5; public int SPEED_OF_SNAKES = 1; public int SNAKES_ATTRACTION = 50; public int SNAKE_CREATION_DELAY = 30; // Bugs configuration public int NUM_OF_BUGS = 1; public int BUG_SPEED = 1; public int BUG_CREATION_DELAY = 60; private WorldConfig(DifficultyStrategy ds) { this.ds = ds; NUM_OF_SNAKES = ds.getNumberOfSnakes(); SPEED_OF_SNAKES = ds.getSpeedOfSnake(); } public static WorldConfig getInstance() { return worldConfig; } public static void createWorldConfig(DifficultyStrategy ds) { worldConfig = new WorldConfig(ds); } public static int getX() { return x; } public static int getY() { return y; } public static int getCellSize() { return cellSize; } } <file_sep>/** * @author (Saumil) */ public class DifficultyLevelHigh implements DifficultyStrategy { private int numberOfSnakes; private int speedOfSnake; private int snakeVisibilityRadius; public DifficultyLevelHigh() { this.numberOfSnakes = 10; this.speedOfSnake = 3; this.snakeVisibilityRadius = 30; } public int getNumberOfSnakes() { return this.numberOfSnakes; } public int getSpeedOfSnake() { return this.speedOfSnake; } public int getSnakeVisibilityRadius() { return this.snakeVisibilityRadius; } }
bc78584ef9b303c89db3f09fb3ba9529569c52a5
[ "Markdown", "Java" ]
21
Markdown
nguyensjsu/sp19-202-game-squad
207f58b7f8a0da04c45b6dcda41e2f1f90aa8417
cc54df4ebc2d8b6995dca4b710e7a0b4e5029916
refs/heads/master
<file_sep>let express = require('express'); let server = express(); let port = 3000 || 8080; server.use(express.static(__dirname + '/public')); server.listen(port, () => { console.log(`Server is up on port ${port}`); });
6c410fef4586e2525db9f20954094c4d02157149
[ "JavaScript" ]
1
JavaScript
VladislavArkavenko/3d-rotating-cube
0604ec366b62ce280ea98150643f74be0fb3566d
b26e6648a91fab5502c701a300eddd75031efbed
refs/heads/master
<repo_name>RatioBuild/HelloWorld<file_sep>/build.sh #!/bin/sh security unlock-keychain -p `cat ~/.build_password` xcodebuild echo "Got it Working, without showing hidden files"
b49f6b4728a923465ae4e7d791bfecd45d935fe6
[ "Shell" ]
1
Shell
RatioBuild/HelloWorld
2d93886f47d1f22ff9928d16435a3627e4147bcb
5c3ea3764bbe4c9bf669d11596fbceb9fdaf6d9c
refs/heads/main
<file_sep>pygame.mixer.set_reserved(2) reserved_channel_0 = pygame.mixer.Channel(0) reserved_channel_1 = pygame.mixer.Channel(1) <file_sep> def read_mtllib(self, mtl_fname): file_mtllib = open(mtl_fname) for line in file_mtllib: words = line.split() command = words[0] data = words[1:] if command == 'newmtl': material = Material() material.name = data[0] self.materials[data[0]] = material elif command == 'map_Kd': material.texture_fname = data[0] <file_sep>from enum import Enum, auto import time class States(Enum): IDLE = auto() STARTING = auto() RUNNING = auto() STOPING = auto() ERROR = auto() class StateObject: def __init__(self): self.__state = States.IDLE def set_state(self, state): self.__state = state def get_state(self): return self.__state class Entity(StateObject): def __init__(self): super().__init__() self.__counter = 0 def inc_counter(self): self.__counter += 1 def sub_counter(self): self.__counter -= 1 def get_counter(self): return self.__counter def set_counter(self, counter): self.__counter = counter SM1 = Entity() SM1.set_state(States.IDLE) SM2 = Entity() SM2.set_state(States.IDLE) while True: #if we are in IDLE state, ask user for statemachine run if SM1.get_state() == States.IDLE: user_input = input("goto RUNNING=ok, goto ERRROR=nok, quit=q") print("-----------------------------------------") if user_input == "ok": SM1.set_state(States.RUNNING) SM1.set_counter(5) elif user_input == "nok": SM1.set_state(States.ERROR) SM1.set_counter(10) elif user_input == "q": break if SM1.get_state() == States.RUNNING: SM1.sub_counter() print(SM1.get_counter()) time.sleep(1) #slow running state if SM1.get_counter() <= 0: SM1.set_state(States.IDLE) if SM1.get_state() == States.ERROR: SM1.sub_counter() print(SM1.get_counter()) time.sleep(0.1) #slow running state if SM1.get_counter() <= 0: SM1.set_state(States.IDLE) print("Statemachine stopped")<file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 27 20:29:39 2020 @author: crtom https://www.youtube.com/watch?v=3UxnelT9aCo """ # Pathfinding - Part 1 # Graphs # KidsCanCode 2017 import pygame as pg from sys import exit vec = pg.math.Vector2 TILESIZE = 48 GRIDWIDTH = 28 GRIDHEIGHT = 15 WIDTH = TILESIZE * GRIDWIDTH HEIGHT = TILESIZE * GRIDHEIGHT FPS = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) MAGENTA = (255, 0, 255) YELLOW = (255, 255, 0) DARKGRAY = (40, 40, 40) LIGHTGRAY = (140, 140, 140) pg.init() screen = pg.display.set_mode((WIDTH, HEIGHT)) clock = pg.time.Clock() class SquareGrid: def __init__(self, width, height): self.width = width self.height = height self.walls = [] self.connections = [vec(1, 0), vec(-1, 0), vec(0, 1), vec(0, -1)] def in_bounds(self, node): return 0 <= node.x < self.width and 0 <= node.y < self.height def passable(self, node): return node not in self.walls def find_neighbors(self, node): neighbors = [node + connection for connection in self.connections] neighbors = filter(self.in_bounds, neighbors) neighbors = filter(self.passable, neighbors) return neighbors def draw(self): for wall in self.walls: rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE)) pg.draw.rect(screen, LIGHTGRAY, rect) def draw_grid(): for x in range(0, WIDTH, TILESIZE): pg.draw.line(screen, LIGHTGRAY, (x, 0), (x, HEIGHT)) for y in range(0, HEIGHT, TILESIZE): pg.draw.line(screen, LIGHTGRAY, (0, y), (WIDTH, y)) g = SquareGrid(GRIDWIDTH, GRIDHEIGHT) walls = [(10, 7), (11, 7), (12, 7), (13, 7), (14, 7), (15, 7), (16, 7), (7, 7), (6, 7), (5, 7), (5, 5), (5, 6), (1, 6), (2, 6), (3, 6), (5, 10), (5, 11), (5, 12), (5, 9), (5, 8), (12, 8), (12, 9), (12, 10), (12, 11), (15, 14), (15, 13), (15, 12), (15, 11), (15, 10), (17, 7), (18, 7), (21, 7), (21, 6), (21, 5), (21, 4), (21, 3), (22, 5), (23, 5), (24, 5), (25, 5), (18, 10), (20, 10), (19, 10), (21, 10), (22, 10), (23, 10), (14, 4), (14, 5), (14, 6), (14, 0), (14, 1), (9, 2), (9, 1), (7, 3), (8, 3), (10, 3), (9, 3), (11, 3), (2, 5), (2, 4), (2, 3), (2, 2), (2, 0), (2, 1), (0, 11), (1, 11), (2, 11), (21, 2), (20, 11), (20, 12), (23, 13), (23, 14), (24, 10), (25, 10), (6, 12), (7, 12), (10, 12), (11, 12), (12, 12), (5, 3), (6, 3), (5, 4)] for wall in walls: g.walls.append(vec(wall)) running = True while running: clock.tick(FPS) for event in pg.event.get(): if event.type == pg.QUIT: running = False if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: running = False if event.key == pg.K_m: # dump the wall list for saving print([(int(loc.x), int(loc.y)) for loc in g.walls]) if event.type == pg.MOUSEBUTTONDOWN: mpos = vec(pg.mouse.get_pos()) // TILESIZE if event.button == 1: if mpos in g.walls: g.walls.remove(mpos) else: g.walls.append(mpos) pg.display.set_caption("{:.2f}".format(clock.get_fps())) screen.fill(DARKGRAY) draw_grid() g.draw() pg.display.flip() pg.quit() exit()<file_sep>import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 picture_file = 'map.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) picture = pygame.image.load(picture_file).convert() picture_pos = Vector2(0, 0) scroll_speed = 1000. clock = pygame.time.Clock() joystick = None if pygame.joystick.get_count() > 0: joystick = pygame.joystick.Joystick(0) joystick.init() if joystick is None: print("Sorry, you need a joystick for this!") pygame.quit() exit() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() scroll_direction = Vector2(*joystick.get_hat(0)) scroll_direction.normalize() screen.fill((255, 255, 255)) screen.blit(picture, (-picture_pos.x, picture_pos.y)) time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 picture_pos += scroll_direction * scroll_speed * time_passed_seconds pygame.display.update() <file_sep>""" Game Template Attributes: g (TYPE): Description """ import pygame as pg # rename for fast typing import random from settings import * class Game: """Summary Attributes: all_sprites (TYPE): Description clock (TYPE): Description playing (bool): Description running (bool): Description screen (TYPE): Description """ def __init__(self): """initialize game window, etc """ pg.init() pg.mixer.init() self.screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption("My Game") self.clock = pg.time.Clock() self.running = True def new(self): """Start a New Game """ self.all_sprites = pg.sprite.Group() def run(self): """Game Loop """ self.playing = True while self.playing: self.clock.tick(FPS) # keep looping at the right speed self.events() self.update() self.draw() def update(self): """Game Loop - Update """ self.all_sprites.update() def events(self): """Game Loop - events """ for event in pg.event.get(): #check for closing window if (event.type == pg.QUIT) or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): if self.playing: self.playing = False self.running = False def draw(self): """Game Loop - draw """ self.screen.fill(BLACK) self.all_sprites.draw(self.screen) pg.display.flip() # after drawing everything, flip the display def show_start_screen(self): """game splash/start screen """ print("game start") pass def show_go_screen(self): """game over/continue screen """ print("game end") pass g = Game() # instance of game object g.show_start_screen() while g.running: g.new() g.run() g.show_go_screen() pg.quit() <file_sep>class StateMachine(object): def __init__(self): self.states = {} # Stores the states self.active_state = None # The currently active state def add_state(self, state): # Add a state to the internal dictionary self.states[state.name] = state def think(self): # Only continue if there is an active state if self.active_state is None: return # Perform the actions of the active state, and check conditions self.active_state.do_actions() new_state_name = self.active_state.check_conditions() if new_state_name is not None: self.set_state(new_state_name) def set_state(self, new_state_name): # Change states and perform any exit / entry actions if self.active_state is not None: self.active_state.exit_actions() self.active_state = self.states[new_state_name] self.active_state.entry_actions() <file_sep>from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * screen = pygame.display.set_mode((640, 480), HWSURFACE|DOUBLEBUF|OPENGL) def resize(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60, float(width)/height, 1, 10000) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def init(): glEnable(GL_DEPTH_TEST) glClearColor(1.0, 1.0, 1.0, 0.0) glShadeModel(GL_FLAT) glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0)) <file_sep>import pygame pygame.init() #---------display------------- display_width = 800 display_height = 600 #color var black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) gameDisplay = pygame.display.set_mode((display_width,display_height)) #set title pygame.display.set_caption('Race Game') clock = pygame.time.Clock() carImg = pygame.image.load('race_car_transp_v2.png') #function to display a car def car(x,y): gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface x = display_width*0.45 y = display_height*0.8 #for computers (x=0,y=0) is top left corner #------------main game loop--------- x_change = 0 chrashed = False while not chrashed: for event in pygame.event.get(): if event.type == pygame.QUIT: chrashed = True #if key pressed start moving if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 #if key released stop moving if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change #------------------------------------ #first draw background, dont paint over car gameDisplay.fill(white) car(x,y) pygame.display.update() clock.tick(60) #------------------------------------ pygame.quit() quit()<file_sep>""" Animation Spritesheet - picture size 32*640 - 10 pictures - 2 rows by 5 pictures Main goal: - cutting subpictures out of a single spritesheet image #------------------------------------------------- picture idexes 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, picture column, row position (0,0) (1,0) (2,0) (3,0) (4,0) (0,1) (1,1) (2,1) (3,1) (4,1) picture column, row pixel position (0,0) (32,0) (64,0) (96,0) (128,0) (0,32) (32,32) (64,32) (96,32) (128,32) #-------------------------------------------------- HANDLES = are used for easy picture offsets - 8 7 6 - --5---4---3--- - 2 1 0 - index offset 0 (0,0) 1 (-hw,0) 2 (-w,0) 3 (0,-hh) 4 (-hw,-hh) #image is centralized 5 (-w,-hh) 6 (0,-h) 7 (-hw,-h) 8 (w,-h) """ import math,random,sys import pygame from pygame.locals import * #esit the program def events(): for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() #define display surface W,H = 320,320 HW, HH = W//2, H//2 AREA = W*H #initialize display pygame.init() CLOCK = pygame.time.Clock() DS = pygame.display.set_mode((W,H)) pygame.display.set_caption("sprite sheets") FPS = 1 #define colours BLACK = (0,0,0) WHITE = (255,255,255) background = pygame.image.load('background.png').convert_alpha() #-------------------------------------- class spritesheet: def __init__(self, filename,cols,rows): self.sheet = pygame.image.load(filename).convert_alpha() self.cols =cols self.rows = rows self.totalCellCount = cols*rows #print(f'self.totalCellCount {self.totalCellCount}') OK self.rect = self.sheet.get_rect() #calling this function gives use rect width #cell width w = self.cellWidth = self.rect.width // cols h = self.cellHeight = self.rect.height // rows hw,hh = self.cellCenter = (w//2,h//2) #print(f'self.rect.width{self.rect.width} self.rect.height:{self.rect.height}') OK #print(f'w={w}, h={h}') #print(f'hw={hw}, hh={hh}') #build a list of cells. We need every cell x and y in pixels #1.) build list of indexes and than multiply those indexes by pixel size self.cells = list([(index%cols*w,index//cols*h,w,h) for index in range(self.totalCellCount)]) self.handle = list([(0,0),(-hw,0),(-w,0),(0,-hh),(-hw,-hh),(-w,-hh),(0,-h),(-hw,-h),(w,-h)]) def draw(self, surface, cellIndex, x, y, handle): surface.blit(self.sheet,(x+self.handle[handle][0],y+self.handle[handle][1]),self.cells[cellIndex]) #---------------------------------------- s = spritesheet(filename="moon_phase_64x320_v1.png",cols=10,rows=2) CENTER_HANDLE = 4 index = 0 #main loop print (s.handle) while True: events() #draw spritesheet #DS.fill(BLACK) DS.blit(background, (0,0)) s.draw(DS, index% s.totalCellCount, HW//2,HH//2,CENTER_HANDLE) index += 1 pygame.draw.circle(DS,WHITE,(HW,HH),2,0) pygame.display.update() CLOCK.tick(FPS) DS.fill(WHITE) <file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 27 23:13:08 2020 @author: crtom """ import pygame as pg from settings import * class Player(pg.sprite.Sprite): def __init__(self, game, x, y): # so player can acces all sprites in the game self.game = game self.groups = game.all_sprites # 1.) sprite class default override: #Call the parent class (Sprite) constructor pg.sprite.Sprite.__init__(self, self.groups) # 2.) sprite class default override: # tile based game - player is only one tile large self.image = pg.Surface((TILESIZE, TILESIZE)) self.image.fill(YELLOW) # 3.) sprite class default override: # Fetch the rectangle object that has the dimensions of the image # Update the position of this object by setting the values of rect.x and rect.y self.rect = self.image.get_rect() #self.rect.center = (WIDTH // 2, HEIGHT // 2) # CUSTOM ATTRIBUTES self.x = x * TILESIZE self.y = y * TILESIZE # delta time, game loop time #self.dt = 0 self.vx, self.vy = 0, 0 # position vector #self.position = Vector2(100.0, 100.0) # direction vector #self.direction = Vector2(0, 0) # movement speed #self.speed = 300. def get_keys(self): self.vx, self.vy = 0, 0 keys = pg.key.get_pressed() if keys[pg.K_LEFT] or keys[pg.K_a]: # self.player.move(dx=-1) self.vx = -PLAYER_SPEED elif keys[pg.K_RIGHT] or keys[pg.K_d]: # IF ENABLES DIAG self.vx = PLAYER_SPEED if keys[pg.K_UP] or keys[pg.K_w]: # IF ENABLES DIAG self.vy = -PLAYER_SPEED if keys[pg.K_DOWN] or keys[pg.K_s]: # IF ENABLES DIAG self.vy = PLAYER_SPEED # DIAGONAL PITAGORA if self.vx != 0 and self.vy != 0: self.vx *= 0.7071 self.vy *= 0.7071 #def set_time_passed_sec(self, dt): # self.dt_sec = dt / 1000.0 # def move(self, dx=0, dy=0): # # only move if not colliding with walls # if not self.collide_with_walls(dx, dy): # self.x += dx # self.y += dy # def collide_with_walls(self, dx = 0, dy = 0): # # OLD collision check # # loop trough the wall group and check # for wall in self.game.walls: # if wall.x == self.x + dx and wall.y == self.y + dy: # # yes we did collide # return True # #no we didnt collide with wall # return False def collide_with_walls(self, direction): # x collision check if direction == 'x': hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall if hits: # sprite was moving to the right # we need to put the sprite to the left edge of the wall if self.vx > 0: self.x = hits[0].rect.left - self.rect.width # sprite was moving to the left # we need to put the sprite to the right edge of the wall if self.vx < 0: self.x = hits[0].rect.right #- self.rect.width # we run into the wall, x velocity = 0 self.vx = 0 # update new position self.rect.x = self.x if direction == 'y': hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall if hits: # sprite was moving down # we need to put the sprite to the top of the wall if self.vy > 0: self.y = hits[0].rect.top - self.rect.height # sprite was moving to the top # we need to put the sprite to the bottom edge of the wall if self.vy < 0: self.y = hits[0].rect.bottom #- self.rect.width # we run into the wall, x velocity = 0 self.vy = 0 # update new position self.rect.y = self.y def update(self): self.get_keys() # # set sprite rectangle position # self.rect.x = self.x * TILESIZE # self.rect.y = self.y * TILESIZE # this will make movement independant of frame rate self.x += self.vx * self.game.dt # get dt from game object self.y += self.vy * self.game.dt # get dt from game object # self.rect.topleft = (self.x, self.y) self.rect.x = self.x self.collide_with_walls('x') self.rect.y = self.y self.collide_with_walls('y') # check if sprite and a group collides # # if hits a wall dont move # # redo movement position # if pg.sprite.spritecollideany(self, self.game.walls): # self.x -= self.vx * self.game.dt # get dt from game object # self.y -= self.vy * self.game.dt # get dt from game object # # self.rect.x = self.x * TILESIZE # # self.rect.y = self.y * TILESIZE # self.rect.topleft = (self.x, self.y) class Wall(pg.sprite.Sprite): def __init__(self, game, x, y): # so player can acces all sprites in the game # member of all sprites group # member of all walls group self.groups = game.all_sprites, game.walls pg.sprite.Sprite.__init__(self, self.groups) self.game = game # tile based game - player is only one tile large self.image = pg.Surface((TILESIZE, TILESIZE)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.x = x self.y = y self.rect.x = x * TILESIZE self.rect.y = y * TILESIZE<file_sep>import pygame pygame.init() gameDisplay = pygame.display.set_mode((800,600)) pygame.display.set_caption('a bit racey') clock = pygame.time.Clock() chrashed = False while not chrashed: for event in pygame.event.get(): if event.type == pygame.QUIT: chrashed = True print(event) pygame.display.update() clock.tick(60)¸#frames per second pygame.quit() quit()<file_sep># -*- coding: utf-8 -*- """ http://inventwithpython.com/pygame/ Created on Tue Dec 15 18:09:41 2020 @author: crtom - BASIC ARHITECTURE, get mouse coordinates #------------------------------------------------------------------------------ #-------------------------------------------------------------------------- #---------------------------------------------------------------------- #------------------------------------------------------------------ #-------------------------------------------------------------- """ import pygame import sys from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT #-------------------------------------------------------------------------- #-------------------------constants---------------------------------------- #-------------------------------------------------------------------------- FPS = 30 WIN_W = 600 WIN_H = 600 """ grid calculations GRID = 600*600 GRID 6x6 = 36 pieces 100x100 per square one piece is 80x80 + margin = 100x100 """ MARGIN_L = 10 BOX_L = 80 #REVEALSPEED = 8 #GAPSIZE = 10 BOARD_W = 6 BOARD_H = 6 # check #assert(BOARDWIDTH*BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches' #XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2) #YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2) # COLORS ( R , G , B ) WHITE = (255, 255, 255) BLACK = ( 0, 0, 0) GREY = (128, 128, 128) SILVER = (192, 192, 192) RED = (255, 0, 0) YELLOW = (255, 255, 0) ORANGE = (255, 128, 0) MAGENTA = (255, 0, 255) PURPLE = (128, 0, 128) LIME = ( 0, 255, 0) BLUE = ( 0, 0, 255) NAVYBLUE= ( 60, 60, 100) CYAN = ( 0, 255, 255) GRAY = (128, 128, 128) MAROON = (128, 0, 0) OLIVE = (128, 128, 0) GREEN = ( 0, 128, 0) TEAL = ( 0, 128, 128) NAVY = ( 0, 0, 128) BGCOLOR = NAVYBLUE LIGHTBGCOLOR = GRAY BOXCOLOR = WHITE HIGHLIGHTCOLOR = BLUE LINE = 'line' DONUT = 'donut' SQUARE = 'square' DIAMOND = 'diamond' LINES = 'lines' OVAL = 'oval' #ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN) #ALLSHAPES = (LINE, DONUT, SQUARE, DIAMOND, LINES, OVAL) #assert len(ALLCOLORS) * len(ALLSHAPES) * 2 <= BOARDWIDTH * BOARDHEIGHT,'Board is too big for the number of shapes/colors defined.' # create a list of touple positions grid_touple_lst = [] for y in range(0, 6): for x in range(0, 6): grid_touple_lst.append((x,y)) grid_pixel_pos_list = [] card_position_list = [] for x in range(0, 600, 100): for y in range(0, 600, 100): grid_pixel_pos_list.append((x, y)) card_position_list.append((x + 10, y + 10)) print(grid_pixel_pos_list) print(card_position_list) #--------------------------BACKGROUND-------------------------------------- def draw_background(): background = pygame.Surface(DISPLAYSURF.get_size()) ts, w, h, c1, c2 = 100, *DISPLAYSURF.get_size(), (160, 160, 160), (192, 192, 192) tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)] for rect, color in tiles: pygame.draw.rect(background, color, rect) DISPLAYSURF.blit(background, (0, 0)) #----------card----------- # 36 tiles cards = [] for i in range(36): position = card_position_list[i] rectangle = [position[1], position[0], 80, 80] surface = pygame.Surface((80,80)) state = 'closed' #opened glow = False dictionary = {'card_n': i, 'position': position, 'surface': surface, 'rectangle': rectangle, 'glow': glow, 'state': state } cards.append(dictionary) print(dictionary) def draw_cards(): for card in cards: #pygame.draw.rect(DISPLAYSURF, GREY, [0, 1, 20, 30], 0) pygame.draw.rect(DISPLAYSURF, BLACK, card['rectangle'], 0) if card['glow'] == True: pass def draw_rect_alpha(surface, color, rect): shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA) pygame.draw.rect(shape_surf, color, shape_surf.get_rect()) surface.blit(shape_surf, rect) #------------------------------------------------------------------------------ #----------------------------main loop----------------------------------------- #------------------------------------------------------------------------------ def main(): # global variables global FPSCLOCK, DISPLAYSURF # for positions position_pixel = (None, None) position_grid = (None, None) position_box = None # for user events mouseMoved = False mouseClicked = False #-------------------------------------------------------------------------- # init pygame pygame.init() FPSCLOCK = pygame.time.Clock() # initialize clock DISPLAYSURF = pygame.display.set_mode((WIN_W, WIN_H)) # initialize surface pygame.display.set_caption('Memory Game') #--------------------------------------------------------- #DISPLAYSURF.fill(BGCOLOR) draw_background() draw_cards() #-------------------------------------------------------------------------- #-------------------------GAME loop---------------------------------------- #-------------------------------------------------------------------------- while True: #----------------------event handling--------------------------------- for event in pygame.event.get(): # event objects have type attribute if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEMOTION: position_pixel = event.pos mouseMoved = True #print('mouse moved') elif event.type == MOUSEBUTTONUP: # mouse click position is in pixels position_pixel = event.pos # set click is true for functions mouseCicked = True #print('mouse clicked') #--------------------------------------------------------------------- # if mouse moved than highlight box if mouseMoved: # window pixels to game grid position_grid = pixel_pos_to_game_grid(position_pixel) # game grid to box number position_box = game_grid_to_touple_pos(position_grid) print('position_pixel = ', position_pixel) print('position_grid = ', position_grid) print('position_box = ', position_box) glow_card(position_box) # reset event flag mouseMoved = False #--------------------------------------------------------------------- if mouseClicked: mouseClicked = False show_card(position_box) update_cards() #------------------------timing---------------------------------------- # draws surface object stored in DISPLAYSURF #pygame.display.update() pygame.display.flip() FPSCLOCK.tick(FPS) #------------------------------------------------------------------------------ #-------------------------function definitions--------------------------------- #------------------------------------------------------------------------------ def update_cards(): global cards for card in cards: # if card is selected, glow sides if card['glow'] == True: pygame.draw.rect(DISPLAYSURF, BLUE, card['rectangle'], 0) else: pygame.draw.rect(DISPLAYSURF, BLACK, card['rectangle'], 0) def show_card(): global cards pass def glow_card(position_box): global cards for i, card in enumerate(cards): # set highlight selected card if i == position_box: card['glow'] = True #print() # = cards[position_box] #pygame.draw.rect(DISPLAYSURF, GREY, [0, 1, 20, 30], 0) #pygame.draw.rect(DISPLAYSURF, BLUE, card['rectangle'], 5) # clear highlight on other cards pass else: card['glow'] = False pass def pixel_pos_to_game_grid(touple_pixel): """ Parameters ---------- touple_pixel : touple position in pixels coordinates. Returns ------- touple_grid : touple position in game grid coordinates. """ x_grid = touple_pixel[0] // 100 # integere division y_grid = touple_pixel[1] // 100 touple_grid = (x_grid, y_grid) return touple_grid def game_grid_to_touple_pos(touple_grid): """ Parameters ---------- mytouple : touple position in game grid coordinates. Returns ------- position_box : number list index from grid_touple_lst """ box_n = None for i, touple in enumerate(grid_touple_lst): if touple_grid == touple: position_box = i return position_box def drawHighlightBox(boxx, boxy): left, top = leftTopCoordsOfBox(boxx, boxy) pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left - 5, top - 5, BOXSIZE + 10, BOXSIZE + 10), 4) def change_box_state(grid_nx, grid_ny): global state_lst # for state in state_lst: # # if back, turn to front # if state == 'front': # pygame.draw.rect(DISPLAYSURF, WHITE, (x, y, 80, 80)) # # if front, turn to back # else: # pygame.draw.rect(DISPLAYSURF, RED, (x, y, 80, 80)) def leftTopCoordsOfBox(boxx, boxy): # Convert board coordinates to pixel coordinates left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN return (left, top) #------------------------------------------------------------------------------ #-------------------------Start application------------------------------------ #------------------------------------------------------------------------------ if __name__ == '__main__': main()<file_sep>import pygame from grid import Grid import os os.environ['SDL_VIDEO_WINDOW_POS'] = '400,100' surface = pygame.display.set_mode((600,600)) pygame.display.set_caption('Tic-tac-toe') grid = Grid() running = True player = "X" while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN and not grid.game_over: if pygame.mouse.get_pressed()[0]: pos = pygame.mouse.get_pos() grid.get_mouse(pos[0] // 200, pos[1] // 200, player) if grid.switch_player: if player == "X": player = "O" else: player = "X" if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and grid.game_over: grid.clear_grid() grid.game_over = False elif event.key == pygame.K_ESCAPE: running = False surface.fill((0,0,0)) grid.draw(surface) pygame.display.flip() <file_sep># -*- coding: utf-8 -*- """ Created on Wed Dec 23 20:46:32 2020 @author: crtom """ import pygame import sys import random from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT import time pygame.init() screen = pygame.display.set_mode((300, 300)) s_r = screen.get_rect() player = pygame.Rect((100, 100, 50, 50)) timer = pygame.time.Clock() flash = 0 grow = True color = pygame.color.Color('Black') E_OUTSIDE = pygame.USEREVENT + 1 E_MOUSE = pygame.USEREVENT + 2 conditions = [ # blink if player is outside screen (lambda: not s_r.contains(player), pygame.event.Event(E_OUTSIDE)), # if mouse if over player then grow and shrink player (lambda: player.collidepoint(pygame.mouse.get_pos()), pygame.event.Event(E_MOUSE))] while True: # generate events from conditions map(pygame.event.post, [e for (c, e) in conditions if c()]) for event in pygame.event.get(): if event.type == pygame.QUIT: raise elif event.type == E_OUTSIDE and not flash: flash = 5 elif event.type == E_MOUSE: if grow: player.inflate_ip(4, 4) grow = player.width < 75 else: player.inflate_ip(-4, -4) grow = player.width < 50 flash = max(flash - 1, 0) if flash % 2: color = pygame.color.Color('White') pressed = pygame.key.get_pressed() l, r, u, d = map(lambda x: x*4, [pressed[k] for k in pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_s]) player.move_ip((-l + r, -u + d)) screen.fill(color) color = pygame.color.Color('Black') pygame.draw.rect(screen, pygame.color.Color('Grey'), player) pygame.display.flip() timer.tick(25)<file_sep>""" Simple pong in python 3 for begginers tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2 """ import turtle wn = turtle.Screen() wn.title("Pong by @TokyoEdTech") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) # Paddle A paddle_a = turtle.Turtle() paddle_a.speed() #sets the speed of animation to max paddle_a.shape("square") #default is 20x20 pixels paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, stretch_len = 1) # strech the square paddle_a.penup() paddle_a.goto(-350,0) # Paddle B paddle_b = turtle.Turtle() paddle_b.speed() #sets the speed of animation to max paddle_b.shape("square") #default is 20x20 pixels paddle_b.color("white") paddle_b.shapesize(stretch_wid=5, stretch_len = 1) # strech the square paddle_b.penup() paddle_b.goto(350,0) # Ball ball = turtle.Turtle() ball.speed() #sets the speed of animation to max ball.shape("square") #default is 20x20 pixels ball.color("white") ball.penup() ball.goto(0,0) # main game loop while True: wn.update() #updates screen<file_sep>import pygame pygame.init() #---------display------------- display_width = 800 display_height = 600 #color var black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) gameDisplay = pygame.display.set_mode((display_width,display_height)) #set title pygame.display.set_caption('Race Game') clock = pygame.time.Clock() carImg = pygame.image.load('race_car_transp_v2.png') #function to display a car def car(x,y): gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface x = display_width*0.45 y = display_height*0.8 #for computers (x=0,y=0) is top left corner #------------main game loop--------- chrashed = False while not chrashed: for event in pygame.event.get(): if event.type == pygame.QUIT: chrashed = True #------------------------------------ #first draw background, dont paint over car gameDisplay.fill(white) car(x,y) pygame.display.update() clock.tick(60) #------------------------------------ pygame.quit() quit()<file_sep>""" Basic Movement and Key Presses video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5 1. create a rectangle 2. move it by key pressed """ import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 def draw_vector(screen, startpoint, vector, color, width, DEBUG = False): """ E *** ***** L**M**R * * * * ----S----- * * O E - vector endpoint M - arrow midpoint L - arrow left point R - arrow right point """ #------------CALCULATIONS--------------- #DEBUG = False # create points E = (0, 0) L = (0, 0) M = (0, 0) R = (0, 0) # copy vector to new v = Vector2(int(vector.x), int(vector.y)) # 1) set S - starrpoint S = (startpoint[0], startpoint[1]) # 2) set E - endpoint E = (v.x + S[0], v.y + S[1]) # 3) Find vector SM v_SM = Vector2(v.x, v.y) v_SM.normalize() v_SM *= 2*width # v_SM *= 10 v_SM = v - v_SM M = (S[0]+v_SM.x, S[1]+v_SM.y) # 3) Find perpendicular vector v_perp = Vector2(-v.y, v.x) v_perp.normalize() v_perp *= width # v_perp *= 5 # 4) Find arrow head points L = (M[0] - v_perp.x, M[1] - v_perp.y) R = (M[0] + v_perp.x, M[1] + v_perp.y) #------------DRAWINGS--------------- # pixels must be integers E = (int(E[0]),int(E[1])) M = (int(M[0]),int(M[1])) L = (int(L[0]),int(L[1])) R = (int(R[0]),int(R[1])) # draw main vector line pygame.draw.line(screen, color, S, M, width) # draw points for debugging purpose # points = S, E, L, M, R # draw arrow head poligone # if very short, dont draw arrow #length = sqrt(v.x pygame.draw.polygon(screen, color, (L, R, E)) WIDTH, HEIGHT = 1000, 800 FPS = 60 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255,0,0) LIME = (0,255,0) BLUE = (0,0,255) YELLOW = (255,255,0) pygame.init() pygame.mixer.init() #### Create a canvas on which to display everything #### screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) #set windows title pygame.display.set_caption("8 way movement vector") # set clock clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((64, 64)) self.image.fill(YELLOW) self.rect = self.image.get_rect() self.rect.center = (WIDTH // 2, HEIGHT // 2) # delta time, game loop time #self.dt = 0 # position vector self.position = Vector2(100.0, 100.0) # direction vector self.direction = Vector2(0, 0) # movement speed self.speed = 300. #def set_time_passed_sec(self, dt): # self.dt_sec = dt / 1000.0 def update(self, dt): dt_sec = dt / 1000.0 self.direction.x, self.direction.y = (0, 0) keystate = pygame.key.get_pressed() if keystate[pygame.K_UP]: self.direction += Vector2(0, -1) if keystate[pygame.K_DOWN]: self.direction += Vector2(0, 1) if keystate[pygame.K_LEFT]: self.direction += Vector2(-1, 0) if keystate[pygame.K_RIGHT]: self.direction += Vector2(1, 0) # direction vector is a unit vector, normalize it # diagonals are 0.707 self.direction.normalize() self.position += self.direction * self.speed * dt_sec # set sprite rectangle position self.rect.x = self.position.x self.rect.y = self.position.y all_sprites = pygame.sprite.Group() player = Player() all_sprites.add(player) #main game loop running = True while running: dt = clock.tick(FPS) dt_sec = dt / 1000.0 # pygame.time.delay(100) #this will be a clock for the game for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False # update #player.set_time_passed_sec(dt) all_sprites.update(dt) screen.fill(BLACK) all_sprites.draw(screen) v_dir = Vector2(player.direction.x, player.direction.y) v_dir *= 100 draw_vector(screen, (player.rect.center[0], player.rect.center[1]), v_dir, BLUE, 4) pygame.display.update() # exit pygame pygame.quit() exit() <file_sep>import cocos from cocos.director import director from pyglet.window import mouse from cocos.scenes import * from random import randint, shuffle import pyglet # This needs to be on the top, otherwise the SceneManager won't work director.init(width=1024, height=576, caption="Match the Shapes!") director.window.pop_handlers() director.window.set_location(400, 200) def load_score(file): with open(file, 'r') as f: score = f.read() return score def save_score(file, scr): with open(file, 'w') as f: f.write(str(scr)) def calculate_score(score): current_time = score loaded_time = load_score("res/score.txt") current_minutes = current_time.split(":")[0] current_seconds = current_time.split(":")[1] loaded_minutes = loaded_time.split(":")[0] loaded_seconds = loaded_time.split(":")[1] time1 = int(current_minutes) * 60 + int(current_seconds) time2 = int(loaded_minutes) * 60 + int(loaded_seconds) if time1 < time2: return True return False """ ALL THE GAME RELATED LAYERS """ class CardLayer(cocos.layer.Layer): is_event_handler = True def __init__(self, image_path): super().__init__() self.clicked = False self.spr = cocos.sprite.Sprite(image_path, anchor=(0, 0)) self.name = image_path.split("/")[2].split(".")[0] self.back = cocos.sprite.Sprite('res/sprites/back.png', anchor=(0, 0)) self.add(self.spr) self.add(self.back) def card_clicked(self, x, y): return x < self.spr.x + self.spr.width and x > self.spr.x and y < self.spr.y + self.spr.height and y > self.spr.y def on_mouse_press(self, x, y, button, modifiers): if button & mouse.LEFT: if self.card_clicked(x, y) and len(CardManager.cards_clicked) < 2: self.clicked = True self.back.visible = False else: self.clicked = False if self.clicked and self not in CardManager.cards_clicked: CardManager.cards_clicked.append(self) CardManager.check_cards() class CardManager(): cards_clicked = [] pairs = 0 def __init__(self): """ 6 x=3, y=2 12 x=4, y=3 20 x=5, y=4 24 x=6, y=4 """ self.level1 = 6 # number of cards at the start of the game self.level2 = 12 self.level3 = 20 self.level4 = 24 self.current_level = self.level4 path = "res/sprites/" files = [path + "circle_blue.png", path + "circle_green.png", path + "circle_red.png", path + "penta_blue.png", path + "penta_green.png", path + "penta_red.png", path + "rect_blue.png", path + "rect_green.png", path + "rect_red.png", path + "star_blue.png", path + "star_green.png", path + "star_red.png"] random_list = [] for i in range(self.current_level // 2): r = randint(0, len(files) - 1) if files[r] not in random_list: random_list.append(files[r]) random_list.append(files[r]) else: while files[r] in random_list: r = randint(0, len(files) - 1) random_list.append(files[r]) random_list.append(files[r]) shuffle(random_list) positions = self.calc_positions() for i, file in enumerate(random_list): card = CardLayer(file) card.spr.image_anchor_x = 0 card.spr.image_anchor_y = 0 card.spr.position = positions[i] card.back.position = card.spr.position SceneManager.game_scene.add(card) def calc_positions(self): xx, yy = 0, 0 if self.current_level == self.level1: xx, yy = 3, 2 elif self.current_level == self.level2: xx, yy = 4, 3 elif self.current_level == self.level3: xx, yy = 5, 4 elif self.current_level == self.level4: xx, yy = 6, 4 positions = [] x_offset = 50 y_offset = 50 for x in range(xx): for y in range(yy): positions.append((x_offset, y_offset)) y_offset += 120 x_offset += 120 y_offset = 50 return positions @staticmethod def flip_cards_back(dt): for card in CardManager.cards_clicked: card.back.visible = True CardManager.cards_clicked = [] # need to set this here also @staticmethod def remove_cards(dt): SceneManager.game_scene.remove(CardManager.cards_clicked[0]) SceneManager.game_scene.remove(CardManager.cards_clicked[1]) CardManager.cards_clicked = [] # need to set this here also @staticmethod def check_cards(): if len(CardManager.cards_clicked) == 2: if CardManager.cards_clicked[0].name == CardManager.cards_clicked[1].name: CardManager.pairs += 1 pyglet.clock.schedule_once(CardManager.remove_cards, 0.5) else: pyglet.clock.schedule_once(CardManager.flip_cards_back, 1.0) if CardManager.pairs == 12: CardManager.pairs = 0 GameScene.game_finished = True SceneManager.change_scene(SceneManager.wining_scene) """ ALL THE MENU RELATED LAYERS """ class MainMenu(cocos.menu.Menu): def __init__(self): super().__init__('CARD MATCH!') items = [] items.append(cocos.menu.MenuItem('New Game', self.on_new_game)) items.append(cocos.menu.MenuItem('Best Time', self.on_best_time)) items.append(cocos.menu.MenuItem('Quit', self.on_quit)) self.create_menu(items, cocos.menu.shake(), cocos.menu.shake_back()) def on_new_game(self): SceneManager.change_scene(SceneManager.game_scene) def on_best_time(self): SceneManager.change_scene(SceneManager.best_time_scene) def on_quit(self): director.window.close() # Back to main button class Button(cocos.layer.Layer): is_event_handler = True def __init__(self, pos): super().__init__() self.spr = cocos.sprite.Sprite('res/sprites/back_to_main.png') self.spr.position = pos self.add(self.spr) def button_clicked(self, x, y): return x > self.spr.x - (self.spr.width//2) and x < self.spr.x + (self.spr.width // 2) and \ y > self.spr.y - (self.spr.height//2) and y < self.spr.y + (self.spr.height // 2) def on_mouse_press(self, x, y, button, modifiers): if button & mouse.LEFT: if self.button_clicked(x, y): SceneManager.change_scene(SceneManager.start_scene) def on_mouse_motion(self, x, y, dx, dy): if self.button_clicked(x, y): self.spr.scale = 1.2 else: self.spr.scale = 1 # The Timer class Timer(cocos.layer.Layer): current_time = "" time_start = None time_stop = None def __init__(self): super().__init__() self.label = cocos.text.Label("", font_name="Times New Roman", font_size=26, anchor_x="center", anchor_y="center") self.start_time = 0 self.label.position = 874, 276 self.add(self.label) Timer.time_start = self.run_scheduler Timer.time_stop = self.stop_scheduler def timer(self, dt): if GameScene.game_finished: self.stop_scheduler() self.start_time = 0 GameScene.game_finished = False else: mins, secs = divmod(self.start_time, 60) time_format = '{:02d}:{:02d}'.format(mins, secs) Timer.current_time = time_format self.label.element.text = time_format self.start_time += 1 def run_scheduler(self): self.schedule_interval(self.timer, 1.0) def stop_scheduler(self): self.unschedule(self.timer) """ ALL THE SCENES """ class StartScene(cocos.scene.Scene): def __init__(self): super().__init__() menu = MainMenu() self.add(cocos.layer.ColorLayer(50, 50, 50, 180)) self.add(menu) class GameScene(cocos.scene.Scene): game_finished = False def __init__(self): super().__init__() self.add(cocos.layer.ColorLayer(50, 50, 50, 180)) self.add(Button(pos=(874, 376))) self.add(Timer()) # def on_enter(self): # super().on_enter() # # def on_exit(self): # super().on_exit() class BestTimeScene(cocos.scene.Scene): def __init__(self): super().__init__() self.add(cocos.layer.ColorLayer(50, 50, 50, 180)) self.add(Button(pos=(512, 156))) self.label = cocos.text.Label("", font_name="Times New Roman", font_size=26, anchor_x="center", anchor_y="center", position=(512, 300)) self.add(self.label) def on_enter(self): super().on_enter() self.label.element.text = load_score("res/score.txt") def on_exit(self): super().on_exit() class WinningScene(cocos.scene.Scene): def __init__(self): super().__init__() self.add(cocos.layer.ColorLayer(50, 50, 50, 180)) self.add(Button(pos=(512, 156))) self.add(cocos.text.Label("Your time was:", font_name="Times New Roman", font_size=26, anchor_x="center", anchor_y="center", position=(512,300))) self.score = cocos.text.Label("", font_name="Times New Roman", font_size=22, anchor_x="center", anchor_y="center", position=(512, 220)) self.add(self.score) def on_enter(self): super().on_enter() self.score.element.text = Timer.current_time if calculate_score(Timer.current_time): save_score("res/score.txt", Timer.current_time) def on_exit(self): super().on_exit() """ THE SCENE MANAGER """ class SceneManager: start_scene = StartScene() best_time_scene = BestTimeScene() game_scene = GameScene() wining_scene = WinningScene() active_scene = start_scene @staticmethod def change_scene(scene): SceneManager.active_scene = scene if SceneManager.active_scene == SceneManager.game_scene: CardManager() Timer.time_start() elif SceneManager.active_scene == SceneManager.start_scene: for child in SceneManager.game_scene.get_children(): if hasattr(child, 'name'): child.kill() director.replace(FlipX3DTransition(SceneManager.active_scene, duration=2)) if __name__ == "__main__": director.run(SceneManager.active_scene)<file_sep>import pygame from pygame.locals import * from sys import exit from random import * from math import pi pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() x, y = pygame.mouse.get_pos() angle = (x/639.)*pi*2. screen.fill((255,255,255)) pygame.draw.arc(screen, (0,0,0), (0,0,639,479), 0, angle) pygame.display.update() <file_sep># -*- coding: utf-8 -*- """ Created on Sat Dec 19 10:54:58 2020 @author: crtom """ import numpy as np def var1(): # build a list of touples from two numpy arrays x = np.linspace(0, 500, 6) y = np.linspace(0, 500, 6) z = zip(x,y) print(list(z)) def var2(): # create a list of touple positions lst = [] for x in range(0, 600, 100): for y in range(0, 600, 100): lst.append((x,y)) print(lst) print('first item:',lst[0]) print('last item:',lst[35]) # create a dictionary of grid def var3(): thisdict = { "position_vertice": (0,0), "position_card": (10,10), "surface": 1964 } print(thisdict["position_vertice"]) print(thisdict["position_vertice"]) print(thisdict["surface"]) def var4(): pass #var3() <file_sep># -*- coding: utf-8 -*- """ Created on Sat Dec 26 22:15:23 2020 @author: crtom """ import math class Vector2D: """A two-dimensional vector with Cartesian coordinates.""" def __init__(self, x, y): self.x, self.y = x, y def __str__(self): """Human-readable string representation of the vector.""" return '{:g}i + {:g}j'.format(self.x, self.y) def __repr__(self): """Unambiguous string representation of the vector.""" return repr((self.x, self.y)) def dot(self, other): """The scalar (dot) product of self and other. Both must be vectors.""" if not isinstance(other, Vector2D): raise TypeError('Can only take dot product of two Vector2D objects') return self.x * other.x + self.y * other.y # Alias the __matmul__ method to dot so we can use a @ b as well as a.dot(b). __matmul__ = dot def __sub__(self, other): """Vector subtraction.""" return Vector2D(self.x - other.x, self.y - other.y) def __add__(self, other): """Vector addition.""" return Vector2D(self.x + other.x, self.y + other.y) def __mul__(self, scalar): """Multiplication of a vector by a scalar.""" if isinstance(scalar, int) or isinstance(scalar, float): return Vector2D(self.x*scalar, self.y*scalar) raise NotImplementedError('Can only multiply Vector2D by a scalar') def __rmul__(self, scalar): """Reflected multiplication so vector * scalar also works.""" return self.__mul__(scalar) def __neg__(self): """Negation of the vector (invert through origin.)""" return Vector2D(-self.x, -self.y) def __truediv__(self, scalar): """True division of the vector by a scalar.""" return Vector2D(self.x / scalar, self.y / scalar) def __mod__(self, scalar): """One way to implement modulus operation: for each component.""" return Vector2D(self.x % scalar, self.y % scalar) def __abs__(self): """Absolute value (magnitude) of the vector.""" return math.sqrt(self.x**2 + self.y**2) def distance_to(self, other): """The distance between vectors self and other.""" return abs(self - other) def to_polar(self): """Return the vector's components in polar coordinates.""" return self.__abs__(), math.atan2(self.y, self.x) if __name__ == '__main__': v1 = Vector2D(2, 5/3) v2 = Vector2D(3, -1.5) print('v1 = ', v1) print('repr(v2) = ', repr(v2)) print('v1 + v2 = ', v1 + v2) print('v1 - v2 = ', v1 - v2) print('abs(v2 - v1) = ', abs(v2 - v1)) print('-v2 = ', -v2) print('v1 * 3 = ', v1 * 3) print('7 * v2 = ', 7 * v1) print('v2 / 2.5 = ', v2 / 2.5) print('v1 % 1 = ', v1 % 1) print('v1.dot(v2) = v1 @ v2 = ', v1 @ v2) print('v1.distance_to(v2) = ',v1.distance_to(v2)) print('v1 as polar vector, (r, theta) =', v1.to_polar())<file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 20 15:27:13 2020 @author: crtom """ import pygame def draw_rect_alpha(surface, color, rect): shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA) pygame.draw.rect(shape_surf, color, shape_surf.get_rect()) surface.blit(shape_surf, rect) def draw_circle_alpha(surface, color, center, radius): target_rect = pygame.Rect(center, (0, 0)).inflate((radius * 2, radius * 2)) shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA) pygame.draw.circle(shape_surf, color, (radius, radius), radius) surface.blit(shape_surf, target_rect) def draw_polygon_alpha(surface, color, points): lx, ly = zip(*points) min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly) target_rect = pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y) shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA) pygame.draw.polygon(shape_surf, color, [(x - min_x, y - min_y) for x, y in points]) surface.blit(shape_surf, target_rect) def draw_background(): background = pygame.Surface(window.get_size()) ts, w, h, c1, c2 = 50, *window.get_size(), (160, 160, 160), (192, 192, 192) tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)] for rect, color in tiles: pygame.draw.rect(background, color, rect) window.blit(background, (0, 0)) pygame.init() window = pygame.display.set_mode((250, 250)) clock = pygame.time.Clock() #print(window.get_size()) run = True while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False draw_background() draw_rect_alpha(window, (0, 0, 255, 127), (55, 90, 140, 140)) draw_circle_alpha(window, (255, 0, 0, 127), (150, 100), 80) draw_polygon_alpha(window, (255, 255, 0, 127), [(100, 10), (100 + 0.8660 * 90, 145), (100 - 0.8660 * 90, 145)]) pygame.display.flip() pygame.quit() exit()<file_sep># -*- coding: utf-8 -*- """ Created on Tue Dec 15 18:09:41 2020 @author: crtom """ import pygame import sys #from vector2 import Vector2 #from vector2 import * from gameobjects.vector2 import * from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT # for antialiased from pygame import gfxdraw def draw_circle(surface, x, y, radius, color): gfxdraw.aacircle(surface, x, y, radius, color) gfxdraw.filled_circle(surface, x, y, radius, color) pygame.init() FPS = 30 # frames per second setting fpsClock = pygame.time.Clock() # returns pygame.Surface objet for window DISPLAYSURF = pygame.display.set_mode((400,400)) pygame.display.set_caption('Hello World!') #point A A = (10.0, 10.0) #point B B = (300.0, 300.0) # vector of distance between points AB AB = Vector2.from_points(A, B) # step vector, length of 1/10 AB step = AB * .01 #start position vector at point A position = Vector2(A[0], A[1]) # for n in range(10): # position += step # print(position) #create point #pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness) Running = True while Running: # event handling for event in pygame.event.get(): # event objects have type attribute if event.type == QUIT: Running = False position += step #print(position.x) # clear background DISPLAYSURF.fill((0,0,0)) pygame.draw.line(DISPLAYSURF, (255, 255, 255),(A[0],A[1]),(position.x, position.y)) #pygame.draw.circle(DISPLAYSURF, (255,255,255), (int(position.x), int(position.y)), 5, 0) draw_circle(DISPLAYSURF, int(position.x), int(position.y), 5, (255,255,255)) # check when vector reaches position if position.x >= AB.x and position.y >= AB.y: print('reached pos') Running = False # draws surface object stored in DISPLAYSURF pygame.display.update() #pygame.time.wait(100) fpsClock.tick(FPS) pygame.quit() sys.exit()<file_sep>def alpha_blend(src, dst): return src * src.a + dst * (1.0—src.a) <file_sep># Memory puzzle http://inventwithpython.com/pygame/ http://inventwithpython.com/pygame/chapter3.html - v1: BASIC ARHITECTURE, timing, quit event. stable application - v2: mouse coordinates, events - v3: create playing grid, and clicked positions, game grid, boxes, transformations - v3_2: pixel, grid all using touples - v4: finished grid with dictionary, moved to card logic - v5: creating card icons, list, shuffle icons - v6: creating game logic and state transitions - v7: add animation of turn card around after 2 sec - Making Sure We Have Enough Icons Tuples vs. Lists, Immutable vs. Mutable One Item Tuples Need a Trailing Comma Converting Between Lists and Tuples The global statement, and Why Global Variables are Evil Data Structures and 2D Lists The “Start Game” Animation The Game Loop The Event Handling Loop Checking Which Box The Mouse Cursor is Over Handling the First Clicked Box Handling a Mismatched Pair of Icons Handling If the Player Won Drawing the Game State to the Screen Creating the “Revealed Boxes” Data Structure Creating the Board Data Structure: Step 1 – Get All Possible Icons Step 2 – Shuffling and Truncating the List of All Icons Step 3 – Placing the Icons on the Board Splitting a List into a List of Lists Different Coordinate Systems Converting from Pixel Coordinates to Box Coordinates Drawing the Icon, and Syntactic Sugar Syntactic Sugar with Getting a Board Space’s Icon’s Shape and Color Drawing the Box Cover Handling the Revealing and Covering Animation Drawing the Entire Board Drawing the Highlight The “Start Game” Animation Revealing and Covering the Groups of Boxes The “Game Won” Animation Telling if the Player Has Won Why Bother Having a main() Function?<file_sep>import pygame pygame.init() window = pygame.display.set_mode((300, 300)) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False window.fill(0) rect = pygame.Rect(window.get_rect().center, (0, 0)).inflate(*([min(window.get_size())//2]*2)) for x in range(rect.width): u = x / (rect.width - 1) color = (round(u*255), 0, round((1-u)*255)) for y in range(rect.height): window.set_at((rect.left + x, rect.top + y), color) pygame.display.flip() pygame.quit() exit()<file_sep># game options/settings WIDTH = 360 HEIGHT = 480 FPS = 30 #RGB color constants WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255,0,0) LIME = (0,255,0) BLUE = (0,0,255) YELLOW = (255,255,0) CYAN = (0,255,255) MAGENTA = (255,0,255) SILVER = (192,192,192) GRAY = (128,128,128) MAROON = (128,0,0) OLIVE = (128,128,0) GREEN = (0,128,0) PURPLE = (128,0,128) TEAL = (0,128,128) NAVY = (0,0,128)<file_sep># -*- coding: utf-8 -*- """ Created on Fri Dec 25 21:10:25 2020 @author: crtom """ """ Basic Movement and Key Presses video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5 1. create a rectangle 2. move it by key pressed """ import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 # draw antialiase line for vectors from pygame import gfxdraw from math import * # defines WIDTH, HEIGHT = 640, 480 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255,0,0) LIME = (0,255,0) BLUE = (0,0,255) YELLOW = (255,255,0) CYAN = (0,255,255) MAGENTA = (255,0,255) SILVER = (192,192,192) GREY = (128,128,128) MAROON = (128,0,0) OLIVE = (128,128,0) GREEN = (0,128,0) PURPLE = (128,0,128) TEAL = (0,128,128) NAVY = (0,0,128) pygame.init() #### Create a canvas on which to display everything #### screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) #set windows title pygame.display.set_caption("vector arrow") #### Create a surface with the same size as the window #### background = pygame.Surface((WIDTH, HEIGHT)) background.fill(WHITE) clock = pygame.time.Clock() def draw_point(screen, color, p, radius): #, color, position, radius point = (int(p[0]), int(p[1])) pygame.draw.circle(screen, color, point, radius) def draw_line(screen, color, startpoint, vector, width): """ Draws line representing vector. """ v1 = Vector2(vector.x, vector.y) endpoint = (v1.x + startpoint[0], v1.y + startpoint[1]) startpoint = (int(startpoint[0]), int(startpoint[1])) endpoint = (int(endpoint[0]), int(endpoint[1])) pygame.draw.line(screen, color, startpoint, endpoint, width) # ----------drawing p_A = (WIDTH // 2, HEIGHT // 2) p_B = (WIDTH // 2, 50) vector_AB = Vector2.from_points(p_A, p_B) # print(p_A) # print(p_B) # #as_tuple #------------------------ screen.blit(background, (0,0)) draw_point(screen, RED, p_A, 5) pygame.display.update() draw_point(screen, BLUE, p_B, 5) pygame.display.update() # draw_line(screen, color, startpoint, vector, width): # ORIGINAL VECTOR draw_line(screen, BLACK, p_A, vector_AB, 3) pygame.display.update() # ROTATED VECTOR angle = 45 x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y vector_AB_rot = Vector2(x_rot, y_rot) draw_line(screen, GREY, p_A, vector_AB_rot, 3) # perpendicualar vector vector_AB_perp = Vector2(-vector_AB_rot.y, vector_AB_rot.x) draw_line(screen, GREY, p_A, vector_AB_perp, 3) pygame.display.update() # arrow head to original vector # first find point on original vector that is a little bellow vector endpoint vector_norm = Vector2(vector_AB.x, vector_AB.y) vector_norm.normalise() vector_norm *= 10 vector_norm = vector_AB - vector_norm draw_line(screen, GREY, p_A, vector_norm, 3) pygame.display.update() # find perpendicular vector to original vector_perp = Vector2(-vector_AB.y, vector_AB.x) vector_perp.normalise() vector_perp *= 5 point = (int(vector_norm.x) + p_A[0], int(vector_norm.y) + p_A[1]) point = (point[0], point[1]) draw_point(screen, BLACK, point, 5) draw_line(screen, GREY, point, vector_perp, 3) draw_line(screen, GREY, point, -vector_perp, 3) # pointL = original_vector_startpoint+ point_R = (point[0] + vector_perp.x, point[1] + vector_perp.y) point_L = (point[0] - vector_perp.x, point[1] - vector_perp.y) draw_point(screen, BLACK, point_R, 5) draw_point(screen, BLACK, point_L, 5) endpoint = vector_AB.x+ p_A[0], vector_AB.y + p_A[1] # draw rectangle pygame.draw.polygon(screen, GREEN, (point_L, point_R, endpoint)) pygame.display.update() print(vector_AB) print(vector_norm) print(point) print(vector_perp) # draw_line(screen, RED, p_A, vector_a, 3) # pygame.display.update() #---------------------- #main game loop clock = pygame.time.Clock() run = True angle = 0. while run: # pygame.time.delay(100) #this will be a clock for the game for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False # calculate times time_passed = clock.tick(30) time_passed_seconds = time_passed / 1000.0 # exit pygame pygame.quit() exit() """ #draw_arrow(screen, 0, 10, GREEN) #------------------DRAWINGS------------------------ #### Blit the surface onto the canvas #### screen.blit(background,(0,0)) #### Blit the points onto canvas angle += 0.01 #draw_arrow(screen, colour, startpoint, vector, width): draw_point(screen, BLUE, p_A, 5) #draw_point(screen, GREEN, p_B, 5) draw_arrow(screen, BLUE, p_A, vector_AB_rot, 2) #screen.blit(arrow, arrow_pos) #### display canvas #### pygame.display.update() x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y vector_AB_rot = Vector2(x_rot, y_rot) """<file_sep>""" Game Template """ import sys import pygame as pg from pygame.locals import* import random from settings import * import time import math WIDTH, HEIGHT = 200, 200 # initialize pygame and create a window pg.init() pg.mixer.init() screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption("My Game") clock = pg.time.Clock() all_sprites = pg.sprite.Group() # game loop running = True while running: # keep looping at the right speed clock.tick(FPS) # process input (events) for event in pg.event.get(): #check for all events that are happening if event.type == pg.QUIT: running = False if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE: running = False # Update all_sprites.update() # draw/render screen.fill(BLACK) all_sprites.draw(screen) # after drawing everything, flip the display pg.display.update() pg.quit()<file_sep>""" Simple pong in python 3 for begginers tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2 """ import turtle wn = turtle.Screen() wn.title("Pong by @TokyoEdTech") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) # main game loop while True: wn.update() #updates screen<file_sep>glBegin(GL_QUADS) glColor(1.0, 0.0, 0.0) # Red glVertex(100.0, 100.0, 0.0) # Top left glVertex(200.0, 100.0, 0.0) # Top right glVertex(200.0, 200.0, 0.0) # Bottom right glVertex(100.0, 200.0, 0.0) # Bottom left glEnd() <file_sep>""" Python: Bouncing Ball Animation with Real-World Physics!! video: https://www.youtube.com/watch?v=9LWpCtbSvG4 Analyst Rising 1.36K subscribers In this tutorial I will be showing you how to code/programme a bouncing ball, with REAL-WORLD PHYSICS, in Python. This is one of many great python tutorials that should get you well on your way to programming some amazing stuff!! """ import pygame from pygame.locals import * import time pygame.init() #---------game constants variables------------- display_width = 300 display_height = 400 #RGB color constants black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) update_ms = 100 frame_speed_sec = (1/update_ms)*1000 #------------------------------------------------------ #create main display window gameDisplay = pygame.display.set_mode((display_width,display_height)) #set main display window title pygame.display.set_caption('gameDisplay') clock = pygame.time.Clock() #----------------------FUNCTIONS------------------------- def fps_display_counter(count): #1. set type font font = pygame.font.SysFont(None,25) #2. render it text = font.render("FPS count: " + str(count),True,white) #3. blit = draw gameDisplay.blit(text,(0,0)) class Particle(object): def __init__(self, x, y, size, colour, thickness): self.x = x self.y = y self.size = size self.colour = colour self.thickness = thickness def display(self): #pygame.draw. pygame.draw.circle(gameDisplay, self.colour, (self.x, self.y), self.size, self.thickness) def game_loop(frame_speed): #main game loop run = True counter = 0 velocity_x = 10 velocity_y = -10 gravity = 0.7 friction = 0.5 while run: counter += 1 #-----------check for pressed keys---------------- for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False #------------------------------------------------- #CONSTRAINTS X if particle.x - particle.size <= 0 or particle.size + particle.x >= display_width: velocity_x = -velocity_x #CONSTRAINTS Y if particle.y - particle.size <= 0 or particle.size + particle.y >= display_height: velocity_y = -velocity_y particle.x += velocity_x particle.y += velocity_y #------------------------------------------------- gameDisplay.fill(black) # draw background fps_display_counter(counter) particle.display() #draw particle ball pygame.display.update() #update display clock.tick(frame_speed) #set FPS update frequency #--------------------------------------- #-----------initialization-------------- particle = Particle(x=150, y=50, size=10, colour=white, thickness=0) #-------------main loop----------------- game_loop(frame_speed_sec) #--------------------------------------- #---------------------------------------<file_sep>def lerp(value1, value2, factor): return value1+(value2-value1)*factor print(lerp(100, 200, 0.)) print(lerp(100, 200, 1.)) print(lerp(100, 200, .5)) print(lerp(100, 200, .25)) <file_sep>"""Snake Game Python Tutorial youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo current time: 33:00 """ import sys import math import random import pygame from pygame.locals import * import tkinter as tk from tkinter import messagebox WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255) class cube(object): """ """ w = 500 #set pixel screen width rows = 20 #set number of rows def __init__(self,start,dirnx=1,dirny=0,color=RED): self.pos = start self.dirnx = 1 self.dirny = 0 self.color = color def move(self,dirnx,dirny): """ move cube, by adding new direction to previous position """ self.dirnx = dirnx self.dirny = dirny self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny) def draw(self,surface,eyes=False): """ drawing: convert x,y grid position to pixel position """ dis = self.w // self.rows #distance between x and y values #variables for easy coding i = self.pos[0] # row j = self.pos[1] # column #draw just a little bit less, so we draw inside of the square. and we dont cover grid. pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 )) #draw eyes if eyes: centre = dis//2 radius = 3 circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1 circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2 pygame.draw.circle(surface, BLACK, circleMiddle, radius) pygame.draw.circle(surface, BLACK, circleMiddle2, radius) def drawGrid(w,rows,surface): """ This function draws a square grid on main display """ #distance between grid lines sizeBtwn = w // rows x = 0 y = 0 #create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn #vertical lines pygame.draw.line(surface, WHITE, (x,0), (x,w)) #horizontal lines pygame.draw.line(surface, WHITE, (0,y), (w,y)) def redrawWindow(surface): global rows, width, s #background surface.fill(BLACK) #draw grid drawGrid(width, rows, surface) #update display pygame.display.update() def main(): global width, rows, s #create game display width = 500 rows = 20 win = pygame.display.set_mode((width, width)) #square display clock = pygame.time.Clock() flag = True FPScount = 0 print(FPScount) while flag: #pygame.time.delay(50) clock.tick(10) #game max speed 10 FPS s.move() redrawWindow(win) FPScount += 1 print(f'FPScount:{FPScount}') #rows = 0 #w = 0 #h = 0 #cube.rows = rows #cube.w = w main() pygame.quit() sys.exit()<file_sep>"""Summary Attributes: BLACK (tuple): Description BLUE (tuple): Description CYAN (tuple): Description FPS (int): Description GRAY (tuple): Description GREEN (tuple): Description HEIGHT (int): Description LIME (tuple): Description MAGENTA (tuple): Description MAROON (tuple): Description NAVY (tuple): Description OLIVE (tuple): Description PURPLE (tuple): Description RED (tuple): Description SILVER (tuple): Description TEAL (tuple): Description TITLE (str): Description WHITE (tuple): Description WIDTH (int): Description YELLOW (tuple): Description """ # game options/settings TITLE = "Doodle Jump!" WIDTH = 480 HEIGHT = 600 WIDTH_MID = WIDTH // 2 HEIGHT_MID = HEIGHT // 2 FPS = 60 FONT_NAME = 'arial' HIGHSCORE_FILE = "highscore.txt" SPRITESHEET_FILE ="spritesheet_jumper.png" #player properties #if positive = move DOWN, negative = move UP PLAYER_ACC = 0.7 PLAYER_FRICTION = -0.1 PLAYER_GRAVITY = 1 PLAYER_JUMP_VELOCITY = -40 # Starting platforms Platform(x, y, width, height) PLATFORM_LIST = [ (0, HEIGHT - 60), (WIDTH//2-50, HEIGHT*3/4), (125, HEIGHT-350), (350, 200), (175, 100) ] #RGB color constants BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255,0,0) LIME = (0,255,0) BLUE = (0,0,255) YELLOW = (255,255,0) CYAN = (0,255,255) MAGENTA = (255,0,255) SILVER = (192,192,192) GRAY = (128,128,128) MAROON = (128,0,0) OLIVE = (128,128,0) GREEN = (0,128,0) PURPLE = (128,0,128) TEAL = (0,128,128) NAVY = (0,0,128) BG_COLOR = TEAL PLATFORM_COLOR = LIME<file_sep>link to the site [Making Games with Python & Pygame (inventwithpython.com)](http://inventwithpython.com/pygame/) <file_sep># Beginning-Game-Development-with-Python-and-Pygame Source Code from Beginning Game Development with Python and Pygame by <NAME> and <NAME> Code is organized by chapter, denoted by the listing name. As the book progresses, we use more and more of the gameobjects library. <file_sep>import math class Vector2: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "(%s, %s)"%(self.x, self.y) def from_points(P1, P2): return Vector2( P2[0] - P1[0], P2[1] - P1[1] ) def get_magnitude(self): return math.sqrt( self.x**2 + self.y**2 ) def normalize(self): magnitude = self.get_magnitude() self.x /= magnitude self.y /= magnitude def __add__(self, rhs): return Vector2(self.x + rhs.x, self.y + rhs.y) def __sub__(self, rhs): return Vector2(self.x - rhs.x, self.y - rhs.y) def __neg__(self): return Vector2(-self.x, -self.y) def __mul__(self, scalar): return Vector2(self.x * scalar, self.y * scalar) def __truediv__(self, scalar): return Vector2(self.x / scalar, self.y / scalar) A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) step = AB * .1 position = Vector2(*A) for n in range(10): position += step print(position) <file_sep>class World(object): def __init__(self): self.entities = {} # Store all the entities self.entity_id = 0 # Last entity id assigned # Draw the nest (a circle) on the background self.background = pygame.surface.Surface(SCREEN_SIZE).convert() self.background.fill((255, 255, 255)) pygame.draw.circle(self.background, (200, 255, 200), NEST_POSITION, int(NEST_SIZE)) def add_entity(self, entity): # Stores the entity then advances the current id self.entities[self.entity_id] = entity entity.id = self.entity_id self.entity_id += 1 def remove_entity(self, entity): del self.entities[entity.id] def get(self, entity_id): # Find the entity, given its id (or None if it is not found) if entity_id in self.entities: return self.entities[entity_id] else: return None def process(self, time_passed): # Process every entity in the world time_passed_seconds = time_passed / 1000.0 for entity in self.entities.itervalues(): entity.process(time_passed_seconds) def render(self, surface): # Draw the background and all the entities surface.blit(self.background, (0, 0)) for entity in self.entities.values(): entity.render(surface) def get_close_entity(self, name, location, e_range=100): # Find an entity within range of a location location = Vector2(*location) for entity in self.entities.values(): if entity.name == name: distance = location.get_distance_to(entity.location) if distance < e_range: return entity return None <file_sep>Welcome to <NAME>'s minigame repository. This repository will contain all of the codes from my minigames, written mainly in python and also Lua. <file_sep># -*- coding: utf-8 -*- """ Created on Thu Dec 24 11:31:56 2020 @author: crtom """ import math import random class Vector: def __init__(self, x: float, y: float): self.x = x self.y = y # Vector operator overload # theory: when called a + b, python calls a.__add__(b) # we now overrdide this methods def __add__(self, other): if isinstance (other, self.__class__): return Vector(self.x + other.x, self.y + other.y ) return Vector(self.x + other, self.y + other) def __sub__(self, other): if isinstance (other, self.__class__): return Vector(self.x - other.x, self.y - other.y ) return Vector(self.x - other, self.y - other) def __mul__(self, other): if isinstance (other, self.__class__): return Vector(self.x * other.x, self.y * other.y ) return Vector(self.x * other, self.y * other) # # reverse multiply override # def __rmul__(self, other): # return Vector(self.x * other, self.y * other) def __rmul__(self, other): return self.__mul__(other) # commutative operation def __truediv__(self, other): if isinstance (other, self.__class__): return Vector(self.x / other.x, self.y / other.y ) return Vector(self.x / other, self.y / other) # check for equal def __eq__(self, other): if isinstance (other, self.__class__): return self.x == other.x and self.y == other.y return self.x == other and self.y == other def make_int_tuple(self): return int(self.x), int(self.y) def set(self, vec): self.x = vec.x self.y = vec.y #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # additional vector calculations # Skalarni produkt (Dot product) #Rezultat se izračuna kot produkt dolžin obeh vektorjev in kosinusa vmesnega kota. def dot(vec1, vec2): return vec1.x * vec2.x + vec1.y * vec2.y # calculate vector angle # angle = arccos[(xa * xb + ya * yb) / (√(xa2 + ya2) * √(xb2 + yb2))] def angle_between(vec1, vec2): return math.acos(dot(vec1, vec2)) #----------------------------------------------------------------------------- #----------------------DISTANCE AND LENGTH FUNCTIONS-------------------------- #----------------------------------------------------------------------------- # vector lengt squared, faster # pitagora a^2+b^2 = c^2 def length_sqr(vec): return vec.x**2 + vec.y**2 # vector length def length(vec): return math.sqrt(length_sqr(vec)) # distance between vector squared, faster def dist_sqr(vec1, vec2): return length_sqr(vec1 - vec2) # distance between vector squared, faster def dist(vec1, vec2): return length(vec1 - vec2) # create a unit vector def normalize(vec): vec_length = length(vec) # check if null size if vec_length < 0.00001: return Vector(0, 1) # return unit vector return Vector(vec.x / vec_length, vec.y / vec_length) # reflections def reflect(incident, normal): return incident - dot(normal, incident) * 2.0 * normal def negate(vec): return Vector(-vec.x, -vec.y) # rotation 90deg clockwise, perpendicual def right(vec): return Vector(-vec.y, vec.x) def left(vec): return negate(right(vec)) # create a random vector def random_vector(): return Vector(random.random()*2.0 - 1.0, random.random()*2.0-1.0) def random_direction(): return normalize(random_vector()) # so we dont have any issues with references def copy(vec): return Vector(vec.x, vec.y) # ---------- testing code def test_operator_overloads(): a = Vector(5, 10) b = Vector(-5, 10) print(a.x, a.y) print(b.x, b.y) c = a + b #Vector class using __add__ operator overload print('__add__:', c.x, c.y) c = a - b #Vector class using __add__ operator overload print('__sub__:', c.x, c.y) c = a * b #Vector class using __add__ operator overload print('__mul__:', c.x, c.y) # normal operator overload c = a * 10 print('__mul__:', c.x, c.y) # reverse operator overload c = 10 * a print('__rmul__:', c.x, c.y) c = a / b #Vector class using __add__ operator overload print('__truediv__:', c.x, c.y) def test_functions(): a = Vector(1, 1) b = Vector(0, 0) print('a = Vector(1, 1): ', a.x, a.y) print('b = Vector(0, 0)', b.x, b.y) print('Skalarni produkt (Dot product):', dot(a, b)) print('angle_between a and b :', angle_between(a, b)) print('length of vector a:', length(a)) print('length_squared:', length_sqr(a)) if __name__ == '__main__': test_functions()<file_sep># Pong - create a game grid<file_sep>from OpenGL.GL import * from OpenGL.GLU import * import pygame import os.path class Material(object): def init (self): self.name = "" self.texture_fname = None self.texture_id = None class FaceGroup(object): def init (self): self.tri_indices = [] self.material_name = "" class Model3D(object): def init (self): self.vertices = [] self.tex_coords = [] self.normals = [] self.materials = {} self.face_groups = [] # Display list id for quick rendering self.display_list_id = None <file_sep>import arcade # Physics MOVEMENT_SPEED = 8 JUMP_SPEED = 28 GRAVITY = 1.1 # Map MAP_WIDTH = 40 * 128 MAP_HEIGHT = 7 * 128 TILE_WIDTH = 128 # Window WINDOW_WIDTH = 1280 WINDOW_HEIGHT = 896 WINDOW_HALF_WIDTH = WINDOW_WIDTH // 2 class MyGameWindow(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) self.set_location(400, 100) arcade.set_background_color(arcade.color.BLACK) self.ground_list = None self.coins_list = None self.player_list = None self.player_sprite = None self.physics_engine = None self.collected_coins = 0 self.setup() def setup(self): my_map = arcade.read_tiled_map("maps/my-map1.tmx", 1) self.ground_list = arcade.generate_sprites(my_map, "ground", 1) self.coins_list = arcade.generate_sprites(my_map, "coins", 1) self.player_list = arcade.SpriteList() self.player_sprite = arcade.Sprite("images/character.png", 1) self.player_sprite.center_x = 640 self.player_sprite.center_y = 350 self.player_list.append(self.player_sprite) self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite, self.ground_list, gravity_constant=GRAVITY) def on_draw(self): arcade.start_render() self.ground_list.draw() self.player_list.draw() self.coins_list.draw() arcade.draw_text(f"collected coins: {self.collected_coins}", arcade.get_viewport()[0] + 10, arcade.get_viewport()[2] + 866, arcade.color.GOLD, font_size=20) def clamp(self, value, mini, maxi): return max(min(value, maxi), mini) def on_update(self, delta_time): self.physics_engine.update() self.player_sprite.center_x = self.clamp(self.player_sprite.center_x, 0, MAP_WIDTH) if self.player_sprite.center_x > WINDOW_HALF_WIDTH and self.player_sprite.center_x < MAP_WIDTH - TILE_WIDTH - WINDOW_HALF_WIDTH: change_view = True else: change_view = False if change_view: arcade.set_viewport(self.player_sprite.center_x - WINDOW_HALF_WIDTH, self.player_sprite.center_x + WINDOW_HALF_WIDTH, 0, WINDOW_HEIGHT) coins_hit = arcade.check_for_collision_with_list(self.player_sprite, self.coins_list) for coin in coins_hit: self.collected_coins += 1 coin.kill() def on_key_press(self, symbol, modifiers): if symbol == arcade.key.RIGHT: self.player_sprite.change_x = MOVEMENT_SPEED if symbol == arcade.key.LEFT: self.player_sprite.change_x = -MOVEMENT_SPEED if symbol == arcade.key.UP: if self.physics_engine.can_jump(): self.player_sprite.change_y = JUMP_SPEED def on_key_release(self, symbol, modifiers): if symbol == arcade.key.LEFT or symbol == arcade.key.RIGHT: self.player_sprite.change_x = 0 MyGameWindow(WINDOW_WIDTH, WINDOW_HEIGHT, 'Simple Platformer template') arcade.run() <file_sep> # calculation positions Listing 5-14. Calculating Positions ```python # point A A = (10.0, 20.0) # Point B B = (30.0, 35.0) # vector of distance between points AB AB = Vector2.from_points(A, B) # step vector, length of 1/10 AB step = AB * .1 #start position vector at point A position = Vector2(A[0], A[1]) for n in range(10): position += step print(position) ``` <file_sep>pygame.mixer.music.load("techno.ogg") pygame.mixer.music.play() <file_sep> def read_obj(self, fname): current_face_group = None file_in = open(fname) for line in file_in: # Parse command and data from each line words = line.split() command = words[0] data = words[1:] if command == 'mtllib': # Material library model_path = os.path.split(fname)[0] mtllib_path = os.path.join( model_path, data[0] ) self.read_mtllib(mtllib_path) elif command == 'v': # Vertex x, y, z = data vertex = (float(x), float(y), float(z)) self.vertices.append(vertex) elif command == 'vt': # Texture coordinate s, t = data tex_coord = (float(s), float(t)) self.tex_coords.append(tex_coord) elif command == 'vn': # Normal x, y, z = data normal = (float(x), float(y), float(z)) self.normals.append(normal) elif command == 'usemtl' : # Use material current_face_group = FaceGroup() current_face_group.material_name = data[0] self.face_groups.append( current_face_group ) elif command == 'f': assert len(data) == 3, "Sorry, only triangles are supported" # Parse indices from triples for word in data: vi, ti, ni = word.split('/') indices = (int(vi) - 1, int(ti) - 1, int(ni) - 1) current_face_group.tri_indices.append(indices) for material in self.materials.values(): model_path = os.path.split(fname)[0] texture_path = os.path.join(model_path, material.texture_fname) texture_surface = pygame.image.load(texture_path) texture_data = pygame.image.tostring(texture_surface, 'RGB', True) material.texture_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, material.texture_id) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glPixelStorei(GL_UNPACK_ALIGNMENT,1) width, height = texture_surface.get_rect().size gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, texture_data) <file_sep># -*- coding: utf-8 -*- """ Created on Tue Dec 15 18:09:41 2020 @author: crtom """ import pygame import sys from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT pygame.init() # returns pygame.Surface objet for window DISPLAYSURF = pygame.display.set_mode((400,300)) pygame.display.set_caption('Hello World!') while True: # event handling for event in pygame.event.get(): # event objects have type attribute if event.type == QUIT: pygame.quit() sys.exit() # draws surface object stored in DISPLAYSURF pygame.display.update() pygame.time.wait(100)<file_sep>import pygame import os letterX = pygame.image.load(os.path.join('res', 'letterX.png')) letterO = pygame.image.load(os.path.join('res', 'letterO.png')) class Grid: def __init__(self): self.grid_lines = [((0,200), (600,200)), # first horizontal line ((0,400), (600,400)), # second horizontal line ((200,0), (200,600)), # first vertical line ((400,0), (400,600))] # second vertical line self.grid = [[0 for x in range(3)] for y in range(3)] self.switch_player = True # search directions N NW W SW S SE E NE self.search_dirs = [(0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)] self.game_over = False def draw(self, surface): for line in self.grid_lines: pygame.draw.line(surface, (200,200,200), line[0], line[1], 2) for y in range(len(self.grid)): for x in range(len(self.grid[y])): if self.get_cell_value(x, y) == "X": surface.blit(letterX, (x*200, y*200)) elif self.get_cell_value(x, y) == "O": surface.blit(letterO, (x*200, y*200)) def get_cell_value(self, x, y): return self.grid[y][x] def set_cell_value(self, x, y, value): self.grid[y][x] = value def get_mouse(self, x, y, player): if self.get_cell_value(x, y) == 0: self.switch_player = True if player == "X": self.set_cell_value(x, y, "X") elif player == "O": self.set_cell_value(x, y, "O") self.check_grid(x, y, player) else: self.switch_player = False def is_within_bounds(self, x, y): return x >= 0 and x < 3 and y >= 0 and y < 3 def check_grid(self, x, y, player): count = 1 for index, (dirx, diry) in enumerate(self.search_dirs): if self.is_within_bounds(x+dirx, y+diry) and self.get_cell_value(x+dirx, y+diry) == player: count += 1 xx = x + dirx yy = y + diry if self.is_within_bounds(xx+dirx, yy+diry) and self.get_cell_value(xx+dirx, yy+diry) == player: count += 1 if count == 3: break if count < 3: new_dir = 0 # mapping the indices to opposite direction: 0-4 1-5 2-6 3-7 4-0 5-1 6-2 7-3 if index == 0: new_dir = self.search_dirs[4] # N to S elif index == 1: new_dir = self.search_dirs[5] # NW to SE elif index == 2: new_dir = self.search_dirs[6] # W to E elif index == 3: new_dir = self.search_dirs[7] # SW to NE elif index == 4: new_dir = self.search_dirs[0] # S to N elif index == 5: new_dir = self.search_dirs[1] # SE to NW elif index == 6: new_dir = self.search_dirs[2] # E to W elif index == 7: new_dir = self.search_dirs[3] # NE to SW if self.is_within_bounds(x + new_dir[0], y + new_dir[1]) \ and self.get_cell_value(x + new_dir[0], y + new_dir[1]) == player: count += 1 if count == 3: break else: count = 1 if count == 3: print(player, 'wins!') self.game_over = True else: self.game_over = self.is_grid_full() def is_grid_full(self): for row in self.grid: for value in row: if value == 0: return False return True def clear_grid(self): for y in range(len(self.grid)): for x in range(len(self.grid[y])): self.set_cell_value(x, y, 0) def print_grid(self): for row in self.grid: print(row) <file_sep>tank.explode() # Do explosion visual explosion_channel = explosion_sound.play() if explosion_channel is not None: left, right = stereo_pan(tank.position.x, SCREEN_SIZE[0]) explosion_channel.set_volume(left, right) <file_sep>self.move_forward() if self.hit_wall(): self.change_direction() <file_sep> def __del__(self): #Called when the model is cleaned up by Python self.free_resources() def free_resources(self): # Delete the display list and textures if self.display_list_id is not None: glDeleteLists(self.display_list_id, 1) self.display_list_id = None # Delete any textures we used for material in self.materials.values(): if material.texture_id is not None: glDeleteTextures(material.texture_id) # Clear all the materials self.materials.clear() # Clear the geometry lists del self.vertices[:] del self.tex_coords[:] del self.normals[:] del self.face_groups[:] <file_sep>from math import radians from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * # Import the Model3D class import model3d SCREEN_SIZE = (800, 600) def resize(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60.0, float(width)/height, .1, 1000.) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def init(): # Enable the GL features we will be using glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glEnable(GL_TEXTURE_2D) glShadeModel(GL_SMOOTH) # Enable light 1 and set position glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glLight(GL_LIGHT0, GL_POSITION, (0, .5, 1)) def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN|HWSURFACE|OPENGL|DOUBLEBUF) resize(*SCREEN_SIZE) init() # Read the skybox model sky_box = model3d.Model3D() sky_box.read_obj('tanksky/skybox.obj') # Set the wraping mode of all textures in the sky-box to GL_CLAMP_TO_EDGE for material in sky_box.materials.values(): glBindTexture(GL_TEXTURE_2D, material.texture_id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) # Used to rotate the world mouse_x = 0.0 mouse_y = 0.0 #Don't display the mouse cursor pygame.mouse.set_visible(False) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() if event.type == KEYDOWN: pygame.quit() quit() # We don't need to clear the color buffer (GL_COLOR_BUFFER_BIT) # because the skybox covers the entire screen glClear(GL_DEPTH_BUFFER_BIT) glLoadIdentity() mouse_rel_x, mouse_rel_y = pygame.mouse.get_rel() mouse_x += float(mouse_rel_x) / 5.0 mouse_y += float(mouse_rel_y) / 5.0 # Rotate around the x and y axes to create a mouse-look camera glRotatef(mouse_y, 1, 0, 0) glRotatef(mouse_x, 0, 1, 0) # Disable lighting and depth test glDisable(GL_LIGHTING) glDepthMask(False) # Draw the skybox sky_box.draw_quick() # Re-enable lighting and depth test before we redraw the world glEnable(GL_LIGHTING) glDepthMask(True) # Here is where we would draw the rest of the world in a game pygame.display.flip() if __name__ == "__main__": run() <file_sep>import pygame from pygame.locals import * from random import randint from gameobjects.vector2 import Vector2 SCREEN_SIZE = (640, 480) # In pixels per second, per second GRAVITY = 250.0 # Increase for more bounciness, but don't go over 1! BOUNCINESS = 0.7 def stero_pan(x_coord, screen_width): right_volume = float(x_coord) / screen_width left_volume = 1.0 - right_volume return (left_volume, right_volume) class Ball(object): def __init__(self, position, speed, image, bounce_sound): self.position = Vector2(position) self.speed = Vector2(speed) self.image = image self.bounce_sound = bounce_sound self.age = 0.0 def update(self, time_passed): w, h = self.image.get_size() screen_width, screen_height = SCREEN_SIZE x, y = self.position x -= w/2 y -= h/2 # Has the ball bounce bounce = False # Has the ball hit the bottom of the screen? if y + h >= screen_height: self.speed.y = -self.speed.y * BOUNCINESS self.position.y = screen_height - h / 2.0 - 1.0 bounce = True # Has the ball hit the left of the screen? if x <= 0: self.speed.x = -self.speed.x * BOUNCINESS self.position.x = w / 2.0 + 1 bounce = True # Has the ball hit the right of the screen elif x + w >= screen_width: self.speed.x = -self.speed.x * BOUNCINESS self.position.x = screen_width - w / 2.0 - 1 bounce = True # Do time based movement self.position += self.speed * time_passed # Add gravity self.speed.y += time_passed * GRAVITY if bounce: self.play_bounce_sound() self.age += time_passed def play_bounce_sound(self): channel = self.bounce_sound.play() if channel is not None: # Get the left and right volumes left, right = stero_pan(self.position.x, SCREEN_SIZE[0]) channel.set_volume(left, right) def render(self, surface): # Draw the sprite center at self.position w, h = self.image.get_size() x, y = self.position x -= w/2 y -= h/2 surface.blit(self.image, (x, y)) def run(): # Initialise 44KHz 16-bit stero sound pygame.mixer.pre_init(44100, 16, 2, 1024*4) pygame.init() pygame.mixer.set_num_channels(8) screen = pygame.display.set_mode(SCREEN_SIZE, 0) print(pygame.display.get_wm_info()) hwnd = pygame.display.get_wm_info()["window"] x, y = (200, 200) pygame.mouse.set_visible(False) clock = pygame.time.Clock() ball_image = pygame.image.load("ball.png").convert_alpha() mouse_image = pygame.image.load("mousecursor.png").convert_alpha() # Load the sound file bounce_sound = pygame.mixer.Sound("bounce.wav") balls = [] while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() if event.type == MOUSEBUTTONDOWN: # Create a new ball at the mouse position random_speed = ( randint(-400, 400), randint(-300, 0) ) new_ball = Ball( event.pos, random_speed, ball_image, bounce_sound ) balls.append(new_ball) time_passed_seconds = clock.tick() / 1000. screen.fill((255, 255, 255)) dead_balls = [] for ball in balls: ball.update(time_passed_seconds) ball.render(screen) # Make not of any balls that are older than 10 seconds if ball.age > 10.0: dead_balls.append(ball) # remove any 'dead' balls from the main list for ball in dead_balls: balls.remove(ball) # Draw the mouse cursor mouse_pos = pygame.mouse.get_pos() screen.blit(mouse_image, mouse_pos) pygame.display.update() if __name__ == "__main__": run() <file_sep>from math import radians from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * SCREEN_SIZE = (800, 600) def resize(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60.0, float(width)/height, .1, 1000.) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def init(): glEnable(GL_TEXTURE_2D) glClearColor(1.0, 1.0, 1.0, 0.0) def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF) resize(*SCREEN_SIZE) init() # Load the textures texture_surface = pygame.image.load("sushitex.png") # Retrieve the texture data texture_data = pygame.image.tostring(texture_surface, 'RGB', True) # Generate a texture id texture_id = glGenTextures(1) # Tell OpenGL we will be using this texture id for texture operations glBindTexture(GL_TEXTURE_2D, texture_id) # Tell OpenGL how to scale images glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) # Tell OpenGL that data is aligned to byte boundries glPixelStorei(GL_UNPACK_ALIGNMENT, 1) # Get the dimensions of the image width, height = texture_surface.get_rect().size gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, texture_data ) clock = pygame.time.Clock() tex_rotation = 0.0 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() time_passed = clock.tick() time_passed_seconds = time_passed / 1000. tex_rotation += time_passed_seconds * 360.0 / 8.0 # Clear the screen (similar to fill) glClear(GL_COLOR_BUFFER_BIT) # Clear the model-view matrix glLoadIdentity() # Set the modelview matrix glTranslatef(0.0, 0.0, -600.0) glRotate(tex_rotation, 1, 0, 0) # Draw a quad (4 vertices, 4 texture coords) glBegin(GL_QUADS) glTexCoord2f(0, 3) glVertex3f(-300, 300, 0) glTexCoord2f(3, 3) glVertex3f(300, 300, 0) glTexCoord2f(3, 0) glVertex3f(300, -300, 0) glTexCoord2f(0, 0) glVertex3f(-300, -300, 0) glEnd() pygame.display.flip() glDeleteTextures(texture_id) if __name__ == "__main__": run() <file_sep># pygame-projects ## Links http://programarcadegames.com/index.php?chapter=example_code ## 1. Import & Initialization ```python import pygame pygame.init() ``` ## 2. Display, Surfaces, Images, and Transformations - for computers (x=0,y=0) is top left corner ## Create screen ```python screen = pygame.display.set_mode((width, height)) ``` Initializes and creates the window where your game will run, and returns a Surface, here assigned to the name “screen.” Note: you’re passing a tuple, hence the double parenthesis. ## Set title ```python display.set_caption('Title of the window') ``` ## Update - Draw Display: blitting is drawing ```python pygame.display.update() ``` Redraws the main display surface if argument list is empty. Optionally, you can pass it a list of Rects, and it will just redraw the portions of the screen indicated in the list. ```python pygame.display.get_surface() ``` Returns a reference to the Surface instantiated with the set_mode() function. Use this if you forget to assign set_mode() to a name. ```python screen.blit() ``` Note: “Surface” is the name of the class, so you’d use the name you assigned when you created the surface. For example, if your main display Surface was called “screen” (as it is above), you’d use screen.blit(), not Surface.blit() ```python Copy pixels from one Surface to another Surface.blit(sourceSurface, destinationRect, optionalSourceRect) ``` Used to draw images to the screen. If you omit the third argument, the entire source Surface is copied to the area of the destination Surface specified by the Rect in the second argument ## Drawing objects - primitives - rectangle pygame.draw.rect(surface, color, rectangle_tuple, width) - polygon - circle pygame.draw.circle(surface, color, center_point, radius, width) - ellipse pygame.draw.ellipse(surface, color, bounding_rectangle, width) - line pygame.draw.line(surface, color, start_point, end_point, width) pygame.draw.lines(surface, color, closed, pointlist, width) - pixel - pixel array ```python pygame.draw.line(Surface, color, (x1,y1), (x2,y2), width) ``` ## Colour objects ```python Creates a color object with RGBA as arguments. pygame.Color(R, G, B) black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) ``` ```python Fills surface with a solid color. Surface.fill(R,G,B) ``` # Rectangle pygame.Rect(top-left-corner-x, top-lef-corner-y, width, height) spamRect = pygame.Rect(10, 20, 200, 300) ### pygame.Rect: rectangle attributes **myRect.left** integer **myRect.right ** integer **myRect.top** integer **myRect.bottom** integer **myRect.centerx ** integer **myRect.centery** integer **myRect.width** integer **myRect.height** integer **myRect.size** A tuple of two ints: (width, height) **myRect.topleft** A tuple of two ints: (left, top) **myRect.topright** A tuple of two ints: (right, top) **myRect.bottomleft** A tuple of two ints: (left, bottom) **myRect.bottomright** A tuple of two ints: (right, bottom) **myRect.midleft** A tuple of two ints: (left, centery) **myRect.midright** A tuple of two ints: (right, centery) **myRect.midtop** A tuple of two ints: (centerx, top) **myRect.midbottom** A tuple of two ints: (centerx, bottom) All of these attributes can be assigned to: ``` rect1.right = 10 rect2.center = (20,30) ``` ## Convert Before you use convert() on any surface, screen has to be initialized with set_mode() ``` import pygame pygame.init() image = pygame.image.load("file_to_load.jpg") print(image.get_rect().size) # you can get size screen = pygame.display.set_mode(image.get_rect().size, 0, 32) image = image.convert() # now you can convert ``` - Changes pixel format ```python Surface.convert() ``` Changes pixel format of the Surface’s image to the format used by the main display. Makes things faster. Use it. ```python Changes pixel format (transparency) Surface.convert_alpha() ``` Same as above, but when the Surface’s image has alpha transparency values to deal with. ```python Get dimensions and location of surface Surface.get_rect() ``` Returns a Rect that will tell you the dimensions and location of the surface. ```python Loads image from disk and gets image size image = pygame.image.load('filename') image_width = image.get_rect().size[0] image_height = image.get_rect().size[1] ``` Note that in Python, directories are indicated by a forward slash, unlike Windows - Rotates Surface counterclockwise by degrees ```python pygame.transform.rotate(Surface, angle) ``` - Resizes Surface to new resolution ```python pygame.transform.scale(Surface, (width, height)) ``` ## Circles ```python pygame.draw.circle(gameDisplay, self.colour, (self.x, self.y), self.size, self.thickness) ## Rectangles - Returns a Rect moved x pixels horizontally and y pixels vertically Rect.move(x, y) ``` - Moves the Rect x pixels horizontally and y pixels vertically ```python Rect.move_ip(x, y) ``` Assignable attributes (in most cases, a tuple of x and y values): top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery, size, width, height # Display examples - Classical way of creating image on display ```python #1.) draw background, dont paint it over image gameDisplay.fill(white) #2.) draw image on position (x,y) x = display_width*0.45 y = display_height*0.8 #use blit to add image to surface gameDisplay.blit(carImg,(x,y)) #3.) update display pygame.display.update() ``` ## Time - Create a Clock object ```python pygame.time.Clock() ``` (assign this to a name), which you can then call the tick() method on to find out how much time has passed since the last time you called tick() ```python Returns the clock framerate pygame.time.Clock.get_fps() ``` ```python Pause game for time specified pygame.time.delay(milliseconds) ``` ```python Returns the number of milliseconds passed since pygame.init() was called pygame.time.get_ticks() ``` ```python Returns the time used in previous tick pygame.time.Clock.get_time() ``` ## Joystick my_joystick = pygame.joystick.Joystick(0) my_joystick.init() ## Events ```python Key press events #if key pressed start moving if event.type == pygame.EVENTDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 #if key released stop moving if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:: x_change = 0 ``` this code changes position only if key is pressed down. When key is released. change is zero. ```python Event for closing main windows press on (x) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() ``` One of the most common ways of event handling, Its a loop which constantly checks for events, quits if the QUIT event is triggered and prevents your game from freezing. ```python Places a new event that you specify on the queue pygame.event.post() ``` ```python Creates a new event object pygame.event.Event() ``` ```python Gets the event from the queue pygame.event.get() ``` ```python Remove all the events from the queue pygame.event.clear() ``` Events are always in a queue. Order of events does matter. ```python Get a list of events pygame.event.get() ``` Call once per frame to get a list of events that occurred since the last time pygame.event.get() was called. - Event type values: - QUIT one - KEYDOWN unicode, key, mod (if you import pygame.locals, compare to e.g. K_a for “a”) - KEYUP key, mod - MOUSEMOTION pos, rel, buttons - MOUSEBUTTONUP pos, button - MOUSEBUTTONDOWN pos, button - JOYAXISMOTION joy, axis, value ### Mouse events - lmb, mmb, rmb = pygame.mouse.get_pressed Returns the mouse buttons pressed as a tuple of three booleans, one for the left, middle, and right mouse buttons. - pygame.mouse.get_rel—Returns the relative mouse movement (or mickeys) as a tuple with the x and y relative movement. - pygame.mouse.get_pos—Returns the mouse coordinates as a tuple of the x and y values. - pygame.mouse.set_pos—Sets the mouse position. Takes the coordinate as a tuple or list for x and y. - pygame.mouse.set_visible—Changes the visibility of the standard mouse cursor. If False, the cursor will be invisible - pygame.mouse.get_focused—Returns True if the Pygame window is receiving mouse input. When Pygame runs in a window, it will only receive mouse input when the window is selected and at the front of the display. - pygame.mouse.set_cursor—Sets the standard cursor image. This is rarely needed since better results can be achieved by blitting an image to the mouse coordinate. - pyGame.mouse.get_cursor—Gets the standard cursor image. See the previous item. ### Joystic Events • pygame.joystick.init—Initializes the joystick module. This is called automatically by pygame.init, so you rarely need to call it yourself. • pygame.joystick.quit—Uninitializes the joystick module. Like init, this function is called automatically and so is not often needed. • pygame.joystick.get_init—Returns True if the joystick module has been initialized. If it returns False, the following joystick functions won’t work. • pygame.joystick.get_count—Returns the number of joysticks currently plugged into the computer. • pygame.joystick.Joystick—Creates a new joystick object that is used to access all information for that stick. The constructor takes the ID of the joystick—the first joystick is ID 0, then ID 1, and so on, up to the number of joysticks available on the system. ## Fonts ```python f = pygame.font.Font(None, 32) ``` Creates a font object of size 32 using the default font. If you know where the .TTF file of the font you want to use is located, you can use the filename as the first argument - create a message and display it on screen ``` ``` ## Rendering ```python surf = f.render(“Hello”, 1, (255,0,255), (255,255,0)) ``` Creates a surface of rendered text using the font of the font object. The first argument is the text itself, the second is whether the text is anti-aliased or not (0 for no), the third argument is a 3-item tuple that defines the RGB values of the color of the text, and the fourth (optional) argument is a 3-item tuple that defines the RGB values of the color of the background. If the fourth argument is not specified, the background will be transparent. This command creates a surface that has the word Hello in magenta on a yellow background, which can then be blitted to the screen like any surface. It’s quite ugly. ## Audio ### Initialize ``` pygame.mixer.init() ``` ### Playing Sound Effects ```python # 1. create a sound object soundObj = pygame.mixer.Sound('beeps.wav') # must be an uncompressed WAV or OGG # 2. start sound soundObj.play() # 3. wait and let the sound play for 1 second time.sleep(1) # 4. stop sound soundObj.stop() ``` ### Playing Background For background music, you do not create objects, since you can only have one music track running at any time. Music is streamed, never fully loaded at once. You can use MIDI files. ```python pygame.mixer.music.load(filename) pygame.mixer.music.play(loops=0, offset) # -1 to repeat indefinitely, offset in sec pygame.mixer.music.stop() ``` # Sprites,module with basic game object classes | [pygame.sprite.Sprite](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite) | Simple base class for visible game objects. | | ------------------------------------------------------------ | ------------------------------------------------------------ | | [pygame.sprite.DirtySprite](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.DirtySprite) | A subclass of Sprite with more attributes and features. | | [pygame.sprite.Group](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group) | A container class to hold and manage multiple Sprite objects. | | [pygame.sprite.RenderPlain](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.RenderPlain) | Same as pygame.sprite.Group | | [pygame.sprite.RenderClear](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.RenderClear) | Same as pygame.sprite.Group | | [pygame.sprite.RenderUpdates](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.RenderUpdates) | Group sub-class that tracks dirty updates. | | [pygame.sprite.OrderedUpdates](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.OrderedUpdates) | RenderUpdates sub-class that draws Sprites in order of addition. | | [pygame.sprite.LayeredUpdates](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.LayeredUpdates) | LayeredUpdates is a sprite group that handles layers and draws like OrderedUpdates. | | [pygame.sprite.LayeredDirty](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.LayeredDirty) | LayeredDirty group is for DirtySprite objects. Subclasses LayeredUpdates. | | [pygame.sprite.GroupSingle](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.GroupSingle) | Group container that holds a single sprite. | | [pygame.sprite.spritecollide](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide) | Find sprites in a group that intersect another sprite. | | [pygame.sprite.collide_rect](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rect) | Collision detection between two sprites, using rects. | | [pygame.sprite.collide_rect_ratio](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rect_ratio) | Collision detection between two sprites, using rects scaled to a ratio. | | [pygame.sprite.collide_circle](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle) | Collision detection between two sprites, using circles. | | [pygame.sprite.collide_circle_ratio](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle_ratio) | Collision detection between two sprites, using circles scaled to a ratio. | | [pygame.sprite.collide_mask](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_mask) | Collision detection between two sprites, using masks. | | [pygame.sprite.groupcollide](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.groupcollide) | Find all sprites that collide between two groups. | | [pygame.sprite.spritecollideany](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollideany) | Simple test if a sprite intersects anything in a group. | ### Class pygame.sprite.Sprite *Simple base class for visible game objects.* | [pygame.sprite.Sprite.update](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.update) | method to control sprite behavior | | ------------------------------------------------------------ | --------------------------------------- | | [pygame.sprite.Sprite.add](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.add) | add the sprite to groups | | [pygame.sprite.Sprite.remove](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.remove) | remove the sprite from groups | | [pygame.sprite.Sprite.kill](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.kill) | remove the Sprite from all Groups | | [pygame.sprite.Sprite.alive](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.alive) | does the sprite belong to any groups | | [pygame.sprite.Sprite.groups](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.groups) | list of Groups that contain this Sprite | ### Class pygame.sprite.Group *A container class to hold and manage multiple Sprite objects.* | [pygame.sprite.Group.sprites](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.sprites) | list of the Sprites this Group contains | | ------------------------------------------------------------ | ------------------------------------------- | | [pygame.sprite.Group.copy](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.copy) | duplicate the Group | | [pygame.sprite.Group.add](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.add) | add Sprites to this Group | | [pygame.sprite.Group.remove](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.remove) | remove Sprites from the Group | | [pygame.sprite.Group.has](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.has) | test if a Group contains Sprites | | [pygame.sprite.Group.update](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.update) | call the update method on contained Sprites | | [pygame.sprite.Group.draw](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.draw) | blit the Sprite images | | [pygame.sprite.Group.clear](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.clear) | draw a background over the Sprites | | [pygame.sprite.Group.empty](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.empty) | remove all Sprites | ## Default subclassing Sprite Object ```python class Block(pygame.sprite.Sprite): # Constructor. Pass in the color of the block, # and its x and y position def __init__(self, color, width, height): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) # Create an image of the block, and fill it with a color. # This could also be an image loaded from the disk. self.image = pygame.Surface([width, height]) self.image.fill(color) # Fetch the rectangle object that has the dimensions of the image # Update the position of this object by setting the values of rect.x and rect.y self.rect = self.image.get_rect() ``` # Groups, and Collision Detection Check if a sprite collides with a group. If collision, returns True ```python # check if sprite and a group walls collides if pg.sprite.spritecollideany(self, self.game.walls) ``` Check for collision ``` hits = pg.sprite.spritecollide(self, self.game.walls, False) ``` ```python class Monster(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(“monster.png”) self.rect = self.image.get_rect() ... monsters = pygame.sprite.RenderPlain((monster1, monster2, monster3)) monsters.update() monsters.draw() Rect.contains(Rect): return True or False Rect.collidepoint(x, y): return True or False Rect.colliderect(Rect): return True or False Rect.collidelist(list): return index pygame.sprite.spritecollide(sprite, group, dokill): return Sprite_list pygame.sprite.groupcollide(group1, group2, dokill1, dokill2): return Sprite_dict ``` ### Updating sprites icons This two codes are the same ```python self.all_sprites.draw(self.screen) ``` ```python for sprite in self.all_sprites: self.screen.blit(sprite.image, sprite.rect) ``` ## OOP Examples - drawing a circle ``` class Particle: def __init__(self, (x, y), size): self.x = x self.y = y self.size = size self.colour = (0, 0, 255) self.thickness = 1 def display(self): pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness) particle = Particle((150, 50), 15) particle.display() ``` ## Resources - [PyGame with Python 3 WEBSITE](https://pythonprogramming.net/pygame-python-3-part-1-intro/) - [PyGame with Python 3 YOUTUBE](https://www.youtube.com/watch?list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO&v=ujOTNg17LjI&feature=emb_title) - [pygame cheat sheet](pygame-cheatsheet.pdf) - [create an image with GIMP](https://www.youtube.com/watch?v=5myI73oFvAA) - SW to create image with transparent background [GIMP open source image editor](https://www.gimp.org/) # Examples ## Simplest pygame code ```python import pygame pygame.init() #### Create a canvas on which to display everything #### window = (400,400) screen = pygame.display.set_mode(window) #### Create a canvas on which to display everything #### #### Create a surface with the same size as the window #### background = pygame.Surface(window) #### Create a surface with the same size as the window #### #### Populate the surface with objects to be displayed #### pygame.draw.rect(background,(0,255,255),(20,20,40,40)) pygame.draw.rect(background,(255,0,255),(120,120,50,50)) #### Populate the surface with objects to be displayed #### #### Blit the surface onto the canvas #### screen.blit(background,(0,0)) #### Blit the surface onto the canvas #### #### Update the the display and wait #### pygame.display.flip() done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True #### Update the the display and wait #### pygame.quit() ``` ## 1_Intro [readme](1_intro/readme.md) ## Tetris [Python and Pygame Tutorial - Build Tetris! Full GameDev Course](https://www.youtube.com/watch?v=zfvxp7PgQ6c&t=1188s) ## Tile map editor www.mapeditor.org Loading .tmx files made from tile-editors. INSTAL pip install pytmx ## **GAME PHYSICS - MECHANICS** ### Tweening- easing functions - linear - quadratic - cubic - quartic - quintic - sinusoidal - exponential - crcular - elastic - back ```python conda install -c conda-forge pytweening ``` <file_sep># -*- coding: utf-8 -*- """ Created on Wed Dec 23 20:47:46 2020 @author: crtom """ import pygame # you'll be able to shoot every 450ms RELOAD_SPEED = 450 # the foes move every 1000ms sideways and every 3500ms down MOVE_SIDE = 1000 MOVE_DOWN = 3500 screen = pygame.display.set_mode((300, 200)) clock = pygame.time.Clock() pygame.display.set_caption("Micro Invader") # create a bunch of events move_side_event = pygame.USEREVENT + 1 move_down_event = pygame.USEREVENT + 2 reloaded_event = pygame.USEREVENT + 3 move_left, reloaded = True, True invaders, colors, shots = [], [] ,[] for x in range(15, 300, 15): for y in range(10, 100, 15): invaders.append(pygame.Rect(x, y, 7, 7)) colors.append(((x * 0.7) % 256, (y * 2.4) % 256)) # set timer for the movement events pygame.time.set_timer(move_side_event, MOVE_SIDE) pygame.time.set_timer(move_down_event, MOVE_DOWN) player = pygame.Rect(150, 180, 10, 7) while True: clock.tick(40) if pygame.event.get(pygame.QUIT): break for e in pygame.event.get(): if e.type == move_side_event: for invader in invaders: invader.move_ip((-10 if move_left else 10, 0)) move_left = not move_left elif e.type == move_down_event: for invader in invaders: invader.move_ip(0, 10) elif e.type == reloaded_event: # when the reload timer runs out, reset it reloaded = True pygame.time.set_timer(reloaded_event, 0) for shot in shots[:]: shot.move_ip((0, -4)) if not screen.get_rect().contains(shot): shots.remove(shot) else: hit = False for invader in invaders[:]: if invader.colliderect(shot): hit = True i = invaders.index(invader) del colors[i] del invaders[i] if hit: shots.remove(shot) pressed = pygame.key.get_pressed() if pressed[pygame.K_LEFT]: player.move_ip((-4, 0)) if pressed[pygame.K_RIGHT]: player.move_ip((4, 0)) if pressed[pygame.K_SPACE]: if reloaded: shots.append(player.copy()) reloaded = False # when shooting, create a timeout of RELOAD_SPEED pygame.time.set_timer(reloaded_event, RELOAD_SPEED) player.clamp_ip(screen.get_rect()) screen.fill((0, 0, 0)) for invader, (a, b) in zip(invaders, colors): pygame.draw.rect(screen, (150, a, b), invader) for shot in shots: pygame.draw.rect(screen, (255, 180, 0), shot) pygame.draw.rect(screen, (180, 180, 180), player) pygame.display.flip()<file_sep>import pymunkoptions pymunkoptions.options["debug"] = False import pymunk import arcade from math import degrees space = pymunk.Space() space.gravity = 0, -1000 mass = 1 radius = 30 segment_shape1 = pymunk.Segment(space.static_body, (500,400), (1300,440), 2) segment_shape1.elasticity = 0.8 segment_shape1.friction = 1.0 space.add(segment_shape1) segment_shape2 = pymunk.Segment(space.static_body, (100,160), (900,100), 2) segment_shape2.elasticity = 0.8 segment_shape2.friction = 1.0 space.add(segment_shape2) class MyGameWindow(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) self.set_location(400, 200) arcade.set_background_color(arcade.color.BLACK) self.sprites = arcade.SpriteList() def on_draw(self): arcade.start_render() arcade.draw_lines([segment_shape1.a, segment_shape1.b], arcade.color.RED, 4) arcade.draw_lines([segment_shape2.a, segment_shape2.b], arcade.color.RED, 4) self.sprites.draw() def on_update(self, delta_time): space.step(delta_time) for index, sprite in enumerate(self.sprites): sprite.angle = degrees(space.bodies[index].angle) sprite.set_position(space.bodies[index].position.x, space.bodies[index].position.y) for body in space.bodies: if body.position.y < -100: self.sprites.remove(sprite) space.remove(body, body.shapes) def on_mouse_press(self, x, y, button, modifiers): if button == arcade.MOUSE_BUTTON_LEFT: circle_moment = pymunk.moment_for_circle(mass, 0, radius) circle_body = pymunk.Body(mass, circle_moment) circle_body.position = x, y circle_shape = pymunk.Circle(circle_body, radius) circle_shape.elasticity = 0.8 circle_shape.friction = 1.0 space.add(circle_body, circle_shape) self.sprites.append(arcade.Sprite("sprites/smile.png", center_x=circle_body.position.x, center_y=circle_body.position.y)) MyGameWindow(1280, 720, 'My game window') arcade.run() <file_sep>print("type (q) = Exit") while True: user_input = input("type input") if user_input == "q": break print(user_input)<file_sep># -*- coding: utf-8 -*- """ Created on Tue Dec 15 18:09:41 2020 @author: crtom """ import pygame import sys from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT def drawPoint(x,y,color): s = pygame.Surface((1,1)) # the object surface 1 x 1 pixel (a point!) s.fill(color) # color as (r,g,b); e.g. (100,20,30) # now get an object 'rectangle' from the object surface and place it at position x,y r,r.x,r.y = s.get_rect(),x,y screen.blit(s,r) # link the object rectangle to the object surface pygame.init() # returns pygame.Surface objet for window DISPLAYSURF = pygame.display.set_mode((400,300)) pygame.display.set_caption('Hello World!') while True: # event handling for event in pygame.event.get(): # event objects have type attribute if event.type == QUIT: pygame.quit() sys.exit() #drawPoint(1, 1, (0,0,0)) #window_surface.set_at((x, y), my_color) DISPLAYSURF.set_at((100, 100), (255,255,0)) # draws surface object stored in DISPLAYSURF pygame.display.update() pygame.time.wait(100)<file_sep>import pygame from pygame.locals import * from gameobjects.vector3 import Vector3 from gameobjects.matrix44 import Matrix44 as Matrix from math import * from random import randint SCREEN_SIZE = (640, 480) CUBE_SIZE = 300 def calculate_viewing_distance(fov, screen_width): d = (screen_width/2.0) / tan(fov/2.0) return d def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, 0) font = pygame.font.SysFont("courier new", 16, True) ball = pygame.image.load("ball.png").convert_alpha() points = [] fov = 75. # Field of view viewing_distance = calculate_viewing_distance(radians(fov), SCREEN_SIZE[0]) # Create a list of points along the edge of a cube for x in range(0, CUBE_SIZE+1, 10): edge_x = x == 0 or x == CUBE_SIZE for y in range(0, CUBE_SIZE+1, 10): edge_y = y == 0 or y == CUBE_SIZE for z in range(0, CUBE_SIZE+1, 10): edge_z = z == 0 or z == CUBE_SIZE if sum((edge_x, edge_y, edge_z)) >= 2: point_x = float(x) - CUBE_SIZE/2 point_y = float(y) - CUBE_SIZE/2 point_z = float(z) - CUBE_SIZE/2 points.append(Vector3(point_x, point_y, point_z)) def point_z(point): return point[2] center_x, center_y = SCREEN_SIZE center_x /= 2 center_y /= 2 ball_w, ball_h = ball.get_size() ball_center_x = ball_w / 2 ball_center_y = ball_h / 2 camera_position = Vector3(0.0, 0.0, 600.) rotation = Vector3() rotation_speed = Vector3(radians(20), radians(20), radians(20)) clock = pygame.time.Clock() # Some colors for drawing red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) white = (255, 255, 255) # Labels for the axes x_surface = font.render("X", True, white) y_surface = font.render("Y", True, white) z_surface = font.render("Z", True, white) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() screen.fill((0, 0, 0)) time_passed = clock.tick() time_passed_seconds = time_passed / 1000. rotation_direction = Vector3() #Adjust the rotation direction depending on key presses pressed_keys = pygame.key.get_pressed() if pressed_keys[K_q]: rotation_direction.x = +1.0 elif pressed_keys[K_a]: rotation_direction.x = -1.0 if pressed_keys[K_w]: rotation_direction.y = +1.0 elif pressed_keys[K_s]: rotation_direction.y = -1.0 if pressed_keys[K_e]: rotation_direction.z = +1.0 elif pressed_keys[K_d]: rotation_direction.z = -1.0 # Apply time based movement to rotation rotation += rotation_direction * rotation_speed * time_passed_seconds # Build the rotation matrix rotation_matrix = Matrix.x_rotation(rotation.x) rotation_matrix *= Matrix.y_rotation(rotation.y) rotation_matrix *= Matrix.z_rotation(rotation.z) transformed_points = [] # Transform all the points and adjust for camera position for point in points: p = rotation_matrix.transform_vec3(point) - camera_position transformed_points.append(p) transformed_points.sort(key=point_z) # Perspective project and blit all the points for x, y, z in transformed_points: if z < 0: x = center_x + x * -viewing_distance / z y = center_y + -y * -viewing_distance / z screen.blit(ball, (x-ball_center_x, y-ball_center_y)) # Function to draw a single axes, see below def draw_axis(color, axis, label): axis = rotation_matrix.transform_vec3(axis * 150.) SCREEN_SIZE = (640, 480) center_x = SCREEN_SIZE[0] / 2.0 center_y = SCREEN_SIZE[1] / 2.0 x, y, z = axis - camera_position x = center_x + x * -viewing_distance / z y = center_y + -y * -viewing_distance / z pygame.draw.line(screen, color, (center_x, center_y), (x, y), 2) w, h = label.get_size() screen.blit(label, (x-w/2, y-h/2)) # Draw the x, y and z axes x_axis = Vector3(1, 0, 0) y_axis = Vector3(0, 1, 0) z_axis = Vector3(0, 0, 1) draw_axis(red, x_axis, x_surface) draw_axis(green, y_axis, y_surface) draw_axis(blue, z_axis, z_surface) # Display rotation information on screen degrees_txt = tuple(degrees(r) for r in rotation) rotation_txt = "Rotation: Q/A %.3f, W/S %.3f, E/D %.3f" % degrees_txt txt_surface = font.render(rotation_txt, True, white) screen.blit(txt_surface, (5, 5)) # Displat the rotation matrix on screen matrix_txt = str(rotation_matrix) txt_y = 25 for line in matrix_txt.split('\n'): txt_surface = font.render(line, True, white) screen.blit(txt_surface, (5, txt_y)) txt_y += 20 pygame.display.update() if __name__ == "__main__": run() <file_sep>from tank import Tank tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol") } alive_tanks = len(tanks) while alive_tanks > 1: for tank_name in sorted( tanks.keys() ): print(tank_name, tanks[tank_name]) first = input("Who fires? ").lower() second = input("Who at? " ).lower() try: first_tank = tanks[first] second_tank = tanks[second] except KeyError as name: print("No such tank!", name) continue if not first_tank.alive or not second_tank.alive: print("One of those tanks is dead!") continue print("*" * 30) first_tank.fire_at(second_tank) if not second_tank.alive: alive_tanks -= 1 print("*" * 30) for tank in tanks.values(): if tank.alive: print(tank.name, "is the winner!") break <file_sep>""" website: https://techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/pygame-animation/ Character Animation video: https://www.youtube.com/watch?v=2-DNswzCkqk&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5&index=2 """ import pygame from pygame.locals import * from rgb_color_dictionary import * pygame.init() #create window win = pygame.display.set_mode((500,500)) #set windows title pygame.display.set_caption("First Game") #load images for animation walkRight =[ pygame.image.load("R1.png"), pygame.image.load("R2.png"), pygame.image.load("R3.png"), pygame.image.load("R4.png"), pygame.image.load("R5.png"), pygame.image.load("R6.png"), pygame.image.load("R7.png"), pygame.image.load("R8.png"), pygame.image.load("R9.png")] walkLeft =[ pygame.image.load("L1.png"), pygame.image.load("L2.png"), pygame.image.load("L3.png"), pygame.image.load("L4.png"), pygame.image.load("L5.png"), pygame.image.load("L6.png"), pygame.image.load("L7.png"), pygame.image.load("L8.png"), pygame.image.load("L9.png")] bg = pygame.image.load("bg.jpg") char = pygame.image.load("standing.png") #defining clock for the game clock=pygame.time.Clock() #character variables x = 50 y = 50 width = 40 height = 60 vel = 5 isJump = False jumpCount = 10 left = False right = False walkCount = 0 def redrawGameWindow(): global walkCount #draw background win.blit(bg,(0,0)) #if we are walking. displaying 9 sprites, 3 per frame = 27 #afte print(walkCount) if walkCount + 1 >=27: walkCount = 0 if left: win.blit(walkLeft[walkCount//3],(x,y)) #integer division to get sprite picture index walkCount += 1 elif right: win.blit(walkRight[walkCount//3],(x,y)) #integer division to get sprite picture index walkCount += 1 else: win.blit(char,(x,y)) pygame.display.update() #main game loop run = True while run: #1st set time for the game #pygame.time.delay(100) #this will be a clock for the game clock.tick(27) keys = {'left':False,'right':False, 'up':False, 'down':False} for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False vx = 0 vy = 0 keystate = pygame.key.get_pressed() #straight moves with screen constraints #cant move up if keystate[pygame.K_UP] and y > vel: vy = -vel #cant move down elif keystate[pygame.K_DOWN] and y < 500 - height - vel: vy = vel #while jumping cant move left or right if not isJump: #cant move off the left screen border if keystate[pygame.K_LEFT] and x > vel: vx = -vel left = True right = False #cant move off the right screen border elif keystate[pygame.K_RIGHT] and x < 500 - width - vel: vx = vel left = False right = True #if right or left not pressed, reset movement else: left = False right = False walkCount = 0 #-----------------jump--------------- if keystate[pygame.K_SPACE]: isJump = True else: if jumpCount >= -10: # we jump for 10 pixels neg = 1 if jumpCount < 0: #when we get to the top of jump neg = -1 y -= (jumpCount ** 2) * 0.5 * neg jumpCount -= 1 #if jumping than we are not walking left or right left = False right = False walkCount = 0 else: isJump = False jumpCount = 10 #diagonals must be slower for sq(2)= 1.414 pitagora if vx != 0 and vy != 0: vx /= 1.414 vy /= 1.414 x += vx y += vy redrawGameWindow() <file_sep>""" Doodle Jump Attributes: g (TYPE): Description """ import pygame as pg import random from settings import * from sprites import * import os from os import path class Game: """Summary Attributes: all_sprites (TYPE): Description clock (TYPE): Description playing (bool): Description running (bool): Description screen (TYPE): Description """ def __init__(self): """initialize game window, etc - load data: load graphics, sound, highscore file """ pg.init() pg.mixer.init() self.screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption(TITLE) self.clock = pg.time.Clock() self.running = True self.playing = True #closeste match to our font name self.font_name = pg.font.match_font(FONT_NAME) self.highscore = 0 self.load_data() def read_highscore_file(self, filename): #if file exists, read from it if os.path.exists(filename): with open(filename, 'r') as f: try: data = int(f.read()) return data except: return 0 # if file doesnt exists, create new else: with open(filename, 'w') as f: try: f.write("0") return 0 except: return 0 def load_data(self): """ method for loading date before starting the game - get folder directories, build paths for files - load graphics - load sounds - load files: highscore """ self.dir = path.dirname(__file__) #get application folder path # load spritesheet image self.img_dir = path.join(self.dir, 'img') spritesheet_file = path.join(self.img_dir, SPRITESHEET_FILE) self.spritesheet = Spritesheet(spritesheet_file) # load high score file highscore_file = path.join(self.dir, HIGHSCORE_FILE) self.highscore = self.read_highscore_file(highscore_file) # load sounds: .ogg files are best self.snd_dir = path.join(self.dir, 'snd') # load jump sound self.jump_snd_file = path.join(self.snd_dir, 'Jump33.wav') self.jump_sound = pg.mixer.Sound(self.jump_snd_file) self.jump_sound.set_volume(0.2) def new(self): """Start a New Game """ self.score = 0 #create sprites groups self.all_sprites = pg.sprite.Group() #create platform group self.platforms = pg.sprite.Group() #add player to sprites group """create a new instance of Player and send it reference to game object so we can access platforms also in player class""" self.player = Player(self) #send reference self.all_sprites.add(self.player) #add platform list to platform group and to sprites group for plat in PLATFORM_LIST: #p = Platform(plat[0],plat[1],plat[2],plat[3]) same as bottom p = Platform(self, *plat) #explode plat list to components self.all_sprites.add(p) self.platforms.add(p) #load music before start of game pg.mixer.music.load(path.join(self.snd_dir, 'Happy Tune.ogg')) def run(self): """Game Loop """ # start music: infinite loop pg.mixer.music.play(loops = -1) self.playing = True while self.playing: self.clock.tick(FPS) # keep looping at the right speed self.events() self.update() self.draw() # stop music with fadeout pg.mixer.music.fadeout(1000) # 1sec fade def update(self): """Game Loop - Update - update all sprites - checking if player hits platform - only if falling - """ #debug number of platforms, check if deleted properly #print(len(self.platforms)) # update all sprites self.all_sprites.update() # PLAYER-PLATFORM COLLISION DETECTION - this stops us from falling # checking if player hits platform - only if falling if self.player.vel.y > 0: # do a collision check with platform hits = pg.sprite.spritecollide(self.player, self.platforms, False) if hits: # hits is a list of multiple collisions # find which platform is lowes lowest = hits[0] for hit in hits: if hit.rect.bottom > lowest.rect.bottom: lowest = hit if self.player.pos.x < lowest.rect.right + 10 and \ self.player.pos.x > lowest.rect.left - 10: #dont snap if the ears touch platform. only feet if self.player.pos.y < lowest.rect.bottom: self.player.pos.y = lowest.rect.top self.player.vel.y = 0 # when we land on paltform, reset jumping ability self.player.jumping = False # SCROLING WINDOW # if player reaches top 1/4 of screen if self.player.rect.top <= HEIGHT/4: #litle math for nicer screnn scrolling. take player speed or number 2 # even if player is not moving, the screen moves until in range self.player.pos.y += max(abs(self.player.vel.y),2) for plat in self.platforms: plat.rect.y += max(abs(self.player.vel.y),2) #remove platforms on the bottom if plat.rect.top >= HEIGHT: plat.kill() #remove bottom ones self.score += 1 # spawn new platforms to keep some avarage number while len(self.platforms) < 6: #randomize creation of platforms width = random.randrange(50, 100) p = Platform(self, random.randrange(0, WIDTH-width), random.randrange(-75, -30)) self.platforms.add(p) self.all_sprites.add(p) # GAME OVER # Die! and game over condition if self.player.rect.bottom > HEIGHT: #do a bling when dying- looks like scroling camera for sprite in self.all_sprites: sprite.rect.y -= max(self.player.vel.y, 10) if sprite.rect.bottom < 0: sprite.kill() if len(self.platforms) == 0: self.playing = False def events(self): """Game Loop - events - close window + escape key event stops game """ for event in pg.event.get(): # check for closing window if (event.type == pg.QUIT) or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): if self.playing: self.playing = False self.running = False self.player.vel.y = 0 # jumping section. jump higher if we hold space if event.type == pg.KEYDOWN: if event.key == pg.K_SPACE: self.player.jump() if event.type == pg.KEYUP: if event.key == pg.K_SPACE: self.player.jump_cut() def draw(self): """Game Loop - draw - fill with background colour - draw all sprites - draw text score - flip everything to display """ self.screen.fill(BG_COLOR) self.all_sprites.draw(self.screen) # put player always in front of other stuff self.screen.blit(self.player.image, self.player.rect) self.draw_text(str(self.score), 22, WHITE, WIDTH_MID, 15) pg.display.flip() def show_start_screen(self): """game splash/start screen """ # start playing music pg.mixer.music.load(path.join(self.snd_dir, 'Yippee.ogg')) pg.mixer.music.set_volume(0.2) # 0 < x < 1 pg.mixer.music.play(loops = -1) self.screen.fill(BG_COLOR) self.draw_text(TITLE, 48, WHITE, WIDTH_MID, HEIGHT//4) self.draw_text("Arrows to move, Space to jump", 22, WHITE, WIDTH_MID, HEIGHT_MID) self.draw_text("Press a key to play", 22, WHITE, WIDTH_MID, HEIGHT*3/4) self.draw_text("High score : " + str(self.highscore), 22, WHITE, WIDTH_MID, 15) pg.display.flip() self.wait_for_key() # stop music pg.mixer.music.fadeout(1000) # s0.5sec fade def show_go_screen(self): """game over/continue screen If player presses (X), than ignore game over screen Game over screen is called only if a player dies - handle highscore file """ if not self.running: return # start playing music pg.mixer.music.load(path.join(self.snd_dir, 'Yippee.ogg')) pg.mixer.music.set_volume(0.2) # 0 < x < 1 pg.mixer.music.play(loops = -1) self.screen.fill(BG_COLOR) self.draw_text("GAME OVER", 48, WHITE, WIDTH_MID, HEIGHT//4) self.draw_text("Score : "+str(self.score), 22, WHITE, WIDTH_MID, HEIGHT_MID) self.draw_text("press a key to play again", 22, WHITE, WIDTH_MID, HEIGHT*3/4) # save highscore if self.score > self.highscore: self.highscore = self.score self.draw_text("NEW HIGH SCORE ! CONGRATS", 22, WHITE, WIDTH_MID, HEIGHT_MID + 40) with open(path.join(self.dir, HIGHSCORE_FILE), "w") as f: f.write(str(self.highscore)) else: self.draw_text("High score : " + str(self.highscore), 22, WHITE, WIDTH_MID, 15) pg.display.flip() self.wait_for_key() # stop music pg.mixer.music.fadeout(1000) # s0.5sec fade def wait_for_key(self): waiting = True while waiting: self.clock.tick(FPS) for event in pg.event.get(): #check for closing window if (event.type == pg.QUIT) or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): """ this is original, but doesnt close screen at game over if self.playing: waiting = False self.running = False self.playing = False """ waiting = False self.running = False self.playing = False if event.type == pg.KEYUP: waiting = False def draw_text(self, text, size, color, x, y): font = pg.font.Font(self.font_name, size) text_surface = font.render(text, True, color) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) self.screen.blit(text_surface, text_rect) #----------------MAIN GAME------------------ g = Game() # instance of game object g.show_start_screen() while g.running: g.new() g.run() g.show_go_screen() pg.quit() <file_sep>print("loading jutri: 10% ##________")<file_sep># -*- coding: utf-8 -*- """ Created on Fri Dec 25 11:08:39 2020 @author: crtom """ import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 pygame.init() HEIGHT, WIDTH = (400,400) #### Create a canvas on which to display everything #### screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) #### Create a surface with the same size as the window #### background = pygame.Surface((WIDTH, HEIGHT)) #background = pygame.image.load(background_image_filename).convert() #sprite = pygame.image.load(sprite_image_filename).convert_alpha() clock = pygame.time.Clock() position = Vector2(100.0, 100.0) speed = 250. heading = Vector2() sprite = pygame.Surface((50, 50)) sprite.fill((255,255,255)) rect = sprite.get_rect() rect.center = (WIDTH / 2, HEIGHT / 2) # at start destination is the same as object position destination = (WIDTH / 2, HEIGHT / 2) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() if event.type == MOUSEBUTTONDOWN: destination_x = event.pos[0] - sprite.get_width()/2.0 destination_y = event.pos[1] - sprite.get_height()/2.0 destination = (destination_x, destination_y) print(destination) heading = Vector2.from_points(position, destination) heading.normalize() #### Blit the surface onto the canvas #### screen.blit(background,(0,0)) #### Blit the surface onto the canvas #### screen.blit(sprite,(int(position.x), int(position.y))) time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 distance_moved = time_passed_seconds * speed position += heading * distance_moved pygame.display.update()<file_sep>import pygame as pg vec = pg.math.Vector2 # define some colors (R, G, B) WHITE = (255, 255, 255) BLACK = (0, 0, 0) DARKGREY = (40, 40, 40) LIGHTGREY = (100, 100, 100) GREEN = (0, 255, 0) RED = (255, 0, 0) YELLOW = (255, 255, 0) BROWN = (106, 55, 5) CYAN = (0, 255, 255) # game settings WIDTH = 1024 # 16 * 64 or 32 * 32 or 64 * 16 HEIGHT = 768 # 16 * 48 or 32 * 24 or 64 * 12 FPS = 60 TITLE = "Tilemap Demo" BGCOLOR = BROWN TILESIZE = 64 GRIDWIDTH = WIDTH / TILESIZE GRIDHEIGHT = HEIGHT / TILESIZE WALL_IMG = 'tileGreen_39.png' # Player settings PLAYER_HEALTH = 100 PLAYER_SPEED = 280 PLAYER_ROT_SPEED = 200 PLAYER_IMG = 'manBlue_gun.png' PLAYER_HIT_RECT = pg.Rect(0, 0, 35, 35) BARREL_OFFSET = vec(30, 10) # Gun settings BULLET_IMG = 'bullet.png' BULLET_SPEED = 500 BULLET_LIFETIME = 1000 BULLET_RATE = 150 KICKBACK = 200 GUN_SPREAD = 5 BULLET_DAMAGE = 10 # Mob settings MOB_IMG = 'zombie1_hold.png' MOB_SPEEDS = [50, 75, 100, 125, 150] MOB_HIT_RECT = pg.Rect(0, 0, 30, 30) MOB_HEALTH = 100 MOB_DAMAGE = 10 MOB_KNOCKBACK = 20 AVOID_RADIUS = 50 # Effects MUZZLE_FLASHES = ['whitePuff15.png', 'whitePuff16.png', 'whitePuff17.png', 'whitePuff18.png'] FLASH_DURATION = 40 # Layers WALL_LAYER = 1 PLAYER_LAYER = 2 BULLET_LAYER = 3 MOB_LAYER = 4 EFFECTS_LAYER = 5 ITEMS_LAYER = 1 # Items ITEM_IMAGES = {'health': 'health_pack.png'} HEALTH_PACK_AMOUNT = 20<file_sep># -*- coding: utf-8 -*- """ Created on Thu Dec 24 11:44:03 2020 @author: crtom """ from vector import Vector a = Vector(5, 10) b = Vector(-5, 10) c = a + b #Vector class using __add__ operator overload print(a.x, a.y) print(b.x, b.y) print(c.x, c.y) # if we want to do a*b. vector multiplication # we need to create constructor overload <file_sep>if self.state == "exploring": self.random_heading() if self.can_see(player): self.state = "seeking" elif self.state == "seeking": self.head_towards("player") if self.in_range_of(player): self.fire_at(player) if not self.can_see(player): self.state = "exploring" <file_sep># -*- coding: utf-8 -*- """ http://inventwithpython.com/pygame/ Created on Tue Dec 15 18:09:41 2020 @author: crtom - BASIC ARHITECTURE, get mouse coordinates #------------------------------------------------------------------------------ #-------------------------------------------------------------------------- #---------------------------------------------------------------------- #------------------------------------------------------------------ #-------------------------------------------------------------- """ import pygame import sys from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT #-------------------------------------------------------------------------- #-------------------------constants---------------------------------------- #-------------------------------------------------------------------------- FPS = 30 WIN_W = 600 WIN_H = 600 """ grid calculations GRID = 600*600 GRID 6x6 = 36 pieces 100x100 per square one piece is 80x80 + margin = 100x100 """ MARGIN_L = 10 BOX_L = 80 #REVEALSPEED = 8 #GAPSIZE = 10 BOARD_W = 6 BOARD_H = 6 # check #assert(BOARDWIDTH*BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches' #XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2) #YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2) # COLORS ( R , G , B ) WHITE = (255, 255, 255) BLACK = ( 0, 0, 0) RED = (255, 0, 0) LIME = ( 0, 255, 0) BLUE = ( 0, 0, 255) NAVYBLUE= ( 60, 60, 100) YELLOW = (255, 255, 0) ORANGE = (255, 128, 0) CYAN = ( 0, 255, 255) MAGENTA = (255, 0, 255) SILVER = (192, 192, 192) GRAY = (128, 128, 128) MAROON = (128, 0, 0) OLIVE = (128, 128, 0) GREEN = ( 0, 128, 0) PURPLE = (128, 0, 128) TEAL = ( 0, 128, 128) NAVY = ( 0, 0, 128) BGCOLOR = NAVYBLUE LIGHTBGCOLOR = GRAY BOXCOLOR = WHITE HIGHLIGHTCOLOR = BLUE LINE = 'line' DONUT = 'donut' SQUARE = 'square' DIAMOND = 'diamond' LINES = 'lines' OVAL = 'oval' #ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN) #ALLSHAPES = (LINE, DONUT, SQUARE, DIAMOND, LINES, OVAL) #assert len(ALLCOLORS) * len(ALLSHAPES) * 2 <= BOARDWIDTH * BOARDHEIGHT,'Board is too big for the number of shapes/colors defined.' # create coordiantion grid_vertices = 0 grid_vertices = [[0 for i in range(6)] for j in range(6)] # create a list of touple positions grid_touple_lst = [] for y in range(0, 6): for x in range(0, 6): grid_touple_lst.append((x,y)) print(grid_touple_lst) # print('first item:', grid_touple_lst[0]) # print('last item:', grid_touple_lst[35]) square_touple_lst = [] for x in range(10, 610, 100): for y in range(10, 610, 100): square_touple_lst.append((x,y)) # print(square_touple_lst) # 'back' # 'front' state_lst = ['back' for i in range(36)] print(state_lst) #------------------------------------------------------------------------------ #----------------------------main loop----------------------------------------- #------------------------------------------------------------------------------ def main(): # global variables global FPSCLOCK, DISPLAYSURF # for positions position_pixel = (None, None) position_grid = (None, None) position_box = None # for user events mouseMoved = False mouseClicked = False #-------------------------------------------------------------------------- # init pygame pygame.init() FPSCLOCK = pygame.time.Clock() # initialize clock DISPLAYSURF = pygame.display.set_mode((WIN_W, WIN_H)) # initialize surface DISPLAYSURF.fill(BGCOLOR) pygame.display.set_caption('Memory Game') # Draws boxes being covered/revealed. "boxes" is a list # of two-item lists, which have the x & y spot of the box. # coordinartes of grid #left, top = leftTopCoordsOfBox(box[0], box[1]) #pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE)) # DRAW GRID for touple in square_touple_lst: x, y = touple pygame.draw.rect(DISPLAYSURF, WHITE, (x, y, 80, 80)) #shape, color = getShapeAndColor(board, box[0], box[1]) #drawIcon(shape, color, box[0], box[1]) #-------------------------------------------------------------------------- #-------------------------GAME loop---------------------------------------- #-------------------------------------------------------------------------- while True: #----------------------event handling--------------------------------- for event in pygame.event.get(): # event objects have type attribute if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEMOTION: position_pixel = event.pos mouseMoved = True #print('mouse moved') elif event.type == MOUSEBUTTONUP: # mouse click position is in pixels position_pixel = event.pos # set click is true for functions mouseCicked = True #print('mouse clicked') #--------------------------------------------------------------------- # if mouse moved than highlight box if mouseMoved: # window pixels to game grid position_grid = pixel_pos_to_game_grid(position_pixel) # game grid to box number position_box = game_grid_to_touple_pos(position_grid) print('position_pixel = ', position_pixel) print('position_grid = ', position_grid) print('position_box = ', position_box) # reset event flag mouseMoved = False #--------------------------------------------------------------------- if mouseClicked: mouseClicked = False #------------------------timing---------------------------------------- # draws surface object stored in DISPLAYSURF pygame.display.update() FPSCLOCK.tick(FPS) #------------------------------------------------------------------------------ #-------------------------function definitions--------------------------------- #------------------------------------------------------------------------------ def pixel_pos_to_game_grid(touple_pixel): """ Parameters ---------- touple_pixel : touple position in pixels coordinates. Returns ------- touple_grid : touple position in game grid coordinates. """ x_grid = touple_pixel[0] // 100 # integere division y_grid = touple_pixel[1] // 100 touple_grid = (x_grid, y_grid) return touple_grid def game_grid_to_touple_pos(touple_grid): """ Parameters ---------- mytouple : touple position in game grid coordinates. Returns ------- box_n : number list index from grid_touple_lst """ box_n = None for i, touple in enumerate(grid_touple_lst): if touple_grid == touple: box_n = i return box_n def change_box_state(grid_nx, grid_ny): global state_lst # for state in state_lst: # # if back, turn to front # if state == 'front': # pygame.draw.rect(DISPLAYSURF, WHITE, (x, y, 80, 80)) # # if front, turn to back # else: # pygame.draw.rect(DISPLAYSURF, RED, (x, y, 80, 80)) def leftTopCoordsOfBox(boxx, boxy): # Convert board coordinates to pixel coordinates left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN return (left, top) #------------------------------------------------------------------------------ #-------------------------Start application------------------------------------ #------------------------------------------------------------------------------ if __name__ == '__main__': main()<file_sep># -*- coding: utf-8 -*- """ Created on Mon Dec 21 22:32:03 2020 @author: crtom """ import random number_list = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70] print("Original list:", number_list) random.shuffle(number_list) print("List after first shuffle:", number_list) random.shuffle(number_list) print("List after second shuffle:", number_list)<file_sep>require('game') function love.load() love.window.setPosition(500, 50, 1) interval = 20 add_apple() end function love.draw() game_draw() if state == GameStates.game_over then -- draw Game Over when the state is game_over love.graphics.print("Game Over!", 330, 350, 0, 4, 4) love.graphics.print("Press Space to restart", 270, 450, 0, 3, 3) end end function love.update() if state == GameStates.running then interval = interval - 1 if interval < 0 then game_update() if tail_length <= 5 then interval = 20 elseif tail_length > 5 and tail_length <= 10 then -- the game will run faster after every 6 collected apple interval = 15 elseif tail_length > 10 and tail_length <= 15 then interval = 10 else interval = 5 end end end end function love.keypressed(key) if key == 'escape' then love.event.quit() elseif key == 'left' and state == GameStates.running then left, right, up, down = true, false, false, false elseif key == 'right' and state == GameStates.running then left, right, up, down = false, true, false, false elseif key == 'up' and state == GameStates.running then left, right, up, down = false, false, true, false elseif key == 'down' and state == GameStates.running then left, right, up, down = false, false, false, true elseif key == 'space' and state == GameStates.game_over then game_restart() elseif key == 'p' then if state == GameStates.running then state = GameStates.pause else state = GameStates.running end end end <file_sep># -*- coding: utf-8 -*- """ Created on Thu Dec 24 17:58:20 2020 @author: crtom """ <file_sep>from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * SCREEN_SIZE = (800, 600) def resize(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45.0, float(width)/height, .1, 1000.) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def init(): glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glClearColor(1.0, 1.0, 1.0, 0.0) def upload_texture(filename, use_alpha=False): # Read an image file and upload a texture if use_alpha: format, gl_format, bits_per_pixel = 'RGBA', GL_RGBA, 4 else: format, gl_format, bits_per_pixel = 'RGB', GL_RGB, 3 img_surface = pygame.image.load(filename) #img_surface = premul_surface(img_surface) data = pygame.image.tostring(img_surface, format, True) texture_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture_id) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) width, height = img_surface.get_rect().size glTexImage2D( GL_TEXTURE_2D, 0, bits_per_pixel, width, height, 0, gl_format, GL_UNSIGNED_BYTE, data ) # Return the texture id, so we can use glBindTexture return texture_id def draw_quad(x, y, z, w, h): # Send four vertices to draw a quad glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex3f(x-w/2, y-h/2, z) glTexCoord2f(1, 0) glVertex3f(x+w/2, y-h/2, z) glTexCoord2f(1, 1) glVertex3f(x+w/2, y+h/2, z) glTexCoord2f(0, 1) glVertex3f(x-w/2, y+h/2, z) glEnd() def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF) resize(*SCREEN_SIZE) init() # Upload the background and fugu texture background_tex = upload_texture('background.png') fugu_tex = upload_texture('fugu.png', True) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() if event.type == KEYDOWN: if event.key == K_1: # Simple alpha blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glBlendEquation(GL_FUNC_ADD) elif event.key == K_2: # Additive alpha blending glBlendFunc(GL_SRC_ALPHA, GL_ONE) glBlendEquation(GL_FUNC_ADD) elif event.key == K_3: # Subtractive blending glBlendFunc(GL_SRC_ALPHA, GL_ONE) glBlendEquation(GL_FUNC_REVERSE_SUBTRACT) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Draw the background glBindTexture(GL_TEXTURE_2D, background_tex) glDisable(GL_BLEND) draw_quad(0, 0, -SCREEN_SIZE[1], 600, 600) glEnable(GL_BLEND) # Draw a texture at the mouse position glBindTexture(GL_TEXTURE_2D, fugu_tex) x, y = pygame.mouse.get_pos() x -= SCREEN_SIZE[0]/2 y -= SCREEN_SIZE[1]/2 draw_quad(x, -y, -SCREEN_SIZE[1], 256, 256) pygame.display.flip() # Free the textures we used glDeleteTextures(background_tex) glDeleteTextures(fugu_tex) if __name__ == "__main__": run() <file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 27 23:08:54 2020 @author: crtom """ WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) MAGENTA = (255, 0, 255) YELLOW = (255, 255, 0) DARKGREY = (40, 40, 40) LIGHTGREY = (140, 140, 140) # game settings WIDTH = 1024 # divisible by 16*64 32*32 HEIGHT = 768 # 16*48 32*24 66*12 FPS = 60 TITLE = 'Tilemap demo' BGCOLOR = DARKGREY TILESIZE = 32 GRIDWIDTH = WIDTH / TILESIZE GRIDHEIGHT = HEIGHT / TILESIZE # player settings PLAYER_SPEED = 600 # 100 px/seconds <file_sep>import pygame from board import Grid from player import Player, Stats from enum import Enum, auto import os os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (400,100) surface = pygame.display.set_mode((1200, 900)) pygame.display.set_caption('Minesweeper') class States(Enum): running = auto() game_over = auto() win = auto() state = States.running player = Player() grid = Grid(player) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN and state == States.running: if pygame.mouse.get_pressed()[0]: # check for the left mouse button pos = pygame.mouse.get_pos() grid.click(pos[0], pos[1]) elif pygame.mouse.get_pressed()[2]: pos = pygame.mouse.get_pos() grid.mark_mine(pos[0]//30, pos[1]//30) if grid.check_if_win(): state = States.win if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and (state == States.game_over or state == States.win): grid.reload() state = States.running if event.key == pygame.K_b: grid.show_mines() surface.fill((0,0,0)) if player.get_health() == 0: state = States.game_over if state == States.game_over: Stats.draw(surface, 'Game over!', (970, 350)) Stats.draw(surface, 'Press Space to restart', (920, 400)) elif state == States.win: Stats.draw(surface, 'You win!', (1000, 350)) Stats.draw(surface, 'Press Space to restart', (920, 400)) grid.draw(surface) Stats.draw(surface, 'Lives remaining', (950, 100)) Stats.draw(surface, str(player.get_health()), (1020, 200)) Stats.draw(surface, 'RMB to mark mine', (950, 550)) Stats.draw(surface, 'press b to show mines', (920, 650)) pygame.display.flip() <file_sep>import pygame my_name = "<NAME>" pygame.init() my_font = pygame.font.SysFont("arial", 64) name_surface = my_font.render(my_name, True, (0, 0, 0), (255, 255, 255)) pygame.image.save(name_surface, "name.png") <file_sep>import math import random import pygame import tkinter as tk from tkinter import messagebox class cube(object): rows = 0 w = 0 def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)): pass def move(self,dirnx,dirny): pass def draw(self,surface,eyes=False): pass class snake(object): def __init__(self,color,pos): pass def move(self): pass def reset(self,pos): pass def addCube(self): pass def draw(self,surface): pass def drawGrid(w,rows,surface): pass def redrawWindow(surface): pass def randomSnack(rows,items): pass def message_box(subject,content): pass def main(): pass rows = 0 w = 0 h = 0 cube.rows = rows cube.w = w main()<file_sep>Python Game Programming Tutorial: Pong for Beginners [Youtube playlist](https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2) - [Pong Part 1 Getting Started](1_pong.py) - [Pong Part 2 Game Objects](2_pong.py) - [Pong Part 3 Moving the Paddles](3_pong.py) - [Pong Part 4 Moving the Ball](4_pong.py) - [Pong Part 5 Colliding with the Paddles](5_pong.py) - [Pong Part 6 Scoring](6_pong.py) - [Pong Part 7 Sounds](7_pong.py) <file_sep>import math import random import pygame import tkinter as tk from tkinter import messagebox WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) class cube(object): rows = 0 w = 0 def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)): pass def move(self,dirnx,dirny): pass def draw(self,surface,eyes=False): pass class snake(object): def __init__(self,color,pos): pass def move(self): pass def reset(self,pos): pass def addCube(self): pass def draw(self,surface): pass def drawGrid(w,rows,surface): """ This function draws a square grid on main display """ #distance between grid lines sizeBtwn = w // rows x = 0 y = 0 #create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn #vertical lines pygame.draw.line(surface, WHITE, (x,0), (x,w)) #horizontal lines pygame.draw.line(surface, WHITE, (0,y), (w,y)) def redrawWindow(surface): global rows, width #background surface.fill(BLACK) #draw grid drawGrid(width, rows, surface) #update display pygame.display.update() def randomSnack(rows,items): pass def message_box(subject,content): pass def main(): global width, rows #create game display width = 500 rows = 20 win = pygame.display.set_mode((width, width)) #square display #snake start position s = snake(color=RED, pos=(10,10)) clock = pygame.time.Clock() flag = True while flag: #pygame.time.delay(50) clock.tick(10) #game max speed 10 FPS redrawWindow(win) #rows = 0 #w = 0 #h = 0 #cube.rows = rows #cube.w = w print("here") main()<file_sep>""" Basic Movement and Key Presses video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5 1. create a rectangle 2. move it by key pressed """ import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 from math import * # define colors BLACK = (0 , 0 , 0) GREEN = (0 , 255 , 0) pygame.init() WIDTH, HEIGHT = 640, 480 #### Create a canvas on which to display everything #### screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) #set windows title pygame.display.set_caption("rotating sprite") #### Create a surface with the same size as the window #### background = pygame.Surface((WIDTH, HEIGHT)) #character variables x = 50 y = 50 width = 40 height = 60 vel = 5 # define a surface (RECTANGLE) sprite_orig = pygame.Surface((50 , 50)) # for making transparent background while rotating an image sprite_orig.set_colorkey(BLACK) # fill the rectangle / surface with green color sprite_orig.fill(GREEN) # creating a copy of orignal image for smooth rotation sprite = sprite_orig.copy() sprite.set_colorkey(BLACK) # define rect for placing the rectangle at the desired position rect = sprite.get_rect() rect.center = (WIDTH // 2 , HEIGHT // 2) # keep rotating the rectangle until running is set to False screen.blit(sprite , rect) # sprite = pygame.Surface((50, 50)) # sprite.fill((255,255,255)) # rect = sprite.get_rect() # rect.center = (WIDTH / 2, HEIGHT / 2) # sprite_pos = Vector2(100.0, 100.0) sprite_speed = 300. sprite_rotation = 0. sprite_rotation_speed = 180. # deg/second clock = pygame.time.Clock() key_direction = Vector2(0, 0) #main game loop clock = pygame.time.Clock() run = True while run: # pygame.time.delay(100) #this will be a clock for the game for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False # key_direction.x, key_direction.y = (0, 0) rotation_direction = 0. keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: rotation_direction = +1 if keystate[pygame.K_RIGHT]: rotation_direction = -1 time_passed = clock.tick(30) time_passed_seconds = time_passed / 1000.0 #-----FIRST DO ROTATION AND POSITION CALCULATIONS # calculate sprite rotation sprite_rotation += rotation_direction * sprite_rotation_speed * time_passed_seconds sprite_rotation %= 360 # making a copy of the old center of the rectangle old_center = rect.center # now do the drawings rotated_sprite = pygame.transform.rotate(sprite_orig, sprite_rotation) rect = rotated_sprite.get_rect() # set the rotated rectangle to the old center rect.center = old_center # clear the screen every time before drawing new objects screen.fill(BLACK) # drawing the rotated rectangle to the screen screen.blit(rotated_sprite , rect) # w, h = rotated_sprite.get_size() # sprite_draw_pos = Vector2(sprite_pos.x - w/2, sprite_pos.y - h/2) # #screen.blit(rotated_sprite, sprite_draw_pos) # #screen.blit(rotated_sprite, (int(sprite_pos.x), int(sprite_pos.y))) # making a copy of the old center of the rectangle # old_center = rect.center #### Blit the surface onto the canvas #### # screen.blit(background,(0,0)) #### Blit the surface onto the canvas #### # screen.blit(sprite,(int(sprite_pos.x), int(sprite_pos.y))) #### display canvas #### pygame.display.update() print(sprite_rotation) #print(heading) # exit pygame pygame.quit() exit() <file_sep>from math import tan def calculate_viewing_distance(fov, screen_width): d = (screen_width/2.0) / tan(fov/2.0) return d <file_sep>import pymunkoptions pymunkoptions.options["debug"] = False import pyglet from pyglet.window import FPSDisplay, key import pymunk from pymunk.pyglet_util import DrawOptions from pymunk.vec2d import Vec2d import random collision_types = { "ball":1, "brick":2, "bottom":3, "player":4 } class Bricks: def __init__(self, space): for x in range(10): for y in range(10): body = pymunk.Body(body_type=pymunk.Body.KINEMATIC) body.position = x*110+90, y*30+500 shape = pymunk.Segment(body, (0,0), (100,0), 8) shape.elasticity = 0.98 shape.collision_type = collision_types["brick"] space.add(body, shape) handler = space.add_collision_handler(collision_types["brick"], collision_types["ball"]) handler.separate = self.remove_brick def remove_brick(self, arbiter, space, data): brick_shape = arbiter.shapes[0] space.remove(brick_shape, brick_shape.body) class Walls: def __init__(self, space): left = pymunk.Segment(space.static_body, (50,110), (50,800), 2) top = pymunk.Segment(space.static_body, (50,800), (1230,800), 2) right = pymunk.Segment(space.static_body, (1230,800), (1230,110), 2) left.elasticity = 0.98 top.elasticity = 0.98 right.elasticity = 0.98 bottom = pymunk.Segment(space.static_body, (50,50), (1230,50), 2) bottom.sensor = True bottom.collision_type = collision_types["bottom"] handler = space.add_collision_handler(collision_types["ball"], collision_types["bottom"]) handler.begin = self.reset_game space.add(left, top, right, bottom) def reset_game(self, arbiter, space, data): window.reset_game() return True class Ball(pymunk.Body): def __init__(self, space, position): super().__init__(1, pymunk.inf) self.position = position.x, position.y+18 shape = pymunk.Circle(self, 10) shape.elasticity = 0.98 shape.collision_type = collision_types["ball"] self.spc = space self.on_paddle = True self.velocity_func = self.constant_velocity self.joint = pymunk.GrooveJoint(space.static_body, self, (100,118), (1180,118), (0,0)) space.add(self, shape, self.joint) def shoot(self): self.on_paddle = False self.spc.remove(self.joint) direction = Vec2d(random.choice([(50,500), (-50,500)])) self.apply_impulse_at_local_point(direction) def constant_velocity(self, body, gravity, damping, dt): body.velocity = body.velocity.normalized()*600 def update(self): if self.position.x < 50 or self.position.x > 1230 or self.position.y > 800: self.velocity *= -1 class Player(pymunk.Body): def __init__(self, space): super().__init__(10, pymunk.inf) self.position = 640, 100 shape = pymunk.Segment(self, (-50,0), (50,0), 8) shape.elasticity = 0.98 shape.collision_type = collision_types["player"] joint = pymunk.GrooveJoint(space.static_body, self, (100,100), (1180,100), (0,0)) space.add(self, shape, joint) class GameWindow(pyglet.window.Window): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_location(300, 50) self.fps = FPSDisplay(self) self.space = pymunk.Space() self.options = DrawOptions() self.player = Player(self.space) self.ball = Ball(self.space, self.player.position) self.walls = Walls(self.space) self.bricks = Bricks(self.space) def on_draw(self): self.clear() self.space.debug_draw(self.options) self.fps.draw() def on_key_press(self, symbol, modifiers): if symbol == key.RIGHT: self.player.velocity = 600, 0 if self.ball.on_paddle: self.ball.velocity = self.player.velocity if symbol == key.LEFT: self.player.velocity = -600, 0 if self.ball.on_paddle: self.ball.velocity = self.player.velocity if symbol == key.SPACE: if self.ball.on_paddle: self.ball.shoot() if symbol == key.R: self.reset_game() def on_key_release(self, symbol, modifiers): if symbol in (key.RIGHT, key.LEFT): self.player.velocity = 0, 0 if self.ball.on_paddle: self.ball.velocity = 0, 0 def reset_game(self): for shape in self.space.shapes: if shape.body != self.space.static_body and shape.body.body_type != pymunk.Body.KINEMATIC: self.space.remove(shape.body, shape) for constraint in self.space.constraints: self.space.remove(constraint) self.player = Player(self.space) self.ball = Ball(self.space, self.player.position) def update(self, dt): self.space.step(dt) self.ball.update() if __name__ == "__main__": window = GameWindow(1280, 900, "Breakout game", resizable=False) pyglet.clock.schedule_interval(window.update, 1/60.0) pyglet.app.run()<file_sep># -*- coding: utf-8 -*- """ Created on Mon Dec 21 11:41:03 2020 @author: crtjur """ import pygame as py # define constants WIDTH = 500 HEIGHT = 500 FPS = 30 # define colors BLACK = (0 , 0 , 0) GREEN = (0 , 255 , 0) # initialize pygame and create screen py.init() screen = py.display.set_mode((WIDTH , HEIGHT)) # for setting FPS clock = py.time.Clock() rot = 0 rot_speed = 2 # define a surface (RECTANGLE) image_orig = py.Surface((100 , 100)) # for making transparent background while rotating an image image_orig.set_colorkey(BLACK) # fill the rectangle / surface with green color image_orig.fill(GREEN) # creating a copy of orignal image for smooth rotation image = image_orig.copy() image.set_colorkey(BLACK) # define rect for placing the rectangle at the desired position rect = image.get_rect() rect.center = (WIDTH // 2 , HEIGHT // 2) # keep rotating the rectangle until running is set to False running = True while running: # set FPS clock.tick(FPS) # clear the screen every time before drawing new objects screen.fill(BLACK) # check for the exit for event in py.event.get(): if event.type == py.QUIT: running = False # making a copy of the old center of the rectangle old_center = rect.center # defining angle of the rotation rot = (rot + rot_speed) % 360 # rotating the orignal image new_image = py.transform.rotate(image_orig , rot) rect = new_image.get_rect() # set the rotated rectangle to the old center rect.center = old_center # drawing the rotated rectangle to the screen screen.blit(new_image , rect) # flipping the display after drawing everything py.display.flip() py.quit()<file_sep>import cx_Freeze executables = [cx_Freeze.Executable("ants_game.py")] cx_Freeze.setup( name="Ant Game", options={"build_exe": {"packages":["pygame"], "include_files":["ant.png","leaf.png","spider.png",'gameobjects']}}, executables = executables ) <file_sep>#pseudocode tank_heading = Vector3(tank_matrix.forward) tank_matrix.translation += tank_heading * tank_speed * time_passed <file_sep># -*- coding: utf-8 -*- """ Created on Wed Dec 23 19:16:26 2020 @author: crtom GRID = 600*600 GRID 6x6 = 36 pieces 100x100 per square one piece is 80x80 + margin = 100x100 """ # create a list of touple positions grid_touple_list = [] grid_pixel_pos_list = [] card_position_list = [] for y in range(0, 6): for x in range(0, 6): grid_touple_list.append((x,y)) grid_pixel_pos_list.append((x*100, y*100)) card_position_list.append(((x*100) + 10, (y*100) + 10)) # for x in range(0, 600, 100): # for y in range(0, 600, 100): # grid_pixel_pos_list.append((x, y)) # card_position_list.append((x + 10, y + 10)) print(grid_touple_list) print(grid_pixel_pos_list) print(card_position_list)<file_sep>import pygame pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 24) class Player: def __init__(self): self.health = 5 def sub_health(self): self.health -= 1 def get_health(self): return self.health class Stats: @staticmethod def draw(surface, label, pos): textsurface = myfont.render(label, False, (255, 255, 255)) surface.blit(textsurface, (pos[0], pos[1])) <file_sep># -*- coding: utf-8 -*- """ Created on Thu Dec 24 18:24:42 2020 @author: crtom vector class from the book game development with pygame Vectors describe: magnitude and direction. """ import math class Vector2(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __str__(self): return "(%s, %s)"%(self.x, self.y) # create vector from two points """These class methods are called from the class and not an instance of the class""" @classmethod def from_points(cls, P1, P2): return cls( P2[0] - P1[0], P2[1] - P1[1] ) # pitagora for distance calculation def get_magnitude(self): return math.sqrt( self.x**2 + self.y**2 ) """Unit vectors always have a length of 1, are often used to represent a heading. When we move into the third dimension, essential for everything from collision detection to lighting. """ def normalize(self): magnitude = self.get_magnitude() self.x /= magnitude self.y /= magnitude # Addition: rhs stands for Right Hand Side def __add__(self, rhs): return Vector2(self.x + rhs.x, self.y + rhs.y) # Substraction: substracting means going in the opposite direction def __sub__(self, rhs): return Vector2(self.x - rhs.x, self.y - rhs.y) # Negation def __neg__(self): return Vector2(-self.x, -self.y) # Multiplication by scalar def __mul__(self, scalar): return Vector2(self.x * scalar, self.y * scalar) def __rmul__(self, scalar): return self.__mul__(scalar) # commutative operation # Division by scalar def __truediv__(self, scalar): return Vector2(self.x / scalar, self.y / scalar) # check for equal def __eq__(self, other): if isinstance (other, self.__class__): return self.x == other.x and self.y == other.y return self.x == other and self.y == other # greater or equal def __ge__(self, other): if isinstance (other, self.__class__): return self.x >= other.x and self.y >= other.y return self.x >= other and self.y >= other def get_value(self): return (self.x, self.y) #----------------------------------------------------------------------------- def test_function_v1(): # create vectors vector_a = Vector2(1, 1) vector_b = Vector2(0, 0) print(vector_a) print(vector_a.x, vector_a.y) # test_create_vector_from_two_points A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) print('vector AB:',AB) # get vector length, magnitude print('magnitude: ', AB.get_magnitude()) AB.normalize() print('normalized:', AB) def test_function_v2(): A = (10.0, 20.0) B = (30.0, 35.0) C = (15.0, 45.0) AB = Vector2.from_points(A, B) BC = Vector2.from_points(B, C) print("Vector AB is", AB) print("Vector BC is", BC) AC = Vector2.from_points(A, C) print("Vector AC is", AC) AC = AB + BC print("Addition: AB + BC is", AC) AC = AB - BC print("Subtraction: AB - BC is", AC) AC = -AB print("Negation: -AB is", AC) AC = 10*AB print("Multiplication: 10*AB is", AC) AC = AB/2 print("Division: AB/2 is", AC) def calculate_position(): #point A A = (10.0, 20.0) #point B B = (30.0, 35.0) # vector of distance between points AB AB = Vector2.from_points(A, B) # step vector, length of 1/10 AB step = AB * .1 #start position vector at point A position = Vector2(A[0], A[1]) for n in range(10): position += step print(position) if __name__ == '__main__': #test_function_v2() calculate_position()<file_sep>def stereo_pan(x_coord, screen_width): right_volume = float(x_coord) / screen_width left_volume = 1.0 - right_volume return (left_volume, right_volume) <file_sep>import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() screen.fill((255, 255, 255)) mouse_pos = pygame.mouse.get_pos() for x in range(0,640,20): pygame.draw.line(screen, (0, 0, 0), (x, 0), mouse_pos) pygame.draw.line(screen, (0, 0, 0), (x, 479), mouse_pos) for y in range(0,480,20): pygame.draw.line(screen, (0, 0, 0), (0, y), mouse_pos) pygame.draw.line(screen, (0, 0, 0), (639, y), mouse_pos) pygame.display.update() <file_sep>from math import sqrt class Vector3(object): def init (self, x, y, z): self.x = x self.y = y self.z = z def add (self, x, y, z): return Vector3(self.x + x, self.y + y, self.z + z) def get_magnitude(self): return sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) <file_sep>class Vector2: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "(%s, %s)"%(self.x, self.y) def from_points(P1, P2): # ( P2[0] - P1[0], P2[1] - P1[1] ) is the same as: # numpy.array(P1) - numpy.array(P1) return Vector2(P2[0] - P1[0], P2[1] - P1[1]) A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) print(AB) <file_sep># -*- coding: utf-8 -*- """ Created on Fri Dec 25 21:10:25 2020 @author: crtom """ """ Basic Movement and Key Presses video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5 1. create a rectangle 2. move it by key pressed """ import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 # draw antialiase line for vectors from pygame import gfxdraw from math import * # defines WIDTH, HEIGHT = 640, 480 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255,0,0) LIME = (0,255,0) BLUE = (0,0,255) YELLOW = (255,255,0) CYAN = (0,255,255) MAGENTA = (255,0,255) SILVER = (192,192,192) GREY = (128,128,128) MAROON = (128,0,0) OLIVE = (128,128,0) GREEN = (0,128,0) PURPLE = (128,0,128) TEAL = (0,128,128) NAVY = (0,0,128) pygame.init() #### Create a canvas on which to display everything #### screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) #set windows title pygame.display.set_caption("vector arrow") #### Create a surface with the same size as the window #### background = pygame.Surface((WIDTH, HEIGHT)) background.fill(WHITE) clock = pygame.time.Clock() def draw_point(screen, color, p, radius): #, color, position, radius point = (int(p[0]), int(p[1])) pygame.draw.circle(screen, color, point, radius) def draw_line(screen, color, startpoint, vector, width): """ Draws line representing vector. """ v1 = Vector2(vector.x, vector.y) endpoint = (v1.x + startpoint[0], v1.y + startpoint[1]) startpoint = (int(startpoint[0]), int(startpoint[1])) endpoint = (int(endpoint[0]), int(endpoint[1])) pygame.draw.line(screen, color, startpoint, endpoint, width) # ----------drawing p_A = (WIDTH // 2, HEIGHT // 2) p_B = (WIDTH // 2, 50) vector_AB = Vector2.from_points(p_A, p_B) # print(p_A) # print(p_B) # #as_tuple #------------------------ screen.blit(background, (0,0)) # draw_point(screen, RED, p_A, 5) # pygame.display.update() # draw_point(screen, BLUE, p_B, 5) # pygame.display.update() # draw_line(screen, color, startpoint, vector, width): # ORIGINAL VECTOR # draw_line(screen, BLACK, p_A, vector_AB, 3) # pygame.display.update() # ROTATED VECTOR angle = 45 x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y vector_AB_rot = Vector2(x_rot, y_rot) # draw_line(screen, GREY, p_A, vector_AB_rot, 3) # perpendicualar vector vector_AB_perp = Vector2(-vector_AB_rot.y, vector_AB_rot.x) # draw_line(screen, GREY, p_A, vector_AB_perp, 3) # pygame.display.update() # arrow head to original vector # first find point on original vector that is a little bellow vector endpoint vector_norm = Vector2(vector_AB.x, vector_AB.y) # vector_norm.normalise() vector_norm *= 10 vector_norm = vector_AB - vector_norm # draw_line(screen, GREY, p_A, vector_norm, 3) # pygame.display.update() # find perpendicular vector to original vector_perp = Vector2(-vector_AB.y, vector_AB.x) vector_perp.normalize() vector_perp *= 5 point = (int(vector_norm.x) + p_A[0], int(vector_norm.y) + p_A[1]) point = (point[0], point[1]) # draw_point(screen, BLACK, point, 5) draw_line(screen, GREY, point, vector_perp, 3) draw_line(screen, GREY, point, -vector_perp, 3) # pointL = original_vector_startpoint+ point_R = (point[0] + vector_perp.x, point[1] + vector_perp.y) point_L = (point[0] - vector_perp.x, point[1] - vector_perp.y) # draw_point(screen, BLACK, point_R, 5) # draw_point(screen, BLACK, point_L, 5) endpoint = vector_AB.x+ p_A[0], vector_AB.y + p_A[1] # draw rectangle # pygame.draw.polygon(screen, GREEN, (point_L, point_R, endpoint)) # pygame.display.update() # print(vector_AB) # print(vector_norm) # print(point) # print(vector_perp) # draw_line(screen, RED, p_A, vector_a, 3) # pygame.display.update() def draw_vector(screen, startpoint, vector, color, width, DEBUG = False): """ E *** ***** L**M**R * * * * ----S----- * * O E - vector endpoint M - arrow midpoint L - arrow left point R - arrow right point """ #------------CALCULATIONS--------------- #DEBUG = False # create points E = (0, 0) L = (0, 0) M = (0, 0) R = (0, 0) # copy vector to new v = Vector2(int(vector.x), int(vector.y)) # 1) set S - starrpoint S = (startpoint[0], startpoint[1]) # 2) set E - endpoint E = (v.x + S[0], v.y + S[1]) # 3) Find vector SM v_SM = Vector2(v.x, v.y) v_SM.normalize() v_SM *= 2*width # v_SM *= 10 v_SM = v - v_SM M = (S[0]+v_SM.x, S[1]+v_SM.y) # 3) Find perpendicular vector v_perp = Vector2(-v.y, v.x) v_perp.normalize() v_perp *= width # v_perp *= 5 # 4) Find arrow head points L = (M[0] - v_perp.x, M[1] - v_perp.y) R = (M[0] + v_perp.x, M[1] + v_perp.y) #------------DRAWINGS--------------- # pixels must be integers E = (int(E[0]),int(E[1])) M = (int(M[0]),int(M[1])) L = (int(L[0]),int(L[1])) R = (int(R[0]),int(R[1])) # draw main vector line pygame.draw.line(screen, color, S, M, width) # draw points for debugging purpose # points = S, E, L, M, R if DEBUG: print('S = ', S) print('E = ', E) print('M = ', M) print('M = ', L) print('M = ', R) pygame.draw.circle(screen, BLUE, S, 5) pygame.draw.circle(screen, BLUE, E, 5) pygame.draw.circle(screen, GREEN, M, 5) pygame.draw.circle(screen, RED, L, 5) pygame.draw.circle(screen, GREY, R, 5) # draw arrow head poligone # if very short, dont draw arrow #length = sqrt(v.x pygame.draw.polygon(screen, color, (L, R, E)) draw_vector(screen, p_A, vector_AB, BLACK, 5) #---------------------- #main game loop clock = pygame.time.Clock() run = True angle = 0. while run: # pygame.time.delay(100) #this will be a clock for the game for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False # calculate times time_passed = clock.tick(30) time_passed_seconds = time_passed / 1000.0 angle += 0.01 x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y vector_AB_rot = Vector2(x_rot, y_rot) # get X component magnitude = sqrt(vector_AB.x**2 + vector_AB.y**2) direction = Vector2(vector_AB_rot.x, vector_AB_rot.y) direction.normalize() # print(direction) #x_component = magnitude * sin(angle) x_component = direction.x * magnitude y_component = direction.y * magnitude #y_component = magnitude * cos(angle) # print('angle:', angle, 'x_component:', x_component,'y_component:', y_component) v_x = Vector2(x_component, 0) v_y = Vector2(0, y_component) #---------------UPDATE DISPALY----------- screen.blit(background, (0,0)) # draw circle pygame.draw.circle(screen, GREY, p_A, int(magnitude),2) pygame.draw.line(screen, GREY, (0, HEIGHT//2), (WIDTH, HEIGHT//2), 2) pygame.draw.line(screen, GREY, (WIDTH//2, 0), (WIDTH//2, HEIGHT), 2) draw_vector(screen, p_A, vector_AB_rot, BLACK, 5) draw_vector(screen, p_A, v_x, RED, 5) draw_vector(screen, p_A, v_y, BLUE, 5) # update all drawing objects pygame.display.update() # exit pygame pygame.quit() exit() """ #draw_arrow(screen, 0, 10, GREEN) #------------------DRAWINGS------------------------ #### Blit the surface onto the canvas #### screen.blit(background,(0,0)) #### Blit the points onto canvas angle += 0.01 #draw_arrow(screen, colour, startpoint, vector, width): draw_point(screen, BLUE, p_A, 5) #draw_point(screen, GREEN, p_B, 5) draw_arrow(screen, BLUE, p_A, vector_AB_rot, 2) #screen.blit(arrow, arrow_pos) #### display canvas #### pygame.display.update() x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y vector_AB_rot = Vector2(x_rot, y_rot) """<file_sep>def perspective_project(vector3, d): x, y, z = vector3 return (x * d/z, -y * d/z) <file_sep>import sys import math import random import pygame from pygame.locals import * import tkinter as tk from tkinter import messagebox clock = pygame.time.Clock() WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) #--------------------------draw grid fuction---------------------------- def drawGrid(w,rows,surface): """ This function draws a square grid on main display """ #distance between grid lines sizeBtwn = w // rows x = 0 y = 0 #create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn #vertical lines pygame.draw.line(surface, WHITE, (x,0), (x,w)) #horizontal lines pygame.draw.line(surface, WHITE, (0,y), (w,y)) #-------------------------cube object----------------------------------------- class cube(object): """ class to create a single grid cube, that has position and movement """ rows = 20 #set number of rows w = 500 #set pixel screen width def __init__(self, start, dirnx, dirny, color = WHITE): self.pos = start #touple (x,y) self.dirnx = 0 self.dirny = 0 self.color = color #touple(r,g,b) def set_direction(self,dirnx,dirny): self.dirnx = dirnx self.dirny = dirny def move(self): """ move cube, by adding new direction to previous position """ self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny) def draw(self,surface): """ drawing: convert x,y grid position to pixel position """ dis = self.w // self.rows #distance between x and y values #variables for easy coding i = self.pos[0] # row j = self.pos[1] # column #draw just a little bit less, so we draw inside of the square. and we dont cover grid. pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 )) #----------------------------------------------------------------------------------- class snake(object): """ class for snake """ body = [] #list of cube objects turns = {} #dictionary of turns ADDING A KEY OF--> # key = current position of snake head # value = direction of turn] def __init__(self,color,pos): self.color = color self.head = cube(pos) self.body.append(self.head) # snake starts with one cube = head self.dirnx = 0 #direction moving x 1, -1 self.dirny = 1 #direction moving y 1, -1 #--------------------------------------------------------------------- def move(self): """ moving our snake in x,y thinking LEFT (self.dirnx=-1, self.dirny=0) RIGHT (self.dirnx=1, self.dirny=0) UP (self.dirnx=0, self.dirny=1) DOWN (self.dirnx=0, self.dirny=-1) """ for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_LEFT]: self.dirnx = -1 self.dirny = 0 # we mustremember where we turned, so other cubes can follow # add a new key #example - here we turned in thar way self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_RIGHT]: self.dirnx = 1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_UP]: self.dirnx = 0 self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx = 0 self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] #look trough all position of snake #we get the index=i and the cube=c of body for i, c in enumerate(self.body): p = c.pos[:] #for each of the sube, we grab position and check turn #if this position in turns, than we move if p in self.turns: turn = self.turns[p] #here we store direction where to move c.move(turn[0],turn[1]) #if we are on the last cube of the snake, remove the turn, we finished it if i == len(self.body)-1: self.turns.pop(p) else: #CHECK IF WE REACHED EDGE OF THE SCREEN #if MOVE LEFT & we are at the left side of screen if (c.dirnx == -1) and (c.pos[0] <= 0): c.pos = (c.rows-1,c.pos[1]) #c.pos = (c.rows-1,c.pos[1]) #if MOVE RIGHT & we are at the left side of screen elif (c.dirnx == 1) and (c.pos[0] >= c.rows-1): c.pos = (0,c.pos[1]) #if MOVE DOWN & we are at the left side of screen elif (c.dirny == 1) and (c.pos[1] >= c.rows-1): c.pos = (c.pos[0],0) #if MOVE UP & we are at the left side of screen elif (c.dirny == -1) and (c.pos[1] <= 0): c.pos = (c.pos[0],c.rows-1) #normal move of cube else: c.move(c.dirnx,c.dirny) #--------------------------------------------------------------------- def addCube(self): """ Figure out where is tail, and add a cube after it """ tail = self.body[-1] dx, dy = tail.dirnx, tail.dirny if dx == 1 and dy == 0: self.body.append(cube((tail.pos[0]-1,tail.pos[1]))) elif dx == -1 and dy == 0: self.body.append(cube((tail.pos[0]+1,tail.pos[1]))) elif dx == 0 and dy == 1: self.body.append(cube((tail.pos[0],tail.pos[1]-1))) elif dx == 0 and dy == -1: self.body.append(cube((tail.pos[0],tail.pos[1]+1))) self.body[-1].dirnx = dx self.body[-1].dirny = dy #--------------------------------------------------------------------- def draw(self,surface): for index, cube in enumerate(self.body): #check where to draw eyes for snake head if index == 0: cube.draw(surface,True) #with eyes else: cube.draw(surface,False) #without eyes #----------------------------------------------------------------------------------- def redrawWindow(surface): global rows, width #background surface.fill(BLACK) #draw grid drawGrid(width, rows, surface) #draw ball ball.draw(surface) #update display pygame.display.update() #--------------------------------------------------------------------------------------- def key_events(): for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): #pygame.quit() #sys.exit() return True #in pong we move in only y directions keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_UP]: self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] return False #--------------------------------------------------------------------------------------- def main(): global width, rows, ball #---------------game initialization--------------------------- #create game display width = 500 rows = 20 #create game objects win = pygame.display.set_mode((width, width)) #square display ball = cube((10,1),0,0,WHITE) ball.set_direction(1,1) #set initial ball movement direction FPScount = 0 #-----------------------continuous game loop------------- GameOver = False while not GameOver: #pygame.time.delay(50) clock.tick(10) #game max speed 10 FPS GameOver = key_events() #update ball position ball.move() #check next direction------------------------------- #CONSTRAINTS X if ball.pos[0] <= 0 or ball.pos[0] >= rows-1: ball.dirnx = -ball.dirnx #CONSTRAINTS Y if ball.pos[1] <= 0 or ball.pos[1] >= rows-1: ball.dirny = -ball.dirny #------------------------------------------------- #if we are moving in right direction #print(f'rows:{rows} ball.pos[0]:{ball.pos[0]} ball.pos[1]:{ball.pos[1]}') #FPScount += 1 #print(FPScount) redrawWindow(win) #--------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------- main() pygame.quit() sys.exit() <file_sep># -*- coding: utf-8 -*- """ Created on Mon Dec 28 18:28:20 2020 @author: crtom """ import pygame as pg from settings import * class Map: def __init__(self, filename): self.data = [] with open(filename, 'rt') as f: for line in f: self.data.append(line.strip()) # remove new line char at end # print(line) # how big map is self.tilewidth = len(self.data[0]) # N of columns self.tileheight = len(self.data) # N of rows # pixel width of the map self.width = self.tilewidth * TILESIZE self.height = self.tileheight * TILESIZE # camera object is independant from other objects. it needs only tilemap class Camera: # 1. must shift the drawing rectangle to what we want to draw # 2. camera must update to where the player offset is """ theory - Returns a Rect moved x pixels horizontally and y pixels vertically Rect.move(x, y) """ def __init__(self, width, height): # use rectangle to track camera #self.camera = pg. Rect(SHIFT_X, SHIFT_Y, width, height) self.camera = pg. Rect(0, 0, width, height) self.width = width self.height = height def apply(self, entity): return entity.rect.move(self.camera.topleft) # update and follow targeted sprite def update(self, target): # if player moves to right, map moves to the left x = -target.rect.x + int(WIDTH / 2) y = -target.rect.y + int(HEIGHT / 2) # now limit scrolling, so we dont see over the map x = min(0, x) # left side y = min(0, y) # top side x = max(-(self.width - WIDTH), x) # right side y = max(-(self.height - HEIGHT), y) # bottom side # ADJUST WHERE our camera rectangle is self.camera = pg.Rect(x, y, self.width, self.height) <file_sep># -*- coding: utf-8 -*- """ Created on Tue Dec 15 18:09:41 2020 @author: crtom - BASIC ARHITECTURE, get mouse coordinates #------------------------------------------------------------------------------ #-------------------------------------------------------------------------- #---------------------------------------------------------------------- #------------------------------------------------------------------ #-------------------------------------------------------------- """ import pygame import sys from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT #-------------------------------------------------------------------------- #-------------------------constants---------------------------------------- #-------------------------------------------------------------------------- FPS = 30 WINDOWWIDTH = 640 WINDOWHEIGHT = 480 REVEALSPEED = 8 BOXSIZE = 40 GAPSIZE = 10 BOARDWIDTH = 10 BOARDHEIGHT = 7 # check assert(BOARDWIDTH*BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches' XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2) YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2) # COLORS ( R , G , B ) WHITE = (255, 255, 255) BLACK = ( 0, 0, 0) RED = (255, 0, 0) LIME = ( 0, 255, 0) BLUE = ( 0, 0, 255) NAVYBLUE= ( 60, 60, 100) YELLOW = (255, 255, 0) ORANGE = (255, 128, 0) CYAN = ( 0, 255, 255) MAGENTA = (255, 0, 255) SILVER = (192, 192, 192) GRAY = (128, 128, 128) MAROON = (128, 0, 0) OLIVE = (128, 128, 0) GREEN = ( 0, 128, 0) PURPLE = (128, 0, 128) TEAL = ( 0, 128, 128) NAVY = ( 0, 0, 128) BGCOLOR = NAVYBLUE LIGHTBGCOLOR = GRAY BOXCOLOR = WHITE HIGHLIGHTCOLOR = BLUE DONUT = 'donut' SQUARE = 'square' DIAMOND = 'diamond' LINES = 'lines' OVAL = 'oval' ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN) ALLSHAPES = (DONUT, SQUARE, DIAMOND, LINES, OVAL) assert len(ALLCOLORS) * len(ALLSHAPES) * 2 <= BOARDWIDTH * BOARDHEIGHT,'Board is too big for the number of shapes/colors defined.' #------------------------------------------------------------------------------ #----------------------------main loop----------------------------------------- #------------------------------------------------------------------------------ def main(): # global variables global FPSCLOCK, DISPLAYSURF # for mouse pos mousex = 0 mousey = 0 #-------------------------------------------------------------------------- # init pygame pygame.init() FPSCLOCK = pygame.time.Clock() # initialize clock DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) # initialize surface DISPLAYSURF.fill(BGCOLOR) pygame.display.set_caption('Memory Game') #-------------------------------------------------------------------------- #-------------------------GAME loop---------------------------------------- #-------------------------------------------------------------------------- while True: #----------------------event handling--------------------------------- for event in pygame.event.get(): # event objects have type attribute if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mousex, mousey = event.pos elif event.type == MOUSEBUTTONUP: mousex, mousey = event.pos mouseCicked = True print(mousex, mousey) #------------------------timing---------------------------------------- # draws surface object stored in DISPLAYSURF pygame.display.update() FPSCLOCK.tick(FPS) #------------------------------------------------------------------------------ #-------------------------function definitions--------------------------------- #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #-------------------------Start application------------------------------------ #------------------------------------------------------------------------------ if __name__ == '__main__': main()<file_sep>""" Basic Movement and Key Presses video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5 1. create a rectangle 2. move it by key pressed """ import pygame from pygame.locals import * from rgb_color_dictionary import * pygame.init() #create window win = pygame.display.set_mode((500,500)) #set windows title pygame.display.set_caption("First Game") #character variables x = 50 y = 50 width = 40 height = 60 vel = 5 class player(object): def __init__(self, x, y, vx, vy, width, height): self.x = x self.y = y self.width = width self.height = height self.vx = vx self.vy = vy self.vel = 5 self.isJump = False self.jumpCount = 10 self.left = False self.right = False self.up = False self.down = False self.walkCount = 0 def draw(self,win): pygame.draw.rect(win,RED,(self.x,self.y,self.width,self.height)) #draw player def set_speed(self, vx, vy): red_cube.vx = vx red_cube.vy = vy def redrawGameWindow(): pygame.display.update() #create a player red_cube = player(x=50,y=50,vx=0,vy=0, width=40,height=60) #main game loop run = True while run: pygame.time.delay(100) #this will be a clock for the game keys = {'left':False,'right':False, 'up':False, 'down':False} for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False red_cube.set_speed(0,0) #cube not moving keystate = pygame.key.get_pressed() #straight moves if keystate[pygame.K_UP]: red_cube.vy = -5 if keystate[pygame.K_DOWN]: red_cube.vy = 5 if keystate[pygame.K_LEFT]: red_cube.vx = -5 if keystate[pygame.K_RIGHT]: red_cube.vx = 5 #diagonals must be slower for sq(2)= 1.414 pitagora if red_cube.vx != 0 and red_cube.vy != 0: red_cube.vx /= 1.414 red_cube.vy /= 1.414 red_cube.x += red_cube.vx red_cube.y += red_cube.vy #print(keys) win.fill(BLACK) #draw background #pygame.draw.rect(win,RED,(x,y,width,height)) #draw player red_cube.draw(win) redrawGameWindow() <file_sep>import os from random import randint class Grid: def __init__(self, WIDTH, HEIGHT): self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.grid = self.create() self.p_x = self.WIDTH // 2 self.p_y = self.HEIGHT - 2 self.set_player_pos(self.p_x, self.p_y) self.timer = 2 self.catched = 0 self.lost = 0 def create(self): brd = [] for h in range(self.HEIGHT): brd.append([]) for w in range(self.WIDTH): if w < 1 or w == self.WIDTH-1: brd[h].append('x') elif h == self.HEIGHT-1: brd[h].append('x') else: brd[h].append('.') return brd def draw(self): self.clear() for row in self.grid: for character in row: print(character, end='') print() print("Eggs catched: " + str(self.catched) + " " + "Eggs lost: " + str(self.lost)) def update(self): self.timer -= 0.5 if self.timer < 0: self.add_egg(randint(1, self.WIDTH-2), 1) self.timer = randint(1, 5) self.move_eggs() def clear(self): os.system('cls') # only works with CMD and Powershell, doesn't work with Git-Bash def set_player_pos(self, x, y): self.p_x, self.p_y = x, y def get_player_pos(self): return self.p_x, self.p_y def set_cell(self, x, y, chr): self.grid[y][x] = chr def get_cell(self, x, y): return self.grid[y][x] def check_Hbounds(self, x): return x > 0 and x < self.WIDTH-1 def check_Vbounds(self, y): return y >= 0 and y < self.HEIGHT-2 def add_egg(self, x, y): self.grid[y][x] = 'o' def move_eggs(self): for y in range(len(self.grid)-1, 0, -1): for x in range(len(self.grid[y])): if self.get_cell(x, y) == 'o' and self.check_Vbounds(y): self.set_cell(x, y, '.') self.set_cell(x, y+1, 'o') if self.get_cell(x, y+2) == 'U': self.catched += 1 elif self.get_cell(x, y) == 'o': self.set_cell(x, y, '.') self.lost += 1 <file_sep>""" Lists & Tic Tac Toe Game - Python 3 Programming Tutorial p.3 user: sentdex playlist: https://www.youtube.com/playlist?list=PLQVvvaa0QuDeAams7fkdcwOGBpGdHpXln link: https://www.youtube.com/watch?v=tf3ezjeTpfI stayed here: https://www.youtube.com/watch?v=BYpSfx7I6x4 """ game = [[1,2,3], [4,5,6], [7,8,9]] def game_board(game_map, player=0, row=0, column=0, just_display = False): try: #print column names print(" a b c") if not just_display: game_map[row][column] = player for count,row in enumerate(game_map): print(count,row) return game_map except IndexError as e: print("Error: make sure you input row/column as 0,1,2", e) except Exception as e: print("something went very wrong",e) def win(current_game): #check horizontal row for same [1,1,1]""" for row in current_game: if row.count(row[0]) == len(row) and row[0] != 0: #print(f"wineer") #check vertical column for same [1,1,1]""" for column in current_game: print(game[column]) game = game_board(game, just_display = True) #game = game_board(game, player=1, row=2, column=1) win(game)<file_sep> print("steamchine example!") # This variable holds the current state of the machine stateNum = 0 def advance_state_machine(): global stateNum if stateNum == 0: # Transition from state 0 to state 1 print("yellow") stateNum = 1 elif stateNum == 1: # Transition from state 1 to state 2 print("red") stateNum = 2 else: # Transition from state 2 to state 0 print("green") stateNum = 0 while True: user_input = input("press up, pres down") print(user_input) if user_input == "q": break elif user_input == "w": advance_state_machine() <file_sep>""" Simple pong in python 3 for begginers tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2 """ import turtle wn = turtle.Screen() wn.title("Pong by @TokyoEdTech") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) # Paddle A paddle_a = turtle.Turtle() paddle_a.speed() #sets the speed of animation to max paddle_a.shape("square") #default is 20x20 pixels paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, stretch_len = 1) # strech the square paddle_a.penup() paddle_a.goto(-350,0) # Paddle B paddle_b = turtle.Turtle() paddle_b.speed() #sets the speed of animation to max paddle_b.shape("square") #default is 20x20 pixels paddle_b.color("white") paddle_b.shapesize(stretch_wid=5, stretch_len = 1) # strech the square paddle_b.penup() paddle_b.goto(350,0) # Ball ball = turtle.Turtle() ball.speed() #sets the speed of animation to max ball.shape("square") #default is 20x20 pixels ball.color("white") ball.penup() ball.goto(0,0) # Functions def paddle_a_up(): y = paddle_a.ycor() #method, returns y coor y+= 20 #add 20 pixels to y coor paddle_a.sety(y) def paddle_a_down(): y = paddle_a.ycor() #method, returns y coor y -= 20 #add 20 pixels to y coor paddle_a.sety(y) def paddle_b_up(): y = paddle_b.ycor() #method, returns y coor y+= 20 #add 20 pixels to y coor paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() #method, returns y coor y -= 20 #add 20 pixels to y coor paddle_b.sety(y) #keyboard biding wn.listen() #listen for key inputs wn.onkey(paddle_a_up,"w") #when user press "w" call function paddle_a_up wn.onkey(paddle_a_down,"s") #when user press "w" call function paddle_a_up wn.onkey(paddle_b_up,"Up") #when user press "w" call function paddle_a_up wn.onkey(paddle_b_down,"Down") #when user press "w" call function paddle_a_up # main game loop while True: wn.update() #updates screen<file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 27 23:13:08 2020 @author: crtom """ import pygame as pg from settings import * from tilemap import collide_hit_rect vec = pg.math.Vector2 class Player(pg.sprite.Sprite): def __init__(self, game, x, y): # so player can acces all sprites in the game self.game = game self.groups = game.all_sprites # 1.) sprite class default override: #Call the parent class (Sprite) constructor pg.sprite.Sprite.__init__(self, self.groups) # 2.) sprite class default override: # tile based game - player is only one tile large # self.image = pg.Surface((TILESIZE, TILESIZE)) # YELLOW BLOCK SPRITE # self.image.fill(YELLOW) self.image = game.player_img # 3.) sprite class default override: # Fetch the rectangle object that has the dimensions of the image # Update the position of this object by setting the values of rect.x and rect.y self.rect = self.image.get_rect() self.hit_rect = PLAYER_HIT_RECT self.hit_rect.center = self.rect.center # CUSTOM ATTRIBUTES #self.dt = 0 self.vel = vec(0, 0) self.pos = vec(x, y) * TILESIZE self.rot = 0 def get_keys(self): self.vel = vec(0, 0) self.rot_speed = 0 keys = pg.key.get_pressed() if keys[pg.K_LEFT] or keys[pg.K_a]: # self.player.move(dx=-1) self.rot_speed = PLAYER_ROT_SPEED elif keys[pg.K_RIGHT] or keys[pg.K_d]: # IF ENABLES DIAG self.rot_speed = -PLAYER_ROT_SPEED if keys[pg.K_UP] or keys[pg.K_w]: # IF ENABLES DIAG self.vel = vec(PLAYER_SPEED, 0).rotate(-self.rot) # backwards move is slower if keys[pg.K_DOWN] or keys[pg.K_s]: # IF ENABLES DIAG self.vel = vec(-PLAYER_SPEED / 2, 0).rotate(-self.rot) def collide_with_walls(self, direction): # x collision check if direction == 'x': # modify this to use hit_rect instead #hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall hits = pg.sprite.spritecollide(self, self.game.walls, False, collide_hit_rect) # false= dont delete the wall if hits: # sprite was moving to the right # we need to put the sprite to the left edge of the wall if self.vel.x > 0: #because we use rectangle centre / 2 self.pos.x = hits[0].rect.left - self.hit_rect.width / 2 # sprite was moving to the left # we need to put the sprite to the right edge of the wall if self.vel.x < 0: self.pos.x = hits[0].rect.right + self.hit_rect.width / 2 #- self.rect.width # we run into the wall, x velocity = 0 self.vel.x = 0 # update new position of hit_rect self.hit_rect.centerx = self.pos.x if direction == 'y': #hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall hits = pg.sprite.spritecollide(self, self.game.walls, False, collide_hit_rect) # false= dont delete the wall if hits: # sprite was moving down # we need to put the sprite to the top of the wall if self.vel.y > 0: self.pos.y = hits[0].rect.top - self.hit_rect.height / 2 # sprite was moving to the top # we need to put the sprite to the bottom edge of the wall if self.vel.y < 0: self.pos.y = hits[0].rect.bottom + self.hit_rect.height / 2 #- self.rect.width # we run into the wall, x velocity = 0 self.vel.y = 0 # update new position of hit_rect self.hit_rect.centery = self.pos.y def update(self): # 1.) read keyboard self.get_keys() # 2.) calculate rotation self.rot = (self.rot + self.rot_speed*self.game.dt) % 360 # 3.) Update player sprite image with rotation self.image = pg.transform.rotate(self.game.player_img, self.rot) self.rect = self.image.get_rect() self.rect.center = self.pos # 4.) calculate position # this will make movement independant of frame rate self.pos += self.vel * self.game.dt # get dt from game object # 5.) check if collision with walls # if collision, than dont reverse to old position aka dont move self.hit_rect.centerx = self.pos.x self.collide_with_walls('x') self.hit_rect.centery = self.pos.y self.collide_with_walls('y') # 6.)when we update movement, be set equal # sprite image rectangle and hit rectangle self.rect.center = self.hit_rect.center class Wall(pg.sprite.Sprite): def __init__(self, game, x, y): # so player can acces all sprites in the game # member of all sprites group # member of all walls group self.groups = game.all_sprites, game.walls pg.sprite.Sprite.__init__(self, self.groups) self.game = game # tile based game - player is only one tile large self.image = pg.Surface((TILESIZE, TILESIZE)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.x = x self.y = y self.rect.x = x * TILESIZE self.rect.y = y * TILESIZE<file_sep>"""Snake Game Python Tutorial youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo current time: 34:00 """ import sys import math import random import pygame from pygame.locals import * import tkinter as tk from tkinter import messagebox BLACK = (0,0,0) WHITE = (255,255,255) RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255) #----------------------------------------------------------------------------------- class cube(object): """ """ rows = 20 #set number of rows w = 500 #set pixel screen width def __init__(self, start, dirnx=1, dirny=0, color = RED): self.pos = start self.dirnx = 1 self.dirny = 0 self.color = color def move(self,dirnx,dirny): """ move cube, by adding new direction to previous position """ self.dirnx = dirnx self.dirny = dirny self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny) def draw(self,surface,eyes=False): """ drawing: convert x,y grid position to pixel position """ dis = self.w // self.rows #distance between x and y values #variables for easy coding i = self.pos[0] # row j = self.pos[1] # column #draw just a little bit less, so we draw inside of the square. and we dont cover grid. pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 )) #draw eyes if eyes: centre = dis//2 radius = 3 circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1 circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2 pygame.draw.circle(surface, BLACK, circleMiddle, radius) pygame.draw.circle(surface, BLACK, circleMiddle2, radius) #----------------------------------------------------------------------------------- class snake(object): """ class for snake """ body = [] #list of cube objects turns = {} #dictionary of turns ADDING A KEY OF--> # key = current position of snake head # value = direction of turn] def __init__(self,color,pos): self.color = color self.head = cube(pos) self.body.append(self.head) # snake starts with one cube = head self.dirnx = 0 #direction moving x 1, -1 self.dirny = 1 #direction moving y 1, -1 #--------------------------------------------------------------------- def move(self): """ moving our snake in x,y thinking LEFT (self.dirnx=-1, self.dirny=0) RIGHT (self.dirnx=1, self.dirny=0) UP (self.dirnx=0, self.dirny=1) DOWN (self.dirnx=0, self.dirny=-1) """ for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_LEFT]: self.dirnx = -1 self.dirny = 0 # we mustremember where we turned, so other cubes can follow # add a new key #example - here we turned in thar way self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_RIGHT]: self.dirnx = 1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_UP]: self.dirnx = 0 self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx = 0 self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] #look trough all position of snake #we get the index=i and the cube=c of body for i, c in enumerate(self.body): p = c.pos[:] #for each of the sube, we grab position and check turn #if this position in turns, than we move if p in self.turns: turn = self.turns[p] #here we store direction where to move c.move(turn[0],turn[1]) #if we are on the last cube of the snake, remove the turn, we finished it if i == len(self.body)-1: self.turns.pop(p) else: #CHECK IF WE REACHED EDGE OF THE SCREEN #if MOVE LEFT & we are at the left side of screen if (c.dirnx == -1) and (c.pos[0] <= 0): c.pos = (c.rows-1,c.pos[1]) #c.pos = (c.rows-1,c.pos[1]) #if MOVE RIGHT & we are at the left side of screen elif (c.dirnx == 1) and (c.pos[0] >= c.rows-1): c.pos = (0,c.pos[1]) #if MOVE DOWN & we are at the left side of screen elif (c.dirny == 1) and (c.pos[1] >= c.rows-1): c.pos = (c.pos[0],0) #if MOVE UP & we are at the left side of screen elif (c.dirny == -1) and (c.pos[1] <= 0): c.pos = (c.pos[0],c.rows-1) #normal move of cube else: c.move(c.dirnx,c.dirny) #--------------------------------------------------------------------- def reset(self,pos): """ - reset snake back to start state - delete turns - delete body - change direction dirnx, dirny """ self.head = cube(pos) self.body = [] self.body.append(self.head) self.turns = {} self.dirnx = 0 self. dirny = 1 #--------------------------------------------------------------------- def addCube(self): """ Figure out where is tail, and add a cube after it """ """ tail = self.body[-1] #last element in list is tail dx = tail.dirnx dy = tail.dirny #check in which direction is tail movin, so we know if we add it to left,right,up,down #we append a new cube to the body, that has one less position that the tail #are we moving right, append to left if dx == 1 and dy == 0: self.body.append(cube((tail.pos[0]-1,tail.pos[1])) #are we moving left, append to right #if dx == -1 and dy == 0: # self.body.append(cube((tail.pos[0]+1,tail.pos[1])) #are we moving up, append to down #if dx == 0 and dy == 1: # self.body.append(cube((tail.pos[0],tail.pos[1]-1)) #are we moving down, append to up #if dx == 0 and dy == -1: # self.body.append(cube((tail.pos[0],tail.pos[1]+1)) #if we just leave it like this. the cube is not moving #add it moving self.body[-1].dirnx = dx self.body[-1].dirny = dy """ tail = self.body[-1] dx, dy = tail.dirnx, tail.dirny if dx == 1 and dy == 0: self.body.append(cube((tail.pos[0]-1,tail.pos[1]))) elif dx == -1 and dy == 0: self.body.append(cube((tail.pos[0]+1,tail.pos[1]))) elif dx == 0 and dy == 1: self.body.append(cube((tail.pos[0],tail.pos[1]-1))) elif dx == 0 and dy == -1: self.body.append(cube((tail.pos[0],tail.pos[1]+1))) self.body[-1].dirnx = dx self.body[-1].dirny = dy #--------------------------------------------------------------------- def draw(self,surface): for index, cube in enumerate(self.body): #check where to draw eyes for snake head if index == 0: cube.draw(surface,True) #with eyes else: cube.draw(surface,False) #without eyes #----------------------------------------------------------------------------------- def drawGrid(w,rows,surface): """ This function draws a square grid on main display """ #distance between grid lines sizeBtwn = w // rows x = 0 y = 0 #create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn #vertical lines pygame.draw.line(surface, WHITE, (x,0), (x,w)) #horizontal lines pygame.draw.line(surface, WHITE, (0,y), (w,y)) #----------------------------------------------------------------------------------- def redrawWindow(surface): global rows, width, s, snack #background surface.fill(BLACK) s.draw(surface) snack.draw(surface) #draw grid drawGrid(width, rows, surface) #update display pygame.display.update() #----------------------------------------------------------------------------------- def randomSnack(rows,item): """ create random snack cubes: we must be sure we dont put a snack on top of the snake """ #global rows positions = item.body while True: x = random.randrange(rows) y = random.randrange(rows) #we get a list of filtered list and check if and of the positions #are the current positions of the snake #if snack position is equal to the *random(x,y) than repeat the loop if len(list(filter(lambda z:z.pos ==(x,y), positions))) > 0: continue else: break return (x,y) #return snack position that is not on the snake #----------------------------------------------------------------------------------- def message_box(subject,content): """ universal message box created from tkinter """ root = tk.Tk() root.attributes("-topmost",True) root.withdraw() messagebox.showinfo(subject,content) try: root.destroy() except: pass #----------------------------------------------------------------------------------- def key_events(): pass #directions = {"right":(1,0), "left":(0,-1), "up":(0,-1), "down":(0,1)} #----------------------------------------------------------------------------------- def main(): global width, rows, s, snack #---------------game initialization--------------------------- #create game display width = 500 rows = 20 win = pygame.display.set_mode((width, width)) #square display #snake start position s = snake(color=RED, pos=(10,10)) snack = cube(randomSnack(rows,s), color = GREEN) print(snack.pos) clock = pygame.time.Clock() flag = True FPScount = 0 print(FPScount) redrawWindow(win) #-----------------------continuous game loop------------- while flag: #pygame.time.delay(50) clock.tick(1) #game max speed 10 FPS s.move() #check if the snack was eaten. if it was if s.body[0].pos == snack.pos: s.addCube() #add new cube to snake snack = cube(randomSnack(rows,s), color = GREEN) #generate new snack cube #check for chrash #is the position that we moved to in list of every snake body cube for x in range(len(s.body)): if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])): print("score: ", len(s.body)) message_box("game over","play again") s.reset((10,10)) break #------------debug fps counter--------- FPScount += 1 print(f'FPScount:{FPScount}') #-------------------------------------- redrawWindow(win) #rows = 0 #w = 0 #h = 0 #cube.rows = rows #cube.w = w main() pygame.quit() sys.exit()<file_sep>import os from os import path HIGHSCORE_FILE = "highscore.txt" folder = path.dirname(__file__) #get application folder path filename = path.join(folder, HIGHSCORE_FILE) print(filename) #if file exists, read from it if os.path.exists(filename): with open(filename, 'r') as f: try: print("file opened") highscore = int(f.read()) print(highscore) except: print("file read error") # if file doesnt exists, create newread from it else: with open(filename, 'w') as f: try: f.write("0") except: pass <file_sep>from math import log, ceil def next_power_of_2(size): return 2 ** ceil(log(size, 2)) <file_sep>from gameobjects.vector3 import * A = (-6, 2, 2) B = (7, 5, 10) plasma_speed = 100 # meters per second AB = Vector3.from_points(A, B) print("Vector to droid is", AB) distance_to_target = AB.get_magnitude() print("Distance to droid is", distance_to_target, "meters") plasma_heading = AB.get_normalized() print("Heading is", plasma_heading) <file_sep># -*- coding: utf-8 -*- """ There are six steps to making text appear on the screen: 1. Create a pygame.font.Font object. 2. Create a Surface object with the text drawn on it by calling the Font object’s render() method. 3. Create a Rect object from the Surface object by calling the Surface object’s get_rect() method. This Rect object will have the width and height correctly set for the text that was rendered, but the top and left attributes will be 0. 4. Set the position of the Rect object by changing one of its attributes. On line 15, we set the center of the Rect object to be at 200, 150. 5. Blit the Surface object with the text onto the Surface object returned by pygame.display.set_mode(). 6. Call pygame.display.update() to make the display Surface appear on the screen. """ import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!') FPS = 30 # frames per second setting fpsClock = pygame.time.Clock() WHITE = (255, 255, 255) GREEN = (0, 255, 0) BLUE = (0, 0, 128) fontObj = pygame.font.Font('freesansbold.ttf', 32) textSurfaceObj = fontObj.render('Hello world!', True, GREEN, BLUE) textRectObj = textSurfaceObj.get_rect() textRectObj.center = (200, 150) while True: # main game loop DISPLAYSURF.fill(WHITE) DISPLAYSURF.blit(textSurfaceObj, textRectObj) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() # must be called after display.update fpsClock.tick(FPS)<file_sep> # Steering Behavior Examples # Seek & Approach # KidsCanCode 2016 # Video lesson: https://youtu.be/g1jo_qsO5c4 import pygame as pg from random import randint, uniform from sys import exit vec = pg.math.Vector2 WIDTH = 800 HEIGHT = 600 FPS = 60 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) DARKGRAY = (40, 40, 40) # Mob properties MOB_SIZE = 32 MAX_SPEED = 5 MAX_FORCE = 0.1 APPROACH_RADIUS = 120 class Mob(pg.sprite.Sprite): def __init__(self): self.groups = all_sprites pg.sprite.Sprite.__init__(self, self.groups) self.image = pg.Surface((MOB_SIZE, MOB_SIZE)) self.image.fill(YELLOW) self.rect = self.image.get_rect() self.pos = vec(randint(0, WIDTH), randint(0, HEIGHT)) self.vel = vec(MAX_SPEED, 0).rotate(uniform(0, 360)) self.acc = vec(0, 0) self.rect.center = self.pos def follow_mouse(self): mpos = pg.mouse.get_pos() self.acc = (mpos - self.pos).normalize() * 0.5 #original def seek(self, target): self.desired = (target - self.pos).normalize() * MAX_SPEED steer = (self.desired - self.vel) if steer.length() > MAX_FORCE: steer.scale_to_length(MAX_FORCE) return steer def seek_with_approach(self, target): self.desired = (target - self.pos) dist = self.desired.length() self.desired.normalize_ip() if dist < APPROACH_RADIUS: self.desired *= dist / APPROACH_RADIUS * MAX_SPEED else: self.desired *= MAX_SPEED steer = (self.desired - self.vel) if steer.length() > MAX_FORCE: steer.scale_to_length(MAX_FORCE) return steer def update(self): # self.follow_mouse() self.acc = self.seek_with_approach(pg.mouse.get_pos()) #self.acc = self.seek(pg.mouse.get_pos()) # equations of motion self.vel += self.acc if self.vel.length() > MAX_SPEED: self.vel.scale_to_length(MAX_SPEED) self.pos += self.vel if self.pos.x > WIDTH: self.pos.x = 0 if self.pos.x < 0: self.pos.x = WIDTH if self.pos.y > HEIGHT: self.pos.y = 0 if self.pos.y < 0: self.pos.y = HEIGHT self.rect.center = self.pos def draw_vectors(self): scale = 25 # vel pg.draw.line(screen, GREEN, self.pos, (self.pos + self.vel * scale), 5) # desired pg.draw.line(screen, RED, self.pos, (self.pos + self.desired * scale), 5) # approach radius pg.draw.circle(screen, WHITE, pg.mouse.get_pos(), APPROACH_RADIUS, 1) pg.init() screen = pg.display.set_mode((WIDTH, HEIGHT)) clock = pg.time.Clock() all_sprites = pg.sprite.Group() Mob() paused = False show_vectors = False running = True while running: clock.tick(FPS) for event in pg.event.get(): if event.type == pg.QUIT: running = False if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: running = False if event.key == pg.K_SPACE: paused = not paused if event.key == pg.K_v: show_vectors = not show_vectors if event.key == pg.K_m: Mob() if not paused: all_sprites.update() pg.display.set_caption("{:.2f}".format(clock.get_fps())) screen.fill(DARKGRAY) all_sprites.draw(screen) if show_vectors: for sprite in all_sprites: sprite.draw_vectors() pg.display.flip() pg.quit() exit()<file_sep>function love.conf(tbl) tbl.window.width = 900 tbl.window.height = 900 tbl.window.title = 'My Snake game' tbl.window.console = true end <file_sep>import pygame pygame.init() #---------display------------- display_width = 800 display_height = 600 #color var black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) gameDisplay = pygame.display.set_mode((display_width,display_height)) #set title pygame.display.set_caption('Race Game') clock = pygame.time.Clock() # load image carImg = pygame.image.load('race_car_transp_v2.png') #get image size in pixels. for colision detection carImg_width = carImg.get_rect().size[0] carImg_height = carImg.get_rect().size[1] #function to display a car def car(x,y): gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface def game_loop(): x = display_width*0.45 y = display_height*0.8 #for computers (x=0,y=0) is top left corner #------------main game loop--------- x_change = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True #if key pressed start moving if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 #if key released stop moving if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change #------------------------------------ gameDisplay.fill(white) #draw background car(x,y) #draw car #check boundaries for chrash if x > display_width - carImg_width or x < 0: gameExit = True pygame.display.update() #update all changes to display clock.tick(60) #------------------------------------ game_loop() #game is running here, until pygame.QUIT pygame.quit() quit()<file_sep>def parallel_project(vector3): return (vector3.x, vector3.y) <file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 27 16:29:01 2020 @author: crtom https://www.youtube.com/watch?v=Qdeb1iinNtk&list=PLX5fBCkxJmm1fPSqgn9gyR3qih8yYLvMj&index=2 Pygame Tutorial - Making a Platformer ep. 2: Images, Input, and Collisions """ import sys import pygame from pygame.locals import* import random #from settings import * import time import math from gameobjects.vector2 import Vector2 from RGB import * WIDTH, HEIGHT = 400, 400 # initialize pygame and create a window pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Platformer") #all_sprites = pygame.sprite.Group() # create background background = pygame.Surface((WIDTH, HEIGHT)) background.fill(WHITE) screen.blit(background, (0,0)) # create player image player_image = pygame.Surface((50, 50)) player_image.fill(BLACK) player_pos = Vector2(200, 150) player_speed = 300 screen.blit(player_image, (player_pos.x, player_pos.y)) # game loop clock = pygame.time.Clock() running = True while running: # process input (events) for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False pressed_keys = pygame.key.get_pressed() key_direction = Vector2(0, 0) if pressed_keys[K_LEFT]: key_direction.x = -1 elif pressed_keys[K_RIGHT]: key_direction.x = +1 if pressed_keys[K_UP]: key_direction.y = -1 elif pressed_keys[K_DOWN]: key_direction.y = +1 key_direction.normalize() time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 #---------- player_pos += key_direction * player_speed * time_passed_seconds # draw/render screen.blit(background, (0,0)) #all_sprites.draw(screen) # screen.blit(player_image, (50, 50)) screen.blit(player_image, (player_pos.x, player_pos.y)) # after drawing everything, flip the display pygame.display.update() pygame.quit() <file_sep>class State(object): def __init__(self, name): self.name = name def do_actions(self): pass def check_conditions(self): pass def entry_actions(self): pass def exit_actions(self): pass <file_sep>from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * screen = pygame.display.set_mode((640, 480), HWSURFACE|DOUBLEBUF|OPENGL) def resize(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60, float(width)/height, 1, 10000) glMatrixMode(GL_MODELVIEW) glLoadIdentity() <file_sep># -*- coding: utf-8 -*- """ Created on Fri Mar 20 15:37:57 2020 @author: crtjur """ """ import turtle tim = turtle.Turtle() # create turtle module object tim.color('red') # tim.pensize(5) #thickness of line tim.shape('turtle') """ #============================================================================== # Turtle adjustments #============================================================================== # This is needed to prevent turtle scripts crashes after multiple runs in the # same IPython Console instance. # See Spyder issue #6278 try: import turtle from turtle import Screen, Terminator def spyder_bye(): try: Screen().bye() turtle.TurtleScreen._RUNNING = True except Terminator: pass turtle.bye = spyder_bye except: pass <file_sep>""" Basic Movement and Key Presses video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5 1. create a rectangle 2. move it by key pressed """ import pygame from pygame.locals import * pygame.init() #create window win = pygame.display.set_mode((500,500)) #set windows title pygame.display.set_caption("First Game") #character variables x = 50 y = 50 width = 40 height = 60 vel = 5 #clock=pygame.time.Clock() #main game loop run = True while run: pygame.time.delay(100) #this will be a clock for the game for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False vx = 0 vy = 0 keystate = pygame.key.get_pressed() #straight moves if keystate[pygame.K_UP]: vy = -5 elif keystate[pygame.K_DOWN]: vy = 5 elif keystate[pygame.K_LEFT]: vx = -5 elif keystate[pygame.K_RIGHT]: vx = 5 x += vx y += vy #draw rectangle win.fill((0,0,0)) pygame.draw.rect(win,(255,0,0),(x,y,width,height)) pygame.display.update() <file_sep># Pygame Tutorials Building a simple game: character can move, jump, shoot, has health,... Object oriented. ## Resources - Channel: Tech With Tim - [Youtube playlist](https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5) - [github](https://github.com/techwithtim/Pygame-Tutorials) ## Files - Pygame Tutorial #1 - Basic Movement and Key Presses [code](1.py) - Pygame Tutorial #2 - Jumping and Boundaries [code](2.py) - Pygame Tutorial #3 - Character Animation & Sprites [code](3.py) - Pygame Tutorial #4 - Optimization & OOP [code](4.py) - Pygame Tutorial #5 - Basic Movement and Key Presses [code](5.py) - Pygame Tutorial #6 - Enemies [code](6.py) - Pygame Tutorial #7 - Collision and hit boxes [code](7.py) - Pygame Tutorial #8 - Scoring and health bars [code](8.py) - Pygame Tutorial #9 - Sound effects, music, collision [code](9.py) - Pygame Tutorial #10 - Finishing touches & next steps [code](10.py)<file_sep>from enum import Enum, auto import time class States(Enum): IDLE = auto() CHASE = auto() ATTACK = auto() DEATH = auto() class GameObject: def __init__(self): self.__state = States.IDLE def set_state(self, state): self.__state = state def get_state(self): return self.__state class Entity(GameObject): def __init__(self): super().__init__() self.__health = 100 def sub_health(self): self.__health -= 20 def get_health(self): return self.__health def set_health(self, health): self.__health = health player = Entity() player.set_state(States.ATTACK) enemy = Entity() enemy.set_health(200) enemy.set_state(States.CHASE) while True: if player.get_state() == States.ATTACK: print("player attacking!") enemy.sub_health() if enemy.get_state() != States.ATTACK: enemy.set_state(States.ATTACK) if enemy.get_health() <= 0: enemy.set_state(States.DEATH) print("enemy died") print("proceed to next level") break elif player.get_state() == States.DEATH: print("player died") break if enemy.get_state() == States.ATTACK: print("enemy attacking!") player.sub_health() if player.get_health() <= 0: player.set_state(States.DEATH) print("player died") print("game over!") break time.sleep(1) print("-----------------------------") print("player's health ", player.get_health()) print("enemy's health", enemy.get_health()) <file_sep>import sys import math import random import pygame from pygame.locals import * import tkinter as tk from tkinter import messagebox WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) def drawGrid(w, rows, surface): """ This function draws a square grid on main display """ # distance between grid lines sizeBtwn = w // rows x = 0 y = 0 # create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn # vertical lines pygame.draw.line(surface, WHITE, (x, 0), (x, w)) # horizontal lines pygame.draw.line(surface, WHITE, (0, y), (w, y)) def redrawWindow(surface): global rows, width #background surface.fill(BLACK) #draw grid drawGrid(width, rows, surface) #update display pygame.display.update() #--------------------------------------------------------------------------------------- def key_events(): for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): #pygame.quit() #sys.exit() return True keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_UP]: self.dirnx = 0 self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx = 0 self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] return False #--------------------------------------------------------------------------------------- def main(): global width, rows, s, snack #---------------game initialization--------------------------- #create game display width = 500 rows = 20 win = pygame.display.set_mode((width, width)) #square display clock = pygame.time.Clock() FPScount = 0 #-----------------------continuous game loop------------- GameOver = False while not GameOver: #pygame.time.delay(50) clock.tick(10) #game max speed 10 FPS GameOver = key_events() print(FPScount) redrawWindow(win) #--------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------- main() pygame.quit() sys.exit()<file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 20 15:27:13 2020 @author: crtom """ import pygame WHITE = (255, 255, 255) BLACK = ( 0, 0, 0) GREY = (128, 128, 128) SILVER = (192, 192, 192) RED = (255, 0, 0) YELLOW = (255, 255, 0) ORANGE = (255, 128, 0) MAGENTA = (255, 0, 255) PURPLE = (128, 0, 128) LIME = ( 0, 255, 0) BLUE = ( 0, 0, 255) NAVYBLUE= ( 60, 60, 100) CYAN = ( 0, 255, 255) GRAY = (128, 128, 128) MAROON = (128, 0, 0) OLIVE = (128, 128, 0) GREEN = ( 0, 128, 0) TEAL = ( 0, 128, 128) NAVY = ( 0, 0, 128) def draw_rect_alpha(surface, color, rect): shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA) pygame.draw.rect(shape_surf, color, shape_surf.get_rect()) surface.blit(shape_surf, rect) def draw_circle_alpha(surface, color, center, radius): target_rect = pygame.Rect(center, (0, 0)).inflate((radius * 2, radius * 2)) shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA) pygame.draw.circle(shape_surf, color, (radius, radius), radius) surface.blit(shape_surf, target_rect) def draw_polygon_alpha(surface, color, points): lx, ly = zip(*points) min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly) target_rect = pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y) shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA) pygame.draw.polygon(shape_surf, color, [(x - min_x, y - min_y) for x, y in points]) surface.blit(shape_surf, target_rect) def draw_background(): background = pygame.Surface(window.get_size()) ts, w, h, c1, c2 = 50, *window.get_size(), (160, 160, 160), (192, 192, 192) tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)] for rect, color in tiles: pygame.draw.rect(background, color, rect) window.blit(background, (0, 0)) pygame.init() window = pygame.display.set_mode((250, 250)) clock = pygame.time.Clock() #-------------------------------------------- #------------background---------------------- #-------------------------------------------- background = pygame.Surface((250, 250)) background.fill((128,128,128)) window.blit(background, (0, 0)) #print(window.get_size()) #-------------------------------------------- #-------------line icon------------- #-------------------------------------------- # icon1 = pygame.Surface((50, 50)) # icon1.fill((255,255,255)) # #pygame.draw.line(surface, color, start_pos, end_pos, width) -> Rect # # draw horizontal line in icon surface # pygame.draw.line(icon1, BLUE, (5,25), (45,25), 5) # # draw vertical line in icon surface # pygame.draw.line(icon1, BLUE, (25,5), (25,45), 5) # #blit icon on main surface # window.blit(icon1, (0, 0)) #-------------------------------------------- #----------------triangle icon---------------- #-------------------------------------------- icon3 = pygame.Surface((50, 50)) icon3.fill((255,255,255)) #line(surface, color, start_pos, end_pos, width) -> Rect # draw horizontal line in icon surface #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect pygame.draw.polygon(icon3, GREEN, ((10,40),(40,40),(25, 10)),4) #blit icon on main surface window.blit(icon3, (0, 0)) #-------------------------------------------- #----------------rectangle empty icon---------------- #-------------------------------------------- #Demo 1: Rectangle #pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height)) icon2 = pygame.Surface((50, 50)) icon2.fill((255,255,255)) #line(surface, color, start_pos, end_pos, width) -> Rect # draw horizontal line in icon surface #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect pygame.draw.rect(icon2, RED, [10,10,30,30],5) #blit icon on main surface window.blit(icon2, (60, 0)) #-------------------------------------------- #----------------circle empty icon----------------- #-------------------------------------------- icon3 = pygame.Surface((50, 50)) icon3.fill((255,255,255)) #line(surface, color, start_pos, end_pos, width) -> Rect # draw horizontal line in icon surface #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect pygame.draw.circle(icon3, GREEN, (25, 25 ), 15, 5) #blit icon on main surface window.blit(icon3, (120, 0)) #-------------------------------------------- #----------------triangle icon---------------- #-------------------------------------------- icon3 = pygame.Surface((50, 50)) icon3.fill((255,255,255)) #line(surface, color, start_pos, end_pos, width) -> Rect # draw horizontal line in icon surface #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect pygame.draw.polygon(icon3, GREEN, ((10,40),(40,40),(25, 10))) #blit icon on main surface window.blit(icon3, (0, 60)) # #-------------------------------------------- # #----------------diamond icon---------------- # #-------------------------------------------- # icon4 = pygame.Surface((50, 50)) # icon4.fill((255,255,255)) # #line(surface, color, start_pos, end_pos, width) -> Rect # # draw horizontal line in icon surface # #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect # pygame.draw.polygon(icon4, GREEN, ((5,25),(25,5),(45, 25),(25, 45))) # #blit icon on main surface # window.blit(icon4, (0, 60)) #-------------------------------------------- #----------------rectangle filled icon---------------- #-------------------------------------------- #Demo 1: Rectangle #pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height)) icon5 = pygame.Surface((50, 50)) icon5.fill((255,255,255)) #line(surface, color, start_pos, end_pos, width) -> Rect # draw horizontal line in icon surface #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect pygame.draw.rect(icon5, RED, [10,10,30,30]) #blit icon on main surface window.blit(icon5, (60, 60)) #-------------------------------------------- #----------------circle filled icon----------------- #-------------------------------------------- icon6 = pygame.Surface((50, 50)) icon6.fill((255,255,255)) #line(surface, color, start_pos, end_pos, width) -> Rect # draw horizontal line in icon surface #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect pygame.draw.circle(icon6, GREEN, (25, 25 ), 15) #blit icon on main surface window.blit(icon6, (120, 60)) #-------------------------------------------- run = True while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # draw_background() # draw_rect_alpha(window, (0, 0, 255, 127), (55, 90, 140, 140)) # draw_circle_alpha(window, (255, 0, 0, 127), (150, 100), 80) # draw_polygon_alpha(window, (255, 255, 0, 127), # [(100, 10), (100 + 0.8660 * 90, 145), (100 - 0.8660 * 90, 145)]) pygame.display.flip() pygame.quit() exit()<file_sep>from math import radians from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * # Import the Model3D class import model3d SCREEN_SIZE = (800, 600) def resize(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60.0, float(width)/height, .1, 1000.) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def init(): glEnable(GL_FOG) glFogfv(GL_FOG_COLOR, (1.0, 1.0, 1.0)) glFogi(GL_FOG_MODE, GL_LINEAR) glFogf(GL_FOG_START, 1.5) glFogf(GL_FOG_END, 3.5) # Enable the GL features we will be using glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glEnable(GL_COLOR_MATERIAL) glEnable(GL_TEXTURE_2D) glEnable(GL_CULL_FACE) glShadeModel(GL_SMOOTH) glClearColor(1.0, 1.0, 1.0, 0.0) # white # Set the material glMaterial(GL_FRONT, GL_AMBIENT, (0.0, 0.0, 0.0, 1.0)) glMaterial(GL_FRONT, GL_DIFFUSE, (0.2, 0.2, 0.2, 1.0)) glMaterial(GL_FRONT, GL_SPECULAR, (1.0, 1.0, 1.0, 1.0)) glMaterial(GL_FRONT, GL_SHININESS, 10.0) # Set light parameters glLight(GL_LIGHT0, GL_AMBIENT, (0.0, 0.0, 0.0, 1.0)) glLight(GL_LIGHT0, GL_DIFFUSE, (0.4, 0.4, 0.4, 1.0)) glLight(GL_LIGHT0, GL_SPECULAR, (1.0, 1.0, 1.0, 1.0)) # Enable light 1 and set position glEnable(GL_LIGHT0) glLight(GL_LIGHT0, GL_POSITION, (0, .5, 1, 0)) def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF) resize(*SCREEN_SIZE) init() clock = pygame.time.Clock() # Read the model tank_model = model3d.Model3D() tank_model.read_obj('mytank.obj') rotation = 0.0 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 glLoadIdentity() glRotatef(15, 1, 0, 0) glTranslatef(0.0, -1.5, -3.5) rotation += time_passed_seconds * 45.0 glRotatef(rotation, 0, 1, 0) tank_model.draw_quick() pygame.display.flip() if __name__ == "__main__": run() <file_sep># Create a display list tank_display_list = glGenLists(1) glNewList(tank_display_list, GL_COMPILE) draw_tank() # End the display list glEndList() <file_sep>import pygame from pygame.locals import * from random import randint class Star(object): def __init__(self, x, y, speed): self.x = x self.y = y self.speed = speed def run(): pygame.init() screen = pygame.display.set_mode((640, 480), FULLSCREEN) stars = [] # Add a few stars for the first frame for n in range(200): x = float(randint(0, 639)) y = float(randint(0, 479)) speed = float(randint(10, 300)) stars.append( Star(x, y, speed) ) clock = pygame.time.Clock() white = (255, 255, 255) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() if event.type == KEYDOWN: pygame.quit() quit() # Add a new star y = float(randint(0, 479)) speed = float(randint(10, 300)) star = Star(640, y, speed) stars.append(star) time_passed = clock.tick() time_passed_seconds = time_passed / 1000. screen.fill((0, 0, 0)) # Draw the stars for star in stars: new_x = star.x - time_passed_seconds * star.speed pygame.draw.aaline(screen, white, (new_x, star.y), (star.x+1., star.y)) star.x = new_x def on_screen(star): return star.x > 0 # Remove stars that are no longer visible stars = list(filter(on_screen, stars)) pygame.display.update() if __name__ == "__main__": run() <file_sep>def subtractive_blend(src, dst): return dst—src * src.a <file_sep>""" Simple pong in python 3 for begginers tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2 """ import turtle import time import random wn = turtle.Screen() wn.title("Pong by @TokyoEdTech") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) score_a = 0 score_b = 0 # Paddle A paddle_a = turtle.Turtle() paddle_a.speed() #sets the speed of animation to max paddle_a.shape("square") #default is 20x20 pixels paddle_a.color("white") paddle_a.shapesize(stretch_wid=5, stretch_len = 1) # strech the square paddle_a.penup() paddle_a.goto(-350,0) # Paddle B paddle_b = turtle.Turtle() paddle_b.speed() #sets the speed of animation to max paddle_b.shape("square") #default is 20x20 pixels paddle_b.color("white") paddle_b.shapesize(stretch_wid=5, stretch_len = 1) # strech the square paddle_b.penup() paddle_b.goto(350,0) # Ball ball = turtle.Turtle() ball.speed() #sets the speed of animation to max ball.shape("square") #default is 20x20 pixels ball.color("white") ball.penup() ball.goto(0,0) ball.dx = 2 #speed ball.dy = 2 print(random.choice([-1,1])) #write scoreboard pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(0,260) pen.write("Player A: 0 Player B: 0", align="center", font=("courier",24,"normal")) # Functions def paddle_a_up(): y = paddle_a.ycor() #method, returns y coor y+= 20 #add 20 pixels to y coor paddle_a.sety(y) def paddle_a_down(): y = paddle_a.ycor() #method, returns y coor y -= 20 #add 20 pixels to y coor paddle_a.sety(y) def paddle_b_up(): y = paddle_b.ycor() #method, returns y coor y+= 20 #add 20 pixels to y coor paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() #method, returns y coor y -= 20 #add 20 pixels to y coor paddle_b.sety(y) #keyboard biding wn.listen() #listen for key inputs wn.onkey(paddle_a_up,"w") #when user press "w" call function paddle_a_up wn.onkey(paddle_a_down,"s") #when user press "w" call function paddle_a_up wn.onkey(paddle_b_up,"Up") #when user press "w" call function paddle_a_up wn.onkey(paddle_b_down,"Down") #when user press "w" call function paddle_a_up # main game loop GameOver = False while not GameOver: wn.update() #updates screen time.sleep(0.01) #move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) #border checking #----------top sides bounce-------- #top side if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 #reverse direction of the ball #bottom side elif ball.ycor() < -285: ball.sety(-285) ball.dy *= -1 #reverse direction of the ball #----------bot sides finish the game-------- #right side if ball.xcor() > 390: ball.goto(0,0) #put ball back to the start ball.dx *= -1 #reverse direction of the ball score_a += 1 pen.clear() pen.write(f"Player A: {score_a} Player B: {score_b}", align="center", font=("courier",24,"normal")) #left side elif ball.xcor() < -390: ball.goto(0,0) #put ball back to the start ball.dx *= -1 #reverse direction of the ball score_b += 1 pen.clear() pen.write(f"Player A: {score_a} Player B: {score_b}", align="center", font=("courier",24,"normal")) #Paddle and ball collisions #if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor()+50 and ball.ycor()>paddle_b.ycor()-50) paddle_b_y_coll = ((ball.ycor() < paddle_b.ycor()+50) and(ball.ycor()>paddle_b.ycor()-50)) paddle_a_y_coll = ((ball.ycor() < paddle_a.ycor()+50) and(ball.ycor()>paddle_a.ycor()-50)) right_coll = ((ball.xcor() > 340) and (ball.xcor() < 350)) left_coll = ((ball.xcor() < -340) and (ball.xcor() > -350)) if paddle_b_y_coll and right_coll: ball.setx(340) ball.dx *= -1 #reverse direction of the ball if paddle_a_y_coll and left_coll: ball.setx(-340) ball.dx *= -1 #reverse direction of the ball #debug #print (f'ball.xcor():{ball.xcor()}') #print (f'ball.ycor():{ball.ycor()}') #print (f'paddle_b.ycor():{paddle_b.ycor()}') #diff = ball.ycor() - paddle_b.ycor() #print (f'diff:{diff}') <file_sep>import math class Vector2: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "(%s, %s)"%(self.x, self.y) def from_points(P1, P2): return Vector2( P2[0] - P1[0], P2[1] - P1[1] ) def get_magnitude(self): return math.sqrt( self.x**2 + self.y**2 ) A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) print(AB) print(AB.get_magnitude()) <file_sep>""" Basic Movement and Key Presses video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5 1. create a rectangle 2. move it by key pressed """ import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 # unit vectors for movement vector_right = Vector2(1, 0) vector_left = Vector2(-1, 0) vector_up = Vector2(0, -1) vector_down = Vector2(0, 1) pygame.init() WIDTH, HEIGHT = 640, 480 #### Create a canvas on which to display everything #### screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) #set windows title pygame.display.set_caption("8 way movement vector") #### Create a surface with the same size as the window #### background = pygame.Surface((WIDTH, HEIGHT)) #character variables x = 50 y = 50 width = 40 height = 60 vel = 5 sprite = pygame.Surface((50, 50)) sprite.fill((255,255,255)) rect = sprite.get_rect() rect.center = (WIDTH / 2, HEIGHT / 2) clock = pygame.time.Clock() sprite_pos = Vector2(100.0, 100.0) sprite_speed = 300. clock = pygame.time.Clock() key_direction = Vector2(0, 0) #main game loop run = True while run: # pygame.time.delay(100) #this will be a clock for the game for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False key_direction.x, key_direction.y = (0, 0) keystate = pygame.key.get_pressed() if keystate[pygame.K_UP]: # key_direction = vector_up key_direction += vector_up if keystate[pygame.K_DOWN]: key_direction += vector_down if keystate[pygame.K_LEFT]: key_direction += vector_left if keystate[pygame.K_RIGHT]: key_direction += vector_right # direction vector is a unit vector, normalize it # diagonals are 0.707 key_direction.normalize() print(key_direction) time_passed = clock.tick(30) time_passed_seconds = time_passed / 1000.0 sprite_pos += key_direction * sprite_speed * time_passed_seconds #### Blit the surface onto the canvas #### screen.blit(background,(0,0)) #### Blit the surface onto the canvas #### screen.blit(sprite,(int(sprite_pos.x), int(sprite_pos.y))) pygame.display.update() # exit pygame pygame.quit() exit() <file_sep># -*- coding: utf-8 -*- """ Created on Wed Mar 18 21:57:53 2020 @author: crtjur """ """ $ python Python 2.7.13 (default, Apr 4 2017, 08:47:57) [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> from simple_device import SimpleDevice >>> device = SimpleDevice() Processing current state: LockedState >>> >>> device.on_event('device_locked') >>> device.on_event('pin_entered') Processing current state: UnlockedState >>> >>> device.state UnlockedState >>> >>> device.on_event('device_locked') Processing current state: LockedState >>> >>> device.state LockedState >>> device.on_event('device_locked') """<file_sep> from OpenGL.GL import * from OpenGL.GLU import * import pygame import os.path class Material(object): def __init__(self): self.name = "" self.texture_fname = None self.texture_id = None class FaceGroup(object): def __init__(self): self.tri_indices = [] self.material_name = "" class Model3D(object): def __init__(self): self.vertices = [] self.tex_coords = [] self.normals = [] self.materials = {} self.face_groups = [] self.display_list_id = None def __del__(self): #Called when the model is cleaned up by Python self.free_resources() def free_resources(self): # Delete the display list and textures if self.display_list_id is not None: glDeleteLists(self.display_list_id, 1) self.display_list_id = None # Delete any textures we used for material in self.materials.values(): if material.texture_id is not None: glDeleteTextures(material.texture_id) # Clear all the materials self.materials.clear() # Clear the geometry lists del self.vertices[:] del self.tex_coords[:] del self.normals[:] del self.face_groups[:] def read_obj(self, fname): current_face_group = None file_in = open(fname) for line in file_in: # Parse command and data from each line words = line.split() command = words[0] data = words[1:] if command == 'mtllib': # Material library model_path = os.path.split(fname)[0] mtllib_path = os.path.join( model_path, data[0] ) self.read_mtllib(mtllib_path) elif command == 'v': # Vertex x, y, z = data vertex = (float(x), float(y), float(z)) self.vertices.append(vertex) elif command == 'vt': # Texture coordinate s, t = data tex_coord = (float(s), float(t)) self.tex_coords.append(tex_coord) elif command == 'vn': # Normal x, y, z = data normal = (float(x), float(y), float(z)) self.normals.append(normal) elif command == 'usemtl' : # Use material current_face_group = FaceGroup() current_face_group.material_name = data[0] self.face_groups.append( current_face_group ) elif command == 'f': assert len(data) == 3, "Sorry, only triangles are supported" # Parse indices from triples for word in data: vi, ti, ni = word.split('/') indices = (int(vi) - 1, int(ti) - 1, int(ni) - 1) current_face_group.tri_indices.append(indices) for material in self.materials.values(): model_path = os.path.split(fname)[0] texture_path = os.path.join(model_path, material.texture_fname) texture_surface = pygame.image.load(texture_path) texture_data = pygame.image.tostring(texture_surface, 'RGB', True) material.texture_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, material.texture_id) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glPixelStorei(GL_UNPACK_ALIGNMENT,1) width, height = texture_surface.get_rect().size gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, texture_data) def read_mtllib(self, mtl_fname): file_mtllib = open(mtl_fname) for line in file_mtllib: words = line.split() command = words[0] data = words[1:] if command == 'newmtl': material = Material() material.name = data[0] self.materials[data[0]] = material elif command == 'map_Kd': material.texture_fname = data[0] def draw(self): vertices = self.vertices tex_coords = self.tex_coords normals = self.normals for face_group in self.face_groups: material = self.materials[face_group.material_name] glBindTexture(GL_TEXTURE_2D, material.texture_id) glBegin(GL_TRIANGLES) for vi, ti, ni in face_group.tri_indices: glTexCoord2fv( tex_coords[ti] ) glNormal3fv( normals[ni] ) glVertex3fv( vertices[vi] ) glEnd() def draw_quick(self): if self.display_list_id is None: self.display_list_id = glGenLists(1) glNewList(self.display_list_id, GL_COMPILE) self.draw() glEndList() glCallList(self.display_list_id) <file_sep>def get_attenuation(distance, constant, linear, quadratic): return 1.0 / (constant + linear * distance + quadratic * (distance ** 2)) <file_sep>https://www.youtube.com/watch?v=3_zEoolypYM&list=PLE3_ZiIESvFSkO7yrG1LVR78VWt4NureV<file_sep>"""Sprite classes for platform game Attributes: vec (TYPE): Description """ import pygame as pg import random from settings import * vec = pg.math.Vector2 class Spritesheet: """Utility class for loading and parsing spritesheets """ def __init__(self, filename): self.spritesheet = pg.image.load(filename).convert() def get_image(self, x, y, width, height): image = pg.Surface((width,height)) # from spritesheet we cut out an image (x, y, width, height) image.blit(self.spritesheet, (0,0), (x, y, width, height)) #resize image image = pg.transform.scale(image, (width//2, height//2)) return image class Player(pg.sprite.Sprite): """Summary Attributes: acc (TYPE): Description game (TYPE): Description image (TYPE): Description pos (TYPE): Description rect (TYPE): Description vel (TYPE): Description """ def __init__(self, game): """Summary Args: game (TYPE): Description """ pg.sprite.Sprite.__init__(self) self.game = game #this is a copy of game for reference self.jumping = False self.walking = False self.current_frame = False self.last_update = False # frame animation self.load_images() self.image = pg.Surface((30,40)) #self.image.fill(YELLOW) # YELLOW RECTANGLE PLAYER #get image from spritesheet #self.image = self.game.spritesheet.get_image(614,1063,120,191) # fix color image background problem #self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.center = (WIDTH_MID, HEIGHT_MID) self.pos = vec(50, HEIGHT_MID) # player spawn location self.vel = vec(0,0) self.acc = vec(0,0) def load_images(self): """Load player images for animation - standing - walk right - walk left - jumping """ # Standing frames self.standing_frames = [ self.game.spritesheet.get_image(614,1063, 120, 191), self.game.spritesheet.get_image(690, 406, 120, 201)] # fix color image background problem for frame in self.standing_frames: frame.set_colorkey(BLACK) # Walking right frames self.walk_frames_r = [ self.game.spritesheet.get_image(678, 860, 120, 201), self.game.spritesheet.get_image(692, 1458, 120, 207)] for frame in self.walk_frames_r: frame.set_colorkey(BLACK) # Walking left frames self.walk_frames_l = [] for frame in self.walk_frames_r: #flip(​Surface, flip vertically, flip horizonally) self.walk_frames_l.append(pg.transform.flip(frame, True, False)) # Jumping frames self.jump_frame = self.game.spritesheet.get_image(382, 763, 150, 181) self.jump_frame.set_colorkey(BLACK) def jump_cut(self): """ Jump cut - when we are jumping we are traveling at 16 speed - jump cut, decreases jump velocity """ if self.jumping: if self.vel.y < -3: self.vel.y = -3 def jump(self): """Jump Jump only if standing on platform Check 2 pixel below if platform is there, than jump allowed 1. temporary lower player for 2 pixel 2. check for collision with platform 3. move player 2 pixel up to original position 4. if collided, than a player can jump """ self.rect.x += 2 hits = pg.sprite.spritecollide(self, self.game.platforms, False) self.rect.x -= 2 if hits and not self.jumping: self.jumping = True self.vel.y = PLAYER_JUMP_VELOCITY self.game.jump_sound.play() def update(self): """ Update player - key press events - movement mehanics equations - (friction, gravity, acc, vel, pos) """ self.animate() self.acc = vec(0,PLAYER_GRAVITY) # 0.5 is gravity keys = pg.key.get_pressed() if keys[pg.K_LEFT]: self.acc.x = -PLAYER_ACC elif keys[pg.K_RIGHT]: self.acc.x = PLAYER_ACC # boundaries constraints # if on RIGTH and if we are deccelerating toward wall if self.pos.x - (self.rect.width//2) <= 0: if self.vel.x < 0 or self.acc.x < 0: self.acc.x = 0 self.vel.x = 0 # if on LEFT and if we are accelerating toward wall if self.pos.x + (self.rect.width//2) >= WIDTH: if self.vel.x > 0 or self.acc.x > 0: self.acc.x = 0 self.vel.x = 0 self.vel += self.vel*PLAYER_FRICTION self.vel += self.acc # if because of friction, we stop. its because velocity # is rounded to 0. But its not 0. so we use treshold if abs(self.vel.x) < 0.1: # if velocity blow 0.1 pixel treshold self.vel.x = 0 # force velocity to 0, if too small #oon equation deltaX = 0.5*(v0 + v) self.pos += self.vel + 0.5*self.acc #self.rect.center = self.pos self.rect.midbottom = self.pos #player standing on platform #position = myFont.render("Position:", 1, WHITE) #screen.blit(position, (0, 0)) def animate(self): """animation is based on time - get current time """ now = pg.time.get_ticks() # animation for moving # if x velocity is not 0, than we are walking if self.vel.x != 0: self.walking = True else: self.walking = False # show walk animation if self.walking: if now - self.last_update > 150: self.last_update = now self.current_frame = (self.current_frame + 1) % len(self.walk_frames_l) #keep track where our bottom of rectangle is #so our character stands on platform bottom = self.rect.bottom # check direction, right/left if self.vel.x > 0: # right walk self.image = self.walk_frames_r[self.current_frame] else: # left walk self.image = self.walk_frames_l[self.current_frame] self.rect = self.image.get_rect() self.rect.bottom = bottom # animation for standing if not self.jumping and not self.walking: if now - self.last_update > 350: self.last_update = now self.current_frame = (self.current_frame + 1) % len(self.standing_frames) #keep track where our bottom of rectangle is #so our character stands on platform bottom = self.rect.bottom self.image = self.standing_frames[self.current_frame] self.rect = self.image.get_rect() self.rect.bottom = bottom class Platform(pg.sprite.Sprite): """Summary Attributes: image (TYPE): Description rect (TYPE): Description """ def __init__(self, game, x, y): """class to create platform and boundaries where we can walk on Args: x (TYPE): Description y (TYPE): Description w (TYPE): Description h (TYPE): Description """ pg.sprite.Sprite.__init__(self) self.game = game # platform frames images = [ self.game.spritesheet.get_image(0, 288, 380 ,94), self.game.spritesheet.get_image(213, 1662, 201, 100)] #select random image self.image = random.choice(images) #self.image = pg.Surface((w, h)) #self.image.fill(PLATFORM_COLOR) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y<file_sep># Platform game ## Links - [Kids Can Code Youtube](https://www.youtube.com/channel/UCNaPQ5uLX5iIEHUCLmfAgKg) - [Pygame Tutorial #2: Platformer](https://www.youtube.com/playlist?list=PLsk-HSGFjnaG-BwZkuAOcVwWldfCLu1pq) ## Code - [1 Settings Up]() - [2 ]() - [3 ]() - [4 ]() - [5 ]() - [6 ]() - [7 ]() - [8 ]() - [9 ]() - [10 ]() - [11 ]() - [12 ]() - [13 ]() - [14 ]() - [15 ]() - [16 ]() - [17 ]() - [18 ]() - [19 ]() ## Game description<file_sep> def draw(self): vertices = self.vertices tex_coords = self.tex_coords normals = self.normals for face_group in self.face_groups: material = self.materials[face_group.material_name] glBindTexture(GL_TEXTURE_2D, material.texture_id) glBegin(GL_TRIANGLES) for vi, ti, ni in face_group.tri_indices: glTexCoord2fv( tex_coords[ti] ) glNormal3fv( normals[ni] ) glVertex3fv( vertices[vi] ) glEnd() def draw_quick(self): if self.display_list_id is None: self.display_list_id = glGenLists(1) glNewList(self.display_list_id, GL_COMPILE) self.draw() glEndList() glCallList(self.display_list_id) <file_sep> import time import msvcrt from grid import Grid GRID_WIDTH = 45 GRID_HEIGHT = 40 game_grid = Grid(GRID_WIDTH, GRID_HEIGHT) def game_loop(): x, y = game_grid.get_player_pos() game_grid.set_cell(x, y, 'U') while True: oldX, oldY = game_grid.get_player_pos() # first get the old position # get user input if msvcrt.kbhit(): char = ord(msvcrt.getch()) # this is blocking without the msvcrt.kbhit() if char == 27: # the ESC key code, exit game break elif char == 97: # a key, move left x -= 1 elif char == 100: # d key, move right x += 1 else: continue if not game_grid.check_Hbounds(x): x, y = oldX, oldY else: game_grid.set_cell(oldX, oldY, '.') game_grid.set_player_pos(x, y) # then set the new position game_grid.set_cell(x, y, 'U') # update the eggs game_grid.update() # draw the game board game_grid.draw() time.sleep(0.1) # 1/10 or 0.1 if __name__ == "__main__": game_loop()<file_sep>import sys import math import random import pygame from pygame.locals import * import tkinter as tk from tkinter import messagebox clock = pygame.time.Clock() WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) #--------------------------draw grid fuction---------------------------- def drawGrid(w,rows,surface): """ This function draws a square grid on main display """ #distance between grid lines sizeBtwn = w // rows x = 0 y = 0 #create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn #vertical lines pygame.draw.line(surface, WHITE, (x,0), (x,w)) #horizontal lines pygame.draw.line(surface, WHITE, (0,y), (w,y)) #-------------------------cube object----------------------------------------- class cube(object): """ class to create a single grid cube, that has position and movement """ rows = 20 #set number of rows w = 500 #set pixel screen width def __init__(self, start, dirnx, dirny, color = WHITE): self.pos = start #touple (x,y) self.dirnx = 0 self.dirny = 0 self.color = color #touple(r,g,b) def set_direction(self,dirnx,dirny): self.dirnx = dirnx self.dirny = dirny def move(self): """ move cube, by adding new direction to previous position """ self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny) def draw(self,surface): """ drawing: convert x,y grid position to pixel position """ dis = self.w // self.rows #distance between x and y values #variables for easy coding i = self.pos[0] # row j = self.pos[1] # column #draw just a little bit less, so we draw inside of the square. and we dont cover grid. pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 )) #----------------------------------------------------------------------------------- def redrawWindow(surface): global rows, width #background surface.fill(BLACK) #draw grid drawGrid(width, rows, surface) #draw ball ball.draw(surface) #update display pygame.display.update() #--------------------------------------------------------------------------------------- def key_events(): for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): #pygame.quit() #sys.exit() return True #in pong we move in only y directions keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_UP]: self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] return False #--------------------------------------------------------------------------------------- def main(): global width, rows, ball #---------------game initialization--------------------------- #create game display width = 500 rows = 20 #create game objects win = pygame.display.set_mode((width, width)) #square display ball = cube((10,1),0,0,WHITE) ball.set_direction(1,1) #set initial ball movement direction FPScount = 0 #-----------------------continuous game loop------------- GameOver = False while not GameOver: #pygame.time.delay(50) clock.tick(10) #game max speed 10 FPS GameOver = key_events() #update ball position ball.move() #check next direction------------------------------- #CONSTRAINTS X if ball.pos[0] <= 0 or ball.pos[0] >= rows-1: ball.dirnx = -ball.dirnx #CONSTRAINTS Y if ball.pos[1] <= 0 or ball.pos[1] >= rows-1: ball.dirny = -ball.dirny #------------------------------------------------- #if we are moving in right direction #print(f'rows:{rows} ball.pos[0]:{ball.pos[0]} ball.pos[1]:{ball.pos[1]}') #FPScount += 1 #print(FPScount) redrawWindow(win) #--------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------- main() pygame.quit() sys.exit() <file_sep>#DO NOT TOUCH game_properties! game_properties = [ "current_score", "high_score", "number_of_lives", "items_in_inventory", "power_ups", "ammo", "enemies_on_screen", "enemy_kills", "enemy_kill_streaks", "minutes_played", "notifications", "achievements"] # Use the game_properties list and dict.fromkeys() to generate a dictionary with all values set to 0. Save the result to a variable called initial_game_state initial_game_state = {}.fromkeys(game_properties,0) print(initial_game_state)<file_sep>from gameobjects.matrix44 import * identity = Matrix44() print(identity) p1 = (1.0, 2.0, 3.0) identity.transform(p1) assert identity.get_column(3) == (0, 0, 0, 1), "Something is wrong with this matrix!" <file_sep>"""Snake Game Python Tutorial youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo current time: 33:00 """ import sys import math import random import pygame from pygame.locals import * import tkinter as tk from tkinter import messagebox WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) class cube(object): """ """ rows = 20 #set number of rows w = 500 #set pixel screen width def __init__(self,start,dirnx=1,dirny=0,color=RED): self.pos = start self.dirnx = 1 self.dirny = 0 self.color = color def move(self,dirnx,dirny): """ move cube, by adding new direction to previous position """ self.dirnx = dirnx self.dirny = dirny self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny) def draw(self,surface,eyes=False): """ drawing: convert x,y grid position to pixel position """ dis = self.w // self.rows #distance between x and y values #variables for easy coding i = self.pos[0] # row j = self.pos[1] # column #draw just a little bit less, so we draw inside of the square. and we dont cover grid. pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 )) #draw eyes if eyes: centre = dis//2 radius = 3 circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1 circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2 pygame.draw.circle(surface, BLACK, circleMiddle, radius) pygame.draw.circle(surface, BLACK, circleMiddle2, radius) class snake(object): """ class for snake """ body = [] #list of cube objects turns = {} #dictionary of turns ADDING A KEY OF--> # key = current position of snake head # value = direction of turn] def __init__(self,color,pos): self.color = color self.head = cube(pos) self.body.append(self.head) # snake starts with one cube = head self.dirnx = 0 #direction moving x 1, -1 self.dirny = 1 #direction moving y 1, -1 def move(self): """ moving our snake in x,y thinking LEFT (self.dirnx=-1, self.dirny=0) RIGHT (self.dirnx=1, self.dirny=0) UP (self.dirnx=0, self.dirny=1) DOWN (self.dirnx=0, self.dirny=-1) """ for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_LEFT]: self.dirnx = -1 self.dirny = 0 # we mustremember where we turned, so other cubes can follow # add a new key #example - here we turned in thar way self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_RIGHT]: self.dirnx = 1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_UP]: self.dirnx = 0 self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx = 0 self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] #look trough all position of snake #we get the index=i and the cube=c of body for i, c in enumerate(self.body): p = c.pos[:] #for each of the sube, we grab position and check turn #if this position in turns, than we move if p in self.turns: turn = self.turns[p] #here we store direction where to move c.move(turn[0],turn[1]) #if we are on the last cube of the snake, remove the turn, we finished it if i == len(self.body)-1: self.turns.pop(p) else: #CHECK IF WE REACHED EDGE OF THE SCREEN #if MOVE LEFT & we are at the left side of screen if (c.dirnx == -1) and (c.pos[0] <= 0): c.pos = (c.rows-1,c.pos[1]) #c.pos = (c.rows-1,c.pos[1]) #if MOVE RIGHT & we are at the left side of screen elif (c.dirnx == 1) and (c.pos[0] >= c.rows-1): c.pos = (0,c.pos[1]) #if MOVE DOWN & we are at the left side of screen elif (c.dirny == 1) and (c.pos[1] >= c.rows-1): c.pos = (c.pos[0],0) #if MOVE UP & we are at the left side of screen elif (c.dirny == -1) and (c.pos[1] <= 0): c.pos = (c.pos[0],c.rows-1) #normal move of cube else: c.move(c.dirnx,c.dirny) def reset(self,pos): pass def addCube(self): pass def draw(self,surface): for index, cube in enumerate(self.body): #check where to draw eyes for snake head if index == 0: cube.draw(surface,True) #with eyes else: cube.draw(surface,False) #without eyes def drawGrid(w,rows,surface): """ This function draws a square grid on main display """ #distance between grid lines sizeBtwn = w // rows x = 0 y = 0 #create grid by drawing lines for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn #vertical lines pygame.draw.line(surface, WHITE, (x,0), (x,w)) #horizontal lines pygame.draw.line(surface, WHITE, (0,y), (w,y)) def redrawWindow(surface): global rows, width, s #background surface.fill(BLACK) s.draw(surface) #draw grid drawGrid(width, rows, surface) #update display pygame.display.update() def randomSnack(rows,items): pass def message_box(subject,content): pass def key_events(): pass #directions = {"right":(1,0), "left":(0,-1), "up":(0,-1), "down":(0,1)} def main(): global width, rows, s #create game display width = 500 rows = 20 win = pygame.display.set_mode((width, width)) #square display #snake start position s = snake(color=RED, pos=(10,10)) clock = pygame.time.Clock() flag = True FPScount = 0 print(FPScount) while flag: #pygame.time.delay(50) clock.tick(10) #game max speed 10 FPS s.move() redrawWindow(win) FPScount += 1 print(f'FPScount:{FPScount}') #rows = 0 #w = 0 #h = 0 #cube.rows = rows #cube.w = w main() pygame.quit() sys.exit()<file_sep>Here are the codes from my video series on youtube, on how to create a Snake game in Lua and Love2d. You can watch the videos here: https://www.youtube.com/playlist?list=PL1P11yPQAo7q_BWMKFZvUlLBqLRUJLrJm <file_sep>import pygame import time import random pygame.init() #---------game constants variables------------- display_width = 800 display_height = 600 #RGB color constants black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) #------------------------------------------------------ #create main display window gameDisplay = pygame.display.set_mode((display_width,display_height)) #set main display window title pygame.display.set_caption('Race Game') clock = pygame.time.Clock() #-------------------load images----------------------------------- # load image carImg = pygame.image.load('race_car_transp_v2.png') #get image size in pixels. for colision detection carImg_width = carImg.get_rect().size[0] carImg_height = carImg.get_rect().size[1] #-------------------FUNCTIONS------------------------------------ #creating things that move towards car def things(thingx,thingy,thingw,thingh,color): pygame.draw.rect((gameDisplay),color,[thingx,thingy,thingw,thingh]) #function to display a car def car(x,y): gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface def text_objects(text,font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def message_display(text): #define look of the writing largeText = pygame.font.Font('freesansbold.ttf',100) #create a custom function for message box display TextSurf, TextRect = text_objects(text, largeText) #center the message box display on of the middle screen TextRect.center =((display_width/2),(display_height/2)) #draw image with blit gameDisplay.blit(TextSurf,TextRect) #update display pygame.display.update() time.sleep(2) game_loop() def crash(): message_display('You Chrashed') def game_loop(): x = display_width*0.45 y = display_height*0.8 #for computers (x=0,y=0) is top left corner #--------------------main game loop-------------------- x_change = 0 #objects apear randomly on x axis thing_startx = random.randrange(0,display_width) #start object off the screen-above thing_starty = -600 thing_speed = 7 thing_width = 100 #pixles thing_height = 100 gameExit = False while not gameExit: #------------key press game logic------------- for event in pygame.event.get(): if event.type == pygame.QUIT: #gameExit = True pygame.quit() quit() #if key pressed start moving if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 #if key released stop moving if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change #------------graphics and logic---------------------- #draw background gameDisplay.fill(white) #draw things things(thing_startx, thing_starty,thing_width,thing_height,black) #move things thing_starty += thing_speed #draw car car(x,y) #----------check boundaries for chrash---------- if x > display_width - carImg_width or x < 0: crash() gameExit = True #----------is thing thing that moves off the screen---------- if thing_starty > display_height: thing_starty = 0 - thing_height thing_startx = random.randrange(0,display_width) #start is 600 off the screen #start is 600 off the screen pygame.display.update() #update all changes to display clock.tick(60) #------------------------------------ game_loop() #game is running here, until pygame.QUIT #pygame.quit() #quit()<file_sep>from gameobjects.vector3 import * A = Vector3(6, 8, 12) B = Vector3(10, 16, 12) print("A is", A) print("B is", B) print("Magnitude of A is", A.get_magnitude()) print("A+B is", A+B) print("A-B is", A-B) print("A normalized is", A.get_normalized()) print("A*2 is", A * 2) <file_sep>import pygame from random import randint pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 18) class Cell: def __init__(self, pos, random_mine): self.visible = False self.mine = random_mine self.show_mine = False self.size = 30 self.color = (200,200,200) self.pos = pos self.label = False self.mine_counter = 0 self.font_color = (0, 0, 0) self.marked = False self.explosion = False def draw(self, surface): if self.visible: pygame.draw.rect(surface, self.color, (self.pos[0], self.pos[1], self.size, self.size)) elif self.marked: pygame.draw.rect(surface, (150, 50, 50), (self.pos[0], self.pos[1], self.size, self.size)) else: pygame.draw.rect(surface, (50,50,50), (self.pos[0], self.pos[1], self.size, self.size)) if self.show_mine and self.mine: pygame.draw.circle(surface, (10,10,10), (self.pos[0]+15, self.pos[1]+15), 15) if self.explosion: pygame.draw.circle(surface, (255,10,10), (self.pos[0]+15, self.pos[1]+15), 15) if self.label: self.show_label(surface, self.mine_counter, self.pos) def show_label(self, surface, label, pos): textsurface = myfont.render(label, False, self.font_color) surface.blit(textsurface, (pos[0]+10, pos[1]+4)) class Grid: def __init__(self, player): self.player = player self.cells = [] self.search_dirs = [(0,-1),(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1)] for y in range(30): self.cells.append([]) for x in range(30): self.cells[y].append(Cell((x*30, y*30), self.random_mines())) self.lines =[] for y in range(1, 31, 1): temp = [] temp.append((0, y * 30)) temp.append((900, y * 30)) self.lines.append(temp) for x in range(1, 31, 1): temp = [] temp.append((x*30, 0)) temp.append((x*30, 900)) self.lines.append(temp) def random_mines(self): r = randint(0, 10) if r > 9: return True else: return False def draw(self, surface): for row in self.cells: for cell in row: cell.draw(surface) for line in self.lines: pygame.draw.line(surface, (0, 125, 0), line[0], line[1]) def is_within_bounds(self, x, y): # need to check for the edges and corners, so list index will not be out of range return x >= 0 and x < 30 and y >= 0 and y < 30 def search(self, x, y): if not self.is_within_bounds(x, y): return cell = self.cells[y][x] if cell.visible: return if cell.mine: #cell.show_mine = True cell.explosion = True self.player.sub_health() return cell.visible = True num_mines = self.num_of_mines(x, y) if num_mines > 0: cell.label = True cell.mine_counter = str(num_mines) return for xx, yy in self.search_dirs: self.search(x+xx, y+yy) def num_of_mines(self, x, y): counter = 0 for xx, yy in self.search_dirs: if self.is_within_bounds(x + xx, y + yy) and self.cells[y + yy][x + xx].mine: counter += 1 return counter def click(self, x, y): grid_x, grid_y = x//30, y//30 self.search(grid_x, grid_y) def reload(self): self.player.health = 5 for row in self.cells: for cell in row: cell.visible = False cell.label = False cell.marked = False cell.show_mine = False cell.explosion = False cell.mine = self.random_mines() def check_if_win(self): if self.player.health < 1: return False for row in self.cells: for cell in row: if not cell.visible and not cell.mine: return False return True def show_mines(self): for row in self.cells: for cell in row: if not cell.show_mine: cell.show_mine = True else: cell.show_mine = False def mark_mine(self, x, y): self.cells[y][x].marked = True <file_sep># Scoring After Tetris for Game Boy, most games adopted a scoring system designed to reward difficult clears by giving points for more lines cleared at once. Some systems also encouraged starting at a higher difficulty. Contents[show] Original Nintendo Scoring System This score was used in Nintendo's versions of Tetris for NES, for Game Boy, and for Super NES. Level Points for 1 line Points for 2 lines Points for 3 lines Points for 4 lines 0 40 100 300 1200 1 80 200 600 2400 2 120 300 900 3600 9 400 1000 3000 12000 n 40 * (n + 1) 100 * (n + 1) 300 * (n + 1) 1200 * (n + 1) For each piece, the game also awards the number of points equal to the number of grid spaces that the player has continuously soft dropped the piece. Unlike the points for lines, this does not increase per level. The New Tetris The New Tetris awards "lines": one for each line cleared, one extra line for clearing four lines with one I tetromino, and several lines for clearing parts of a 4x4 square. This does not increase as the game gets faster. Soft and firm drops do not give points instead, they allow the player to place more tetrominoes (and clear more lines) in the three minute sprint game. Tetris Worlds Each mode of Tetris Worlds has its own scoring system. As in The New Tetris, the unit of score in each mode is lines 2, 3, and 4-line clears grant additional points in some modes. Tetris Deluxe Tetris Deluxe scoring system is similar to Tetris Worlds. Tetris DS Each mode of Tetris DS has its own scoring system. Most notably, the system used in Standard mode represents a fusion of the 1, 3, 5, 8 pattern used in several modes of Tetris Worlds with the section multiplier of the NES and Game Boy system. Guideline scoring system Most games released after Tetris DS have the same scoring system. Here is the guideline scoring system as of 2009 (uses 3-corner T). Action Point Value Single/Mini T-spin 100×level Mini T-Spin Single 200×level Double 300×level T-Spin 400×level Triple 500×level Tetris/T-Spin Single 800×level B2B T-Spin Single/B2B Tetris/T-Spin Double 1,200×level T-Spin Triple 1,600×level B2B T-Spin Double 1,800×level B2B T-Spin Triple 2,400×level Combo LC×LV+50×LV Soft drop 1 point per cell (Max of 20) Hard drop 2 points per cell (Max of 40) <file_sep>def saturate_color(color): red, green, blue = color red = min(red, 255) green = min(green, 255) blue = min(blue, 255) return red, green, blue <file_sep>def additive_blend(src, dst): return src * src.a + dst <file_sep>class AntStateExploring(State): def __init__(self, ant): # Call the base class constructor to initialize the State State.__init__(self, "exploring") # Set the ant that this State will manipulate self.ant = ant def random_destination(self): # Select a point in the screen w, h = SCREEN_SIZE self.ant.destination = Vector2(randint(0, w), randint(0, h)) def do_actions(self): # Change direction, 1 in 20 calls if randint(1, 20) == 1: self.random_destination() def check_conditions(self): # If there is a nearby leaf, switch to seeking state leaf = self.ant.world.get_close_entity("leaf", self.ant.location) if leaf is not None: self.ant.leaf_id = leaf.id return "seeking" # If there is a nearby spider, switch to hunting state spider = self.ant.world.get_close_entity("spider", NEST_POSITION, NEST_SIZE) if spider is not None: if self.ant.location.get_distance_to(spider.location) < 100.: self.ant.spider_id = spider.id return "hunting" return None def entry_actions(self): # Start with random speed and heading self.ant.speed = 120. + randint(-30, 30) self.random_destination() <file_sep>def scale_color(color, scale): red, green, blue = color red = int(red*scale) green = int(green*scale) blue = int(blue*scale) return red, green, blue fireball_orange = (221, 99, 20) print(fireball_orange) print(scale_color(fireball_orange, .5)) <file_sep>class GameEntity(object): def __init__(self, world, name, image): self.world = world self.name = name self.image = image self.location = Vector2(0, 0) self.destination = Vector2(0, 0) self.speed = 0. self.brain = StateMachine() self.id = 0 def render(self, surface): x, y = self.location w, h = self.image.get_size() surface.blit(self.image, (x-w/2, y-h/2)) def process(self, time_passed): self.brain.think() if self.speed > 0 and self.location != self.destination: vec_to_destination = self.destination - self.location distance_to_destination = vec_to_destination.get_length() heading = vec_to_destination.get_normalized() travel_distance = min(distance_to_destination, time_passed * self.speed) self.location += travel_distance * heading <file_sep> -- game states GameStates = {pause='pause', running='running', game_over='game over'} state = GameStates.running local snakeX = 15 local snakeY = 15 local dirX = 0 local dirY = 0 local SIZE = 30 local appleX = 0 local appleY = 0 local tail = {} tail_length = 0 up = false down = false left = false right = false function add_apple() -- randomize the apples's position on x and y between 0 and 29 math.randomseed(os.time()) appleX = math.random(SIZE-1) appleY = math.random(SIZE-1) end function game_draw() love.graphics.setColor(1.0, 0.35, 0.4, 1.0) -- draw the snake's head love.graphics.rectangle('fill', snakeX*SIZE, snakeY*SIZE, SIZE, SIZE, 10, 10) love.graphics.setColor(0.7, 0.35, 0.4, 1.0) -- draw the snake's tails for _, v in ipairs(tail) do love.graphics.rectangle('fill', v[1]*SIZE, v[2]*SIZE, SIZE, SIZE, 15, 15) end love.graphics.setColor(0.8, 0.9, 0.0, 1.0) -- draw the apple love.graphics.rectangle('fill', appleX*SIZE, appleY*SIZE, SIZE, SIZE, 10, 10) love.graphics.setColor(1, 1, 1, 1) -- darw the collected apples text love.graphics.print('collected apples: '.. tail_length, 10, 10, 0, 1.5, 1.5) end function game_update() if up and dirY == 0 then dirX, dirY = 0, -1 elseif down and dirY == 0 then dirX, dirY = 0, 1 elseif left and dirX == 0 then dirX, dirY = -1, 0 elseif right and dirX == 0 then dirX, dirY = 1, 0 end local oldX = snakeX local oldY = snakeY snakeX = snakeX + dirX snakeY = snakeY + dirY if snakeX == appleX and snakeY == appleY then add_apple() tail_length = tail_length + 1 table.insert(tail, {0,0}) end if snakeX < 0 then snakeX = SIZE - 1 elseif snakeX > SIZE - 1 then snakeX = 0 elseif snakeY < 0 then snakeY = SIZE - 1 elseif snakeY > SIZE - 1 then snakeY = 0 end if tail_length > 0 then for _, v in ipairs(tail) do local x, y = v[1], v[2] -- following the (c=a, a=b, b=c) logic v[1], v[2] = oldX, oldY oldX, oldY = x, y end end for _, v in ipairs(tail) do if snakeX == v[1] and snakeY == v[2] then state = GameStates.game_over end end end function game_restart() snakeX, snakeY = 15, 15 dirX, dirY = 0, 0 tail = {} up, down, left, right = false, false, false, false tail_length = 0 state = GameStates.running add_apple() end <file_sep>import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) # Get a list of joystick objects joysticks = [] for joystick_no in range(pygame.joystick.get_count()): stick = pygame.joystick.Joystick(joystick_no) stick.init() joysticks.append(stick) if not joysticks: print("Sorry! No joystick(s) to test.") pygame.quit() exit() active_joystick = 0 pygame.display.set_caption(joysticks[0].get_name()) def draw_axis(surface, x, y, axis_x, axis_y, size): line_col = (128, 128, 128) num_lines = 40 step = size / float(num_lines) for n in range(num_lines): line_col = [(192, 192, 192), (220, 220, 220)][n&1] pygame.draw.line(surface, line_col, (x+n*step, y), (x+n*step, y+size)) pygame.draw.line(surface, line_col, (x, y+n*step), (x+size, y+n*step)) pygame.draw.line(surface, (0, 0, 0), (x, y+size/2), (x+size, y+size/2)) pygame.draw.line(surface, (0, 0, 0), (x+size/2, y), (x+size/2, y+size)) draw_x = int(x + (axis_x * size + size) / 2.) draw_y = int(y + (axis_y * size + size) / 2.) draw_pos = (draw_x, draw_y) center_pos = (x+size/2, y+size/2) pygame.draw.line(surface, (0, 0, 0), center_pos, draw_pos, 5) pygame.draw.circle(surface, (0, 0, 255), draw_pos, 10) def draw_dpad(surface, x, y, axis_x, axis_y): col = (255, 0, 0) if axis_x == -1: pygame.draw.circle(surface, col, (x-20, y), 10) elif axis_x == +1: pygame.draw.circle(surface, col, (x+20, y), 10) if axis_y == -1: pygame.draw.circle(surface, col, (x, y+20), 10) elif axis_y == +1: pygame.draw.circle(surface, col, (x, y-20), 10) while True: joystick = joysticks[active_joystick] for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() if event.type == KEYDOWN: if event.key >= K_0 and event.key <= K_1: num = event.key - K_0 if num < len(joysticks): active_joystick = num name = joysticks[active_joystick].get_name() pygame.display.set_caption(name) # Get a list of all the axis axes = [] for axis_no in range(joystick.get_numaxes()): axes.append( joystick.get_axis(axis_no) ) axis_size = min(256, 640 / (joystick.get_numaxes()/2)) pygame.draw.rect(screen, (255, 255,255), (0, 0, 640, 480)) # Draw all the axes (analog sticks) x = 0 for axis_no in range(0, len(axes), 2): axis_x = axes[axis_no] if axis_no+1 < len(axes): axis_y = axes[axis_no+1] else: axis_y = 0. draw_axis(screen, x, 0, axis_x, axis_y, axis_size) x += axis_size # Draw all the hats (d-pads) x, y = 50, 300 for hat_no in range(joystick.get_numhats()): axis_x, axis_y = joystick.get_hat(hat_no) draw_dpad(screen, x, y, axis_x, axis_y) x+= 100 #Draw all the buttons x, y = 0.0, 390.0 button_width = 640 / joystick.get_numbuttons() for button_no in range(joystick.get_numbuttons()): if joystick.get_button(button_no): pygame.draw.circle(screen, (0, 255, 0), (int(x), int(y)), 20) x += button_width pygame.display.update() <file_sep>class Ant(GameEntity): def __init__(self, world, image): # Call the base class constructor GameEntity.__init__(self, world, "ant", image) # Create instances of each of the states exploring_state = AntStateExploring(self) seeking_state = AntStateSeeking(self) delivering_state = AntStateDelivering(self) hunting_state = AntStateHunting(self) # Add the states to the state machine (self.brain) self.brain.add_state(exploring_state) self.brain.add_state(seeking_state) self.brain.add_state(delivering_state) self.brain.add_state(hunting_state) self.carry_image = None def carry(self, image): self.carry_image = image def drop(self, surface): # Blit the 'carry' image to the background and reset it if self.carry_image: x, y = self.location w, h = self.carry_image.get_size() surface.blit(self.carry_image, (x-w, y-h/2)) self.carry_image = None def render(self, surface): # Call the render function of the base class GameEntity.render(self, surface) # Extra code to render the 'carry' image if self.carry_image: x, y = self.location w, h = self.carry_image.get_size() surface.blit(self.carry_image, (x-w, y-h/2)) <file_sep>import pyglet from pyglet.window import key from pyglet.window import FPSDisplay from random import randint, choice window = pyglet.window.Window(width=1200, height=900, caption="Space Invaders", resizable=False) window.set_location(400, 100) fps_display = FPSDisplay(window) fps_display.label.font_size = 50 main_batch = pyglet.graphics.Batch() def load_high_score(file): with open(file, 'r') as f: score = f.read() return score def save_high_score(file, scr): with open(file, 'w') as f: f.write(str(scr)) # region Sprites, Labels and Animations # loading static images space = pyglet.image.load('res/sprites/space.jpg') player_image = pyglet.image.load('res/sprites/PlayerShip.png') # space_ship.png player_laser = pyglet.image.load('res/sprites/laser.png') enemy_laser = pyglet.image.load('res/sprites/enemy_laser.png') stats_bg_image = pyglet.image.load('res/sprites/stats_bg_white.png') # loading sprite sheet animations for the ufo_head ufo_head = pyglet.image.load('res/sprites/ufoHead_Sh.png') ufo_head_seq = pyglet.image.ImageGrid(ufo_head, 1, 8, item_width=100, item_height=100) ufo_head_texture = pyglet.image.TextureGrid(ufo_head_seq) ufo_head_anim = pyglet.image.Animation.from_image_sequence(ufo_head_texture[0:], 0.1, loop=True) # loading sprite sheet animations for the enemy space ship enemy_ship = pyglet.image.load('res/sprites/enemyShip_Sh01.png') enemy_ship_seq = pyglet.image.ImageGrid(enemy_ship, 1, 15, item_width=100, item_height=100) enemy_ship_texture = pyglet.image.TextureGrid(enemy_ship_seq) enemy_ship_anim = pyglet.image.Animation.from_image_sequence(enemy_ship_texture[0:], 0.1, loop=True) # loading sprite sheet animations for explosion xplosion_image = pyglet.image.load('res/sprites/explosion.png') xplosion_seq = pyglet.image.ImageGrid(xplosion_image, 4, 5, item_width=96, item_height=96) xplosion_textures = pyglet.image.TextureGrid(xplosion_seq) xplosion_anim = pyglet.image.Animation.from_image_sequence(xplosion_textures[0:], 0.05, loop=True) # creating a label called "enemies destroyed" text1 = pyglet.text.Label("enemies destroyed", x=1000 , y=850, batch=main_batch) text1.italic = True text1.bold = True text1.font_size = 16 # creating a label called "score" text2 = pyglet.text.Label("score", x=1000 , y=750, batch=main_batch) text2.italic = True text2.bold = True text2.font_size = 16 # creating a label called "player health" text3 = pyglet.text.Label("player health", x=1000 , y=650, batch=main_batch) text3.italic = True text3.bold = True text3.font_size = 16 # creating a label for high score text high_score_text = pyglet.text.Label("high score", x=1000 , y=450, batch=main_batch) high_score_text.italic = True high_score_text.bold = True high_score_text.font_size = 20 # label for displaying the high score value high_score = load_high_score("res/score.txt") high_score_value = pyglet.text.Label(high_score, x=1100, y=400, batch=main_batch) high_score_value.color = (120, 200, 150, 255) high_score_value.font_size = 24 # creating a label to display the number of destroyed enemies num_enemies_destroyed = pyglet.text.Label(str(0), x=1100, y=800, batch=main_batch) num_enemies_destroyed.color = (120, 200, 150, 255) num_enemies_destroyed.font_size = 22 # creating a label to display the score num_score = pyglet.text.Label(str(0), x=1100, y=700, batch=main_batch) num_score.color = (220, 100, 150, 255) num_score.font_size = 22 # creating a label to display the player's health numb_player_health = pyglet.text.Label(str(5), x=1100, y=600, batch=main_batch) numb_player_health.color = (0, 100, 50, 255) numb_player_health.font_size = 22 game_over_text = pyglet.text.Label("game over", x=600 , y=500) game_over_text.anchor_x = "center" game_over_text.anchor_y = "center" game_over_text.italic = True game_over_text.bold = True game_over_text.font_size = 60 reload_text = pyglet.text.Label("press r to reload", x=600 , y=350) reload_text.anchor_x = "center" reload_text.anchor_y = "center" reload_text.italic = True reload_text.bold = True reload_text.font_size = 40 intro_text = pyglet.text.Label("press space to start", x=600 , y=450) intro_text.anchor_x = "center" intro_text.anchor_y = "center" intro_text.italic = True intro_text.bold = True intro_text.font_size = 40 player = pyglet.sprite.Sprite(player_image, x=500, y=100, batch=main_batch) stats_bg = pyglet.sprite.Sprite(stats_bg_image, x=980, y=300, batch=main_batch) stats_bg.opacity = 10 # endregion #explosion = pyglet.media.StaticSource(pyglet.media.load('../res/sounds/exp_01.wav', streaming=False)) explosion = pyglet.media.load('res/sounds/exp_01.wav', streaming=False) player_gun_sound = pyglet.media.load('res/sounds/player_gun.wav', streaming=False) player_laser_list = [] enemy_laser_list = [] enemy_list = [] bg_list = [] explosion_list = [] # when creating a new enemy, it will choose a random direction from the list below directions = [1, -1] player_speed = 300 left = False right = False destroyed_enemies = 0 # this for only stats next_wave = 0 score = 0 fire = False player_fire_rate = 0 enemy_fire_rate = 0 ufo_head_spawner = 0 enemy_ship_spawner = 0 ufo_head_spawner_count = 1 enemy_ship_spawner_count = 5 preloaded = False player_health = 5 player_is_alive = True explode_time = 2 enemy_explode = False shake_time = 0 game = False flash_time = 1 player_flash = False @window.event def on_draw(): window.clear() if not preloaded: preload() for bg in bg_list: bg.draw() if game: main_batch.draw() else: intro_text.draw() if not player_is_alive: game_over_text.draw() reload_text.draw() fps_display.draw() def reload(): global player_is_alive, next_wave, score, destroyed_enemies, player_fire_rate, enemy_fire_rate, explode_time global ufo_head_spawner, enemy_ship_spawner, ufo_head_spawner_count, enemy_ship_spawner_count, player_health global enemy_explode, shake_time, high_score next_wave = 0 score = 0 player_health = 5 player_fire_rate = 0 enemy_fire_rate = 0 ufo_head_spawner = 0 enemy_ship_spawner = 0 ufo_head_spawner_count = 1 enemy_ship_spawner_count = 5 explode_time = 2 enemy_explode = False shake_time = 0 destroyed_enemies = 0 player_is_alive = True player.x, player.y = 500, 100 player.batch = main_batch # reload the score from the score text file high_score = load_high_score("res/score.txt") high_score_value.text = high_score num_enemies_destroyed.text = str(destroyed_enemies) num_score.text = str(score) numb_player_health.text = str(player_health) for obj in enemy_list: obj.batch = None for obj in enemy_laser_list: obj.batch = None enemy_list.clear() enemy_laser_list.clear() @window.event def on_key_press(symbol, modifiers): global right, left, fire, game if symbol == key.RIGHT: right = True if symbol == key.LEFT: left = True if symbol == key.SPACE: fire = True if not game: game = True fire = False # to prevent firing when the game starts if symbol == key.R: reload() @window.event def on_key_release(symbol, modifiers): global right, left, fire if symbol == key.RIGHT: right = False if symbol == key.LEFT: left = False if symbol == key.SPACE: fire = False def player_move(entity, dt): if right and entity.x < 1000: entity.x += player_speed * dt if left and entity.x > 100: entity.x -= player_speed * dt # this function runs only once, it loads two background images at the start def preload(): global preloaded for i in range(2): bg_list.append(pyglet.sprite.Sprite(space, x=0, y=i*1200)) preloaded = True def bg_move(dt): for bg in bg_list: bg.y -= 50*dt if bg.y <= -1300: bg_list.remove(bg) bg_list.append(pyglet.sprite.Sprite(space, x=0, y=1100)) def enemy_move(enemies, yspeed, dt): global score for enemy in enemies: if enemy.x >= 1000: enemy.x = 1000 enemy.speed *= -1 if enemy.x <= 100: enemy.x = 100 enemy.speed *= -1 enemy.y -= yspeed*dt enemy.x += enemy.speed * dt if enemy.y <= 450 and enemy.y >= 449.4 and player_is_alive: score -= 1 num_score.text = str(score) if enemy.y <= -100: enemies.remove(enemy) def enemy_spawn(dt): global ufo_head_spawner, enemy_ship_spawner, player_is_alive, ufo_head_spawner_count, enemy_ship_spawner_count global next_wave ufo_head_spawner -= dt enemy_ship_spawner -= dt if player_is_alive: if ufo_head_spawner <= 0: enemy_list.append(pyglet.sprite.Sprite(ufo_head_anim, x=600, y=950, batch=main_batch)) enemy_list[-1].speed = randint(100, 300) * choice(directions) # last spawned entity in entity list enemy_list[-1].hit_count = 0 enemy_list[-1].MAX_HIT = 2 ufo_head_spawner += ufo_head_spawner_count if enemy_ship_spawner <= 0: enemy_list.append(pyglet.sprite.Sprite(enemy_ship_anim, x=600, y=950, batch=main_batch)) enemy_list[-1].speed = randint(100, 300) * choice(directions) # last spawned entity in entity list enemy_list[-1].hit_count = 0 enemy_list[-1].MAX_HIT = 8 enemy_ship_spawner += enemy_ship_spawner_count if next_wave >= 20: ufo_head_spawner_count -= 0.05 enemy_ship_spawner_count -= 0.2 next_wave = 0 def enemy_shoot(dt): global enemy_fire_rate enemy_fire_rate -= dt if enemy_fire_rate <= 0: for enemy in enemy_list: if randint(0, 10) >= 5: enemy_laser_list.append(pyglet.sprite.Sprite(enemy_laser, enemy.x + 50, enemy.y, batch=main_batch)) enemy_fire_rate += 5 def update_enemy_shoot(dt): for lsr in enemy_laser_list: lsr.y -= 400 * dt if lsr.y < -50: # if the lasers y position is belov -100 it gets removed from the laser list enemy_laser_list.remove(lsr) def player_shoot(dt): global player_fire_rate player_fire_rate -= dt if player_fire_rate <= 0: player_laser_list.append(pyglet.sprite.Sprite(player_laser, player.x + 32, player.y + 96, batch=main_batch)) player_fire_rate += 0.2 if player_is_alive: player_gun_sound.play() def update_player_shoot(dt): for lsr in player_laser_list: lsr.y += 400 * dt if lsr.y > 950: # if the lasers y position is above 950 it gets removed from the laser list player_laser_list.remove(lsr) def screen_shake(): global shake_time, enemy_explode shake_time -= 0.1 x = randint(-10, 10) if shake_time <= 0: bg_list[0].x = x bg_list[1].x = x shake_time += 0.11 elif shake_time >= 0: bg_list[0].x = 0 bg_list[1].x = 0 enemy_explode = False def enemy_hit(entity): global destroyed_enemies, score, next_wave, enemy_explode entity.hit_count += 1 if entity.hit_count >= entity.MAX_HIT and player_is_alive: enemy_explode = True explosion_list.append(pyglet.sprite.Sprite(xplosion_anim, x=entity.x, y=entity.y, batch=main_batch)) enemy_list.remove(entity) # remove the enemy from enemy list when gets shot two times #entity.batch = None # remove the enemy from the main batch entity.delete() # here it works, but in test_02_batcher_tester.py often gives error??? explosion.play() destroyed_enemies += 1 # this only for displaying the stats next_wave += 1 score += 1 num_enemies_destroyed.text = str(destroyed_enemies) num_score.text = str(score) def player_hit(): global player_health, numb_player_health, player_flash player_health -= 1 numb_player_health.text = str(player_health) player_flash = True if player_health <= 0: player.batch = None game_over() def update_flash(): global flash_time, player_flash flash_time -= 0.2 player.color = (255, 0, 0) if flash_time <= 0: player.color = (255, 255, 255) flash_time = 1 player_flash = False def update_explosion(): global explode_time explode_time -= 0.1 if explode_time <= 0: for exp in explosion_list: explosion_list.remove(exp) exp.delete() explode_time += 2 def game_over(): global player_is_alive player_is_alive = False if score > int(high_score): save_high_score('res/score.txt', score) def bullet_collision(entity, bullet_list): for lsr in bullet_list: if lsr.x < entity.x + entity.width and lsr.x + lsr.width > entity.x \ and lsr.y < entity.y + entity.height and lsr.height + lsr.y > entity.y: bullet_list.remove(lsr) # remove the laser from laser list when colliding with an enemy return True def update(dt): if game: player_move(player, dt) enemy_move(enemy_list, 30, dt) if fire: player_shoot(dt) update_player_shoot(dt) enemy_shoot(dt) update_enemy_shoot(dt) for entity in enemy_list: if bullet_collision(entity, player_laser_list): enemy_hit(entity) if bullet_collision(player, enemy_laser_list) and player_is_alive: player_hit() if player_flash: update_flash() update_explosion() enemy_spawn(dt) if enemy_explode: screen_shake() bg_move(dt) if __name__ == "__main__": pyglet.clock.schedule_interval(update, 1.0/60) pyglet.app.run() <file_sep># import the turtle module so we can use all the neat code it contains from turtle import Turtle, Screen KEY_REPEAT_RATE = 20 # in milliseconds # Create a variable `tina` that is a Turtle() object. Set shape to 'turtle' tina = Turtle('turtle') # Create a variable `screen`, a Screen() object, that will handle keys screen = Screen() # Define functions for each arrow key def go_left(): tina.left(7) if repeating: screen.ontimer(go_left, KEY_REPEAT_RATE) def go_right(): tina.right(7) if repeating: screen.ontimer(go_right, KEY_REPEAT_RATE) def go_forward(): tina.forward(10) if repeating: screen.ontimer(go_forward, KEY_REPEAT_RATE) def go_backward(): tina.backward(10) if repeating: screen.ontimer(go_backward, KEY_REPEAT_RATE) def start_repeat(func): global repeating repeating = True func() def stop_repeat(): global repeating repeating = False repeating = False # Tell the program which functions go with which keys screen.onkeypress(lambda: start_repeat(go_left), 'Left') screen.onkeyrelease(stop_repeat, 'Left') screen.onkeypress(lambda: start_repeat(go_right), 'Right') screen.onkeyrelease(stop_repeat, 'Right') screen.onkeypress(lambda: start_repeat(go_forward), 'Up') screen.onkeyrelease(stop_repeat, 'Up') screen.onkeypress(lambda: start_repeat(go_backward), 'Down') screen.onkeyrelease(stop_repeat, 'Down') # Tell the screen to listen for key presses screen.listen() screen.mainloop()<file_sep>""" Python: Bouncing Ball Animation with Real-World Physics!! video: https://www.youtube.com/watch?v=9LWpCtbSvG4 Analyst Rising 1.36K subscribers In this tutorial I will be showing you how to code/programme a bouncing ball, with REAL-WORLD PHYSICS, in Python. This is one of many great python tutorials that should get you well on your way to programming some amazing stuff!! """ import pygame from pygame.locals import * import time pygame.init() #---------game constants variables------------- display_width = 300 display_height = 400 #RGB color constants black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) dt_ms = 100 frame_speed_sec = (1/dt_ms)*1000 #------------------------------------------------------ #create main display window gameDisplay = pygame.display.set_mode((display_width,display_height)) #set main display window title pygame.display.set_caption('gameDisplay') clock = pygame.time.Clock() #----------------------FUNCTIONS------------------------- def fps_display(value): #1. set type font font = pygame.font.SysFont(None,25) #2. render it text = font.render("FPS count: " + str(value),True,white) #3. blit = draw gameDisplay.blit(text,(0,0)) class Particle(object): def __init__(self, x, y, size, colour, thickness): self.x = x self.y = y self.size = size self.colour = colour self.thickness = thickness def display(self): #pygame.draw. pygame.draw.circle(gameDisplay, self.colour, (self.x, self.y), self.size, self.thickness) def game_loop(frame_speed): #main game loop run = True counter = 0 velocity_x = 00 velocity_y = 10 gravity = 0.1 friction = 0.05 speed=0 dx = 10 dy = 10 while run: counter += 1 #-----------check for pressed keys---------------- for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False #------------------------------------------------- # CONSTRAINTS X RIGHT SIDE if particle.x - particle.size <= 0: #dx = -dx dx *= -(dx*friction) # CONSTRAINTS X LEFT SIDE if particle.size + particle.x >= display_width: #dx = -dx dx *= -(dx*friction) #CONSTRAINTS Y UP if particle.y - particle.size <= 0: dy *= -1 #CONSTRAINTS Y DOWN if particle.size + particle.y >= display_height: dy *= -1 #check if we are moving down if velocity_y < 0: velocity_y = velocity_y*(1-gravity) #if velocity_y > 0: #dy = velocity_y*(1+gravity) #dx = velocity_x print(f"{dx} dx") print(f"{dy} dy") particle.x += int(round(dx)) particle.y += int(round(dy)) print(velocity_y) #------------------------------------------------- gameDisplay.fill(black) # draw background #fps_display(counter) fps_display(dx) #speed_display() particle.display() #draw particle ball pygame.display.update() #update display clock.tick(frame_speed) #set FPS update frequency #--------------------------------------- #-----------initialization-------------- particle = Particle(x=150, y=50, size=30, colour=white, thickness=0) #-------------main loop----------------- game_loop(frame_speed_sec) #--------------------------------------- #---------------------------------------<file_sep>from math import radians from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * from gameobjects.matrix44 import * from gameobjects.vector3 import * SCREEN_SIZE = (800, 600) def resize(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60.0, float(width)/height, .1, 1000.) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def init(): glEnable(GL_DEPTH_TEST) glShadeModel(GL_FLAT) glClearColor(1.0, 1.0, 1.0, 0.0) glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0)) class Cube(object): def __init__(self, position, color): self.position = position self.color = color # Cube information num_faces = 6 vertices = [ (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0) ] normals = [ (0.0, 0.0, +1.0), # front (0.0, 0.0, -1.0), # back (+1.0, 0.0, 0.0), # right (-1.0, 0.0, 0.0), # left (0.0, +1.0, 0.0), # top (0.0, -1.0, 0.0) ] # bottom vertex_indices = [ (0, 1, 2, 3), # front (4, 5, 6, 7), # back (1, 5, 6, 2), # right (0, 4, 7, 3), # left (3, 2, 6, 7), # top (0, 1, 5, 4) ] # bottom def render(self): # Set the cube color, applies to all vertices till next call glColor( self.color ) # Adjust all the vertices so that the cube is at self.position vertices = [] for v in self.vertices: vertices.append( tuple(Vector3(v)+ self.position) ) # Draw all 6 faces of the cube glBegin(GL_QUADS) for face_no in range(self.num_faces): glNormal3dv( self.normals[face_no] ) v1, v2, v3, v4 = self.vertex_indices[face_no] glVertex( vertices[v1] ) glVertex( vertices[v2] ) glVertex( vertices[v3] ) glVertex( vertices[v4] ) glEnd() class Map(object): def __init__(self): map_surface = pygame.image.load("map.png") map_surface.lock() w, h = map_surface.get_size() self.cubes = [] # Create a cube for every non-white pixel for y in range(h): for x in range(w): r, g, b, a = map_surface.get_at((x, y)) if (r, g, b) != (255, 255, 255): gl_col = (r/255.0, g/255.0, b/255.0) position = (float(x), 0.0, float(y)) cube = Cube( position, gl_col ) self.cubes.append(cube) map_surface.unlock() self.display_list = None def render(self): if self.display_list is None: # Create a display list self.display_list = glGenLists(1) glNewList(self.display_list, GL_COMPILE) # Draw the cubes for cube in self.cubes: cube.render() # End the display list glEndList() else: # Render the display list glCallList(self.display_list) def run(): pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF) resize(*SCREEN_SIZE) init() clock = pygame.time.Clock() # This object renders the 'map' map = Map() # Camera transform matrix camera_matrix = Matrix44() camera_matrix.translate = (10.0, .6, 10.0) # Initialize speeds and directions rotation_direction = Vector3() rotation_speed = radians(90.0) movement_direction = Vector3() movement_speed = 5.0 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() if event.type == KEYUP and event.key == K_ESCAPE: pygame.quit() quit() # Clear the screen, and z-buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); time_passed = clock.tick() time_passed_seconds = time_passed / 1000. pressed = pygame.key.get_pressed() # Reset rotation and movement directions rotation_direction.set(0.0, 0.0, 0.0) movement_direction.set(0.0, 0.0, 0.0) # Modify direction vectors for key presses if pressed[K_LEFT]: rotation_direction.y = +1.0 elif pressed[K_RIGHT]: rotation_direction.y = -1.0 if pressed[K_UP]: rotation_direction.x = -1.0 elif pressed[K_DOWN]: rotation_direction.x = +1.0 if pressed[K_z]: rotation_direction.z = -1.0 elif pressed[K_x]: rotation_direction.z = +1.0 if pressed[K_q]: movement_direction.z = -1.0 elif pressed[K_a]: movement_direction.z = +1.0 # Calculate rotation matrix and multiply by camera matrix rotation = rotation_direction * rotation_speed * time_passed_seconds rotation_matrix = Matrix44.xyz_rotation(*rotation) camera_matrix *= rotation_matrix # Calcluate movment and add it to camera matrix translate heading = Vector3(camera_matrix.forward) movement = heading * movement_direction.z * movement_speed camera_matrix.translate += movement * time_passed_seconds # Upload the inverse camera matrix to OpenGL glLoadMatrixd(camera_matrix.get_inverse().to_opengl()) # Light must be transformed as well glLight(GL_LIGHT0, GL_POSITION, (0, 1.5, 1, 0)) # Render the map map.render() # Show the screen pygame.display.flip() if __name__ == "__main__": run() <file_sep>""" Jumping and variables video: https://www.youtube.com/watch?v=2-DNswzCkqk&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5&index=2 1. constraing are where we can move 2. jumping IF JUMPING: dont move left right """ import pygame from pygame.locals import * from rgb_color_dictionary import * pygame.init() #create window win = pygame.display.set_mode((500,500)) #set windows title pygame.display.set_caption("First Game") #character variables x = 50 y = 50 width = 40 height = 60 vel = 20 isJump = False jumpCount = 10 #clock=pygame.time.Clock() #main game loop run = True while run: pygame.time.delay(100) #this will be a clock for the game keys = {'left':False,'right':False, 'up':False, 'down':False} for event in pygame.event.get(): #check for all events that are happening if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: run = False vx = 0 vy = 0 keystate = pygame.key.get_pressed() #straight moves with screen constraints #cant move up if keystate[pygame.K_UP] and y > vel: vy = -vel #cant move down if keystate[pygame.K_DOWN] and y < 500 - height - vel: vy = vel if not isJump: #cant move off the left screen border if keystate[pygame.K_LEFT] and x > vel: vx = -vel #cant move off the right screen border if keystate[pygame.K_RIGHT] and x < 500 - width - vel: vx = vel #-----------------jump--------------- if keystate[pygame.K_SPACE]: isJump = True else: if jumpCount >= -10: # we jump for 10 pixels neg = 1 if jumpCount < 0: #when we get to the top of jump neg = -1 y -= (jumpCount ** 2) * 0.5 * neg jumpCount -= 1 else: isJump = False jumpCount = 10 #diagonals must be slower for sq(2)= 1.414 pitagora if vx != 0 and vy != 0: vx /= 1.414 vy /= 1.414 x += vx y += vy #draw rectangle win.fill(BLACK) pygame.draw.rect(win,RED,(x,y,width,height)) pygame.display.update() <file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 27 23:13:08 2020 @author: crtom """ import pygame as pg from settings import * vec = pg.math.Vector2 class Player(pg.sprite.Sprite): def __init__(self, game, x, y): # so player can acces all sprites in the game self.game = game self.groups = game.all_sprites # 1.) sprite class default override: #Call the parent class (Sprite) constructor pg.sprite.Sprite.__init__(self, self.groups) # 2.) sprite class default override: # tile based game - player is only one tile large # self.image = pg.Surface((TILESIZE, TILESIZE)) # YELLOW BLOCK SPRITE # self.image.fill(YELLOW) self.image = game.player_img # 3.) sprite class default override: # Fetch the rectangle object that has the dimensions of the image # Update the position of this object by setting the values of rect.x and rect.y self.rect = self.image.get_rect() # CUSTOM ATTRIBUTES #self.dt = 0 self.vel = vec(0, 0) self.pos = vec(x, y) * TILESIZE self.rot = 0 def get_keys(self): self.vel = vec(0, 0) self.rot_speed = 0 keys = pg.key.get_pressed() if keys[pg.K_LEFT] or keys[pg.K_a]: # self.player.move(dx=-1) self.vel.x = -PLAYER_SPEED elif keys[pg.K_RIGHT] or keys[pg.K_d]: # IF ENABLES DIAG self.vel.x = PLAYER_SPEED if keys[pg.K_UP] or keys[pg.K_w]: # IF ENABLES DIAG self.vel.y = -PLAYER_SPEED if keys[pg.K_DOWN] or keys[pg.K_s]: # IF ENABLES DIAG self.vel.y = PLAYER_SPEED # DIAGONAL PITAGORA if self.vel.x != 0 and self.vel.y != 0: self.vel *= 0.7071 def collide_with_walls(self, direction): # x collision check if direction == 'x': hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall if hits: # sprite was moving to the right # we need to put the sprite to the left edge of the wall if self.vel.x > 0: self.pos.x = hits[0].rect.left - self.rect.width # sprite was moving to the left # we need to put the sprite to the right edge of the wall if self.vel.x < 0: self.pos.x = hits[0].rect.right #- self.rect.width # we run into the wall, x velocity = 0 self.vel.x = 0 # update new position self.rect.x = self.pos.x if direction == 'y': hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall if hits: # sprite was moving down # we need to put the sprite to the top of the wall if self.vel.y > 0: self.pos.y = hits[0].rect.top - self.rect.height # sprite was moving to the top # we need to put the sprite to the bottom edge of the wall if self.vel.y < 0: self.pos.y = hits[0].rect.bottom #- self.rect.width # we run into the wall, x velocity = 0 self.vel.y = 0 # update new position self.rect.y = self.pos.y def update(self): self.get_keys() # this will make movement independant of frame rate self.pos += self.vel * self.game.dt # get dt from game object self.rect.x = self.pos.x self.collide_with_walls('x') self.rect.y = self.pos.y self.collide_with_walls('y') # check if sprite and a group collides # # if hits a wall dont move # # redo movement position # if pg.sprite.spritecollideany(self, self.game.walls): # self.x -= self.vx * self.game.dt # get dt from game object # self.y -= self.vy * self.game.dt # get dt from game object # # self.rect.x = self.x * TILESIZE # # self.rect.y = self.y * TILESIZE # self.rect.topleft = (self.x, self.y) class Wall(pg.sprite.Sprite): def __init__(self, game, x, y): # so player can acces all sprites in the game # member of all sprites group # member of all walls group self.groups = game.all_sprites, game.walls pg.sprite.Sprite.__init__(self, self.groups) self.game = game # tile based game - player is only one tile large self.image = pg.Surface((TILESIZE, TILESIZE)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.x = x self.y = y self.rect.x = x * TILESIZE self.rect.y = y * TILESIZE<file_sep>import turtle import time import random import winsound import os import winsound import tkinter as tk def key(event): """shows key or tk code for the key""" if event.keysym == 'Escape': root.destroy() if event.char == event.keysym: # normal number and letter characters print( 'Normal Key %r' % event.char ) elif len(event.char) == 1: # charcters like []/.,><#$ also Return and ctrl/key print( 'Punctuation Key %r (%r)' % (event.keysym, event.char) ) else: # f1 to f12, shift keys, caps lock, Home, End, Delete ... print( 'Special Key %r' % event.keysym ) root = tk.Tk() print( "Press a key (Escape key to exit):" ) root.bind_all('<Key>', key) # don't show the tk window root.withdraw() root.mainloop()
65dd75184787aaab9f1a91bdbadb454c3115c8e7
[ "Markdown", "Python", "Lua" ]
162
Python
CrtomirJuren/pygame-projects
f710f36050bfe3ece866bbda7d570caa1e037d7a
fdae4eb56b69daef13d6d548edce6f7f4ce33262
refs/heads/master
<repo_name>Shendow/Shenesis<file_sep>/Shenesis/lua/gui_playonline.lua require("lib/managers/menu/WalletGuiObject") local is_win_32 = SystemInfo:platform() == Idstring("WIN32") PlayOnlineGui = PlayOnlineGui or class() function PlayOnlineGui:init(ws, fullscreen_ws, node) managers.menu:active_menu().renderer.ws:hide() self._ws = ws self._fullscreen_ws = fullscreen_ws self._init_layer = self._ws:panel():layer() managers.menu_component:close_contract_gui() self:_setup() self:set_layer(1000) end function PlayOnlineGui:start_finding_servers() if (self.server_list_panels) then for id, pnl in pairs (self.server_list_panels) do self.list_panel:remove(pnl) end end self.server_list = {} self.server_list_panels = {} CrimeNetManager:_find_online_games_shenesis() end function PlayOnlineGui:update_server_list(joblist) if not (self.list_panel) then return end self.server_list = joblist local padding = 10 local y = padding local amount = 0 for id, job in pairs (joblist) do amount = amount + 1 if (amount > 35) then break end local wi, he = self.list_panel:w(), 24 local jobpnl = self.list_panel:panel({name = "jobpnl_" .. id}) jobpnl:set_w(wi) jobpnl:set_h(he) jobpnl:set_top(y) local bg = jobpnl:rect({ name = "bg", color = tweak_data.screen_colors.crimenet_lines, layer = 17, blend_mode = "add" }) bg:set_alpha(0) y = y + he self.server_list_panels[id] = jobpnl local job_tweak = tweak_data.narrative:job_data(job.job_id) local job_string = job.job_id and managers.localization:to_upper_text(job_tweak.name_id) or job.level_name or "NO JOB" local host_name = SH.QuickLabel(jobpnl, "host_name", job.host_name, nil, nil, nil, "center") local num_plrs = SH.QuickLabel(jobpnl, "num_plrs", job.num_plrs .. "/4", nil, nil, "right", "center") local state_name = SH.QuickLabel(jobpnl, "state_name", job.state_name, nil, nil, "right", "center") local level_name = SH.QuickLabel(jobpnl, "level_name", utf8.to_upper(job_string), nil, nil, "right", "center") managers.gui_data:safe_to_full_16_9(host_name:world_x(), host_name:world_center_y()) host_name:set_left(padding) host_name:set_center_y(jobpnl:height() * 0.5) managers.gui_data:safe_to_full_16_9(num_plrs:world_x(), num_plrs:world_center_y()) num_plrs:set_right(jobpnl:width() - padding) num_plrs:set_center_y(jobpnl:height() * 0.5) managers.gui_data:safe_to_full_16_9(state_name:world_x(), state_name:world_center_y()) state_name:set_right(jobpnl:width() - 30 - padding) state_name:set_center_y(jobpnl:height() * 0.5) managers.gui_data:safe_to_full_16_9(level_name:world_x(), level_name:world_center_y()) level_name:set_right(jobpnl:width() - 185 - padding) level_name:set_center_y(jobpnl:height() * 0.5) end end function PlayOnlineGui:update_server_info(job) local heistpnl = self.heistpnl local job_tweak = tweak_data.narrative:job_data(job.job_id) local job_string = job.job_id and managers.localization:to_upper_text(job_tweak.name_id) or job.level_name or "NO JOB" local briefing_string = job.job_id and managers.localization:to_upper_text(job_tweak.briefing_id) or "NO BRIEFING" if not (job_tweak.briefing_id) then SH.PrintTable(job_tweak) print("--------") end local difficulty_string = managers.localization:to_upper_text(tweak_data.difficulty_name_ids[tweak_data.difficulties[job.difficulty_id]]) if (self._server_label) then heistpnl:remove(self._server_label) self._server_label = nil end if (self._server_state_label) then heistpnl:remove(self._server_state_label) self._server_state_label = nil end if (self._heist_label) then heistpnl:remove(self._heist_label) self._heist_label = nil end if (self._difficulty_label) then heistpnl:remove(self._difficulty_label) self._difficulty_label = nil end if (self._briefing_label) then heistpnl:remove(self._briefing_label) self._briefing_label = nil end local host_name = SH.QuickLabel(heistpnl, "host_name", job.host_name, nil, tweak_data.screen_colors.button_stage_2) host_name:set_top(self.server_label:top()) host_name:set_left(self.server_label:left() + 57) self._server_label = host_name local state_name = SH.QuickLabel(heistpnl, "state_name", job.state_name, nil, tweak_data.screen_colors.button_stage_2) state_name:set_top(self.server_state_label:top()) state_name:set_left(self.server_state_label:left() + 98) self._server_state_label = state_name local level_name = SH.QuickLabel(heistpnl, "level_name", job_string, nil, tweak_data.screen_colors.button_stage_2) level_name:set_top(self.heist_label:top()) level_name:set_left(self.heist_label:left() + 44) self._heist_label = level_name local difficulty = SH.QuickLabel(heistpnl, "difficulty", difficulty_string, nil, tweak_data.screen_colors.button_stage_2) difficulty:set_top(self.difficulty_label:top()) difficulty:set_left(self.difficulty_label:left() + 79) self._difficulty_label = difficulty local briefing = heistpnl:text({ name = "objective_text", text = briefing_string, layer = 1, align = "left", vertical = "top", font_size = tweak_data.hud.small_font_size, font = tweak_data.hud.small_font, w = heistpnl:w() - 20, h = heistpnl:h(), x = self.difficulty_label:left(), y = self.difficulty_label:top() + 36, wrap = true, word_wrap = true }) self._briefing_label = briefing -- local briefing = SH.QuickLabel(heistpnl, "briefing", briefing_string, nil, tweak_data.screen_colors.button_stage_2) -- briefing:set_top(self.difficulty_label:top() + 24) -- briefing:set_left(self.difficulty_label:left()) -- self._briefing_label = briefing end function PlayOnlineGui:set_players_online(amount) if not (self.heisters_label) then return end local txt = utf8.to_upper(managers.localization:text("heisters_x")) .. managers.money:add_decimal_marks_to_string(string.format("%.3d", amount)) self.heisters_label:set_text(txt) end function PlayOnlineGui:_setup() if (alive(self._panel)) then self._ws:panel():remove(self._panel) end self:start_finding_servers() self._panel = self._ws:panel():panel({ visible = true, layer = self._init_layer, valign = "center" }) self._fullscreen_panel = self._fullscreen_ws:panel():panel() WalletGuiObject.set_wallet(self._panel) local title_text = SH.QuickLabel(self._panel, "play_online", utf8.to_upper(managers.localization:text("play_online")), "large") local title_bg_text = self._fullscreen_panel:text({ name = "play_online", text = utf8.to_upper(managers.localization:text("play_online")), h = 90, align = "left", vertical = "top", font_size = tweak_data.menu.pd2_massive_font_size, font = tweak_data.menu.pd2_massive_font, color = tweak_data.screen_colors.button_stage_3, alpha = 0.4, blend_mode = "add", layer = 1 }) local x, y = managers.gui_data:safe_to_full_16_9(title_text:world_x(), title_text:world_center_y()) title_bg_text:set_world_left(x) title_bg_text:set_world_center_y(y) title_bg_text:move(-13, 9) MenuBackdropGUI.animate_bg_text(self, title_bg_text) local HEIST_INFO_WIDTH = 0.35 local HEIST_LIST = 1 - HEIST_INFO_WIDTH local MARGIN = 10 local heistpnl = self._panel:panel({name = "heistpnl"}) heistpnl:set_w(math.round(self._panel:w() * HEIST_INFO_WIDTH)) heistpnl:set_h(math.round(self._panel:h() * 0.75)) heistpnl:set_top(title_text:bottom() + 32) self.heistpnl = heistpnl BoxGuiObject:new(heistpnl, {sides = {1, 1, 1, 1}}) local padding = 10 local server_label = SH.QuickLabel(heistpnl, "server_x", utf8.to_upper(managers.localization:text("server_x"))) self.server_label = server_label local server_state_label = SH.QuickLabel(heistpnl, "server_state_x", utf8.to_upper(managers.localization:text("server_state_x"))) self.server_state_label = server_state_label local heist_label = SH.QuickLabel(heistpnl, "heist_x", utf8.to_upper(managers.localization:text("heist_x"))) self.heist_label = heist_label local difficulty_label = SH.QuickLabel(heistpnl, "difficulty_x", utf8.to_upper(managers.localization:text("difficulty_x"))) self.difficulty_label = difficulty_label local y = padding managers.gui_data:safe_to_full_16_9(server_label:world_x(), server_label:world_center_y()) server_label:move(padding, y) y = y + server_label:height() managers.gui_data:safe_to_full_16_9(server_state_label:world_x(), server_state_label:world_center_y()) server_state_label:move(padding, y) y = y + server_state_label:height() managers.gui_data:safe_to_full_16_9(heist_label:world_x(), heist_label:world_center_y()) heist_label:move(padding, y) y = y + heist_label:height() managers.gui_data:safe_to_full_16_9(difficulty_label:world_x(), difficulty_label:world_center_y()) difficulty_label:move(padding, y) y = y + difficulty_label:height() local listpnl = self._panel:panel({name = "listpnl"}) listpnl:set_w(math.round(self._panel:w() * HEIST_LIST - MARGIN)) listpnl:set_h(math.round(self._panel:h() * 0.75)) listpnl:set_top(title_text:bottom() + 32) listpnl:set_left(heistpnl:right() + MARGIN) self.list_panel = listpnl BoxGuiObject:new(listpnl, {sides = {1, 1, 1, 1}}) self._list_scroll_bar_panel = self._panel:panel({ name = "list_scroll_bar_panel", w = 20, h = listpnl:h() }) self._list_scroll_bar_panel:set_world_left(listpnl:world_right()) self._list_scroll_bar_panel:set_world_top(listpnl:world_top()) local texture, rect = tweak_data.hud_icons:get_icon_data("scrollbar_arrow") local scroll_up_indicator_arrow = self._list_scroll_bar_panel:bitmap({ name = "scroll_up_indicator_arrow", texture = texture, texture_rect = rect, layer = 2, color = Color.white }) scroll_up_indicator_arrow:set_center_x(self._list_scroll_bar_panel:w() * 0.5) local texture, rect = tweak_data.hud_icons:get_icon_data("scrollbar_arrow") local scroll_down_indicator_arrow = self._list_scroll_bar_panel:bitmap({ name = "scroll_down_indicator_arrow", texture = texture, texture_rect = rect, layer = 2, color = Color.white, rotation = 180 }) scroll_down_indicator_arrow:set_bottom(self._list_scroll_bar_panel:h()) scroll_down_indicator_arrow:set_center_x(self._list_scroll_bar_panel:w() * 0.5) local bar_h = scroll_down_indicator_arrow:top() - scroll_up_indicator_arrow:bottom() self._list_scroll_bar_panel:rect({ color = Color.black, alpha = 0.05, y = scroll_up_indicator_arrow:bottom(), h = bar_h, w = 4 }):set_center_x(self._list_scroll_bar_panel:w() * 0.5) bar_h = scroll_down_indicator_arrow:bottom() - scroll_up_indicator_arrow:top() local scroll_bar = self._list_scroll_bar_panel:panel({ name = "scroll_bar", layer = 2, h = bar_h }) local scroll_bar_box_panel = scroll_bar:panel({ name = "scroll_bar_box_panel", w = 4, halign = "scale", valign = "scale" }) self._list_scroll_bar_box_class = BoxGuiObject:new(scroll_bar_box_panel, { sides = { 2, 2, 0, 0 } }) self._list_scroll_bar_box_class:set_aligns("scale", "scale") scroll_bar_box_panel:set_w(8) scroll_bar_box_panel:set_center_x(scroll_bar:w() * 0.5) scroll_bar:set_top(scroll_up_indicator_arrow:top()) scroll_bar:set_center_x(scroll_up_indicator_arrow:center_x()) local y = padding --[[ local distance_label = SH.QuickLabel(listpnl, "distance_filter", utf8.to_upper(managers.localization:text("distance_filter"))) local difficulty_label = SH.QuickLabel(listpnl, "difficulty_filter", utf8.to_upper(managers.localization:text("difficulty_filter"))) managers.gui_data:safe_to_full_16_9(distance_label:world_x(), distance_label:world_center_y()) distance_label:move(padding + 20, y) y = y + distance_label:height() managers.gui_data:safe_to_full_16_9(difficulty_label:world_x(), difficulty_label:world_center_y()) difficulty_label:move(padding + 20, y) y = y + difficulty_label:height() ]]-- local bottompnl = self._panel:panel({name = "bottompnl"}) bottompnl:set_w(self._panel:w()) bottompnl:set_h(32) bottompnl:set_top(listpnl:bottom() + MARGIN) bottompnl:set_left(heistpnl:left()) self.bottom_panel = bottompnl BoxGuiObject:new(bottompnl, {sides = {1, 1, 1, 1}}) local heisters_label = SH.QuickLabel(bottompnl, "heisters_x", utf8.to_upper(managers.localization:text("heisters_x")) .. "0") self.heisters_label = heisters_label managers.gui_data:safe_to_full_16_9(heisters_label:world_x(), heisters_label:world_center_y()) heisters_label:set_left(padding) heisters_label:set_center_y(bottompnl:height() * 0.5) local update_text = bottompnl:text({ name = "update_button", text = utf8.to_upper(managers.localization:text("update")), align = "right", vertical = "center", h = tweak_data.menu.pd2_small_font_size, font_size = tweak_data.menu.pd2_small_font_size, font = tweak_data.menu.pd2_small_font, blend_mode = "add", color = tweak_data.screen_colors.button_stage_3 }) update_text:set_right(bottompnl:width() - padding) update_text:set_center_y(bottompnl:height() * 0.5) if (managers.menu:is_pc_controller()) then local back_text = self._panel:text({ name = "back_button", text = utf8.to_upper(managers.localization:text("menu_back")), align = "right", vertical = "bottom", h = tweak_data.menu.pd2_large_font_size, font_size = tweak_data.menu.pd2_large_font_size, font = tweak_data.menu.pd2_large_font, blend_mode = "add", color = tweak_data.screen_colors.button_stage_3 }) local _, _, w, h = back_text:text_rect() back_text:set_size(w, h) back_text:set_position(math.round(back_text:x()), math.round(back_text:y())) back_text:set_right(self._panel:w()) back_text:set_bottom(self._panel:h()) local bg_back = self._fullscreen_panel:text({ name = "back_button", text = utf8.to_upper(managers.localization:text("menu_back")), h = 90, align = "right", vertical = "bottom", blend_mode = "add", font_size = tweak_data.menu.pd2_massive_font_size, font = tweak_data.menu.pd2_massive_font, color = tweak_data.screen_colors.button_stage_3, alpha = 0.4, layer = 1 }) local x, y = managers.gui_data:safe_to_full_16_9(self._panel:child("back_button"):world_right(), self._panel:child("back_button"):world_center_y()) bg_back:set_world_right(x) bg_back:set_world_center_y(y) bg_back:move(13, -9) MenuBackdropGUI.animate_bg_text(self, bg_back) end local black_rect = self._fullscreen_panel:rect({ color = Color(0.4, 0, 0, 0), layer = 1 }) local blur = self._fullscreen_panel:bitmap({ texture = "guis/textures/test_blur_df", w = self._fullscreen_ws:panel():w(), h = self._fullscreen_ws:panel():h(), render_template = "VertexColorTexturedBlur3D", layer = -1 }) local func = function(o) over(0.6, function(p) o:set_alpha(p) end) end blur:animate(func) end function PlayOnlineGui:set_layer(layer) self._panel:set_layer(self._init_layer + layer) end function PlayOnlineGui:input_focus() return 1 end function PlayOnlineGui:mouse_moved(o, x, y) if (managers.menu:is_pc_controller()) then local back_button = self._panel:child("back_button") if (back_button:inside(x, y)) then if not self._back_highlight then self._back_highlight = true back_button:set_color(tweak_data.screen_colors.button_stage_2) managers.menu_component:post_event("highlight") end else self._back_highlight = false back_button:set_color(tweak_data.screen_colors.button_stage_3) end local update_button = self.bottom_panel:child("update_button") if (update_button:inside(x, y)) then if not self._update_highlight then self._update_highlight = true update_button:set_color(tweak_data.screen_colors.button_stage_2) managers.menu_component:post_event("highlight") end else self._update_highlight = false update_button:set_color(tweak_data.screen_colors.button_stage_3) end -- Recipe for bad lags? for id, pnl in pairs (self.server_list_panels) do local x2, y2 = pnl:world_left(), pnl:world_top() local bg = pnl:child("bg") if (self.list_panel and self.list_panel:inside(x2, y2) and pnl:inside(x, y)) then local job = self.server_list[id] if (job) then if (bg) then bg:set_alpha(0.1) end self:update_server_info(job) end else if (bg) then bg:set_alpha(0) end end end end if (self._panel:inside(x, y)) then return true end end function PlayOnlineGui:mouse_pressed(button, x, y) if (button == Idstring("0")) then if (self._panel:child("back_button"):inside(x, y)) then managers.menu:back() return end if (self.bottom_panel:child("update_button"):inside(x, y)) then self:start_finding_servers() return end for id, pnl in pairs (self.server_list_panels) do local x2, y2 = pnl:world_left(), pnl:world_top() if (self.list_panel and self.list_panel:inside(x2, y2)) then if (pnl:inside(x, y)) then local job = self.server_list[id] managers.network.matchmake:join_server_with_check(job.room_id) break end end end end end function PlayOnlineGui:confirm_pressed() return false end function PlayOnlineGui:close() self.server_list = {} managers.menu:active_menu().renderer.ws:show() WalletGuiObject.close_wallet(self._panel) self._ws:panel():remove(self._panel) self._fullscreen_ws:panel():remove(self._fullscreen_panel) end <file_sep>/Shenesis/core.lua if not (Shenesis) then Shenesis = true SH = {} SH.LuaPath = "Shenesis/lua/" end SH.HookFiles = { ["lib/managers/menumanager"] = "menumanager.lua", ["lib/managers/localizationmanager"] = "localizationmanager.lua", ["lib/managers/menu/menucomponentmanager"] = { "menucomponentmanager.lua", "gui_playonline.lua", }, ["lib/managers/crimenetmanager"] = "crimenetmanager.lua", } local function file_is_readable(fname) local fil = io.open(fname, "r") if (fil ~= nil) then io.close(fil) return true end return false end local function istable(o) return type(o) == "table" end local function Msg(text) io.stderr:write(text) end local function MsgN(text) Msg(text .. "\n") end local function CountTable(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end local function PrintTable(t, indent, done) done = done or {} indent = indent or 0 for key, value in pairs (t) do Msg(string.rep("\t", indent)) if (istable(value) and not done[value]) then done[value] = true Msg(tostring(key) .. ":" .. "\n") PrintTable(value, indent + 2, done) else Msg(tostring (key) .. "\t=\t") Msg(tostring(value) .. "\n") end end end local function QuickLabel(parent, name, text, font, color, xalign, yalign) xalign = xalign or "left" yalign = yalign or "top" font = font or "small" color = color or tweak_data.screen_colors.text return parent:text({ name = name, text = text, align = xalign, vertical = yalign, h = tweak_data.menu["pd2_" .. font .. "_font_size"], font_size = tweak_data.menu["pd2_" .. font .. "_font_size"], font = tweak_data.menu["pd2_" .. font .. "_font"], color = color }) end io.file_is_readable = file_is_readable SH.Msg = Msg SH.MsgN = MsgN SH.PrintTable = PrintTable SH.CountTable = CountTable SH.QuickLabel = QuickLabel local function SafeDoFile(fileName) local success, errorMsg = pcall(function() if (io.file_is_readable(fileName)) then dofile(fileName) else MsgN("[Error] Could not open file '" .. fileName .. "'! Does it exist, is it readable?") end end) if not (success) then MsgN("[Error]\nFile: " .. fileName .. "\n" .. errorMsg) end end SH.SafeDoFile = SafeDoFile if (RequiredScript) then local requiredScript = RequiredScript:lower() local hf = SH.HookFiles[requiredScript] if (hf) then if (type(hf) == "table") then for _, fil in pairs (hf) do SafeDoFile(SH.LuaPath .. fil) end else SafeDoFile(SH.LuaPath .. SH.HookFiles[requiredScript]) end end end<file_sep>/README.md Shenesis ======== A classic server list modification for PAYDAY 2. By classic I mean that the design is inspired by PAYDAY: THE HEIST's server list. How do I install it? ======== Download these files (besides LICENSE and README.md), and drop them in your PAYDAY 2 game directory. You will also need IPHLAPI.dll, which is what allows this mod and other lua mods to work. At the moment I can't add it to the repository somehow. If you are asked to overwrite PD2Hook.yml, I recommend you check your game's PD2Hook.yml file and the mod's. Overwriting it would disable all other lua scripts that you may have running. Info you need to know ======== This is EXPERIMENTAL. You may crash or it may look weird on some resolutions. If you find any problem related to this mod, please send me an e-mail (shenesis(at)gmail.com). I recommend you make a backup of your save before installing this mod - Here's a link showing you how: http://steamcommunity.com/sharedfiles/filedetails/?id=170416480<file_sep>/Shenesis/lua/menumanager.lua local menu_manager_init_orig = MenuManager.init function MenuManager:init(is_start_menu) menu_manager_init_orig(self, is_start_menu) if (is_start_menu) then addCustomMenu() end end function addCustomMenu() local mainMenuNodes = managers.menu._registered_menus.menu_main.logic._data._nodes local crimenet = -1 for id, v in pairs (mainMenuNodes["main"]._items) do if (v._parameters.name == "crimenet") then crimenet = id break end end if (crimenet == -1) then -- wat? return end local btn = deep_clone(mainMenuNodes.options._items[1]) btn._parameters.name = "sh_play_online" btn._parameters.text_id = "play_online" btn._parameters.help_id = "play_online_desc" btn._parameters.next_node = "play_online" mainMenuNodes["main"]:insert_item(btn, crimenet + 1) -- After Crime.net local node = deep_clone(mainMenuNodes["infamytree"]) node._parameters.name = "sh_play_online_real" node._parameters.help_id = "play_online_desc" node._parameters.topic_id = "play_online" node._parameters.sync_state = "play_online" node._parameters.menu_components[1] = "play_online" node._items = {} mainMenuNodes["play_online"] = node end function MenuCallbackHandler:multichoiceTest(item) io.write("Multichoice value: " .. tostring(item:value()) .. "\n") end<file_sep>/Shenesis/lua/crimenetmanager.lua function CrimeNetManager:_find_online_games_shenesis(friends_only) if not (self._active_server_jobs_shenesis) then self._active_server_jobs_shenesis = {} end local function f(info) managers.network.matchmake:search_lobby_done() local room_list = info.room_list local attribute_list = info.attribute_list local dead_list = {} for id, _ in pairs(self._active_server_jobs_shenesis) do dead_list[id] = true end local servers = {} for i, room in ipairs(room_list) do local name_str = tostring(room.owner_name) local attributes_numbers = attribute_list[i].numbers if managers.network.matchmake:is_server_ok(friends_only, room.owner_id, attributes_numbers) then dead_list[room.room_id] = nil local host_name = name_str local level_id = tweak_data.levels:get_level_name_from_index(attributes_numbers[1] % 1000) local name_id = level_id and tweak_data.levels[level_id] and tweak_data.levels[level_id].name_id local level_name = name_id and managers.localization:text(name_id) or "LEVEL NAME ERROR" local difficulty_id = attributes_numbers[2] local difficulty = tweak_data:index_to_difficulty(difficulty_id) local job_id = tweak_data.narrative:get_job_name_from_index(math.floor(attributes_numbers[1] / 1000)) local kick_option = attributes_numbers[8] == 0 and 0 or 1 local state_string_id = tweak_data:index_to_server_state(attributes_numbers[4]) local state_name = state_string_id and managers.localization:text("menu_lobby_server_state_" .. state_string_id) or "UNKNOWN" local state = attributes_numbers[4] local num_plrs = attributes_numbers[5] local is_friend = false if Steam:logged_on() and Steam:friends() then for _, friend in ipairs(Steam:friends()) do if friend:id() == room.owner_id then is_friend = true end end end if name_id then local room = { room_id = room.room_id, id = room.room_id, level_id = level_id, difficulty = difficulty, difficulty_id = difficulty_id, num_plrs = num_plrs, host_name = host_name, state_name = state_name, state = state, level_name = level_name, job_id = job_id, is_friend = is_friend, kick_option = kick_option } self._active_server_jobs_shenesis[room.room_id] = room end end end for id, _ in pairs(dead_list) do self._active_server_jobs_shenesis[id] = nil end managers.menu_component:update_shenesis_server_list(self._active_server_jobs_shenesis) end managers.network.matchmake:register_callback("search_lobby", f) managers.network.matchmake:search_lobby(friends_only) -- Get total heisters local usrs_f = function(success, amount) print("usrs_f", success, amount) if (success) then managers.menu_component:set_shenesis_players_online(amount) end end Steam:sa_handler():concurrent_users_callback(usrs_f) Steam:sa_handler():get_concurrent_users() end<file_sep>/Shenesis/lua/localizationmanager.lua SH.Localization = { ["play_online"] = "PLAY ONLINE", ["play_online_desc"] = "PLAY PAYDAY 2 MULTIPLAYER.", ["play_with_anyone"] = "PLAY WITH ANYONE", ["play_with_anyone_desc"] = "PLAY WITH RANDOM PEOPLE.", ["play_with_friends"] = "PLAY WITH YOUR FRIENDS", ["play_with_friends_desc"] = "PLAY WITH YOUR FRIENDS.", ["server_x"] = "SERVER:", ["server_state_x"] = "SERVER STATE:", ["heist_x"] = "HEIST:", ["difficulty_x"] = "DIFFICULTY:", ["heisters_x"] = "PLAYERS: ", ["distance_filter"] = "DISTANCE FILTER", ["difficulty_filter"] = "DIFFICULTY FILTER", ["update"] = "UPDATE", } local OldLocalizationManagerText = LocalizationManager.text function LocalizationManager:text(string_id, macros) return SH.Localization[string_id] or OldLocalizationManagerText(self, string_id, macros) end<file_sep>/Shenesis/lua/menucomponentmanager.lua local OldMenuComponentManagerInit = MenuComponentManager.init function MenuComponentManager:init() OldMenuComponentManagerInit(self) self._active_components.play_online = { create = callback(self, self, "_create_play_online"), close = callback(self, self, "close_play_online") } end local OldMenuComponentManagerInputFocus = MenuComponentManager.input_focus function MenuComponentManager:input_focus() OldMenuComponentManagerInputFocus(self) if self._playonline_gui then return self._playonline_gui:input_focus() end end local OldMenuComponentManagerMouseMoved = MenuComponentManager.mouse_moved function MenuComponentManager:mouse_moved(o, x, y) local wanted_pointer = "arrow" if (self._playonline_gui) then local used, pointer = self._playonline_gui:mouse_moved(o, x, y) wanted_pointer = pointer or wanted_pointer if (used) then return true, wanted_pointer end end return OldMenuComponentManagerMouseMoved(self, o, x, y) end local OldMenuComponentManagerMousePressed = MenuComponentManager.mouse_pressed function MenuComponentManager:mouse_pressed(o, button, x, y) if (self._playonline_gui and self._playonline_gui:mouse_pressed(button, x, y)) then return true end return OldMenuComponentManagerMousePressed(self, o, button, x, y) end function MenuComponentManager:update_shenesis_server_list(data) if (self._playonline_gui) then self._playonline_gui:update_server_list(data) end end function MenuComponentManager:set_shenesis_players_online(amount) if (self._playonline_gui) then self._playonline_gui:set_players_online(amount) end end function MenuComponentManager:_create_play_online() self:create_play_online() end function MenuComponentManager:create_play_online(node) self:close_play_online() self._playonline_gui = PlayOnlineGui:new(self._ws, self._fullscreen_ws, node) end function MenuComponentManager:close_play_online() if (self._playonline_gui) then self._playonline_gui:close() self._playonline_gui = nil end end
754f9ee17c45775f288102bd25ccd39f4f3bb9e7
[ "Markdown", "Lua" ]
7
Lua
Shendow/Shenesis
c76921d85d29bd8043b6f60fe5387e8817cb1ff1
42804e64f0b51536fa1fa99c8877de62a1c6c869
refs/heads/master
<repo_name>cryoem/eman-deps-feedstock<file_sep>/recipe/test_imports.py from bisect import insort from builtins import object from builtins import range from collections import Counter from collections import MutableMapping from collections import defaultdict from copy import copy from copy import deepcopy from distutils.spawn import find_executable from functools import reduce from future import standard_library from future.utils import with_metaclass from io import StringIO from math import acos from math import atan2 from math import ceil from math import log10 from math import pi from math import pow from math import sin from math import sqrt from math import tanh from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.backends.backend_pdf import FigureCanvasPdf from matplotlib.figure import Figure from matplotlib.ticker import MaxNLocator from mpl_toolkits.mplot3d import Axes3D from multiprocessing import Array from multiprocessing import Pool from numpy import arange from numpy import array from operator import itemgetter from optparse import OptionParser from os import path from os import remove from os import system from os import unlink from past.utils import old_div from pickle import dump from pickle import dumps from pickle import load from pickle import loads from pprint import pprint from pylab import colorbar from pylab import figure from pylab import scatter from pylab import show from pylab import subplot from queue import Queue from random import choice from random import uniform from scipy import ndimage from scipy import optimize from scipy import sparse from scipy.interpolate import interp1d from scipy.optimize import minimize from scipy.signal import argrelextrema from scipy.signal import find_peaks_cwt from scipy.stats import norm from shutil import copy2 from shutil import copyfile from sklearn import linear_model from sklearn.cluster import KMeans from sklearn.decomposition import PCA from struct import pack from struct import unpack from sys import argv from sys import exit from sys import stdout from time import ctime from time import gmtime from time import localtime from time import mktime from time import sleep from time import strftime from time import strptime from time import time from weakref import WeakKeyDictionary from xml.sax.handler import ContentHandler from zlib import compress from zlib import decompress import _thread import abc import argparse import atexit import base64 import collections import colorsys import copy import datetime import fnmatch import gc import getpass import glob import importlib import itertools import json import math import matplotlib import matplotlib.cm import matplotlib.mlab import matplotlib.pyplot import multiprocessing import numpy import numpy.linalg import operator import os import os.path import pickle import platform import pprint import pylab import queue import random import re import scipy import scipy.ndimage import scipy.spatial.distance import select import shelve import shutil import signal import sklearn.decomposition import socket import string import struct import subprocess import sys import tempfile import tensorflow import tensorflow.keras.models import threading import time import traceback import warnings import weakref import webbrowser import xml.etree.ElementTree import xml.sax import zlib <file_sep>/recipe/test_imports_gui.py from OpenGL import GL from OpenGL import GLU from OpenGL import GLUT from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5 import QtOpenGL from PyQt5 import QtWidgets from PyQt5.QtCore import QEvent from PyQt5.QtCore import QTimer from PyQt5.QtCore import Qt <file_sep>/recipe/test_imports_pydusa.py from mpi import MPI_CHAR from mpi import MPI_COMM_WORLD from mpi import mpi_bcast from mpi import mpi_comm_rank from mpi import mpi_finalize from mpi import mpi_get_count from mpi import mpi_init from mpi import mpi_probe from mpi import mpi_recv from mpi import mpi_send <file_sep>/recipe/test_imports_future.py from __future__ import division from __future__ import print_function from __future__ import print_function, division
1a242994ac0d8e0ef51a972a0d96408a0fc69001
[ "Python" ]
4
Python
cryoem/eman-deps-feedstock
4ed7a5e37a8191846358cc45758b91c286a72235
bbe02c22c5e47d59873a7ea1d84e23aae2e8c639
refs/heads/master
<file_sep>import numpy as np from numpy.lib.stride_tricks import as_strided from audio_utils import AudioSegment from scipy.io.wavfile import read EPS = 1e-5 def specgram_real(data, NFFT=256, Fs=2, noverlap=128): """ Computes the spectrogram for a real signal. The parameters follow the naming convention of matplotlib.mlab.specgram Params: data : 1D numpy array NFFT : number of elements in the window Fs : sample rate noverlap : number of elements to overlap each window Returns: x : 2D numpy array, frequency x time freq : 1D array of frequency of each row in x Note this is a truncating computation e.g. if NFFT=10, noverlap=5 and the signal has 23 elements, then the last 3 elements will be truncated. """ assert not np.iscomplexobj(data), "Must not pass in complex numbers" stride = NFFT - noverlap window = np.hanning(NFFT)[:, None] window_norm = np.sum(window**2) # The scaling below follows the convention of # matplotlib.mlab.specgram which is the same as # matlabs specgram. Seems somewhat arbitrary thus # TODO, awni, check on the validity of this scaling. scale = window_norm * Fs trunc = (len(data) - NFFT) % stride x = data[:len(data) - trunc] # "stride trick" reshape to include overlap nshape = (NFFT, (len(x) - NFFT) // stride + 1) nstrides = (x.strides[0], x.strides[0] * stride) x = as_strided(x, shape=nshape, strides=nstrides) # broadcast window, compute fft over columns and square mod x = np.fft.rfft(x * window, axis=0) x = np.absolute(x)**2 # scale, 2.0 for everything except dc and nfft/2 x[1:-1, :] *= (2.0 / scale) x[(0, -1), :] /= scale freqs = float(Fs) / NFFT * np.arange(x.shape[0]) return (x, freqs) def get_feat_dim(step, window, max_freq, **kwargs): # TODO sanjeev Figure this out! feat_dim_map = {(10, 20, 8000): 81, (10, 20, 16000): 161} key = (step, window, max_freq) assert key in feat_dim_map return feat_dim_map[key] def compute_volume_normalized_feature(audio_file, feature_info): audio = AudioSegment.from_wav(audio_file) audio = audio.normalize() assert audio.normalized, "Audio segment was not normalized" return compute_raw_feature(audio.wav_data, feature_info) def compute_raw_feature(audio_file, feature_info): """ Compute time x frequency feature matrix *without* any normalization, striding, or splicing. We *do* convert to log-space. """ # spec is frequency x time spec, _ = compute_specgram( audio_file, step=feature_info['step'], window=feature_info['window'], max_freq=feature_info['max_freq']) # transpose to time x frequency return np.log(spec + EPS).astype(np.float32).T def compute_specgram(audio_file, step=10, window=20, max_freq=8000, shift=0): """ audio_file : audio wav file step : step size in ms between windows window : window size in ms max_freq : keep frequencies below value shift: time in ms to be clipped form the audio data, use negative values to clip form the end Uses default window for specgram (hamming). Return value is Frequency x Time matrix. """ Fs, data = read(audio_file) return compute_specgram_raw(Fs, data, step, window, max_freq, shift) def compute_specgram_raw(Fs, data, step, window, max_freq, shift, spec_fn=specgram_real): """ Same as above when you've already read audio_file """ shift = (Fs/1000) * shift if shift < 0: data[-shift:] = data[:shift] elif shift > 0: data[:-shift] = data[shift:] # If we have two channels, take just the first if len(data.shape) == 2: data = data[:, 0].squeeze() step_sec = step/1000. window_sec = window/1000. if step_sec > window_sec: raise ValueError("Step size must not be greater than window size") noverlap = int((window_sec - step_sec) * Fs) NFFT = int(window_sec * Fs) Pxx, freqs = spec_fn(data, NFFT=NFFT, Fs=Fs, noverlap=noverlap)[0:2] try: ind = np.where(freqs == max_freq/2)[0][0] + 1 except IndexError: return None, None return Pxx[:ind, :], freqs[:ind] <file_sep>''' Collection of classes to help with finding and adding noise to audio ''' import os import wave import pydub import random import string import subprocess import numpy as np import glob from scipy import stats from cStringIO import StringIO # from utils import parmap import scikits.audiolab as ab import linecache import re import json MSEC = 1000 # pydub frames are in ms, so multiply with MSEC when indexing FRAME_RATE = 16000 DEVNULL = open(os.devnull, 'w') ROOT_DIR = '/scratch/sanjeev/random-youtube-1/' TMP_DIR = '/scratch/sanjeev/tmp/' class AudioSegment(pydub.AudioSegment): ''' Helper class to manipulate `AudioSegment`s Some functions may use sox ''' sox_cmd = 'sox -t wav - -t wav -' effects = ['echo', 'chorus', 'speed', 'pitch', 'flanger', 'reverb', 'tempo', 'overdrive'] @property def power_dB(self): ''' power of the segment in decibels ''' if self.rms == 0: return 0 return pydub.utils.ratio_to_db(self.rms) def normalize(self, required_power_in_dB=70): ''' Performs a best effort power normalization If the power could not be set to the required_power_in_dB it returns the altered audio without failing! ''' delta = required_power_in_dB - self.power_dB self.normalize_gap = delta self = self + delta self = self.set_frame_rate(FRAME_RATE) self.__class__ = AudioSegment self.normalize_gap = abs(self.power_dB - required_power_in_dB) < 5 return self @property def wav_data(self): assert self.frame_rate == FRAME_RATE, "Frame rate set incorrectly." assert hasattr(self, 'normalize_gap'), "Normalize audio before accessing wav_data." wav_file = StringIO() self.export(wav_file, format='wav') wav_file.seek(0) return wav_file @classmethod def get_random_effect(cls): return cls.effects[random.randint(0, len(cls.effects)-1)] def add_effect(self, effect, params=[]): ''' Uses sox to add one of these effects Read AudioSegment.effects to see the list of effects available ''' # Write the current file to console assert self.duration_seconds < 100, '{0:.2f}'.format(self.duration_seconds) original_file = StringIO() self.export(original_file, format='wav') original_file.seek(0) wav_data = original_file.read() # Add the effect using sox try: effect_cmd = AudioSegment._get_effect_param(effect, params) sox_cmd = '{0} {1}'.format(self.sox_cmd, effect_cmd) process = subprocess.Popen(sox_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=DEVNULL, shell=True) effected_file = StringIO(process.communicate(wav_data)[0]) effected_file.seek(0) # Return the updated one return AudioSegment.from_wav(effected_file) except Exception as msg: print msg, effect return self @classmethod def _get_effect_param(cls, effect, params=[]): # Make sure params is a list if not hasattr(params, '__getitem__'): params = [params] if effect == 'echo': delay = random.randint(50, 350) decay = random.randint(1, 7) * 0.1 return 'echo 1 1 {0} {1:.2}'.format(delay, decay) elif effect == 'chorus': opts = 'chorus 1 1 ' num_people = random.randint(1, 5) for i in range(num_people): delay = random.randint(21, 90) decay = random.randint(1, 7) * 0.1 speed = random.random() + 0.5 depth = random.random() + 1.5 opts += ' {0} {1:.2} {2:.2} {3:.2} -s' \ .format(delay, decay, speed, depth) return opts elif effect == 'flanger': delay = random.randint(0, 30) depth = random.randint(0, 10) regen = random.randint(-95, 95) width = random.randint(60, 100) speed = random.random() + 0.1 phase = random.randint(0, 100) return 'flanger {0} {1} {2} {3} {4:.2} sin {5} lin' \ .format(delay, depth, regen, width, speed, phase) elif effect == 'reverb': return 'reverb ' elif effect == 'tempo': amount = params[0] if len(params) > 0 else random.random() + 0.5 return 'tempo -s {0:.2}'.format(amount) elif effect == 'speed': amount = params[0] if len(params) > 0 else random.random() + 0.5 return 'speed {0:.2}'.format(amount) elif effect == 'pitch': amount = params[0] if len(params) > 0 else random.randint(-400, 400) return 'pitch {0}'.format(amount) elif effect == 'overdrive': amount = params[0] if len(params) > 0 else 20*abs(random.random()) return 'overdrive {0:.2}'.format(amount) return '' def sample_clip(self, required_duration): ''' Randomly sample a clip of `required_duration` seconds from self ''' self_duration = int(self.duration_seconds * MSEC) # in ms required_duration = int(required_duration * MSEC) # in ms assert self_duration >= 20 + required_duration, 'Cannot sample!' start_time = random.randint(10, self_duration-required_duration-10) clip = self[start_time:start_time+required_duration] clip.__class__ = AudioSegment return clip def add_noise(self, noise, snr_dB, final_duration=None, effect=None): ''' Adds the given noise signal such that the snr_dB is maintained ''' signal_duration = int(self.duration_seconds * MSEC) # in ms noise_duration = int(noise.duration_seconds * MSEC) # in ms assert noise_duration >= signal_duration, 'Noise smaller than signal' if effect: noise = noise.add_effect(effect) if final_duration: noise = noise.sample_clip(final_duration or self.duration_seconds) delta = self.power_dB - noise.power_dB - snr_dB noise_clip = noise + delta merged = noise_clip * self merged.__class__ = AudioSegment return merged def make_segments(self, prefix, duration=60, outdir=TMP_DIR): ''' Saves consecutive `duration` seconds long clips from self into outdir with names of form `prefix.{starting_second}.wav` ''' split_files = [] duration = int(duration * MSEC) for start_pos in range(0, len(self), duration): seg_x = self[start_pos:start_pos + duration] if seg_x.duration_seconds * MSEC >= duration: basename = '{0}.{1}.wav'.format(prefix, start_pos) fname = os.path.join(outdir, basename) seg_x.set_channels(1) seg_x.set_frame_rate(FRAME_RATE) seg_x.export(fname, format='wav') split_files.append((basename, duration)) return split_files class Youtube(object): ''' Pulls and converts audio from youtube ''' url_alpha = list(string.ascii_letters + string.digits) base_url = 'https://www.youtube.com/watch?v=%s' ydl_cmd = ['youtube-dl', '-x', '--cache-dir', TMP_DIR, '--output'] avconv_cmd = 'avconv -y -f {2} -i {0} -vn -b 64k -ar {3} -ac 1 -f flac {1}' ydl_filename_format = '%(id)s.%(ext)s' def __init__(self, yt_id, deloop=False): ''' Initializing this class downloads a youtube file in wav format into `ROOT_DIR` ''' self.yt_id = yt_id url = self.base_url % self.yt_id audio_fname = os.path.join(TMP_DIR, self.ydl_filename_format) ydl_params = self.ydl_cmd + [audio_fname, url] tmp_file = glob.glob(audio_fname % {'id': yt_id, 'ext' : '*'}) final_fname = os.path.join(ROOT_DIR, self.ydl_filename_format) sound_file = final_fname % {'id': yt_id, 'ext': 'wav'} if os.path.exists(sound_file): print sound_file, 'exists' return if len(tmp_file) == 0: status = subprocess.call(ydl_params, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=DEVNULL) if status != 0: print 'downloading ', yt_id, ' failed' return tmp_file = glob.glob(audio_fname % {'id': yt_id, 'ext' : '*'})[0] inpformat = tmp_file[tmp_file.rindex('.')+1:] if deloop: # The headers are wrong in long files, use flac # for all processing on large files sound_file = self._flac_encode(tmp_file) self.audio = self.get_loopless_segment(sound_file) else: self.audio = AudioSegment.from_file(tmp_file, format=inpformat) print 'saving to', sound_file self.audio.set_channels(1) self.audio.set_frame_rate(FRAME_RATE) # TODO Best if the bit rate could also be set to 64k, # usually gives about 2x savings in disk space consumed self.audio.export(sound_file, format='wav') def _random_yt_id(self): ''' Get a random youtube video id ''' return random.sample(self.url_alpha, 11) def _flac_encode(self, inpfile): ''' Youtube sounds are downloaded as m4a files. These cannot be loaded by scikit.audiolab. Wav files do not support files > 2G, so we temporarily convert to a flac format with smaller sample and bit rate ''' inpformat = inpfile[inpfile.rindex('.')+1:] flacfile = inpfile.replace(inpformat, 'flac') conv_cmd = self.avconv_cmd.format(inpfile, flacfile, inpformat, FRAME_RATE) subprocess.call(conv_cmd.split(' '), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=DEVNULL) os.remove(inpfile) return flacfile def get_loopless_segment(self, inpfile): inpformat = inpfile[inpfile.rindex('.')+1:] corrfname = inpfile.replace(inpformat, 'corr.npy') if not os.path.exists(corrfname): print corrfname, 'not found' source = ab.Sndfile(inpfile, 'r') source_data = source.read_frames(source.nframes) num_frames = source_data.shape[0] clip_size = int(0.1 * FRAME_RATE) max_start_pos = FRAME_RATE * 10 start_pos = random.randint(0, num_frames-clip_size-10) start_pos = min(max_start_pos, start_pos) clip_data = source_data[start_pos:start_pos+clip_size] corr = norm_correlation(clip_data, source_data) # Why are there duplicates! with open(corrfname, 'w') as save_file: np.save(save_file, corr) else: corr = np.load(corrfname) reps = np.sort(np.unique(np.where(corr > 0.98)[0])) gaps = np.array([]) if reps.shape[0] > 2: gaps = reps[1:] - reps[:-1] gaps = gaps[np.unique(np.where(gaps > 10.)[0])] audio = AudioSegment.from_file(inpfile, inpformat) os.remove(inpfile) file_duration = audio.duration_seconds / 60. if gaps.shape[0] > 0: loop_duration = stats.mode(gaps)[0][0]/FRAME_RATE audio = audio[0:loop_duration * MSEC] print '{0} {1:.2f} {2:.2f}'.format(inpfile, file_duration, audio.duration_seconds / 60.) return audio def norm_correlation(t, s): ''' Fast normalized correlation function for matching template `t` against the source `s` Refer http://stackoverflow.com/questions/23705107 ''' import pandas as pd n = len(t) nt = (t-np.mean(t))/(np.std(t)*n) sum_nt = nt.sum() a = pd.rolling_mean(s, n)[n-1:-1] b = pd.rolling_std(s, n)[n-1:-1] b *= np.sqrt((n-1.0) / n) c = np.convolve(nt[::-1], s, mode="valid")[:-1] result = (c - sum_nt * a) / b return result def get_pcm_audio(pcmdata, nchannel=1, samplerate=8000, nbit=16): ''' Converts pcm data to an AudioSegment ''' wavbuffer = StringIO() wavfile = wave.open(wavbuffer, 'wb') wavfile.setparams((nchannel, nbit/8, samplerate, 0, 'NONE', 'NONE')) wavfile.writeframes(pcmdata) wavfile.close() wavbuffer.seek(0) return AudioSegment.from_wav(wavbuffer) current_seq_filename = "" #Need filename to know when to clear cache def getline(seq_filename, line_num): '''Gets line of text. Clears linecache if file changes''' global current_seq_filename if seq_filename != current_seq_filename: linecache.clearcache() current_seq_filename = seq_filename return linecache.getline(seq_filename, line_num) def get_raw_audio(fname): ''' Loads audio segment from file. Load method depends on file extension ''' audio_fmt = fname[1+fname.rindex('.'):] if audio_fmt == 'pcm': with open(fname, 'rb') as pcmfile: pcmdata = pcmfile.read() audio = get_pcm_audio(pcmdata) elif re.match("""seq_\d+""", audio_fmt): pos = fname.rindex('_') seq_filename, line_num = fname[:pos], int(fname[1+pos:]) data_line = getline(seq_filename, line_num) audio_data = json.loads(data_line)["audio_data"].decode('base64') try: # Assume this is a wav file audio = AudioSegment(data=audio_data) except Exception as e: # if not, its pcm. We only have these two. audio = get_pcm_audio(audio_data) else: audio = AudioSegment.from_file(fname, format=audio_fmt) return audio def get_wav_duration(wavfile): return AudioSegment.from_wav(wavfile).duration_seconds def download_sounds(ytid): try: ytid = ytid.strip() if ytid: Youtube(ytid) except Exception as error: print ytid, error # if __name__ == '__main__': # with open('ytids', 'r') as yt: # ids = yt.readlines() # parmap(download_sounds, ids)<file_sep>from __future__ import print_function import os import struct import random import math import numpy import theano.tensor as T from opendeep.data import Dataset, TRAIN, VALID, TEST from opendeep.log import config_root_logger from opendeep.models.single_layer.lstm import LSTM from opendeep.optimization import RMSProp from opendeep.monitor import Monitor, Plot from opendeep import dataset_shared basedir = 'data/ecg/apnea-ecg' label_ext = ".apn" data_ext = ".dat" extra_ext = ".qrs" def find_train_files(directory, find_ext): for root, dirs, files in os.walk(directory): for basename in files: name, ext = os.path.splitext(basename) if ext == find_ext and name.split(os.sep)[-1][0] in ['a', 'b', 'c'] and len(name.split(os.sep)[-1]) == 3: filename = os.path.join(root, basename) yield filename class ECG(Dataset): def __init__(self, source_dir, train_split=0.8, valid_split=0.15): self.train = None, None self.train_shape = None self.valid = None, None self.valid_shape = None self.test = None, None self.test_shape = None def getSubset(self, subset): if subset is TRAIN: return self.train elif subset is VALID: return self.valid elif subset is TEST: return self.test else: return None, None def getDataShape(self, subset): if subset is TRAIN: return self.train_shape elif subset is VALID: return self.valid_shape elif subset is TEST: return self.test_shape else: return None def main(): pass if __name__ == '__main__': # http://www.physionet.org/physiobank/database/apnea-ecg/ # if we want logging config_root_logger() i=0 for f in find_train_files(basedir, label_ext): if i==0: data = numpy.fromfile(f, dtype=numpy.bool) print(data.shape) else: pass i+=1 i=0 for f in find_train_files(basedir, data_ext): if i == 0: data = numpy.fromfile(f, dtype=numpy.float16) print(data.shape) else: pass i += 1 i = 0 for f in find_train_files(basedir, extra_ext): if i == 0: data = numpy.fromfile(f, dtype=numpy.bool) print(data.shape) else: pass i += 1<file_sep>import os import numpy from feature_helpers import compute_specgram audio_ext = ['.wav'] basedir = 'data/sounds/' def main(steps, windows, max_freqs): # create the datasets! # go through everything in the data/sounds directory for f in find_audio_files(basedir): name, ext = os.path.splitext(f) for max_freq in max_freqs: for window in windows: for step in steps: processed_name = name + '_processed_%d_%d_%d.npy'%(step, window, max_freq) # if the current processed version doesn't exist if not os.path.exists(processed_name): # process the file! processed, _freqs = compute_specgram(audio_file=f, step=step, window=window, max_freq=max_freq) if processed is not None: print f, '--->', processed_name processed = processed.transpose() print processed.shape numpy.save(processed_name, processed) def find_audio_files(directory): for root, dirs, files in os.walk(directory): for basename in files: _, ext = os.path.splitext(basename) if ext in audio_ext: filename = os.path.join(root, basename) yield filename if __name__ == '__main__': freqs = [2000, 4000, 8000] windows = [10, 20] steps = [10] main(steps, windows, freqs)<file_sep>from __future__ import print_function import os import random import math import numpy import theano.tensor as T from opendeep.data import Dataset, TRAIN, VALID, TEST from opendeep.log import config_root_logger from opendeep.models import Prototype, SoftmaxLayer from opendeep.models.single_layer.lstm import LSTM from opendeep.optimization import RMSProp from opendeep.monitor import Monitor, Plot from opendeep.utils.misc import numpy_one_hot from opendeep import dataset_shared basedir = 'data/sounds/' sizes = {'10_10_2000': 11, '10_20_2000': 21, '10_10_4000': 21, '10_20_4000': 41, '10_10_8000': 41, '10_20_8000': 81} classes = ['normal', 'murmer', 'extrahls', 'artifact', 'extrastole'] def find_processed_files(directory, size_key): for root, dirs, files in os.walk(directory): for basename in files: name, ext = os.path.splitext(basename) if ext == ".npy" and "processed_%s" % size_key in name: filename = os.path.join(root, basename) yield filename def get_label(filename): for i, c in enumerate(classes): if c in filename: return i return None class HeartSound(Dataset): def __init__(self, source_dir, size_key, one_hot=False, train_split=0.9, valid_split=0.1): print("Getting dataset %s" % size_key) # grab the datasets from the preprocessed files datasets = [(numpy.load(f), get_label(f)) for f in find_processed_files(source_dir, size_key)] # make sure they are all the correct dimensionality datasets = [(data.shape, data, label) for data, label in datasets if data.shape[1] == sizes[size_key] and label is not None] print("Found %d examples" % len(datasets)) # shuffle! random.seed(1) random.shuffle(datasets) # shapes shapes = [shape for shape, _, _ in datasets] # data dataset = [data for _, data, _ in datasets] # labels labels = numpy.asarray([label for _, _, label in datasets], dtype='int8') # make the labels into one-hot vectors if one_hot: labels = numpy_one_hot(labels, n_classes=5) train_len = int(math.floor(train_split * len(dataset))) valid_len = int(math.floor(valid_split * len(dataset))) valid_stop = train_len + valid_len print("# train: %d examples" % train_len) train_datasets = dataset[:train_len] train_labels = labels[:train_len] if valid_len > 0: valid_datasets = dataset[train_len:valid_stop] valid_labels = labels[train_len:valid_stop] else: valid_datasets = [] if train_len + valid_len < len(dataset): test_datasets = dataset[valid_stop:] test_labels = labels[valid_stop:] else: test_datasets = [] # median_train_len = int(numpy.median(numpy.asarray(shapes[:train_len]), axis=0)[0]) min_train_len = int(numpy.min(numpy.asarray(shapes[:train_len]), axis=0)[0]) max_train_len = int(numpy.max(numpy.asarray(shapes[:train_len]), axis=0)[0]) # train = numpy.array([data[:min_train_len] for data in train_datasets], dtype='float32') train = numpy.array( [numpy.pad(data, [(0, max_train_len-data.shape[0]), (0, 0)], mode='constant') for data in train_datasets], dtype='float32' ) self.train_shape = train.shape self.train = (dataset_shared(train, borrow=True), dataset_shared(train_labels, borrow=True)) if len(valid_datasets) > 0: min_valid_len = int(numpy.min(numpy.asarray(shapes[train_len:valid_stop]), axis=0)[0]) max_valid_len = int(numpy.max(numpy.asarray(shapes[train_len:valid_stop]), axis=0)[0]) # valid = numpy.array([data[:min_valid_len] for data in valid_datasets], dtype='float32') valid = numpy.array( [numpy.pad(data, [(0, max_valid_len-data.shape[0]), (0, 0)], mode='constant') for data in valid_datasets], dtype='float32' ) self.valid_shape = valid.shape self.valid = (dataset_shared(valid, borrow=True), dataset_shared(valid_labels, borrow=True)) else: self.valid = None, None self.valid_shape = None if len(test_datasets) > 0: min_test_len = int(numpy.min(numpy.asarray(shapes[valid_stop:]), axis=0)[0]) max_test_len = int(numpy.max(numpy.asarray(shapes[valid_stop:]), axis=0)[0]) # valid = numpy.array([data[:min_test_len] for data in test_datasets], dtype='float32') test = numpy.array( [numpy.pad(data, [(0, max_test_len - data.shape[0]), (0, 0)], mode='constant') for data in test_datasets], dtype='float32' ) self.test_shape = test.shape self.test = (dataset_shared(test, borrow=True), dataset_shared(test_labels, borrow=True)) else: self.test = None, None self.test_shape = None print("Train shape: %s" % str(self.train_shape)) print("Valid shape: %s" % str(self.valid_shape)) print("Test shape: %s" % str(self.test_shape)) print("Dataset %s initialized!" % size_key) def getSubset(self, subset): if subset is TRAIN: return self.train elif subset is VALID: return self.valid elif subset is TEST: return self.test else: return None, None def getDataShape(self, subset): if subset is TRAIN: return self.train_shape elif subset is VALID: return self.valid_shape elif subset is TEST: return self.test_shape else: return None def main(size_key): out_vector = True # grab the data for this step size, window, and max frequency heartbeats = HeartSound(basedir, size_key, one_hot=out_vector) # define our model! we are using lstm with mean-pooling and softmax as classification hidden_size = int(max(math.floor(sizes[size_key]*.4), 1)) n_classes = 5 lstm_layer = LSTM(input_size=sizes[size_key], hidden_size=hidden_size, output_size=1, # don't care about output size hidden_activation='tanh', inner_hidden_activation='sigmoid', weights_init='uniform', weights_interval='montreal', r_weights_init='orthogonal', clip_recurrent_grads=5., noise='dropout', noise_level=0.6, direction='bidirectional') # mean of the hiddens across timesteps (reduces ndim by 1) mean_pooling = T.mean(lstm_layer.get_hiddens(), axis=0) # last hiddens as an alternative to mean pooling over time last_hiddens = lstm_layer.get_hiddens()[-1] # now the classification layer softmax_layer = SoftmaxLayer(inputs_hook=(hidden_size, mean_pooling), output_size=n_classes, out_as_probs=out_vector) # make it into a prototype! model = Prototype(layers=[lstm_layer, softmax_layer], outdir='outputs/prototype%s' % size_key) # optimizer optimizer = RMSProp(dataset=heartbeats, model=model, n_epoch=500, batch_size=10, save_frequency=10, learning_rate=1e-4, #1e-6 grad_clip=None, hard_clip=False ) # monitors errors = Monitor(name='error', expression=model.get_monitors()['softmax_error'], train=True, valid=True, test=True) # plot the monitor plot = Plot('heartbeat %s' % size_key, monitor_channels=[errors], open_browser=True) optimizer.train(plot=plot) if __name__ == '__main__': # http://www.peterjbentley.com/heartchallenge/ # if we want logging config_root_logger() for step in [10]: for freq in [8000]: for window in [20, 10]: size_key = "%d_%d_%d" % (step, window, freq) main(size_key)
e1225a89d606602aa7e9cb6dfc1bd0d139e62e1c
[ "Python" ]
5
Python
mbeissinger/eko
2d40bd983d61a968a9024430ec0197c352f56859
733474c3b986bd255b7c65b15ff7a469ac23075f
refs/heads/master
<repo_name>Tyzanol/cloud-mta-build-tool<file_sep>/internal/artifacts/project_test.go package artifacts import ( "io/ioutil" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "gopkg.in/yaml.v2" "github.com/SAP/cloud-mta-build-tool/internal/commands" "github.com/SAP/cloud-mta/mta" ) var _ = Describe("Project", func() { var _ = Describe("runBuilder", func() { It("Sanity", func() { buildersCfg := commands.BuilderTypeConfig commands.BuilderTypeConfig = []byte(` builders: - name: testbuilder info: "installing module dependencies & remove dev dependencies" path: "path to config file which override the following default commands" type: - command: go version `) Ω(execBuilder("testbuilder")).Should(Succeed()) commands.BuilderTypeConfig = buildersCfg }) It("Fails on command execution", func() { buildersCfg := commands.BuilderTypeConfig commands.BuilderTypeConfig = []byte(` builders: - name: testbuilder info: "installing module dependencies & remove dev dependencies" path: "path to config file which override the following default commands" type: - command: go test unknown_test.go `) Ω(execBuilder("testbuilder")).Should(HaveOccurred()) commands.BuilderTypeConfig = buildersCfg }) Context("pre & post builder commands", func() { oMta := &mta.MTA{} BeforeEach(func() { mtaFile, _ := ioutil.ReadFile("./testdata/mta/mta.yaml") yaml.Unmarshal(mtaFile, oMta) }) It("before-all builder", func() { v := beforeExec(oMta) Ω(v).Should(Equal("mybuilder")) }) It("after-all builder", func() { v := afterExec(oMta) Ω(v).Should(Equal("otherbuilder")) }) }) }) }) <file_sep>/internal/artifacts/project.go package artifacts import ( "fmt" "github.com/SAP/cloud-mta/mta" "github.com/pkg/errors" "github.com/SAP/cloud-mta-build-tool/internal/archive" "github.com/SAP/cloud-mta-build-tool/internal/commands" "github.com/SAP/cloud-mta-build-tool/internal/exec" ) // ExecuteProjectBuild - execute pre or post phase of project build func ExecuteProjectBuild(source, descriptor, phase string, getWd func() (string, error)) error { if phase != "pre" && phase != "post" { return fmt.Errorf("the %s phase of mta project build is invalid; supported phases: pre, post", phase) } loc, err := dir.Location(source, "", descriptor, getWd) if err != nil { return err } oMta, err := loc.ParseFile() if err != nil { return err } if phase == "pre" && oMta.BuildParams != nil { return execBuilder(beforeExec(oMta)) } if phase == "post" && oMta.BuildParams != nil { return execBuilder(afterExec(oMta)) } return nil } // get build params for before-all section func beforeExec(m *mta.MTA) string { if m.BuildParams.BeforeAll != nil { beforeBuilder, ok := m.BuildParams.BeforeAll["builder"] if ok { return beforeBuilder.(string) } } return "" } // get build params for after-all section func afterExec(m *mta.MTA) string { if m.BuildParams.AfterAll != nil { afterBuilder, ok := m.BuildParams.AfterAll["builder"] if ok { return afterBuilder.(string) } } return "" } func execBuilder(builder string) error { if builder == "" { return nil } dummyModule := mta.Module{ BuildParams: map[string]interface{}{ "builder": builder, }, } builderCommands, err := commands.CommandProvider(dummyModule) if err != nil { return errors.Wrap(err, "failed to parse the builder types configuration") } cmds := commands.CmdConverter(".", builderCommands.Command) // Execute commands err = exec.Execute(cmds) if err != nil { return errors.Wrapf(err, `the "%v" builder failed when executing commands`, builder) } return err }
4759fbf8374dc9f9c8cf64bf7a2663fe7afc639b
[ "Go" ]
2
Go
Tyzanol/cloud-mta-build-tool
6763e88ee92fff76905e992e1812ebc9431751d2
3efb7cae0c86382021c99461f80d9c8afa358013
refs/heads/master
<file_sep>const crypto = require('crypto'); const API_SECRET = '82f192d903f363f22a031dfdbbeaf851'; const api_key = '<KEY>'; const generateMessage = (url, params) => { let message = url + '?'; Object.keys(params).sort().forEach((key) => { message = `${message}${key}=${params[key]}&`; }); return message.substring(0, message.length - 1); } const generateSignedUrl = (url, params) => { const message = generateMessage(url, params); const signature = crypto.createHmac('SHA256', API_SECRET).update(message).digest('hex'); return `${message}&signData=${signature}` } module.exports = { generateMessage: generateMessage, generateSignedUrl: generateSignedUrl }<file_sep>#!/bin/bash grunt compile && node --inspect tribeca/service/main.js<file_sep>/// <reference path="../utils.ts" /> /// <reference path="../../common/models.ts" /> /// <reference path="nullgw.ts" /> ///<reference path="../interfaces.ts"/> import ws = require('ws'); import Q = require("q"); import colors = require('colors'); import crypto = require("crypto"); import request = require("request"); import url = require("url"); import querystring = require("querystring"); import Config = require("../config"); import NullGateway = require("./nullgw"); import Models = require("../../common/models"); import Utils = require("../utils"); import util = require("util"); import Interfaces = require("../interfaces"); import moment = require("moment"); import _ = require("lodash"); import log from "../logging"; var shortId = require("shortid"); var API_KEY = ''; var API_SECRET = ''; var generateMessage = (url, params) => { let message = url + '?'; var keys = Object.keys(params).sort() for (var i = 0; i < keys.length; i++) { var key = keys[i]; message = message + key + '=' + params[key] + '&'; } return message.substring(0, message.length - 1); } var generateSign = (url, params) => { var message = generateMessage(url, params); return crypto.createHmac('SHA256', API_SECRET).update(message).digest('hex').toLowerCase(); } var generateSignedUrl = (url, params) => { var message = generateMessage(url, params); var signature = generateSign(url, params); return message + '&signData=' + signature; } var bitforexPlaceOrder = (order) => { var PLACE_ORDER_URL = '/api/v1/trade/placeOrder'; var params = Object.assign({}, order); params.accessKey = API_KEY; params.nonce = new Date().getTime(); params.signData = generateSign(PLACE_ORDER_URL, params); return { actionUrl: PLACE_ORDER_URL, msg: params }; } var bitforexCancelOrder = (order) => { var PLACE_ORDER_URL = '/api/v1/trade/cancelOrder'; var params = Object.assign({}, order); params.accessKey = API_KEY; params.nonce = new Date().getTime(); params.signData = generateSign(PLACE_ORDER_URL, params); return { actionUrl: PLACE_ORDER_URL, msg: params }; } var bitforexGetAllAssets = () => { var PLACE_ORDER_URL = '/api/v1/fund/allAccount'; var params:any = {}; params.accessKey = API_KEY; params.nonce = new Date().getTime(); params.signData = generateSign(PLACE_ORDER_URL, params); return { actionUrl: PLACE_ORDER_URL, msg: params }; } interface BitforexMessageIncomingMessage { param : any; success?: boolean; data : any; event? : string; } interface BitforexDepthObject { price : number; amount : number; } interface BitforexDepthMessage { asks : Array<BitforexDepthObject>; bids : Array<BitforexDepthObject>; } interface OrderAck { result: string; // "true" or "false" order_id: number; } interface SignedMessage { signData?: string; } interface Order extends SignedMessage { symbol: string; tradeType: number; price: number; amount: number; } interface Cancel extends SignedMessage { orderId: string; symbol: string; } /* DIRECTION 1: BUY 2: SELL */ interface BitforexTradeRecord { amount: number; direction: number; price: number; tid: string; time: number; } interface SubscriptionRequest extends SignedMessage { } // CHANNEL is bitforex websocket event //Inigo V1 class BitforexWebsocket { send = <T>(msg: any, cb?: () => void) => { this._ws.send(JSON.stringify(msg), (e: Error) => { if (!e && cb) cb(); }); } setHandler = <T>(channel : string, handler: (newMsg : Models.Timestamped<T>) => void) => { if (!this._handlers[channel]) { this._handlers[channel] = [handler]; } else { this._handlers[channel].push(handler); } } private onMessage = (raw : string) => { var t = Utils.date(); try { if (raw.indexOf('pong_p') !== -1) { return; } var msg : BitforexMessageIncomingMessage = JSON.parse(raw); if (msg.event !== 'depth10' && msg.event !== 'trade') { return; } if (typeof msg.success !== "undefined") { if (msg.success !== true) this._log.warn("Unsuccessful message", msg); else this._log.info("Successfully connected to %s", msg.event); } var handlers = this._handlers[msg.event]; if (typeof handlers === "undefined") { this._log.warn("Got message on unknown topic", msg); return; } _(handlers).forEach((handler) => { handler(new Models.Timestamped(msg.data, t)); }); } catch (e) { this._log.error(e, "Error parsing msg %o", raw); throw e; } }; ConnectChanged = new Utils.Evt<Models.ConnectivityStatus>(); private _serializedHeartbeat = 'ping_p'; private _log = log("tribeca:gateway:BitforexWebsocket"); private _handlers : { [channel : string] : [(newMsg : Models.Timestamped<any>) => void]} = {}; private _ws : ws; public pingInterval: any; constructor(config : Config.IConfigProvider) { this._ws = new ws(config.GetString("BitforexWsUrl")); this._ws.on("open", () => { this.pingInterval = setInterval(() => { this._ws.send(this._serializedHeartbeat); }, 10000); this.ConnectChanged.trigger(Models.ConnectivityStatus.Connected) }); this._ws.on("message", this.onMessage); this._ws.on("close", () => this.ConnectChanged.trigger(Models.ConnectivityStatus.Disconnected)); } } // Inigo V1 class BitforexMarketDataGateway implements Interfaces.IMarketDataGateway { ConnectChanged = new Utils.Evt<Models.ConnectivityStatus>(); MarketTrade = new Utils.Evt<Models.GatewayMarketTrade>(); private onTrade = (trades : Models.Timestamped<Array<BitforexTradeRecord>>) => { // [tid, price, amount, time, type] _.forEach(trades.data, (trade : BitforexTradeRecord) => { var px = trade.price; var amt = trade.amount; var side = trade.direction === 2 ? Models.Side.Ask : Models.Side.Bid; var mt = new Models.GatewayMarketTrade(px, amt, trades.time, trades.data.length > 0, side); this.MarketTrade.trigger(mt); }); }; MarketData = new Utils.Evt<Models.Market>(); private static GetLevel = (n: BitforexDepthObject) : Models.MarketSide => new Models.MarketSide(n.price, n.amount); private readonly Depth: number = 25; private onDepth = (depth : Models.Timestamped<BitforexDepthMessage>) => { var msg = depth.data; var bids = _(msg.bids).take(this.Depth).map(BitforexMarketDataGateway.GetLevel).value(); var asks = _(msg.asks).reverse().take(this.Depth).map(BitforexMarketDataGateway.GetLevel).value() var mkt = new Models.Market(bids, asks, depth.time); this.MarketData.trigger(mkt); }; private _log = log("tribeca:gateway:BitofrexMD"); constructor(socket : BitforexWebsocket, symbolProvider: BitforexSymbolProvider) { console.log(colors.green('BITFOREX START DATA GATEWAY')); var depthChannel = "depth10"; var tradesChannel = "trade"; socket.setHandler(depthChannel, this.onDepth); socket.setHandler(tradesChannel, this.onTrade); socket.ConnectChanged.on(cs => { this.ConnectChanged.trigger(cs); // if (cs == Models.ConnectivityStatus.Connected) { // socket.send(depthChannel, {}); // socket.send(tradesChannel, {}); // } }); } } // Inigo V1 class BitforexOrderEntryGateway implements Interfaces.IOrderEntryGateway { OrderUpdate = new Utils.Evt<Models.OrderStatusUpdate>(); ConnectChanged = new Utils.Evt<Models.ConnectivityStatus>(); generateClientOrderId = () => shortId.generate(); supportsCancelAllOpenOrders = () : boolean => { return false; }; cancelAllOpenOrders = () : Q.Promise<number> => { return Q(0); }; public cancelsByClientOrderId = false; private static GetOrderType(side: Models.Side, type: Models.OrderType) : number { if (side === Models.Side.Bid) { return 1; } if (side === Models.Side.Ask) { return 2; } throw new Error("unable to convert " + Models.Side[side] + " and " + Models.OrderType[type]); } sendOrder = (order : Models.OrderStatusReport) => { var o : Order = { symbol: this._symbolProvider.coinSymbol, tradeType: BitforexOrderEntryGateway.GetOrderType(order.side, order.type), price: order.price, amount: order.quantity }; var requestData = bitforexPlaceOrder(o); this._http.post(requestData.actionUrl, requestData.msg).then((data) => { this.onOrderAck(data); this.OrderUpdate.trigger({ orderId: order.orderId, computationalLatency: Utils.fastDiff(Utils.date(), order.time) }); }).done(); // this._socket.send<OrderAck>("ok_spotusd_trade", this._signer.signMessage(o), () => { // this.OrderUpdate.trigger({ // orderId: order.orderId, // computationalLatency: Utils.fastDiff(Utils.date(), order.time) // }); // }); }; private onOrderAck = (ts: Models.Timestamped<any>) => { var orderId:string = ts.data.data.orderId.toString(); var osr : Models.OrderStatusUpdate = { orderId: orderId, time: ts.time }; if (ts.data.success === true) { osr.exchangeId = orderId; osr.orderStatus = Models.OrderStatus.Working; } else { osr.orderStatus = Models.OrderStatus.Rejected; } this.OrderUpdate.trigger(osr); }; cancelOrder = (cancel : Models.OrderStatusReport) => { var c : Cancel = {orderId: cancel.exchangeId, symbol: this._symbolProvider.coinSymbol }; const requestData = bitforexCancelOrder(c); this._http.post(requestData.actionUrl, requestData.msg).then((data) => { this.onCancel(data, cancel.exchangeId.toString()); this.OrderUpdate.trigger({ orderId: cancel.orderId, computationalLatency: Utils.fastDiff(Utils.date(), cancel.time) }); }).done(); // this._socket.send<OrderAck>("ok_spotusd_cancel_order", this._signer.signMessage(c), () => { // this.OrderUpdate.trigger({ // orderId: cancel.orderId, // computationalLatency: Utils.fastDiff(Utils.date(), cancel.time) // }); // }); }; private onCancel = (ts: Models.Timestamped<any>, orderId: string) => { var osr : Models.OrderStatusUpdate = { exchangeId: orderId, time: ts.time }; if (ts.data.success === true) { osr.orderStatus = Models.OrderStatus.Cancelled; } else { osr.orderStatus = Models.OrderStatus.Rejected; osr.cancelRejected = true; } this.OrderUpdate.trigger(osr); }; replaceOrder = (replace : Models.OrderStatusReport) => { this.cancelOrder(replace); this.sendOrder(replace); }; private static getStatus(status: number) : Models.OrderStatus { // status: -1: cancelled, 0: pending, 1: partially filled, 2: fully filled, 4: cancel request in process switch (status) { case -1: return Models.OrderStatus.Cancelled; case 0: return Models.OrderStatus.Working; case 1: return Models.OrderStatus.Working; case 2: return Models.OrderStatus.Complete; case 4: return Models.OrderStatus.Working; default: return Models.OrderStatus.Other; } } private onTrade = (tsMsg : Models.Timestamped<Array<BitforexTradeRecord>>) => { var t = tsMsg.time; var trades = tsMsg.data; for (var i = 0; i < trades.length; i++) { var msg : BitforexTradeRecord = trades[i]; // var avgPx = parseFloat(msg.averagePrice); // var lastQty = parseFloat(msg.sigTradeAmount); // var lastPx = parseFloat(msg.sigTradePrice); var status : Models.OrderStatusUpdate = { exchangeId: msg.tid, orderStatus: BitforexOrderEntryGateway.getStatus(2), time: t, quantity: msg.amount, price: msg.price, // lastQuantity: lastQty > 0 ? lastQty : undefined, // lastPrice: lastPx > 0 ? lastPx : undefined, // averagePrice: avgPx > 0 ? avgPx : undefined, // pendingCancel: msg.status === 4, // partiallyFilled: msg.status === 1 }; this.OrderUpdate.trigger(status); } }; private _log = log("tribeca:gateway:BitforexOE"); constructor( private _socket : BitforexWebsocket, private _http : BitforexHttp, private _signer: BitforexMessageSigner, private _symbolProvider: BitforexSymbolProvider) { // _socket.setHandler("ok_usd_realtrades", this.onTrade); // _socket.setHandler("ok_spotusd_trade", this.onOrderAck); // _socket.setHandler("ok_spotusd_cancel_order", this.onCancel); _socket.setHandler("trade", this.onTrade); _socket.ConnectChanged.on(cs => { this.ConnectChanged.trigger(cs); if (cs === Models.ConnectivityStatus.Connected) { _socket.send([ { type: 'subHq', event: 'depth10', param: { businessType: _symbolProvider.coinSymbol, dType: 0, size: 100, } }, { type: 'subHq', event: 'trade', param: { businessType: _symbolProvider.coinSymbol, size: 100, } } ]); } }); } } // Inigo v1 class BitforexMessageSigner { public signMessage = (url: string, m : SignedMessage) : SignedMessage => { m.signData = generateSign(url, m); return m; }; constructor(config : Config.IConfigProvider) { } } class BitforexHttp { post = <T>(actionUrl: string, msg : SignedMessage) : Q.Promise<Models.Timestamped<T>> => { var d = Q.defer<Models.Timestamped<T>>(); request({ url: url.resolve(this._baseUrl, actionUrl), body: querystring.stringify(this._signer.signMessage(actionUrl, msg)), headers: {"Content-Type": "application/x-www-form-urlencoded"}, method: "POST" }, (err, resp, body) => { if (err) d.reject(err); else { try { var t = Utils.date(); var data = JSON.parse(body); d.resolve(new Models.Timestamped(data, t)); } catch (e) { this._log.error(err, "url: %s, err: %o, body: %o", actionUrl, err, body); d.reject(e); } } }); return d.promise; }; private _log = log("tribeca:gateway:BitforexHTTP"); private _baseUrl : string; constructor(config : Config.IConfigProvider, private _signer: BitforexMessageSigner) { this._baseUrl = config.GetString("BitforexHttpUrl") } } // Inigo V1 class BitforexPositionGateway implements Interfaces.IPositionGateway { PositionUpdate = new Utils.Evt<Models.CurrencyPosition>(); private static convertCurrency(name : string) : Models.Currency { switch (name.toLowerCase()) { case "usd": return Models.Currency.USD; case "gbt": return Models.Currency.GBT; case "btc": return Models.Currency.BTC; default: throw new Error("Unsupported currency " + name); } } private trigger = () => { const requestData = bitforexGetAllAssets(); this._http.post<Array<any>>(requestData.actionUrl, requestData.msg).then(msg => { var currencies = msg.data || []; for (var i = 0; i < currencies.length; i++) { try { var currency = currencies[i]; var currencyName = currency.currency; var currencyModel = BitforexPositionGateway.convertCurrency(currencyName); var amount = currency.active; var held = currency.frozen; var pos = new Models.CurrencyPosition(amount, held, currencyModel); this.PositionUpdate.trigger(pos); } catch (e) { console.log(e); } } }).done(); }; private _log = log("tribeca:gateway:BitofrexPG"); constructor(private _http : BitforexHttp) { console.log(colors.green('BITFOREX START POSITION GATEWAY')); setInterval(this.trigger, 15000); setTimeout(this.trigger, 10); } } class BitforexBaseGateway implements Interfaces.IExchangeDetailsGateway { public get hasSelfTradePrevention() { return false; } name() : string { return "Bitforex"; } makeFee() : number { return 0.001; } takeFee() : number { return 0.002; } exchange() : Models.Exchange { return Models.Exchange.Bitforex; } constructor(public minTickIncrement: number) { console.log(colors.green('BITFOREX START BASE GATEWAY')); } } // Inigo v1 class BitforexSymbolProvider { public symbol : string; public coinSymbol: string; public symbolWithoutUnderscore: string; constructor(pair: Models.CurrencyPair) { const GetCurrencySymbol = (s: Models.Currency) : string => Models.fromCurrency(s); this.symbol = GetCurrencySymbol(pair.base) + "_" + GetCurrencySymbol(pair.quote); this.coinSymbol = 'coin-' + GetCurrencySymbol(pair.quote).toLowerCase() + '-' + GetCurrencySymbol(pair.base).toLowerCase(); this.symbolWithoutUnderscore = GetCurrencySymbol(pair.base) + GetCurrencySymbol(pair.quote); } } class Bitforex extends Interfaces.CombinedGateway { constructor(config : Config.IConfigProvider, pair: Models.CurrencyPair) { console.log(colors.green('BITFOREX START SYMBOL')); var symbol = new BitforexSymbolProvider(pair); console.log(colors.green('BITFOREX START SIGNER')); var signer = new BitforexMessageSigner(config); console.log(colors.green('BITFOREX START HTTP')); var http = new BitforexHttp(config, signer); console.log(colors.green('BITFOREX START SOCKET')); var socket = new BitforexWebsocket(config); console.log(colors.green('BITFOREX START ORDER ENTRY GATEWAY')); var orderGateway = config.GetString("BitforexOrderDestination") == "Bitforex" ? <Interfaces.IOrderEntryGateway>new BitforexOrderEntryGateway(socket, http, signer, symbol) : new NullGateway.NullOrderGateway(); super( new BitforexMarketDataGateway(socket, symbol), orderGateway, new BitforexPositionGateway(http), new BitforexBaseGateway(.000000000001)); // uh... todo } } // Inigo v1 export async function createBitforex(config : Config.IConfigProvider, pair: Models.CurrencyPair) : Promise<Interfaces.CombinedGateway> { console.log(colors.green('BITFOREX START')); API_KEY = config.GetString("BitforexApiKey") API_SECRET = config.GetString("BitforexSecretKey") return new Bitforex(config, pair); }
2cf9938895a0831fbfa154d640ba70c8ab26779f
[ "JavaScript", "TypeScript", "Shell" ]
3
JavaScript
williamaurreav23/tribeca
5db37217e53b5c1bf48303c0f78f28f84b67b433
8480f0aab0e92e137e0bb8baf0998322e301dbc8
refs/heads/main
<file_sep>import { nextTick, unref, watch } from 'vue-demi' import { MotionInstance, MotionVariants } from '../types' export function registerLifeCycleHooks<T extends MotionVariants>({ target, variants, variant, }: MotionInstance<T>) { const _variants = unref(variants) const stop = watch( () => target, () => { // Lifecycle hooks bindings if (_variants && _variants.enter) { // Set initial before the element is mounted if (_variants.initial) variant.value = 'initial' // Set enter animation, once the element is mounted nextTick(() => (variant.value = 'enter')) } }, { immediate: true, flush: 'pre', }, ) return { stop } } <file_sep>/*! * @vueuse/motion v1.6.0 * (c) 2021 * @license MIT */ import * as vue_demi from 'vue-demi' import { CSSProperties, SVGAttributes, Ref, UnwrapRef, Directive, Plugin, } from 'vue-demi' import { VueInstance, MaybeRef, Fn } from '@vueuse/core' import * as csstype from 'csstype' import { MaybeRef as MaybeRef$1 } from '@vueuse/shared' declare type GenericHandler = (...args: any) => void /** * A generic subscription manager. */ declare class SubscriptionManager<Handler extends GenericHandler> { private subscriptions add(handler: Handler): () => undefined notify( /** * Using ...args would be preferable but it's array creation and this * might be fired every frame. */ a?: Parameters<Handler>[0], b?: Parameters<Handler>[1], c?: Parameters<Handler>[2], ): void clear(): void } /** * `MotionValue` is used to track the state and velocity of motion values. */ declare class MotionValue<V = any> { /** * The current state of the `MotionValue`. */ private current /** * The previous state of the `MotionValue`. */ private prev /** * Duration, in milliseconds, since last updating frame. */ private timeDelta /** * Timestamp of the last time this `MotionValue` was updated. */ private lastUpdated /** * Functions to notify when the `MotionValue` updates. */ updateSubscribers: SubscriptionManager<Subscriber<V>> /** * A reference to the currently-controlling Popmotion animation */ private stopAnimation? /** * Tracks whether this value can output a velocity. */ private canTrackVelocity /** * @param init - The initiating value * @param config - Optional configuration options */ constructor(init: V) /** * Adds a function that will be notified when the `MotionValue` is updated. * * It returns a function that, when called, will cancel the subscription. */ onChange(subscription: Subscriber<V>): () => void clearListeners(): void /** * Sets the state of the `MotionValue`. * * @param v * @param render */ set(v: V): void /** * Update and notify `MotionValue` subscribers. * * @param v * @param render */ updateAndNotify: (v: V) => void /** * Returns the latest state of `MotionValue` * * @returns - The latest state of `MotionValue` */ get(): V /** * Get previous value. * * @returns - The previous latest state of `MotionValue` */ getPrevious(): V /** * Returns the latest velocity of `MotionValue` * * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. */ getVelocity(): number /** * Schedule a velocity check for the next frame. */ private scheduleVelocityCheck /** * Updates `prev` with `current` if the value hasn't been updated this frame. * This ensures velocity calculations return `0`. */ private velocityCheck /** * Registers a new animation to control this `MotionValue`. Only one * animation can drive a `MotionValue` at one time. */ start(animation: StartAnimation): Promise<void> /** * Stop the currently active animation. */ stop(): void /** * Returns `true` if this value is currently animating. */ isAnimating(): boolean /** * Clear the current animation reference. */ private clearAnimation /** * Destroy and clean up subscribers to this `MotionValue`. */ destroy(): void } declare type ResolvedKeyframesTarget = | [null, ...number[]] | number[] | [null, ...string[]] | string[] declare type KeyframesTarget = | ResolvedKeyframesTarget | [null, ...CustomValueType[]] | CustomValueType[] declare type ResolvedSingleTarget = string | number declare type SingleTarget = ResolvedSingleTarget | CustomValueType declare type ResolvedValueTarget = | ResolvedSingleTarget | ResolvedKeyframesTarget declare type ValueTarget = SingleTarget | KeyframesTarget declare type Props = { [key: string]: any } declare type EasingFunction = (v: number) => number declare type Easing = | [number, number, number, number] | 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | 'circIn' | 'circOut' | 'circInOut' | 'backIn' | 'backOut' | 'backInOut' | 'anticipate' | EasingFunction interface Orchestration { /** * Delay the animation by this duration (in seconds). Defaults to `0`. */ delay?: number /** * Callback triggered on animation complete. */ onComplete?: () => void /** * Should the value be set imediately */ immediate?: boolean } interface Repeat { /** * The number of times to repeat the transition. Set to `Infinity` for perpetual repeating. * * Without setting `repeatType`, this will loop the animation. */ repeat?: number /** * How to repeat the animation. This can be either: * * "loop": Repeats the animation from the start * * "reverse": Alternates between forward and backwards playback * * "mirror": Switchs `from` and `to` alternately */ repeatType?: 'loop' | 'reverse' | 'mirror' /** * When repeating an animation, `repeatDelay` will set the * duration of the time to wait, in seconds, between each repetition. */ repeatDelay?: number } /** * An animation that animates between two or more values over a specific duration of time. * This is the default animation for non-physical values like `color` and `opacity`. */ interface Tween extends Repeat { /** * Set `type` to `"tween"` to use a duration-based tween animation. * If any non-orchestration `transition` values are set without a `type` property, * this is used as the default animation. */ type?: 'tween' /** * The duration of the tween animation. Set to `0.3` by default, 0r `0.8` if animating a series of keyframes. */ duration?: number /** * The easing function to use. Set as one of the below. * * - The name of an existing easing function. * - An array of four numbers to define a cubic bezier curve. * - An easing function, that accepts and returns a value `0-1`. * * If the animating value is set as an array of multiple values for a keyframes * animation, `ease` can be set as an array of easing functions to set different easings between * each of those values. */ ease?: Easing | Easing[] /** * The duration of time already elapsed in the animation. Set to `0` by * default. */ elapsed?: number /** * When animating keyframes, `times` can be used to determine where in the animation each keyframe is reached. * Each value in `times` is a value between `0` and `1`, representing `duration`. * * There must be the same number of `times` as there are keyframes. * Defaults to an array of evenly-spread durations. */ times?: number[] /** * When animating keyframes, `easings` can be used to define easing functions between each keyframe. This array should be one item fewer than the number of keyframes, as these easings apply to the transitions between the keyframes. */ easings?: Easing[] /** * The value to animate from. * By default, this is the current state of the animating value. */ from?: number | string to?: number | string | ValueTarget velocity?: number delay?: number } /** * An animation that simulates spring physics for realistic motion. * This is the default animation for physical values like `x`, `y`, `scale` and `rotate`. */ interface Spring extends Repeat { /** * Set `type` to `"spring"` to animate using spring physics for natural * movement. Type is set to `"spring"` by default. */ type: 'spring' /** * Stiffness of the spring. Higher values will create more sudden movement. * Set to `100` by default. */ stiffness?: number /** * Strength of opposing force. If set to 0, spring will oscillate * indefinitely. Set to `10` by default. */ damping?: number /** * Mass of the moving object. Higher values will result in more lethargic * movement. Set to `1` by default. */ mass?: number /** * The duration of the animation, defined in seconds. Spring animations can be a maximum of 10 seconds. * * If `bounce` is set, this defaults to `0.8`. * * Note: `duration` and `bounce` will be overridden if `stiffness`, `damping` or `mass` are set. */ duration?: number /** * `bounce` determines the "bounciness" of a spring animation. * * `0` is no bounce, and `1` is extremely bouncy. * * If `duration` is set, this defaults to `0.25`. * * Note: `bounce` and `duration` will be overridden if `stiffness`, `damping` or `mass` are set. */ bounce?: number /** * End animation if absolute speed (in units per second) drops below this * value and delta is smaller than `restDelta`. Set to `0.01` by default. */ restSpeed?: number /** * End animation if distance is below this value and speed is below * `restSpeed`. When animation ends, spring gets “snapped” to. Set to * `0.01` by default. */ restDelta?: number /** * The value to animate from. * By default, this is the initial state of the animating value. */ from?: number | string to?: number | string | ValueTarget /** * The initial velocity of the spring. By default this is the current velocity of the component. */ velocity?: number delay?: number } /** * An animation that decelerates a value based on its initial velocity, * usually used to implement inertial scrolling. * * Optionally, `min` and `max` boundaries can be defined, and inertia * will snap to these with a spring animation. * * This animation will automatically precalculate a target value, * which can be modified with the `modifyTarget` property. * * This allows you to add snap-to-grid or similar functionality. * * Inertia is also the animation used for `dragTransition`, and can be configured via that prop. */ interface Inertia { /** * Set `type` to animate using the inertia animation. Set to `"tween"` by * default. This can be used for natural deceleration, like momentum scrolling. */ type: 'inertia' /** * A function that receives the automatically-calculated target and returns a new one. Useful for snapping the target to a grid. */ modifyTarget?(v: number): number /** * If `min` or `max` is set, this affects the stiffness of the bounce * spring. Higher values will create more sudden movement. Set to `500` by * default. */ bounceStiffness?: number /** * If `min` or `max` is set, this affects the damping of the bounce spring. * If set to `0`, spring will oscillate indefinitely. Set to `10` by * default. */ bounceDamping?: number /** * A higher power value equals a further target. Set to `0.8` by default. */ power?: number /** * Adjusting the time constant will change the duration of the * deceleration, thereby affecting its feel. Set to `700` by default. */ timeConstant?: number /** * End the animation if the distance to the animation target is below this value, and the absolute speed is below `restSpeed`. * When the animation ends, the value gets snapped to the animation target. Set to `0.01` by default. * Generally the default values provide smooth animation endings, only in rare cases should you need to customize these. */ restDelta?: number /** * Minimum constraint. If set, the value will "bump" against this value (or immediately spring to it if the animation starts as less than this value). */ min?: number /** * Maximum constraint. If set, the value will "bump" against this value (or immediately snap to it, if the initial animation value exceeds this value). */ max?: number /** * The value to animate from. By default, this is the current state of the animating value. */ from?: number | string /** * The initial velocity of the animation. * By default this is the current velocity of the component. */ velocity?: number delay?: number } /** * Keyframes tweens between multiple `values`. * * These tweens can be arranged using the `duration`, `easings`, and `times` properties. */ interface Keyframes { /** * Set `type` to `"keyframes"` to animate using the keyframes animation. * Set to `"tween"` by default. This can be used to animate between a series of values. */ type: 'keyframes' /** * An array of values to animate between. */ values: KeyframesTarget /** * An array of numbers between 0 and 1, where `1` represents the `total` duration. * * Each value represents at which point during the animation each item in the animation target should be hit, so the array should be the same length as `values`. * * Defaults to an array of evenly-spread durations. */ times?: number[] /** * An array of easing functions for each generated tween, or a single easing function applied to all tweens. * * This array should be one item less than `values`, as these easings apply to the transitions *between* the `values`. */ ease?: Easing | Easing[] /** * Popmotion's easing prop to define individual easings. `ease` will be mapped to this prop in keyframes animations. */ easings?: Easing | Easing[] elapsed?: number /** * The total duration of the animation. Set to `0.3` by default. */ duration?: number repeatDelay?: number from?: number | string to?: number | string | ValueTarget velocity?: number delay?: number } declare type PopmotionTransitionProps = Tween | Spring | Keyframes | Inertia declare type PermissiveTransitionDefinition = { [key: string]: any } declare type TransitionDefinition = | Tween | Spring | Keyframes | Inertia | PermissiveTransitionDefinition declare type TransitionMap = Orchestration & { [key: string]: TransitionDefinition } /** * Transition props */ declare type Transition = | (Orchestration & Repeat & TransitionDefinition) | (Orchestration & Repeat & TransitionMap) declare type MakeCustomValueType<T> = { [K in keyof T]: T[K] | CustomValueType } declare type Target = MakeCustomValueType<MotionProperties> declare type MakeKeyframes<T> = { [K in keyof T]: T[K] | T[K][] | [null, ...T[K][]] } declare type TargetWithKeyframes = MakeKeyframes<Target> /** * An object that specifies values to animate to. Each value may be set either as * a single value, or an array of values. */ declare type TargetAndTransition = TargetWithKeyframes & { transition?: Transition transitionEnd?: Target } declare type TargetResolver = ( custom: any, current: Target, velocity: Target, ) => TargetAndTransition interface CustomValueType { mix: (from: any, to: any) => (p: number) => number | string toValue: () => number | string } declare type MotionValuesMap = { [key in keyof PermissiveMotionProperties]: MotionValue } interface MotionTransitions { /** * Stop ongoing transitions for the current element. */ stop: (keys?: string | string[]) => void /** * Start a transition, push it to the `transitions` array. * * @param transition * @param values */ push: ( key: string, value: ResolvedValueTarget, target: MotionProperties, transition: Transition, onComplete?: () => void, ) => void /** * @internal Local transitions reference */ motionValues: MotionValuesMap } /** * Permissive properties keys */ declare type PropertiesKeys = { [key: string]: string | number | undefined | any } /** * SVG Supported properties */ declare type SVGPathProperties = { pathLength?: number pathOffset?: number pathSpacing?: number } /** * Transform properties */ declare type TransformProperties = { x?: string | number y?: string | number z?: string | number translateX?: string | number translateY?: string | number translateZ?: string | number rotate?: string | number rotateX?: string | number rotateY?: string | number rotateZ?: string | number scale?: string | number scaleX?: string | number scaleY?: string | number scaleZ?: string | number skew?: string | number skewX?: string | number skewY?: string | number originX?: string | number originY?: string | number originZ?: string | number perspective?: string | number transformPerspective?: string | number } /** * Relevant styling properties */ declare type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> declare type StyleProperties = Omit< CSSProperties, | 'transition' | 'rotate' | 'scale' | 'perspective' | 'transform' | 'transformBox' | 'transformOrigin' | 'transformStyle' > /** * Available properties for useMotion variants */ declare type MotionProperties = | StyleProperties | SVGAttributes | TransformProperties | SVGPathProperties /** * Permissive properties for useSpring */ declare type PermissiveMotionProperties = MotionProperties & { [key: string]: ResolvedSingleTarget } /** * Variant */ declare type Variant = { transition?: Transition } & MotionProperties /** * Motion variants object */ declare type MotionVariants = { initial?: Variant enter?: Variant leave?: Variant visible?: Variant hovered?: Variant tapped?: Variant focused?: Variant [key: string]: Variant | undefined } declare type PermissiveTarget = VueInstance | MotionTarget declare type MotionTarget = HTMLElement | SVGElement | null | undefined interface MotionInstance<T = MotionVariants> extends MotionControls { target: MaybeRef<PermissiveTarget> variants: MaybeRef<T> variant: Ref<keyof T> state: Ref<Variant | undefined> motionProperties: UnwrapRef<MotionProperties> } declare type UseMotionOptions = { syncVariants?: boolean lifeCycleHooks?: boolean visibilityHooks?: boolean eventListeners?: boolean } declare type MotionControls = { /** * Apply a variant declaration and execute the resolved transitions. * * @param variant * @returns Promise<void[]> */ apply: (variant: Variant | string) => Promise<void[]> | undefined /** * Apply a variant declaration without transitions. * * @param variant */ set: (variant: Variant | string) => void /** * Stop all the ongoing transitions for the current element. */ stopTransitions: Fn /** * Helper to be passed to <transition> leave event. * * @param done */ leave: (done: () => void) => void } declare type SpringControls = { /** * Apply new values with transitions. * * @param variant */ set: (properties: MotionProperties) => void /** * Stop all transitions. * * @param variant */ stop: (key?: string | string[]) => void /** * Object containing all the current values of the spring. * * @param */ values: MotionProperties } declare type MotionInstanceBindings<T = MotionVariants> = { [key: string]: MotionInstance<T> } declare module '@vue/runtime-core' { interface ComponentCustomProperties { $motions?: MotionInstanceBindings } } declare module '@vue/runtime-dom' { interface HTMLAttributes { variants?: MotionVariants initial?: Variant enter?: Variant leave?: Variant visible?: Variant hovered?: Variant tapped?: Variant focused?: Variant } } interface MotionPluginOptions { directives?: { [key: string]: MotionVariants } excludePresets?: boolean } declare type StopAnimation = { stop: () => void } declare type Transformer<T> = (v: T) => T declare type Subscriber<T> = (v: T) => void declare type PassiveEffect<T> = (v: T, safeSetter: (v: T) => void) => void declare type StartAnimation = (complete?: () => void) => StopAnimation declare const directive: ( variants?: MotionVariants | undefined, ) => Directive<HTMLElement | SVGElement> declare const MotionPlugin: Plugin declare const fade: MotionVariants declare const fadeVisible: MotionVariants declare const pop: MotionVariants declare const popVisible: MotionVariants declare const rollLeft: MotionVariants declare const rollVisibleLeft: MotionVariants declare const rollRight: MotionVariants declare const rollVisibleRight: MotionVariants declare const rollTop: MotionVariants declare const rollVisibleTop: MotionVariants declare const rollBottom: MotionVariants declare const rollVisibleBottom: MotionVariants declare const slideLeft: MotionVariants declare const slideVisibleLeft: MotionVariants declare const slideRight: MotionVariants declare const slideVisibleRight: MotionVariants declare const slideTop: MotionVariants declare const slideVisibleTop: MotionVariants declare const slideBottom: MotionVariants declare const slideVisibleBottom: MotionVariants /** * Reactive style object implementing all native CSS properties. * * @param props */ declare function reactiveStyle(props?: StyleProperties): { state: { alignContent?: string | undefined alignItems?: string | undefined alignSelf?: string | undefined alignTracks?: string | undefined animationDelay?: string | undefined animationDirection?: string | undefined animationDuration?: string | undefined animationFillMode?: string | undefined animationIterationCount?: | csstype.AnimationIterationCountProperty | undefined animationName?: string | undefined animationPlayState?: string | undefined animationTimingFunction?: string | undefined appearance?: csstype.AppearanceProperty | undefined aspectRatio?: string | undefined backdropFilter?: string | undefined backfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined backgroundAttachment?: string | undefined backgroundBlendMode?: string | undefined backgroundClip?: string | undefined backgroundColor?: string | undefined backgroundImage?: string | undefined backgroundOrigin?: string | undefined backgroundPositionX?: | csstype.BackgroundPositionXProperty<string | number> | undefined backgroundPositionY?: | csstype.BackgroundPositionYProperty<string | number> | undefined backgroundRepeat?: string | undefined backgroundSize?: csstype.BackgroundSizeProperty<string | number> | undefined blockOverflow?: string | undefined blockSize?: csstype.BlockSizeProperty<string | number> | undefined borderBlockColor?: string | undefined borderBlockEndColor?: string | undefined borderBlockEndStyle?: csstype.BorderBlockEndStyleProperty | undefined borderBlockEndWidth?: | csstype.BorderBlockEndWidthProperty<string | number> | undefined borderBlockStartColor?: string | undefined borderBlockStartStyle?: csstype.BorderBlockStartStyleProperty | undefined borderBlockStartWidth?: | csstype.BorderBlockStartWidthProperty<string | number> | undefined borderBlockStyle?: csstype.BorderBlockStyleProperty | undefined borderBlockWidth?: | csstype.BorderBlockWidthProperty<string | number> | undefined borderBottomColor?: string | undefined borderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined borderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined borderBottomStyle?: csstype.BorderBottomStyleProperty | undefined borderBottomWidth?: | csstype.BorderBottomWidthProperty<string | number> | undefined borderCollapse?: csstype.BorderCollapseProperty | undefined borderEndEndRadius?: | csstype.BorderEndEndRadiusProperty<string | number> | undefined borderEndStartRadius?: | csstype.BorderEndStartRadiusProperty<string | number> | undefined borderImageOutset?: | csstype.BorderImageOutsetProperty<string | number> | undefined borderImageRepeat?: string | undefined borderImageSlice?: csstype.BorderImageSliceProperty | undefined borderImageSource?: string | undefined borderImageWidth?: | csstype.BorderImageWidthProperty<string | number> | undefined borderInlineColor?: string | undefined borderInlineEndColor?: string | undefined borderInlineEndStyle?: csstype.BorderInlineEndStyleProperty | undefined borderInlineEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined borderInlineStartColor?: string | undefined borderInlineStartStyle?: csstype.BorderInlineStartStyleProperty | undefined borderInlineStartWidth?: | csstype.BorderInlineStartWidthProperty<string | number> | undefined borderInlineStyle?: csstype.BorderInlineStyleProperty | undefined borderInlineWidth?: | csstype.BorderInlineWidthProperty<string | number> | undefined borderLeftColor?: string | undefined borderLeftStyle?: csstype.BorderLeftStyleProperty | undefined borderLeftWidth?: | csstype.BorderLeftWidthProperty<string | number> | undefined borderRightColor?: string | undefined borderRightStyle?: csstype.BorderRightStyleProperty | undefined borderRightWidth?: | csstype.BorderRightWidthProperty<string | number> | undefined borderSpacing?: csstype.BorderSpacingProperty<string | number> | undefined borderStartEndRadius?: | csstype.BorderStartEndRadiusProperty<string | number> | undefined borderStartStartRadius?: | csstype.BorderStartStartRadiusProperty<string | number> | undefined borderTopColor?: string | undefined borderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined borderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined borderTopStyle?: csstype.BorderTopStyleProperty | undefined borderTopWidth?: csstype.BorderTopWidthProperty<string | number> | undefined bottom?: csstype.BottomProperty<string | number> | undefined boxDecorationBreak?: csstype.BoxDecorationBreakProperty | undefined boxShadow?: string | undefined boxSizing?: csstype.BoxSizingProperty | undefined breakAfter?: csstype.BreakAfterProperty | undefined breakBefore?: csstype.BreakBeforeProperty | undefined breakInside?: csstype.BreakInsideProperty | undefined captionSide?: csstype.CaptionSideProperty | undefined caretColor?: string | undefined clear?: csstype.ClearProperty | undefined clipPath?: string | undefined color?: string | undefined colorAdjust?: csstype.ColorAdjustProperty | undefined colorScheme?: string | undefined columnCount?: csstype.ColumnCountProperty | undefined columnFill?: csstype.ColumnFillProperty | undefined columnGap?: csstype.ColumnGapProperty<string | number> | undefined columnRuleColor?: string | undefined columnRuleStyle?: string | undefined columnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined columnSpan?: csstype.ColumnSpanProperty | undefined columnWidth?: csstype.ColumnWidthProperty<string | number> | undefined contain?: string | undefined content?: string | undefined contentVisibility?: csstype.ContentVisibilityProperty | undefined counterIncrement?: string | undefined counterReset?: string | undefined counterSet?: string | undefined cursor?: string | undefined direction?: csstype.DirectionProperty | undefined display?: string | undefined emptyCells?: csstype.EmptyCellsProperty | undefined filter?: string | undefined flexBasis?: csstype.FlexBasisProperty<string | number> | undefined flexDirection?: csstype.FlexDirectionProperty | undefined flexGrow?: csstype.GlobalsNumber | undefined flexShrink?: csstype.GlobalsNumber | undefined flexWrap?: csstype.FlexWrapProperty | undefined float?: csstype.FloatProperty | undefined fontFamily?: string | undefined fontFeatureSettings?: string | undefined fontKerning?: csstype.FontKerningProperty | undefined fontLanguageOverride?: string | undefined fontOpticalSizing?: csstype.FontOpticalSizingProperty | undefined fontSize?: csstype.FontSizeProperty<string | number> | undefined fontSizeAdjust?: csstype.FontSizeAdjustProperty | undefined fontSmooth?: csstype.FontSmoothProperty<string | number> | undefined fontStretch?: string | undefined fontStyle?: string | undefined fontSynthesis?: string | undefined fontVariant?: string | undefined fontVariantCaps?: csstype.FontVariantCapsProperty | undefined fontVariantEastAsian?: string | undefined fontVariantLigatures?: string | undefined fontVariantNumeric?: string | undefined fontVariantPosition?: csstype.FontVariantPositionProperty | undefined fontVariationSettings?: string | undefined fontWeight?: csstype.FontWeightProperty | undefined forcedColorAdjust?: csstype.ForcedColorAdjustProperty | undefined gridAutoColumns?: | csstype.GridAutoColumnsProperty<string | number> | undefined gridAutoFlow?: string | undefined gridAutoRows?: csstype.GridAutoRowsProperty<string | number> | undefined gridColumnEnd?: csstype.GridColumnEndProperty | undefined gridColumnStart?: csstype.GridColumnStartProperty | undefined gridRowEnd?: csstype.GridRowEndProperty | undefined gridRowStart?: csstype.GridRowStartProperty | undefined gridTemplateAreas?: string | undefined gridTemplateColumns?: | csstype.GridTemplateColumnsProperty<string | number> | undefined gridTemplateRows?: | csstype.GridTemplateRowsProperty<string | number> | undefined hangingPunctuation?: string | undefined height?: csstype.HeightProperty<string | number> | undefined hyphens?: csstype.HyphensProperty | undefined imageOrientation?: string | undefined imageRendering?: csstype.ImageRenderingProperty | undefined imageResolution?: string | undefined initialLetter?: csstype.InitialLetterProperty | undefined inlineSize?: csstype.InlineSizeProperty<string | number> | undefined inset?: csstype.InsetProperty<string | number> | undefined insetBlock?: csstype.InsetBlockProperty<string | number> | undefined insetBlockEnd?: csstype.InsetBlockEndProperty<string | number> | undefined insetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined insetInline?: csstype.InsetInlineProperty<string | number> | undefined insetInlineEnd?: csstype.InsetInlineEndProperty<string | number> | undefined insetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined isolation?: csstype.IsolationProperty | undefined justifyContent?: string | undefined justifyItems?: string | undefined justifySelf?: string | undefined justifyTracks?: string | undefined left?: csstype.LeftProperty<string | number> | undefined letterSpacing?: csstype.LetterSpacingProperty<string | number> | undefined lineBreak?: csstype.LineBreakProperty | undefined lineHeight?: csstype.LineHeightProperty<string | number> | undefined lineHeightStep?: csstype.LineHeightStepProperty<string | number> | undefined listStyleImage?: string | undefined listStylePosition?: csstype.ListStylePositionProperty | undefined listStyleType?: string | undefined marginBlock?: csstype.MarginBlockProperty<string | number> | undefined marginBlockEnd?: csstype.MarginBlockEndProperty<string | number> | undefined marginBlockStart?: | csstype.MarginBlockStartProperty<string | number> | undefined marginBottom?: csstype.MarginBottomProperty<string | number> | undefined marginInline?: csstype.MarginInlineProperty<string | number> | undefined marginInlineEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined marginInlineStart?: | csstype.MarginInlineStartProperty<string | number> | undefined marginLeft?: csstype.MarginLeftProperty<string | number> | undefined marginRight?: csstype.MarginRightProperty<string | number> | undefined marginTop?: csstype.MarginTopProperty<string | number> | undefined maskBorderMode?: csstype.MaskBorderModeProperty | undefined maskBorderOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined maskBorderRepeat?: string | undefined maskBorderSlice?: csstype.MaskBorderSliceProperty | undefined maskBorderSource?: string | undefined maskBorderWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined maskClip?: string | undefined maskComposite?: string | undefined maskImage?: string | undefined maskMode?: string | undefined maskOrigin?: string | undefined maskPosition?: csstype.MaskPositionProperty<string | number> | undefined maskRepeat?: string | undefined maskSize?: csstype.MaskSizeProperty<string | number> | undefined maskType?: csstype.MaskTypeProperty | undefined mathStyle?: csstype.MathStyleProperty | undefined maxBlockSize?: csstype.MaxBlockSizeProperty<string | number> | undefined maxHeight?: csstype.MaxHeightProperty<string | number> | undefined maxInlineSize?: csstype.MaxInlineSizeProperty<string | number> | undefined maxLines?: csstype.MaxLinesProperty | undefined maxWidth?: csstype.MaxWidthProperty<string | number> | undefined minBlockSize?: csstype.MinBlockSizeProperty<string | number> | undefined minHeight?: csstype.MinHeightProperty<string | number> | undefined minInlineSize?: csstype.MinInlineSizeProperty<string | number> | undefined minWidth?: csstype.MinWidthProperty<string | number> | undefined mixBlendMode?: csstype.MixBlendModeProperty | undefined motionDistance?: csstype.OffsetDistanceProperty<string | number> | undefined motionPath?: string | undefined motionRotation?: string | undefined objectFit?: csstype.ObjectFitProperty | undefined objectPosition?: csstype.ObjectPositionProperty<string | number> | undefined offsetAnchor?: csstype.OffsetAnchorProperty<string | number> | undefined offsetDistance?: csstype.OffsetDistanceProperty<string | number> | undefined offsetPath?: string | undefined offsetRotate?: string | undefined offsetRotation?: string | undefined opacity?: csstype.OpacityProperty | undefined order?: csstype.GlobalsNumber | undefined orphans?: csstype.GlobalsNumber | undefined outlineColor?: string | undefined outlineOffset?: csstype.OutlineOffsetProperty<string | number> | undefined outlineStyle?: string | undefined outlineWidth?: csstype.OutlineWidthProperty<string | number> | undefined overflowAnchor?: csstype.OverflowAnchorProperty | undefined overflowBlock?: csstype.OverflowBlockProperty | undefined overflowClipBox?: csstype.OverflowClipBoxProperty | undefined overflowClipMargin?: | csstype.OverflowClipMarginProperty<string | number> | undefined overflowInline?: csstype.OverflowInlineProperty | undefined overflowWrap?: csstype.OverflowWrapProperty | undefined overflowX?: csstype.OverflowXProperty | undefined overflowY?: csstype.OverflowYProperty | undefined overscrollBehaviorBlock?: | csstype.OverscrollBehaviorBlockProperty | undefined overscrollBehaviorInline?: | csstype.OverscrollBehaviorInlineProperty | undefined overscrollBehaviorX?: csstype.OverscrollBehaviorXProperty | undefined overscrollBehaviorY?: csstype.OverscrollBehaviorYProperty | undefined paddingBlock?: csstype.PaddingBlockProperty<string | number> | undefined paddingBlockEnd?: | csstype.PaddingBlockEndProperty<string | number> | undefined paddingBlockStart?: | csstype.PaddingBlockStartProperty<string | number> | undefined paddingBottom?: csstype.PaddingBottomProperty<string | number> | undefined paddingInline?: csstype.PaddingInlineProperty<string | number> | undefined paddingInlineEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined paddingInlineStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined paddingLeft?: csstype.PaddingLeftProperty<string | number> | undefined paddingRight?: csstype.PaddingRightProperty<string | number> | undefined paddingTop?: csstype.PaddingTopProperty<string | number> | undefined pageBreakAfter?: csstype.PageBreakAfterProperty | undefined pageBreakBefore?: csstype.PageBreakBeforeProperty | undefined pageBreakInside?: csstype.PageBreakInsideProperty | undefined paintOrder?: string | undefined perspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined placeContent?: string | undefined pointerEvents?: csstype.PointerEventsProperty | undefined position?: csstype.PositionProperty | undefined quotes?: string | undefined resize?: csstype.ResizeProperty | undefined right?: csstype.RightProperty<string | number> | undefined rowGap?: csstype.RowGapProperty<string | number> | undefined rubyAlign?: csstype.RubyAlignProperty | undefined rubyMerge?: csstype.RubyMergeProperty | undefined rubyPosition?: string | undefined scrollBehavior?: csstype.ScrollBehaviorProperty | undefined scrollMargin?: csstype.ScrollMarginProperty<string | number> | undefined scrollMarginBlock?: | csstype.ScrollMarginBlockProperty<string | number> | undefined scrollMarginBlockEnd?: | csstype.ScrollMarginBlockEndProperty<string | number> | undefined scrollMarginBlockStart?: | csstype.ScrollMarginBlockStartProperty<string | number> | undefined scrollMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollMarginInline?: | csstype.ScrollMarginInlineProperty<string | number> | undefined scrollMarginInlineEnd?: | csstype.ScrollMarginInlineEndProperty<string | number> | undefined scrollMarginInlineStart?: | csstype.ScrollMarginInlineStartProperty<string | number> | undefined scrollMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollPadding?: csstype.ScrollPaddingProperty<string | number> | undefined scrollPaddingBlock?: | csstype.ScrollPaddingBlockProperty<string | number> | undefined scrollPaddingBlockEnd?: | csstype.ScrollPaddingBlockEndProperty<string | number> | undefined scrollPaddingBlockStart?: | csstype.ScrollPaddingBlockStartProperty<string | number> | undefined scrollPaddingBottom?: | csstype.ScrollPaddingBottomProperty<string | number> | undefined scrollPaddingInline?: | csstype.ScrollPaddingInlineProperty<string | number> | undefined scrollPaddingInlineEnd?: | csstype.ScrollPaddingInlineEndProperty<string | number> | undefined scrollPaddingInlineStart?: | csstype.ScrollPaddingInlineStartProperty<string | number> | undefined scrollPaddingLeft?: | csstype.ScrollPaddingLeftProperty<string | number> | undefined scrollPaddingRight?: | csstype.ScrollPaddingRightProperty<string | number> | undefined scrollPaddingTop?: | csstype.ScrollPaddingTopProperty<string | number> | undefined scrollSnapAlign?: string | undefined scrollSnapMargin?: csstype.ScrollMarginProperty<string | number> | undefined scrollSnapMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollSnapMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollSnapMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollSnapMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollSnapStop?: csstype.ScrollSnapStopProperty | undefined scrollSnapType?: string | undefined scrollbarColor?: string | undefined scrollbarGutter?: string | undefined scrollbarWidth?: csstype.ScrollbarWidthProperty | undefined shapeImageThreshold?: csstype.ShapeImageThresholdProperty | undefined shapeMargin?: csstype.ShapeMarginProperty<string | number> | undefined shapeOutside?: string | undefined tabSize?: csstype.TabSizeProperty<string | number> | undefined tableLayout?: csstype.TableLayoutProperty | undefined textAlign?: csstype.TextAlignProperty | undefined textAlignLast?: csstype.TextAlignLastProperty | undefined textCombineUpright?: string | undefined textDecorationColor?: string | undefined textDecorationLine?: string | undefined textDecorationSkip?: string | undefined textDecorationSkipInk?: csstype.TextDecorationSkipInkProperty | undefined textDecorationStyle?: csstype.TextDecorationStyleProperty | undefined textDecorationThickness?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textDecorationWidth?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textEmphasisColor?: string | undefined textEmphasisPosition?: string | undefined textEmphasisStyle?: string | undefined textIndent?: csstype.TextIndentProperty<string | number> | undefined textJustify?: csstype.TextJustifyProperty | undefined textOrientation?: csstype.TextOrientationProperty | undefined textOverflow?: string | undefined textRendering?: csstype.TextRenderingProperty | undefined textShadow?: string | undefined textSizeAdjust?: string | undefined textTransform?: csstype.TextTransformProperty | undefined textUnderlineOffset?: | csstype.TextUnderlineOffsetProperty<string | number> | undefined textUnderlinePosition?: string | undefined top?: csstype.TopProperty<string | number> | undefined touchAction?: string | undefined transitionDelay?: string | undefined transitionDuration?: string | undefined transitionProperty?: string | undefined transitionTimingFunction?: string | undefined translate?: csstype.TranslateProperty<string | number> | undefined unicodeBidi?: csstype.UnicodeBidiProperty | undefined userSelect?: csstype.UserSelectProperty | undefined verticalAlign?: csstype.VerticalAlignProperty<string | number> | undefined visibility?: csstype.VisibilityProperty | undefined whiteSpace?: csstype.WhiteSpaceProperty | undefined widows?: csstype.GlobalsNumber | undefined width?: csstype.WidthProperty<string | number> | undefined willChange?: string | undefined wordBreak?: csstype.WordBreakProperty | undefined wordSpacing?: csstype.WordSpacingProperty<string | number> | undefined wordWrap?: csstype.WordWrapProperty | undefined writingMode?: csstype.WritingModeProperty | undefined zIndex?: csstype.ZIndexProperty | undefined zoom?: csstype.ZoomProperty | undefined all?: csstype.Globals | undefined animation?: csstype.AnimationProperty | undefined background?: csstype.BackgroundProperty<string | number> | undefined backgroundPosition?: | csstype.BackgroundPositionProperty<string | number> | undefined border?: csstype.BorderProperty<string | number> | undefined borderBlock?: csstype.BorderBlockProperty<string | number> | undefined borderBlockEnd?: csstype.BorderBlockEndProperty<string | number> | undefined borderBlockStart?: | csstype.BorderBlockStartProperty<string | number> | undefined borderBottom?: csstype.BorderBottomProperty<string | number> | undefined borderColor?: string | undefined borderImage?: csstype.BorderImageProperty | undefined borderInline?: csstype.BorderInlineProperty<string | number> | undefined borderInlineEnd?: | csstype.BorderInlineEndProperty<string | number> | undefined borderInlineStart?: | csstype.BorderInlineStartProperty<string | number> | undefined borderLeft?: csstype.BorderLeftProperty<string | number> | undefined borderRadius?: csstype.BorderRadiusProperty<string | number> | undefined borderRight?: csstype.BorderRightProperty<string | number> | undefined borderStyle?: string | undefined borderTop?: csstype.BorderTopProperty<string | number> | undefined borderWidth?: csstype.BorderWidthProperty<string | number> | undefined columnRule?: csstype.ColumnRuleProperty<string | number> | undefined columns?: csstype.ColumnsProperty<string | number> | undefined flex?: csstype.FlexProperty<string | number> | undefined flexFlow?: string | undefined font?: string | undefined gap?: csstype.GapProperty<string | number> | undefined grid?: string | undefined gridArea?: csstype.GridAreaProperty | undefined gridColumn?: csstype.GridColumnProperty | undefined gridRow?: csstype.GridRowProperty | undefined gridTemplate?: string | undefined lineClamp?: csstype.LineClampProperty | undefined listStyle?: string | undefined margin?: csstype.MarginProperty<string | number> | undefined mask?: csstype.MaskProperty<string | number> | undefined maskBorder?: csstype.MaskBorderProperty | undefined motion?: csstype.OffsetProperty<string | number> | undefined offset?: csstype.OffsetProperty<string | number> | undefined outline?: csstype.OutlineProperty<string | number> | undefined overflow?: string | undefined overscrollBehavior?: string | undefined padding?: csstype.PaddingProperty<string | number> | undefined placeItems?: string | undefined placeSelf?: string | undefined textDecoration?: csstype.TextDecorationProperty<string | number> | undefined textEmphasis?: string | undefined MozAnimationDelay?: string | undefined MozAnimationDirection?: string | undefined MozAnimationDuration?: string | undefined MozAnimationFillMode?: string | undefined MozAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined MozAnimationName?: string | undefined MozAnimationPlayState?: string | undefined MozAnimationTimingFunction?: string | undefined MozAppearance?: csstype.MozAppearanceProperty | undefined MozBackfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined MozBorderBottomColors?: string | undefined MozBorderEndColor?: string | undefined MozBorderEndStyle?: csstype.BorderInlineEndStyleProperty | undefined MozBorderEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined MozBorderLeftColors?: string | undefined MozBorderRightColors?: string | undefined MozBorderStartColor?: string | undefined MozBorderStartStyle?: csstype.BorderInlineStartStyleProperty | undefined MozBorderTopColors?: string | undefined MozBoxSizing?: csstype.BoxSizingProperty | undefined MozColumnCount?: csstype.ColumnCountProperty | undefined MozColumnFill?: csstype.ColumnFillProperty | undefined MozColumnGap?: csstype.ColumnGapProperty<string | number> | undefined MozColumnRuleColor?: string | undefined MozColumnRuleStyle?: string | undefined MozColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined MozColumnWidth?: csstype.ColumnWidthProperty<string | number> | undefined MozContextProperties?: string | undefined MozFontFeatureSettings?: string | undefined MozFontLanguageOverride?: string | undefined MozHyphens?: csstype.HyphensProperty | undefined MozImageRegion?: string | undefined MozMarginEnd?: csstype.MarginInlineEndProperty<string | number> | undefined MozMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined MozOrient?: csstype.MozOrientProperty | undefined MozOsxFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined MozPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined MozPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined MozPerspective?: csstype.PerspectiveProperty<string | number> | undefined MozPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined MozStackSizing?: csstype.MozStackSizingProperty | undefined MozTabSize?: csstype.TabSizeProperty<string | number> | undefined MozTextBlink?: csstype.MozTextBlinkProperty | undefined MozTextSizeAdjust?: string | undefined MozTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined MozTransformStyle?: csstype.TransformStyleProperty | undefined MozTransitionDelay?: string | undefined MozTransitionDuration?: string | undefined MozTransitionProperty?: string | undefined MozTransitionTimingFunction?: string | undefined MozUserFocus?: csstype.MozUserFocusProperty | undefined MozUserModify?: csstype.MozUserModifyProperty | undefined MozUserSelect?: csstype.UserSelectProperty | undefined MozWindowDragging?: csstype.MozWindowDraggingProperty | undefined MozWindowShadow?: csstype.MozWindowShadowProperty | undefined msAccelerator?: csstype.MsAcceleratorProperty | undefined msAlignSelf?: string | undefined msBlockProgression?: csstype.MsBlockProgressionProperty | undefined msContentZoomChaining?: csstype.MsContentZoomChainingProperty | undefined msContentZoomLimitMax?: string | undefined msContentZoomLimitMin?: string | undefined msContentZoomSnapPoints?: string | undefined msContentZoomSnapType?: csstype.MsContentZoomSnapTypeProperty | undefined msContentZooming?: csstype.MsContentZoomingProperty | undefined msFilter?: string | undefined msFlexDirection?: csstype.FlexDirectionProperty | undefined msFlexPositive?: csstype.GlobalsNumber | undefined msFlowFrom?: string | undefined msFlowInto?: string | undefined msGridColumns?: csstype.MsGridColumnsProperty<string | number> | undefined msGridRows?: csstype.MsGridRowsProperty<string | number> | undefined msHighContrastAdjust?: csstype.MsHighContrastAdjustProperty | undefined msHyphenateLimitChars?: csstype.MsHyphenateLimitCharsProperty | undefined msHyphenateLimitLines?: csstype.MsHyphenateLimitLinesProperty | undefined msHyphenateLimitZone?: | csstype.MsHyphenateLimitZoneProperty<string | number> | undefined msHyphens?: csstype.HyphensProperty | undefined msImeAlign?: csstype.MsImeAlignProperty | undefined msJustifySelf?: string | undefined msLineBreak?: csstype.LineBreakProperty | undefined msOrder?: csstype.GlobalsNumber | undefined msOverflowStyle?: csstype.MsOverflowStyleProperty | undefined msOverflowX?: csstype.OverflowXProperty | undefined msOverflowY?: csstype.OverflowYProperty | undefined msScrollChaining?: csstype.MsScrollChainingProperty | undefined msScrollLimitXMax?: | csstype.MsScrollLimitXMaxProperty<string | number> | undefined msScrollLimitXMin?: | csstype.MsScrollLimitXMinProperty<string | number> | undefined msScrollLimitYMax?: | csstype.MsScrollLimitYMaxProperty<string | number> | undefined msScrollLimitYMin?: | csstype.MsScrollLimitYMinProperty<string | number> | undefined msScrollRails?: csstype.MsScrollRailsProperty | undefined msScrollSnapPointsX?: string | undefined msScrollSnapPointsY?: string | undefined msScrollSnapType?: csstype.MsScrollSnapTypeProperty | undefined msScrollTranslation?: csstype.MsScrollTranslationProperty | undefined msScrollbar3dlightColor?: string | undefined msScrollbarArrowColor?: string | undefined msScrollbarBaseColor?: string | undefined msScrollbarDarkshadowColor?: string | undefined msScrollbarFaceColor?: string | undefined msScrollbarHighlightColor?: string | undefined msScrollbarShadowColor?: string | undefined msTextAutospace?: csstype.MsTextAutospaceProperty | undefined msTextCombineHorizontal?: string | undefined msTextOverflow?: string | undefined msTouchAction?: string | undefined msTouchSelect?: csstype.MsTouchSelectProperty | undefined msTransform?: string | undefined msTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined msTransitionDelay?: string | undefined msTransitionDuration?: string | undefined msTransitionProperty?: string | undefined msTransitionTimingFunction?: string | undefined msUserSelect?: csstype.MsUserSelectProperty | undefined msWordBreak?: csstype.WordBreakProperty | undefined msWrapFlow?: csstype.MsWrapFlowProperty | undefined msWrapMargin?: csstype.MsWrapMarginProperty<string | number> | undefined msWrapThrough?: csstype.MsWrapThroughProperty | undefined msWritingMode?: csstype.WritingModeProperty | undefined WebkitAlignContent?: string | undefined WebkitAlignItems?: string | undefined WebkitAlignSelf?: string | undefined WebkitAnimationDelay?: string | undefined WebkitAnimationDirection?: string | undefined WebkitAnimationDuration?: string | undefined WebkitAnimationFillMode?: string | undefined WebkitAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined WebkitAnimationName?: string | undefined WebkitAnimationPlayState?: string | undefined WebkitAnimationTimingFunction?: string | undefined WebkitAppearance?: csstype.WebkitAppearanceProperty | undefined WebkitBackdropFilter?: string | undefined WebkitBackfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined WebkitBackgroundClip?: string | undefined WebkitBackgroundOrigin?: string | undefined WebkitBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined WebkitBorderBeforeColor?: string | undefined WebkitBorderBeforeStyle?: string | undefined WebkitBorderBeforeWidth?: | csstype.WebkitBorderBeforeWidthProperty<string | number> | undefined WebkitBorderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined WebkitBorderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined WebkitBorderImageSlice?: csstype.BorderImageSliceProperty | undefined WebkitBorderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined WebkitBorderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined WebkitBoxDecorationBreak?: csstype.BoxDecorationBreakProperty | undefined WebkitBoxReflect?: | csstype.WebkitBoxReflectProperty<string | number> | undefined WebkitBoxShadow?: string | undefined WebkitBoxSizing?: csstype.BoxSizingProperty | undefined WebkitClipPath?: string | undefined WebkitColumnCount?: csstype.ColumnCountProperty | undefined WebkitColumnFill?: csstype.ColumnFillProperty | undefined WebkitColumnGap?: csstype.ColumnGapProperty<string | number> | undefined WebkitColumnRuleColor?: string | undefined WebkitColumnRuleStyle?: string | undefined WebkitColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined WebkitColumnSpan?: csstype.ColumnSpanProperty | undefined WebkitColumnWidth?: csstype.ColumnWidthProperty<string | number> | undefined WebkitFilter?: string | undefined WebkitFlexBasis?: csstype.FlexBasisProperty<string | number> | undefined WebkitFlexDirection?: csstype.FlexDirectionProperty | undefined WebkitFlexGrow?: csstype.GlobalsNumber | undefined WebkitFlexShrink?: csstype.GlobalsNumber | undefined WebkitFlexWrap?: csstype.FlexWrapProperty | undefined WebkitFontFeatureSettings?: string | undefined WebkitFontKerning?: csstype.FontKerningProperty | undefined WebkitFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined WebkitFontVariantLigatures?: string | undefined WebkitHyphens?: csstype.HyphensProperty | undefined WebkitJustifyContent?: string | undefined WebkitLineBreak?: csstype.LineBreakProperty | undefined WebkitLineClamp?: csstype.WebkitLineClampProperty | undefined WebkitMarginEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined WebkitMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined WebkitMaskAttachment?: string | undefined WebkitMaskBoxImageOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined WebkitMaskBoxImageRepeat?: string | undefined WebkitMaskBoxImageSlice?: csstype.MaskBorderSliceProperty | undefined WebkitMaskBoxImageSource?: string | undefined WebkitMaskBoxImageWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined WebkitMaskClip?: string | undefined WebkitMaskComposite?: string | undefined WebkitMaskImage?: string | undefined WebkitMaskOrigin?: string | undefined WebkitMaskPosition?: | csstype.WebkitMaskPositionProperty<string | number> | undefined WebkitMaskPositionX?: | csstype.WebkitMaskPositionXProperty<string | number> | undefined WebkitMaskPositionY?: | csstype.WebkitMaskPositionYProperty<string | number> | undefined WebkitMaskRepeat?: string | undefined WebkitMaskRepeatX?: csstype.WebkitMaskRepeatXProperty | undefined WebkitMaskRepeatY?: csstype.WebkitMaskRepeatYProperty | undefined WebkitMaskSize?: csstype.WebkitMaskSizeProperty<string | number> | undefined WebkitMaxInlineSize?: | csstype.MaxInlineSizeProperty<string | number> | undefined WebkitOrder?: csstype.GlobalsNumber | undefined WebkitOverflowScrolling?: | csstype.WebkitOverflowScrollingProperty | undefined WebkitPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined WebkitPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined WebkitPerspective?: csstype.PerspectiveProperty<string | number> | undefined WebkitPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined WebkitPrintColorAdjust?: csstype.ColorAdjustProperty | undefined WebkitRubyPosition?: string | undefined WebkitScrollSnapType?: string | undefined WebkitShapeMargin?: csstype.ShapeMarginProperty<string | number> | undefined WebkitTapHighlightColor?: string | undefined WebkitTextCombine?: string | undefined WebkitTextDecorationColor?: string | undefined WebkitTextDecorationLine?: string | undefined WebkitTextDecorationSkip?: string | undefined WebkitTextDecorationStyle?: csstype.TextDecorationStyleProperty | undefined WebkitTextEmphasisColor?: string | undefined WebkitTextEmphasisPosition?: string | undefined WebkitTextEmphasisStyle?: string | undefined WebkitTextFillColor?: string | undefined WebkitTextOrientation?: csstype.TextOrientationProperty | undefined WebkitTextSizeAdjust?: string | undefined WebkitTextStrokeColor?: string | undefined WebkitTextStrokeWidth?: | csstype.WebkitTextStrokeWidthProperty<string | number> | undefined WebkitTextUnderlinePosition?: string | undefined WebkitTouchCallout?: csstype.WebkitTouchCalloutProperty | undefined WebkitTransform?: string | undefined WebkitTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined WebkitTransformStyle?: csstype.TransformStyleProperty | undefined WebkitTransitionDelay?: string | undefined WebkitTransitionDuration?: string | undefined WebkitTransitionProperty?: string | undefined WebkitTransitionTimingFunction?: string | undefined WebkitUserModify?: csstype.WebkitUserModifyProperty | undefined WebkitUserSelect?: csstype.UserSelectProperty | undefined WebkitWritingMode?: csstype.WritingModeProperty | undefined MozAnimation?: csstype.AnimationProperty | undefined MozBorderImage?: csstype.BorderImageProperty | undefined MozColumnRule?: csstype.ColumnRuleProperty<string | number> | undefined MozColumns?: csstype.ColumnsProperty<string | number> | undefined MozTransition?: string | undefined msContentZoomLimit?: string | undefined msContentZoomSnap?: string | undefined msFlex?: csstype.FlexProperty<string | number> | undefined msScrollLimit?: string | undefined msScrollSnapX?: string | undefined msScrollSnapY?: string | undefined msTransition?: string | undefined WebkitAnimation?: csstype.AnimationProperty | undefined WebkitBorderBefore?: | csstype.WebkitBorderBeforeProperty<string | number> | undefined WebkitBorderImage?: csstype.BorderImageProperty | undefined WebkitBorderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined WebkitColumnRule?: csstype.ColumnRuleProperty<string | number> | undefined WebkitColumns?: csstype.ColumnsProperty<string | number> | undefined WebkitFlex?: csstype.FlexProperty<string | number> | undefined WebkitFlexFlow?: string | undefined WebkitMask?: csstype.WebkitMaskProperty<string | number> | undefined WebkitMaskBoxImage?: csstype.MaskBorderProperty | undefined WebkitTextEmphasis?: string | undefined WebkitTextStroke?: | csstype.WebkitTextStrokeProperty<string | number> | undefined WebkitTransition?: string | undefined azimuth?: string | undefined boxAlign?: csstype.BoxAlignProperty | undefined boxDirection?: csstype.BoxDirectionProperty | undefined boxFlex?: csstype.GlobalsNumber | undefined boxFlexGroup?: csstype.GlobalsNumber | undefined boxLines?: csstype.BoxLinesProperty | undefined boxOrdinalGroup?: csstype.GlobalsNumber | undefined boxOrient?: csstype.BoxOrientProperty | undefined boxPack?: csstype.BoxPackProperty | undefined clip?: string | undefined fontVariantAlternates?: string | undefined gridColumnGap?: csstype.GridColumnGapProperty<string | number> | undefined gridGap?: csstype.GridGapProperty<string | number> | undefined gridRowGap?: csstype.GridRowGapProperty<string | number> | undefined imeMode?: csstype.ImeModeProperty | undefined offsetBlock?: csstype.InsetBlockProperty<string | number> | undefined offsetBlockEnd?: csstype.InsetBlockEndProperty<string | number> | undefined offsetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined offsetInline?: csstype.InsetInlineProperty<string | number> | undefined offsetInlineEnd?: | csstype.InsetInlineEndProperty<string | number> | undefined offsetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined scrollSnapCoordinate?: | csstype.ScrollSnapCoordinateProperty<string | number> | undefined scrollSnapDestination?: | csstype.ScrollSnapDestinationProperty<string | number> | undefined scrollSnapPointsX?: string | undefined scrollSnapPointsY?: string | undefined scrollSnapTypeX?: csstype.ScrollSnapTypeXProperty | undefined scrollSnapTypeY?: csstype.ScrollSnapTypeYProperty | undefined scrollbarTrackColor?: string | undefined KhtmlBoxAlign?: csstype.BoxAlignProperty | undefined KhtmlBoxDirection?: csstype.BoxDirectionProperty | undefined KhtmlBoxFlex?: csstype.GlobalsNumber | undefined KhtmlBoxFlexGroup?: csstype.GlobalsNumber | undefined KhtmlBoxLines?: csstype.BoxLinesProperty | undefined KhtmlBoxOrdinalGroup?: csstype.GlobalsNumber | undefined KhtmlBoxOrient?: csstype.BoxOrientProperty | undefined KhtmlBoxPack?: csstype.BoxPackProperty | undefined KhtmlLineBreak?: csstype.LineBreakProperty | undefined KhtmlOpacity?: csstype.OpacityProperty | undefined KhtmlUserSelect?: csstype.UserSelectProperty | undefined MozBackgroundClip?: string | undefined MozBackgroundInlinePolicy?: csstype.BoxDecorationBreakProperty | undefined MozBackgroundOrigin?: string | undefined MozBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined MozBinding?: string | undefined MozBorderRadius?: csstype.BorderRadiusProperty<string | number> | undefined MozBorderRadiusBottomleft?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined MozBorderRadiusBottomright?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined MozBorderRadiusTopleft?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined MozBorderRadiusTopright?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined MozBoxAlign?: csstype.BoxAlignProperty | undefined MozBoxDirection?: csstype.BoxDirectionProperty | undefined MozBoxFlex?: csstype.GlobalsNumber | undefined MozBoxOrdinalGroup?: csstype.GlobalsNumber | undefined MozBoxOrient?: csstype.BoxOrientProperty | undefined MozBoxPack?: csstype.BoxPackProperty | undefined MozBoxShadow?: string | undefined MozFloatEdge?: csstype.MozFloatEdgeProperty | undefined MozForceBrokenImageIcon?: csstype.GlobalsNumber | undefined MozOpacity?: csstype.OpacityProperty | undefined MozOutline?: csstype.OutlineProperty<string | number> | undefined MozOutlineColor?: string | undefined MozOutlineRadius?: | csstype.MozOutlineRadiusProperty<string | number> | undefined MozOutlineRadiusBottomleft?: | csstype.MozOutlineRadiusBottomleftProperty<string | number> | undefined MozOutlineRadiusBottomright?: | csstype.MozOutlineRadiusBottomrightProperty<string | number> | undefined MozOutlineRadiusTopleft?: | csstype.MozOutlineRadiusTopleftProperty<string | number> | undefined MozOutlineRadiusTopright?: | csstype.MozOutlineRadiusToprightProperty<string | number> | undefined MozOutlineStyle?: string | undefined MozOutlineWidth?: csstype.OutlineWidthProperty<string | number> | undefined MozTextAlignLast?: csstype.TextAlignLastProperty | undefined MozTextDecorationColor?: string | undefined MozTextDecorationLine?: string | undefined MozTextDecorationStyle?: csstype.TextDecorationStyleProperty | undefined MozUserInput?: csstype.MozUserInputProperty | undefined msImeMode?: csstype.ImeModeProperty | undefined msScrollbarTrackColor?: string | undefined OAnimation?: csstype.AnimationProperty | undefined OAnimationDelay?: string | undefined OAnimationDirection?: string | undefined OAnimationDuration?: string | undefined OAnimationFillMode?: string | undefined OAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined OAnimationName?: string | undefined OAnimationPlayState?: string | undefined OAnimationTimingFunction?: string | undefined OBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined OBorderImage?: csstype.BorderImageProperty | undefined OObjectFit?: csstype.ObjectFitProperty | undefined OObjectPosition?: | csstype.ObjectPositionProperty<string | number> | undefined OTabSize?: csstype.TabSizeProperty<string | number> | undefined OTextOverflow?: string | undefined OTransform?: string | undefined OTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined OTransition?: string | undefined OTransitionDelay?: string | undefined OTransitionDuration?: string | undefined OTransitionProperty?: string | undefined OTransitionTimingFunction?: string | undefined WebkitBoxAlign?: csstype.BoxAlignProperty | undefined WebkitBoxDirection?: csstype.BoxDirectionProperty | undefined WebkitBoxFlex?: csstype.GlobalsNumber | undefined WebkitBoxFlexGroup?: csstype.GlobalsNumber | undefined WebkitBoxLines?: csstype.BoxLinesProperty | undefined WebkitBoxOrdinalGroup?: csstype.GlobalsNumber | undefined WebkitBoxOrient?: csstype.BoxOrientProperty | undefined WebkitBoxPack?: csstype.BoxPackProperty | undefined WebkitScrollSnapPointsX?: string | undefined WebkitScrollSnapPointsY?: string | undefined alignmentBaseline?: csstype.AlignmentBaselineProperty | undefined baselineShift?: csstype.BaselineShiftProperty<string | number> | undefined clipRule?: csstype.ClipRuleProperty | undefined colorInterpolation?: csstype.ColorInterpolationProperty | undefined colorRendering?: csstype.ColorRenderingProperty | undefined dominantBaseline?: csstype.DominantBaselineProperty | undefined fill?: string | undefined fillOpacity?: csstype.GlobalsNumber | undefined fillRule?: csstype.FillRuleProperty | undefined floodColor?: string | undefined floodOpacity?: csstype.GlobalsNumber | undefined glyphOrientationVertical?: | csstype.GlyphOrientationVerticalProperty | undefined lightingColor?: string | undefined marker?: string | undefined markerEnd?: string | undefined markerMid?: string | undefined markerStart?: string | undefined shapeRendering?: csstype.ShapeRenderingProperty | undefined stopColor?: string | undefined stopOpacity?: csstype.GlobalsNumber | undefined stroke?: string | undefined strokeDasharray?: | csstype.StrokeDasharrayProperty<string | number> | undefined strokeDashoffset?: | csstype.StrokeDashoffsetProperty<string | number> | undefined strokeLinecap?: csstype.StrokeLinecapProperty | undefined strokeLinejoin?: csstype.StrokeLinejoinProperty | undefined strokeMiterlimit?: csstype.GlobalsNumber | undefined strokeOpacity?: csstype.GlobalsNumber | undefined strokeWidth?: csstype.StrokeWidthProperty<string | number> | undefined textAnchor?: csstype.TextAnchorProperty | undefined vectorEffect?: csstype.VectorEffectProperty | undefined } style: Ref<StyleProperties> } /** * Reactive transform string implementing all native CSS transform properties. * * @param props * @param enableHardwareAcceleration */ declare function reactiveTransform( props?: TransformProperties, enableHardwareAcceleration?: boolean, ): { state: { x?: string | number | undefined y?: string | number | undefined z?: string | number | undefined translateX?: string | number | undefined translateY?: string | number | undefined translateZ?: string | number | undefined rotate?: string | number | undefined rotateX?: string | number | undefined rotateY?: string | number | undefined rotateZ?: string | number | undefined scale?: string | number | undefined scaleX?: string | number | undefined scaleY?: string | number | undefined scaleZ?: string | number | undefined skew?: string | number | undefined skewX?: string | number | undefined skewY?: string | number | undefined originX?: string | number | undefined originY?: string | number | undefined originZ?: string | number | undefined perspective?: string | number | undefined transformPerspective?: string | number | undefined } transform: vue_demi.Ref<string> } /** * A Composable giving access to a StyleProperties object, and binding the generated style object to a target. * * @param target */ declare function useElementStyle( target: MaybeRef<PermissiveTarget>, onInit?: (initData: Partial<StyleProperties>) => void, ): { style: { alignContent?: string | undefined alignItems?: string | undefined alignSelf?: string | undefined alignTracks?: string | undefined animationDelay?: string | undefined animationDirection?: string | undefined animationDuration?: string | undefined animationFillMode?: string | undefined animationIterationCount?: | csstype.AnimationIterationCountProperty | undefined animationName?: string | undefined animationPlayState?: string | undefined animationTimingFunction?: string | undefined appearance?: csstype.AppearanceProperty | undefined aspectRatio?: string | undefined backdropFilter?: string | undefined backfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined backgroundAttachment?: string | undefined backgroundBlendMode?: string | undefined backgroundClip?: string | undefined backgroundColor?: string | undefined backgroundImage?: string | undefined backgroundOrigin?: string | undefined backgroundPositionX?: | csstype.BackgroundPositionXProperty<string | number> | undefined backgroundPositionY?: | csstype.BackgroundPositionYProperty<string | number> | undefined backgroundRepeat?: string | undefined backgroundSize?: csstype.BackgroundSizeProperty<string | number> | undefined blockOverflow?: string | undefined blockSize?: csstype.BlockSizeProperty<string | number> | undefined borderBlockColor?: string | undefined borderBlockEndColor?: string | undefined borderBlockEndStyle?: csstype.BorderBlockEndStyleProperty | undefined borderBlockEndWidth?: | csstype.BorderBlockEndWidthProperty<string | number> | undefined borderBlockStartColor?: string | undefined borderBlockStartStyle?: csstype.BorderBlockStartStyleProperty | undefined borderBlockStartWidth?: | csstype.BorderBlockStartWidthProperty<string | number> | undefined borderBlockStyle?: csstype.BorderBlockStyleProperty | undefined borderBlockWidth?: | csstype.BorderBlockWidthProperty<string | number> | undefined borderBottomColor?: string | undefined borderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined borderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined borderBottomStyle?: csstype.BorderBottomStyleProperty | undefined borderBottomWidth?: | csstype.BorderBottomWidthProperty<string | number> | undefined borderCollapse?: csstype.BorderCollapseProperty | undefined borderEndEndRadius?: | csstype.BorderEndEndRadiusProperty<string | number> | undefined borderEndStartRadius?: | csstype.BorderEndStartRadiusProperty<string | number> | undefined borderImageOutset?: | csstype.BorderImageOutsetProperty<string | number> | undefined borderImageRepeat?: string | undefined borderImageSlice?: csstype.BorderImageSliceProperty | undefined borderImageSource?: string | undefined borderImageWidth?: | csstype.BorderImageWidthProperty<string | number> | undefined borderInlineColor?: string | undefined borderInlineEndColor?: string | undefined borderInlineEndStyle?: csstype.BorderInlineEndStyleProperty | undefined borderInlineEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined borderInlineStartColor?: string | undefined borderInlineStartStyle?: csstype.BorderInlineStartStyleProperty | undefined borderInlineStartWidth?: | csstype.BorderInlineStartWidthProperty<string | number> | undefined borderInlineStyle?: csstype.BorderInlineStyleProperty | undefined borderInlineWidth?: | csstype.BorderInlineWidthProperty<string | number> | undefined borderLeftColor?: string | undefined borderLeftStyle?: csstype.BorderLeftStyleProperty | undefined borderLeftWidth?: | csstype.BorderLeftWidthProperty<string | number> | undefined borderRightColor?: string | undefined borderRightStyle?: csstype.BorderRightStyleProperty | undefined borderRightWidth?: | csstype.BorderRightWidthProperty<string | number> | undefined borderSpacing?: csstype.BorderSpacingProperty<string | number> | undefined borderStartEndRadius?: | csstype.BorderStartEndRadiusProperty<string | number> | undefined borderStartStartRadius?: | csstype.BorderStartStartRadiusProperty<string | number> | undefined borderTopColor?: string | undefined borderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined borderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined borderTopStyle?: csstype.BorderTopStyleProperty | undefined borderTopWidth?: csstype.BorderTopWidthProperty<string | number> | undefined bottom?: csstype.BottomProperty<string | number> | undefined boxDecorationBreak?: csstype.BoxDecorationBreakProperty | undefined boxShadow?: string | undefined boxSizing?: csstype.BoxSizingProperty | undefined breakAfter?: csstype.BreakAfterProperty | undefined breakBefore?: csstype.BreakBeforeProperty | undefined breakInside?: csstype.BreakInsideProperty | undefined captionSide?: csstype.CaptionSideProperty | undefined caretColor?: string | undefined clear?: csstype.ClearProperty | undefined clipPath?: string | undefined color?: string | undefined colorAdjust?: csstype.ColorAdjustProperty | undefined colorScheme?: string | undefined columnCount?: csstype.ColumnCountProperty | undefined columnFill?: csstype.ColumnFillProperty | undefined columnGap?: csstype.ColumnGapProperty<string | number> | undefined columnRuleColor?: string | undefined columnRuleStyle?: string | undefined columnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined columnSpan?: csstype.ColumnSpanProperty | undefined columnWidth?: csstype.ColumnWidthProperty<string | number> | undefined contain?: string | undefined content?: string | undefined contentVisibility?: csstype.ContentVisibilityProperty | undefined counterIncrement?: string | undefined counterReset?: string | undefined counterSet?: string | undefined cursor?: string | undefined direction?: csstype.DirectionProperty | undefined display?: string | undefined emptyCells?: csstype.EmptyCellsProperty | undefined filter?: string | undefined flexBasis?: csstype.FlexBasisProperty<string | number> | undefined flexDirection?: csstype.FlexDirectionProperty | undefined flexGrow?: csstype.GlobalsNumber | undefined flexShrink?: csstype.GlobalsNumber | undefined flexWrap?: csstype.FlexWrapProperty | undefined float?: csstype.FloatProperty | undefined fontFamily?: string | undefined fontFeatureSettings?: string | undefined fontKerning?: csstype.FontKerningProperty | undefined fontLanguageOverride?: string | undefined fontOpticalSizing?: csstype.FontOpticalSizingProperty | undefined fontSize?: csstype.FontSizeProperty<string | number> | undefined fontSizeAdjust?: csstype.FontSizeAdjustProperty | undefined fontSmooth?: csstype.FontSmoothProperty<string | number> | undefined fontStretch?: string | undefined fontStyle?: string | undefined fontSynthesis?: string | undefined fontVariant?: string | undefined fontVariantCaps?: csstype.FontVariantCapsProperty | undefined fontVariantEastAsian?: string | undefined fontVariantLigatures?: string | undefined fontVariantNumeric?: string | undefined fontVariantPosition?: csstype.FontVariantPositionProperty | undefined fontVariationSettings?: string | undefined fontWeight?: csstype.FontWeightProperty | undefined forcedColorAdjust?: csstype.ForcedColorAdjustProperty | undefined gridAutoColumns?: | csstype.GridAutoColumnsProperty<string | number> | undefined gridAutoFlow?: string | undefined gridAutoRows?: csstype.GridAutoRowsProperty<string | number> | undefined gridColumnEnd?: csstype.GridColumnEndProperty | undefined gridColumnStart?: csstype.GridColumnStartProperty | undefined gridRowEnd?: csstype.GridRowEndProperty | undefined gridRowStart?: csstype.GridRowStartProperty | undefined gridTemplateAreas?: string | undefined gridTemplateColumns?: | csstype.GridTemplateColumnsProperty<string | number> | undefined gridTemplateRows?: | csstype.GridTemplateRowsProperty<string | number> | undefined hangingPunctuation?: string | undefined height?: csstype.HeightProperty<string | number> | undefined hyphens?: csstype.HyphensProperty | undefined imageOrientation?: string | undefined imageRendering?: csstype.ImageRenderingProperty | undefined imageResolution?: string | undefined initialLetter?: csstype.InitialLetterProperty | undefined inlineSize?: csstype.InlineSizeProperty<string | number> | undefined inset?: csstype.InsetProperty<string | number> | undefined insetBlock?: csstype.InsetBlockProperty<string | number> | undefined insetBlockEnd?: csstype.InsetBlockEndProperty<string | number> | undefined insetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined insetInline?: csstype.InsetInlineProperty<string | number> | undefined insetInlineEnd?: csstype.InsetInlineEndProperty<string | number> | undefined insetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined isolation?: csstype.IsolationProperty | undefined justifyContent?: string | undefined justifyItems?: string | undefined justifySelf?: string | undefined justifyTracks?: string | undefined left?: csstype.LeftProperty<string | number> | undefined letterSpacing?: csstype.LetterSpacingProperty<string | number> | undefined lineBreak?: csstype.LineBreakProperty | undefined lineHeight?: csstype.LineHeightProperty<string | number> | undefined lineHeightStep?: csstype.LineHeightStepProperty<string | number> | undefined listStyleImage?: string | undefined listStylePosition?: csstype.ListStylePositionProperty | undefined listStyleType?: string | undefined marginBlock?: csstype.MarginBlockProperty<string | number> | undefined marginBlockEnd?: csstype.MarginBlockEndProperty<string | number> | undefined marginBlockStart?: | csstype.MarginBlockStartProperty<string | number> | undefined marginBottom?: csstype.MarginBottomProperty<string | number> | undefined marginInline?: csstype.MarginInlineProperty<string | number> | undefined marginInlineEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined marginInlineStart?: | csstype.MarginInlineStartProperty<string | number> | undefined marginLeft?: csstype.MarginLeftProperty<string | number> | undefined marginRight?: csstype.MarginRightProperty<string | number> | undefined marginTop?: csstype.MarginTopProperty<string | number> | undefined maskBorderMode?: csstype.MaskBorderModeProperty | undefined maskBorderOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined maskBorderRepeat?: string | undefined maskBorderSlice?: csstype.MaskBorderSliceProperty | undefined maskBorderSource?: string | undefined maskBorderWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined maskClip?: string | undefined maskComposite?: string | undefined maskImage?: string | undefined maskMode?: string | undefined maskOrigin?: string | undefined maskPosition?: csstype.MaskPositionProperty<string | number> | undefined maskRepeat?: string | undefined maskSize?: csstype.MaskSizeProperty<string | number> | undefined maskType?: csstype.MaskTypeProperty | undefined mathStyle?: csstype.MathStyleProperty | undefined maxBlockSize?: csstype.MaxBlockSizeProperty<string | number> | undefined maxHeight?: csstype.MaxHeightProperty<string | number> | undefined maxInlineSize?: csstype.MaxInlineSizeProperty<string | number> | undefined maxLines?: csstype.MaxLinesProperty | undefined maxWidth?: csstype.MaxWidthProperty<string | number> | undefined minBlockSize?: csstype.MinBlockSizeProperty<string | number> | undefined minHeight?: csstype.MinHeightProperty<string | number> | undefined minInlineSize?: csstype.MinInlineSizeProperty<string | number> | undefined minWidth?: csstype.MinWidthProperty<string | number> | undefined mixBlendMode?: csstype.MixBlendModeProperty | undefined motionDistance?: csstype.OffsetDistanceProperty<string | number> | undefined motionPath?: string | undefined motionRotation?: string | undefined objectFit?: csstype.ObjectFitProperty | undefined objectPosition?: csstype.ObjectPositionProperty<string | number> | undefined offsetAnchor?: csstype.OffsetAnchorProperty<string | number> | undefined offsetDistance?: csstype.OffsetDistanceProperty<string | number> | undefined offsetPath?: string | undefined offsetRotate?: string | undefined offsetRotation?: string | undefined opacity?: csstype.OpacityProperty | undefined order?: csstype.GlobalsNumber | undefined orphans?: csstype.GlobalsNumber | undefined outlineColor?: string | undefined outlineOffset?: csstype.OutlineOffsetProperty<string | number> | undefined outlineStyle?: string | undefined outlineWidth?: csstype.OutlineWidthProperty<string | number> | undefined overflowAnchor?: csstype.OverflowAnchorProperty | undefined overflowBlock?: csstype.OverflowBlockProperty | undefined overflowClipBox?: csstype.OverflowClipBoxProperty | undefined overflowClipMargin?: | csstype.OverflowClipMarginProperty<string | number> | undefined overflowInline?: csstype.OverflowInlineProperty | undefined overflowWrap?: csstype.OverflowWrapProperty | undefined overflowX?: csstype.OverflowXProperty | undefined overflowY?: csstype.OverflowYProperty | undefined overscrollBehaviorBlock?: | csstype.OverscrollBehaviorBlockProperty | undefined overscrollBehaviorInline?: | csstype.OverscrollBehaviorInlineProperty | undefined overscrollBehaviorX?: csstype.OverscrollBehaviorXProperty | undefined overscrollBehaviorY?: csstype.OverscrollBehaviorYProperty | undefined paddingBlock?: csstype.PaddingBlockProperty<string | number> | undefined paddingBlockEnd?: | csstype.PaddingBlockEndProperty<string | number> | undefined paddingBlockStart?: | csstype.PaddingBlockStartProperty<string | number> | undefined paddingBottom?: csstype.PaddingBottomProperty<string | number> | undefined paddingInline?: csstype.PaddingInlineProperty<string | number> | undefined paddingInlineEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined paddingInlineStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined paddingLeft?: csstype.PaddingLeftProperty<string | number> | undefined paddingRight?: csstype.PaddingRightProperty<string | number> | undefined paddingTop?: csstype.PaddingTopProperty<string | number> | undefined pageBreakAfter?: csstype.PageBreakAfterProperty | undefined pageBreakBefore?: csstype.PageBreakBeforeProperty | undefined pageBreakInside?: csstype.PageBreakInsideProperty | undefined paintOrder?: string | undefined perspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined placeContent?: string | undefined pointerEvents?: csstype.PointerEventsProperty | undefined position?: csstype.PositionProperty | undefined quotes?: string | undefined resize?: csstype.ResizeProperty | undefined right?: csstype.RightProperty<string | number> | undefined rowGap?: csstype.RowGapProperty<string | number> | undefined rubyAlign?: csstype.RubyAlignProperty | undefined rubyMerge?: csstype.RubyMergeProperty | undefined rubyPosition?: string | undefined scrollBehavior?: csstype.ScrollBehaviorProperty | undefined scrollMargin?: csstype.ScrollMarginProperty<string | number> | undefined scrollMarginBlock?: | csstype.ScrollMarginBlockProperty<string | number> | undefined scrollMarginBlockEnd?: | csstype.ScrollMarginBlockEndProperty<string | number> | undefined scrollMarginBlockStart?: | csstype.ScrollMarginBlockStartProperty<string | number> | undefined scrollMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollMarginInline?: | csstype.ScrollMarginInlineProperty<string | number> | undefined scrollMarginInlineEnd?: | csstype.ScrollMarginInlineEndProperty<string | number> | undefined scrollMarginInlineStart?: | csstype.ScrollMarginInlineStartProperty<string | number> | undefined scrollMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollPadding?: csstype.ScrollPaddingProperty<string | number> | undefined scrollPaddingBlock?: | csstype.ScrollPaddingBlockProperty<string | number> | undefined scrollPaddingBlockEnd?: | csstype.ScrollPaddingBlockEndProperty<string | number> | undefined scrollPaddingBlockStart?: | csstype.ScrollPaddingBlockStartProperty<string | number> | undefined scrollPaddingBottom?: | csstype.ScrollPaddingBottomProperty<string | number> | undefined scrollPaddingInline?: | csstype.ScrollPaddingInlineProperty<string | number> | undefined scrollPaddingInlineEnd?: | csstype.ScrollPaddingInlineEndProperty<string | number> | undefined scrollPaddingInlineStart?: | csstype.ScrollPaddingInlineStartProperty<string | number> | undefined scrollPaddingLeft?: | csstype.ScrollPaddingLeftProperty<string | number> | undefined scrollPaddingRight?: | csstype.ScrollPaddingRightProperty<string | number> | undefined scrollPaddingTop?: | csstype.ScrollPaddingTopProperty<string | number> | undefined scrollSnapAlign?: string | undefined scrollSnapMargin?: csstype.ScrollMarginProperty<string | number> | undefined scrollSnapMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollSnapMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollSnapMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollSnapMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollSnapStop?: csstype.ScrollSnapStopProperty | undefined scrollSnapType?: string | undefined scrollbarColor?: string | undefined scrollbarGutter?: string | undefined scrollbarWidth?: csstype.ScrollbarWidthProperty | undefined shapeImageThreshold?: csstype.ShapeImageThresholdProperty | undefined shapeMargin?: csstype.ShapeMarginProperty<string | number> | undefined shapeOutside?: string | undefined tabSize?: csstype.TabSizeProperty<string | number> | undefined tableLayout?: csstype.TableLayoutProperty | undefined textAlign?: csstype.TextAlignProperty | undefined textAlignLast?: csstype.TextAlignLastProperty | undefined textCombineUpright?: string | undefined textDecorationColor?: string | undefined textDecorationLine?: string | undefined textDecorationSkip?: string | undefined textDecorationSkipInk?: csstype.TextDecorationSkipInkProperty | undefined textDecorationStyle?: csstype.TextDecorationStyleProperty | undefined textDecorationThickness?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textDecorationWidth?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textEmphasisColor?: string | undefined textEmphasisPosition?: string | undefined textEmphasisStyle?: string | undefined textIndent?: csstype.TextIndentProperty<string | number> | undefined textJustify?: csstype.TextJustifyProperty | undefined textOrientation?: csstype.TextOrientationProperty | undefined textOverflow?: string | undefined textRendering?: csstype.TextRenderingProperty | undefined textShadow?: string | undefined textSizeAdjust?: string | undefined textTransform?: csstype.TextTransformProperty | undefined textUnderlineOffset?: | csstype.TextUnderlineOffsetProperty<string | number> | undefined textUnderlinePosition?: string | undefined top?: csstype.TopProperty<string | number> | undefined touchAction?: string | undefined transitionDelay?: string | undefined transitionDuration?: string | undefined transitionProperty?: string | undefined transitionTimingFunction?: string | undefined translate?: csstype.TranslateProperty<string | number> | undefined unicodeBidi?: csstype.UnicodeBidiProperty | undefined userSelect?: csstype.UserSelectProperty | undefined verticalAlign?: csstype.VerticalAlignProperty<string | number> | undefined visibility?: csstype.VisibilityProperty | undefined whiteSpace?: csstype.WhiteSpaceProperty | undefined widows?: csstype.GlobalsNumber | undefined width?: csstype.WidthProperty<string | number> | undefined willChange?: string | undefined wordBreak?: csstype.WordBreakProperty | undefined wordSpacing?: csstype.WordSpacingProperty<string | number> | undefined wordWrap?: csstype.WordWrapProperty | undefined writingMode?: csstype.WritingModeProperty | undefined zIndex?: csstype.ZIndexProperty | undefined zoom?: csstype.ZoomProperty | undefined all?: csstype.Globals | undefined animation?: csstype.AnimationProperty | undefined background?: csstype.BackgroundProperty<string | number> | undefined backgroundPosition?: | csstype.BackgroundPositionProperty<string | number> | undefined border?: csstype.BorderProperty<string | number> | undefined borderBlock?: csstype.BorderBlockProperty<string | number> | undefined borderBlockEnd?: csstype.BorderBlockEndProperty<string | number> | undefined borderBlockStart?: | csstype.BorderBlockStartProperty<string | number> | undefined borderBottom?: csstype.BorderBottomProperty<string | number> | undefined borderColor?: string | undefined borderImage?: csstype.BorderImageProperty | undefined borderInline?: csstype.BorderInlineProperty<string | number> | undefined borderInlineEnd?: | csstype.BorderInlineEndProperty<string | number> | undefined borderInlineStart?: | csstype.BorderInlineStartProperty<string | number> | undefined borderLeft?: csstype.BorderLeftProperty<string | number> | undefined borderRadius?: csstype.BorderRadiusProperty<string | number> | undefined borderRight?: csstype.BorderRightProperty<string | number> | undefined borderStyle?: string | undefined borderTop?: csstype.BorderTopProperty<string | number> | undefined borderWidth?: csstype.BorderWidthProperty<string | number> | undefined columnRule?: csstype.ColumnRuleProperty<string | number> | undefined columns?: csstype.ColumnsProperty<string | number> | undefined flex?: csstype.FlexProperty<string | number> | undefined flexFlow?: string | undefined font?: string | undefined gap?: csstype.GapProperty<string | number> | undefined grid?: string | undefined gridArea?: csstype.GridAreaProperty | undefined gridColumn?: csstype.GridColumnProperty | undefined gridRow?: csstype.GridRowProperty | undefined gridTemplate?: string | undefined lineClamp?: csstype.LineClampProperty | undefined listStyle?: string | undefined margin?: csstype.MarginProperty<string | number> | undefined mask?: csstype.MaskProperty<string | number> | undefined maskBorder?: csstype.MaskBorderProperty | undefined motion?: csstype.OffsetProperty<string | number> | undefined offset?: csstype.OffsetProperty<string | number> | undefined outline?: csstype.OutlineProperty<string | number> | undefined overflow?: string | undefined overscrollBehavior?: string | undefined padding?: csstype.PaddingProperty<string | number> | undefined placeItems?: string | undefined placeSelf?: string | undefined textDecoration?: csstype.TextDecorationProperty<string | number> | undefined textEmphasis?: string | undefined MozAnimationDelay?: string | undefined MozAnimationDirection?: string | undefined MozAnimationDuration?: string | undefined MozAnimationFillMode?: string | undefined MozAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined MozAnimationName?: string | undefined MozAnimationPlayState?: string | undefined MozAnimationTimingFunction?: string | undefined MozAppearance?: csstype.MozAppearanceProperty | undefined MozBackfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined MozBorderBottomColors?: string | undefined MozBorderEndColor?: string | undefined MozBorderEndStyle?: csstype.BorderInlineEndStyleProperty | undefined MozBorderEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined MozBorderLeftColors?: string | undefined MozBorderRightColors?: string | undefined MozBorderStartColor?: string | undefined MozBorderStartStyle?: csstype.BorderInlineStartStyleProperty | undefined MozBorderTopColors?: string | undefined MozBoxSizing?: csstype.BoxSizingProperty | undefined MozColumnCount?: csstype.ColumnCountProperty | undefined MozColumnFill?: csstype.ColumnFillProperty | undefined MozColumnGap?: csstype.ColumnGapProperty<string | number> | undefined MozColumnRuleColor?: string | undefined MozColumnRuleStyle?: string | undefined MozColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined MozColumnWidth?: csstype.ColumnWidthProperty<string | number> | undefined MozContextProperties?: string | undefined MozFontFeatureSettings?: string | undefined MozFontLanguageOverride?: string | undefined MozHyphens?: csstype.HyphensProperty | undefined MozImageRegion?: string | undefined MozMarginEnd?: csstype.MarginInlineEndProperty<string | number> | undefined MozMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined MozOrient?: csstype.MozOrientProperty | undefined MozOsxFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined MozPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined MozPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined MozPerspective?: csstype.PerspectiveProperty<string | number> | undefined MozPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined MozStackSizing?: csstype.MozStackSizingProperty | undefined MozTabSize?: csstype.TabSizeProperty<string | number> | undefined MozTextBlink?: csstype.MozTextBlinkProperty | undefined MozTextSizeAdjust?: string | undefined MozTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined MozTransformStyle?: csstype.TransformStyleProperty | undefined MozTransitionDelay?: string | undefined MozTransitionDuration?: string | undefined MozTransitionProperty?: string | undefined MozTransitionTimingFunction?: string | undefined MozUserFocus?: csstype.MozUserFocusProperty | undefined MozUserModify?: csstype.MozUserModifyProperty | undefined MozUserSelect?: csstype.UserSelectProperty | undefined MozWindowDragging?: csstype.MozWindowDraggingProperty | undefined MozWindowShadow?: csstype.MozWindowShadowProperty | undefined msAccelerator?: csstype.MsAcceleratorProperty | undefined msAlignSelf?: string | undefined msBlockProgression?: csstype.MsBlockProgressionProperty | undefined msContentZoomChaining?: csstype.MsContentZoomChainingProperty | undefined msContentZoomLimitMax?: string | undefined msContentZoomLimitMin?: string | undefined msContentZoomSnapPoints?: string | undefined msContentZoomSnapType?: csstype.MsContentZoomSnapTypeProperty | undefined msContentZooming?: csstype.MsContentZoomingProperty | undefined msFilter?: string | undefined msFlexDirection?: csstype.FlexDirectionProperty | undefined msFlexPositive?: csstype.GlobalsNumber | undefined msFlowFrom?: string | undefined msFlowInto?: string | undefined msGridColumns?: csstype.MsGridColumnsProperty<string | number> | undefined msGridRows?: csstype.MsGridRowsProperty<string | number> | undefined msHighContrastAdjust?: csstype.MsHighContrastAdjustProperty | undefined msHyphenateLimitChars?: csstype.MsHyphenateLimitCharsProperty | undefined msHyphenateLimitLines?: csstype.MsHyphenateLimitLinesProperty | undefined msHyphenateLimitZone?: | csstype.MsHyphenateLimitZoneProperty<string | number> | undefined msHyphens?: csstype.HyphensProperty | undefined msImeAlign?: csstype.MsImeAlignProperty | undefined msJustifySelf?: string | undefined msLineBreak?: csstype.LineBreakProperty | undefined msOrder?: csstype.GlobalsNumber | undefined msOverflowStyle?: csstype.MsOverflowStyleProperty | undefined msOverflowX?: csstype.OverflowXProperty | undefined msOverflowY?: csstype.OverflowYProperty | undefined msScrollChaining?: csstype.MsScrollChainingProperty | undefined msScrollLimitXMax?: | csstype.MsScrollLimitXMaxProperty<string | number> | undefined msScrollLimitXMin?: | csstype.MsScrollLimitXMinProperty<string | number> | undefined msScrollLimitYMax?: | csstype.MsScrollLimitYMaxProperty<string | number> | undefined msScrollLimitYMin?: | csstype.MsScrollLimitYMinProperty<string | number> | undefined msScrollRails?: csstype.MsScrollRailsProperty | undefined msScrollSnapPointsX?: string | undefined msScrollSnapPointsY?: string | undefined msScrollSnapType?: csstype.MsScrollSnapTypeProperty | undefined msScrollTranslation?: csstype.MsScrollTranslationProperty | undefined msScrollbar3dlightColor?: string | undefined msScrollbarArrowColor?: string | undefined msScrollbarBaseColor?: string | undefined msScrollbarDarkshadowColor?: string | undefined msScrollbarFaceColor?: string | undefined msScrollbarHighlightColor?: string | undefined msScrollbarShadowColor?: string | undefined msTextAutospace?: csstype.MsTextAutospaceProperty | undefined msTextCombineHorizontal?: string | undefined msTextOverflow?: string | undefined msTouchAction?: string | undefined msTouchSelect?: csstype.MsTouchSelectProperty | undefined msTransform?: string | undefined msTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined msTransitionDelay?: string | undefined msTransitionDuration?: string | undefined msTransitionProperty?: string | undefined msTransitionTimingFunction?: string | undefined msUserSelect?: csstype.MsUserSelectProperty | undefined msWordBreak?: csstype.WordBreakProperty | undefined msWrapFlow?: csstype.MsWrapFlowProperty | undefined msWrapMargin?: csstype.MsWrapMarginProperty<string | number> | undefined msWrapThrough?: csstype.MsWrapThroughProperty | undefined msWritingMode?: csstype.WritingModeProperty | undefined WebkitAlignContent?: string | undefined WebkitAlignItems?: string | undefined WebkitAlignSelf?: string | undefined WebkitAnimationDelay?: string | undefined WebkitAnimationDirection?: string | undefined WebkitAnimationDuration?: string | undefined WebkitAnimationFillMode?: string | undefined WebkitAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined WebkitAnimationName?: string | undefined WebkitAnimationPlayState?: string | undefined WebkitAnimationTimingFunction?: string | undefined WebkitAppearance?: csstype.WebkitAppearanceProperty | undefined WebkitBackdropFilter?: string | undefined WebkitBackfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined WebkitBackgroundClip?: string | undefined WebkitBackgroundOrigin?: string | undefined WebkitBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined WebkitBorderBeforeColor?: string | undefined WebkitBorderBeforeStyle?: string | undefined WebkitBorderBeforeWidth?: | csstype.WebkitBorderBeforeWidthProperty<string | number> | undefined WebkitBorderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined WebkitBorderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined WebkitBorderImageSlice?: csstype.BorderImageSliceProperty | undefined WebkitBorderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined WebkitBorderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined WebkitBoxDecorationBreak?: csstype.BoxDecorationBreakProperty | undefined WebkitBoxReflect?: | csstype.WebkitBoxReflectProperty<string | number> | undefined WebkitBoxShadow?: string | undefined WebkitBoxSizing?: csstype.BoxSizingProperty | undefined WebkitClipPath?: string | undefined WebkitColumnCount?: csstype.ColumnCountProperty | undefined WebkitColumnFill?: csstype.ColumnFillProperty | undefined WebkitColumnGap?: csstype.ColumnGapProperty<string | number> | undefined WebkitColumnRuleColor?: string | undefined WebkitColumnRuleStyle?: string | undefined WebkitColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined WebkitColumnSpan?: csstype.ColumnSpanProperty | undefined WebkitColumnWidth?: csstype.ColumnWidthProperty<string | number> | undefined WebkitFilter?: string | undefined WebkitFlexBasis?: csstype.FlexBasisProperty<string | number> | undefined WebkitFlexDirection?: csstype.FlexDirectionProperty | undefined WebkitFlexGrow?: csstype.GlobalsNumber | undefined WebkitFlexShrink?: csstype.GlobalsNumber | undefined WebkitFlexWrap?: csstype.FlexWrapProperty | undefined WebkitFontFeatureSettings?: string | undefined WebkitFontKerning?: csstype.FontKerningProperty | undefined WebkitFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined WebkitFontVariantLigatures?: string | undefined WebkitHyphens?: csstype.HyphensProperty | undefined WebkitJustifyContent?: string | undefined WebkitLineBreak?: csstype.LineBreakProperty | undefined WebkitLineClamp?: csstype.WebkitLineClampProperty | undefined WebkitMarginEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined WebkitMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined WebkitMaskAttachment?: string | undefined WebkitMaskBoxImageOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined WebkitMaskBoxImageRepeat?: string | undefined WebkitMaskBoxImageSlice?: csstype.MaskBorderSliceProperty | undefined WebkitMaskBoxImageSource?: string | undefined WebkitMaskBoxImageWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined WebkitMaskClip?: string | undefined WebkitMaskComposite?: string | undefined WebkitMaskImage?: string | undefined WebkitMaskOrigin?: string | undefined WebkitMaskPosition?: | csstype.WebkitMaskPositionProperty<string | number> | undefined WebkitMaskPositionX?: | csstype.WebkitMaskPositionXProperty<string | number> | undefined WebkitMaskPositionY?: | csstype.WebkitMaskPositionYProperty<string | number> | undefined WebkitMaskRepeat?: string | undefined WebkitMaskRepeatX?: csstype.WebkitMaskRepeatXProperty | undefined WebkitMaskRepeatY?: csstype.WebkitMaskRepeatYProperty | undefined WebkitMaskSize?: csstype.WebkitMaskSizeProperty<string | number> | undefined WebkitMaxInlineSize?: | csstype.MaxInlineSizeProperty<string | number> | undefined WebkitOrder?: csstype.GlobalsNumber | undefined WebkitOverflowScrolling?: | csstype.WebkitOverflowScrollingProperty | undefined WebkitPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined WebkitPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined WebkitPerspective?: csstype.PerspectiveProperty<string | number> | undefined WebkitPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined WebkitPrintColorAdjust?: csstype.ColorAdjustProperty | undefined WebkitRubyPosition?: string | undefined WebkitScrollSnapType?: string | undefined WebkitShapeMargin?: csstype.ShapeMarginProperty<string | number> | undefined WebkitTapHighlightColor?: string | undefined WebkitTextCombine?: string | undefined WebkitTextDecorationColor?: string | undefined WebkitTextDecorationLine?: string | undefined WebkitTextDecorationSkip?: string | undefined WebkitTextDecorationStyle?: csstype.TextDecorationStyleProperty | undefined WebkitTextEmphasisColor?: string | undefined WebkitTextEmphasisPosition?: string | undefined WebkitTextEmphasisStyle?: string | undefined WebkitTextFillColor?: string | undefined WebkitTextOrientation?: csstype.TextOrientationProperty | undefined WebkitTextSizeAdjust?: string | undefined WebkitTextStrokeColor?: string | undefined WebkitTextStrokeWidth?: | csstype.WebkitTextStrokeWidthProperty<string | number> | undefined WebkitTextUnderlinePosition?: string | undefined WebkitTouchCallout?: csstype.WebkitTouchCalloutProperty | undefined WebkitTransform?: string | undefined WebkitTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined WebkitTransformStyle?: csstype.TransformStyleProperty | undefined WebkitTransitionDelay?: string | undefined WebkitTransitionDuration?: string | undefined WebkitTransitionProperty?: string | undefined WebkitTransitionTimingFunction?: string | undefined WebkitUserModify?: csstype.WebkitUserModifyProperty | undefined WebkitUserSelect?: csstype.UserSelectProperty | undefined WebkitWritingMode?: csstype.WritingModeProperty | undefined MozAnimation?: csstype.AnimationProperty | undefined MozBorderImage?: csstype.BorderImageProperty | undefined MozColumnRule?: csstype.ColumnRuleProperty<string | number> | undefined MozColumns?: csstype.ColumnsProperty<string | number> | undefined MozTransition?: string | undefined msContentZoomLimit?: string | undefined msContentZoomSnap?: string | undefined msFlex?: csstype.FlexProperty<string | number> | undefined msScrollLimit?: string | undefined msScrollSnapX?: string | undefined msScrollSnapY?: string | undefined msTransition?: string | undefined WebkitAnimation?: csstype.AnimationProperty | undefined WebkitBorderBefore?: | csstype.WebkitBorderBeforeProperty<string | number> | undefined WebkitBorderImage?: csstype.BorderImageProperty | undefined WebkitBorderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined WebkitColumnRule?: csstype.ColumnRuleProperty<string | number> | undefined WebkitColumns?: csstype.ColumnsProperty<string | number> | undefined WebkitFlex?: csstype.FlexProperty<string | number> | undefined WebkitFlexFlow?: string | undefined WebkitMask?: csstype.WebkitMaskProperty<string | number> | undefined WebkitMaskBoxImage?: csstype.MaskBorderProperty | undefined WebkitTextEmphasis?: string | undefined WebkitTextStroke?: | csstype.WebkitTextStrokeProperty<string | number> | undefined WebkitTransition?: string | undefined azimuth?: string | undefined boxAlign?: csstype.BoxAlignProperty | undefined boxDirection?: csstype.BoxDirectionProperty | undefined boxFlex?: csstype.GlobalsNumber | undefined boxFlexGroup?: csstype.GlobalsNumber | undefined boxLines?: csstype.BoxLinesProperty | undefined boxOrdinalGroup?: csstype.GlobalsNumber | undefined boxOrient?: csstype.BoxOrientProperty | undefined boxPack?: csstype.BoxPackProperty | undefined clip?: string | undefined fontVariantAlternates?: string | undefined gridColumnGap?: csstype.GridColumnGapProperty<string | number> | undefined gridGap?: csstype.GridGapProperty<string | number> | undefined gridRowGap?: csstype.GridRowGapProperty<string | number> | undefined imeMode?: csstype.ImeModeProperty | undefined offsetBlock?: csstype.InsetBlockProperty<string | number> | undefined offsetBlockEnd?: csstype.InsetBlockEndProperty<string | number> | undefined offsetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined offsetInline?: csstype.InsetInlineProperty<string | number> | undefined offsetInlineEnd?: | csstype.InsetInlineEndProperty<string | number> | undefined offsetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined scrollSnapCoordinate?: | csstype.ScrollSnapCoordinateProperty<string | number> | undefined scrollSnapDestination?: | csstype.ScrollSnapDestinationProperty<string | number> | undefined scrollSnapPointsX?: string | undefined scrollSnapPointsY?: string | undefined scrollSnapTypeX?: csstype.ScrollSnapTypeXProperty | undefined scrollSnapTypeY?: csstype.ScrollSnapTypeYProperty | undefined scrollbarTrackColor?: string | undefined KhtmlBoxAlign?: csstype.BoxAlignProperty | undefined KhtmlBoxDirection?: csstype.BoxDirectionProperty | undefined KhtmlBoxFlex?: csstype.GlobalsNumber | undefined KhtmlBoxFlexGroup?: csstype.GlobalsNumber | undefined KhtmlBoxLines?: csstype.BoxLinesProperty | undefined KhtmlBoxOrdinalGroup?: csstype.GlobalsNumber | undefined KhtmlBoxOrient?: csstype.BoxOrientProperty | undefined KhtmlBoxPack?: csstype.BoxPackProperty | undefined KhtmlLineBreak?: csstype.LineBreakProperty | undefined KhtmlOpacity?: csstype.OpacityProperty | undefined KhtmlUserSelect?: csstype.UserSelectProperty | undefined MozBackgroundClip?: string | undefined MozBackgroundInlinePolicy?: csstype.BoxDecorationBreakProperty | undefined MozBackgroundOrigin?: string | undefined MozBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined MozBinding?: string | undefined MozBorderRadius?: csstype.BorderRadiusProperty<string | number> | undefined MozBorderRadiusBottomleft?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined MozBorderRadiusBottomright?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined MozBorderRadiusTopleft?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined MozBorderRadiusTopright?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined MozBoxAlign?: csstype.BoxAlignProperty | undefined MozBoxDirection?: csstype.BoxDirectionProperty | undefined MozBoxFlex?: csstype.GlobalsNumber | undefined MozBoxOrdinalGroup?: csstype.GlobalsNumber | undefined MozBoxOrient?: csstype.BoxOrientProperty | undefined MozBoxPack?: csstype.BoxPackProperty | undefined MozBoxShadow?: string | undefined MozFloatEdge?: csstype.MozFloatEdgeProperty | undefined MozForceBrokenImageIcon?: csstype.GlobalsNumber | undefined MozOpacity?: csstype.OpacityProperty | undefined MozOutline?: csstype.OutlineProperty<string | number> | undefined MozOutlineColor?: string | undefined MozOutlineRadius?: | csstype.MozOutlineRadiusProperty<string | number> | undefined MozOutlineRadiusBottomleft?: | csstype.MozOutlineRadiusBottomleftProperty<string | number> | undefined MozOutlineRadiusBottomright?: | csstype.MozOutlineRadiusBottomrightProperty<string | number> | undefined MozOutlineRadiusTopleft?: | csstype.MozOutlineRadiusTopleftProperty<string | number> | undefined MozOutlineRadiusTopright?: | csstype.MozOutlineRadiusToprightProperty<string | number> | undefined MozOutlineStyle?: string | undefined MozOutlineWidth?: csstype.OutlineWidthProperty<string | number> | undefined MozTextAlignLast?: csstype.TextAlignLastProperty | undefined MozTextDecorationColor?: string | undefined MozTextDecorationLine?: string | undefined MozTextDecorationStyle?: csstype.TextDecorationStyleProperty | undefined MozUserInput?: csstype.MozUserInputProperty | undefined msImeMode?: csstype.ImeModeProperty | undefined msScrollbarTrackColor?: string | undefined OAnimation?: csstype.AnimationProperty | undefined OAnimationDelay?: string | undefined OAnimationDirection?: string | undefined OAnimationDuration?: string | undefined OAnimationFillMode?: string | undefined OAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined OAnimationName?: string | undefined OAnimationPlayState?: string | undefined OAnimationTimingFunction?: string | undefined OBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined OBorderImage?: csstype.BorderImageProperty | undefined OObjectFit?: csstype.ObjectFitProperty | undefined OObjectPosition?: | csstype.ObjectPositionProperty<string | number> | undefined OTabSize?: csstype.TabSizeProperty<string | number> | undefined OTextOverflow?: string | undefined OTransform?: string | undefined OTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined OTransition?: string | undefined OTransitionDelay?: string | undefined OTransitionDuration?: string | undefined OTransitionProperty?: string | undefined OTransitionTimingFunction?: string | undefined WebkitBoxAlign?: csstype.BoxAlignProperty | undefined WebkitBoxDirection?: csstype.BoxDirectionProperty | undefined WebkitBoxFlex?: csstype.GlobalsNumber | undefined WebkitBoxFlexGroup?: csstype.GlobalsNumber | undefined WebkitBoxLines?: csstype.BoxLinesProperty | undefined WebkitBoxOrdinalGroup?: csstype.GlobalsNumber | undefined WebkitBoxOrient?: csstype.BoxOrientProperty | undefined WebkitBoxPack?: csstype.BoxPackProperty | undefined WebkitScrollSnapPointsX?: string | undefined WebkitScrollSnapPointsY?: string | undefined alignmentBaseline?: csstype.AlignmentBaselineProperty | undefined baselineShift?: csstype.BaselineShiftProperty<string | number> | undefined clipRule?: csstype.ClipRuleProperty | undefined colorInterpolation?: csstype.ColorInterpolationProperty | undefined colorRendering?: csstype.ColorRenderingProperty | undefined dominantBaseline?: csstype.DominantBaselineProperty | undefined fill?: string | undefined fillOpacity?: csstype.GlobalsNumber | undefined fillRule?: csstype.FillRuleProperty | undefined floodColor?: string | undefined floodOpacity?: csstype.GlobalsNumber | undefined glyphOrientationVertical?: | csstype.GlyphOrientationVerticalProperty | undefined lightingColor?: string | undefined marker?: string | undefined markerEnd?: string | undefined markerMid?: string | undefined markerStart?: string | undefined shapeRendering?: csstype.ShapeRenderingProperty | undefined stopColor?: string | undefined stopOpacity?: csstype.GlobalsNumber | undefined stroke?: string | undefined strokeDasharray?: | csstype.StrokeDasharrayProperty<string | number> | undefined strokeDashoffset?: | csstype.StrokeDashoffsetProperty<string | number> | undefined strokeLinecap?: csstype.StrokeLinecapProperty | undefined strokeLinejoin?: csstype.StrokeLinejoinProperty | undefined strokeMiterlimit?: csstype.GlobalsNumber | undefined strokeOpacity?: csstype.GlobalsNumber | undefined strokeWidth?: csstype.StrokeWidthProperty<string | number> | undefined textAnchor?: csstype.TextAnchorProperty | undefined vectorEffect?: csstype.VectorEffectProperty | undefined } stop: () => void } /** * A Composable giving access to a TransformProperties object, and binding the generated transform string to a target. * * @param target */ declare function useElementTransform( target: MaybeRef<PermissiveTarget>, onInit?: (initData: Partial<TransformProperties>) => void, ): { transform: { x?: string | number | undefined y?: string | number | undefined z?: string | number | undefined translateX?: string | number | undefined translateY?: string | number | undefined translateZ?: string | number | undefined rotate?: string | number | undefined rotateX?: string | number | undefined rotateY?: string | number | undefined rotateZ?: string | number | undefined scale?: string | number | undefined scaleX?: string | number | undefined scaleY?: string | number | undefined scaleZ?: string | number | undefined skew?: string | number | undefined skewX?: string | number | undefined skewY?: string | number | undefined originX?: string | number | undefined originY?: string | number | undefined originZ?: string | number | undefined perspective?: string | number | undefined transformPerspective?: string | number | undefined } stop: () => void } /** * A Vue Composable that put your components in motion. * * @docs https://motion.vueuse.js.org * * @param target * @param variants * @param options */ declare function useMotion<T extends MotionVariants>( target: MaybeRef<PermissiveTarget>, variants?: MaybeRef<T>, options?: UseMotionOptions, ): MotionInstance<T> /** * A Composable handling motion controls, pushing resolved variant to useMotionTransitions manager. * * @param transform * @param style * @param currentVariant */ declare function useMotionControls<T extends MotionVariants>( motionProperties: MotionProperties, variants?: MaybeRef<T>, { push, stop }?: MotionTransitions, ): MotionControls /** * A Composable giving access to both `transform` and `style`objects for a single element. * * @param target */ declare function useMotionProperties( target: MaybeRef<PermissiveTarget>, defaultValues?: Partial<MotionProperties>, ): { motionProperties: | { alignContent?: string | undefined alignItems?: string | undefined alignSelf?: string | undefined alignTracks?: string | undefined animationDelay?: string | undefined animationDirection?: string | undefined animationDuration?: string | undefined animationFillMode?: string | undefined animationIterationCount?: | csstype.AnimationIterationCountProperty | undefined animationName?: string | undefined animationPlayState?: string | undefined animationTimingFunction?: string | undefined appearance?: csstype.AppearanceProperty | undefined aspectRatio?: string | undefined backdropFilter?: string | undefined backfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined backgroundAttachment?: string | undefined backgroundBlendMode?: string | undefined backgroundClip?: string | undefined backgroundColor?: string | undefined backgroundImage?: string | undefined backgroundOrigin?: string | undefined backgroundPositionX?: | csstype.BackgroundPositionXProperty<string | number> | undefined backgroundPositionY?: | csstype.BackgroundPositionYProperty<string | number> | undefined backgroundRepeat?: string | undefined backgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined blockOverflow?: string | undefined blockSize?: csstype.BlockSizeProperty<string | number> | undefined borderBlockColor?: string | undefined borderBlockEndColor?: string | undefined borderBlockEndStyle?: csstype.BorderBlockEndStyleProperty | undefined borderBlockEndWidth?: | csstype.BorderBlockEndWidthProperty<string | number> | undefined borderBlockStartColor?: string | undefined borderBlockStartStyle?: | csstype.BorderBlockStartStyleProperty | undefined borderBlockStartWidth?: | csstype.BorderBlockStartWidthProperty<string | number> | undefined borderBlockStyle?: csstype.BorderBlockStyleProperty | undefined borderBlockWidth?: | csstype.BorderBlockWidthProperty<string | number> | undefined borderBottomColor?: string | undefined borderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined borderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined borderBottomStyle?: csstype.BorderBottomStyleProperty | undefined borderBottomWidth?: | csstype.BorderBottomWidthProperty<string | number> | undefined borderCollapse?: csstype.BorderCollapseProperty | undefined borderEndEndRadius?: | csstype.BorderEndEndRadiusProperty<string | number> | undefined borderEndStartRadius?: | csstype.BorderEndStartRadiusProperty<string | number> | undefined borderImageOutset?: | csstype.BorderImageOutsetProperty<string | number> | undefined borderImageRepeat?: string | undefined borderImageSlice?: csstype.BorderImageSliceProperty | undefined borderImageSource?: string | undefined borderImageWidth?: | csstype.BorderImageWidthProperty<string | number> | undefined borderInlineColor?: string | undefined borderInlineEndColor?: string | undefined borderInlineEndStyle?: csstype.BorderInlineEndStyleProperty | undefined borderInlineEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined borderInlineStartColor?: string | undefined borderInlineStartStyle?: | csstype.BorderInlineStartStyleProperty | undefined borderInlineStartWidth?: | csstype.BorderInlineStartWidthProperty<string | number> | undefined borderInlineStyle?: csstype.BorderInlineStyleProperty | undefined borderInlineWidth?: | csstype.BorderInlineWidthProperty<string | number> | undefined borderLeftColor?: string | undefined borderLeftStyle?: csstype.BorderLeftStyleProperty | undefined borderLeftWidth?: | csstype.BorderLeftWidthProperty<string | number> | undefined borderRightColor?: string | undefined borderRightStyle?: csstype.BorderRightStyleProperty | undefined borderRightWidth?: | csstype.BorderRightWidthProperty<string | number> | undefined borderSpacing?: | csstype.BorderSpacingProperty<string | number> | undefined borderStartEndRadius?: | csstype.BorderStartEndRadiusProperty<string | number> | undefined borderStartStartRadius?: | csstype.BorderStartStartRadiusProperty<string | number> | undefined borderTopColor?: string | undefined borderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined borderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined borderTopStyle?: csstype.BorderTopStyleProperty | undefined borderTopWidth?: | csstype.BorderTopWidthProperty<string | number> | undefined bottom?: csstype.BottomProperty<string | number> | undefined boxDecorationBreak?: csstype.BoxDecorationBreakProperty | undefined boxShadow?: string | undefined boxSizing?: csstype.BoxSizingProperty | undefined breakAfter?: csstype.BreakAfterProperty | undefined breakBefore?: csstype.BreakBeforeProperty | undefined breakInside?: csstype.BreakInsideProperty | undefined captionSide?: csstype.CaptionSideProperty | undefined caretColor?: string | undefined clear?: csstype.ClearProperty | undefined clipPath?: string | undefined color?: string | undefined colorAdjust?: csstype.ColorAdjustProperty | undefined colorScheme?: string | undefined columnCount?: csstype.ColumnCountProperty | undefined columnFill?: csstype.ColumnFillProperty | undefined columnGap?: csstype.ColumnGapProperty<string | number> | undefined columnRuleColor?: string | undefined columnRuleStyle?: string | undefined columnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined columnSpan?: csstype.ColumnSpanProperty | undefined columnWidth?: csstype.ColumnWidthProperty<string | number> | undefined contain?: string | undefined content?: string | undefined contentVisibility?: csstype.ContentVisibilityProperty | undefined counterIncrement?: string | undefined counterReset?: string | undefined counterSet?: string | undefined cursor?: string | undefined direction?: csstype.DirectionProperty | undefined display?: string | undefined emptyCells?: csstype.EmptyCellsProperty | undefined filter?: string | undefined flexBasis?: csstype.FlexBasisProperty<string | number> | undefined flexDirection?: csstype.FlexDirectionProperty | undefined flexGrow?: csstype.GlobalsNumber | undefined flexShrink?: csstype.GlobalsNumber | undefined flexWrap?: csstype.FlexWrapProperty | undefined float?: csstype.FloatProperty | undefined fontFamily?: string | undefined fontFeatureSettings?: string | undefined fontKerning?: csstype.FontKerningProperty | undefined fontLanguageOverride?: string | undefined fontOpticalSizing?: csstype.FontOpticalSizingProperty | undefined fontSize?: csstype.FontSizeProperty<string | number> | undefined fontSizeAdjust?: csstype.FontSizeAdjustProperty | undefined fontSmooth?: csstype.FontSmoothProperty<string | number> | undefined fontStretch?: string | undefined fontStyle?: string | undefined fontSynthesis?: string | undefined fontVariant?: string | undefined fontVariantCaps?: csstype.FontVariantCapsProperty | undefined fontVariantEastAsian?: string | undefined fontVariantLigatures?: string | undefined fontVariantNumeric?: string | undefined fontVariantPosition?: csstype.FontVariantPositionProperty | undefined fontVariationSettings?: string | undefined fontWeight?: csstype.FontWeightProperty | undefined forcedColorAdjust?: csstype.ForcedColorAdjustProperty | undefined gridAutoColumns?: | csstype.GridAutoColumnsProperty<string | number> | undefined gridAutoFlow?: string | undefined gridAutoRows?: csstype.GridAutoRowsProperty<string | number> | undefined gridColumnEnd?: csstype.GridColumnEndProperty | undefined gridColumnStart?: csstype.GridColumnStartProperty | undefined gridRowEnd?: csstype.GridRowEndProperty | undefined gridRowStart?: csstype.GridRowStartProperty | undefined gridTemplateAreas?: string | undefined gridTemplateColumns?: | csstype.GridTemplateColumnsProperty<string | number> | undefined gridTemplateRows?: | csstype.GridTemplateRowsProperty<string | number> | undefined hangingPunctuation?: string | undefined height?: csstype.HeightProperty<string | number> | undefined hyphens?: csstype.HyphensProperty | undefined imageOrientation?: string | undefined imageRendering?: csstype.ImageRenderingProperty | undefined imageResolution?: string | undefined initialLetter?: csstype.InitialLetterProperty | undefined inlineSize?: csstype.InlineSizeProperty<string | number> | undefined inset?: csstype.InsetProperty<string | number> | undefined insetBlock?: csstype.InsetBlockProperty<string | number> | undefined insetBlockEnd?: | csstype.InsetBlockEndProperty<string | number> | undefined insetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined insetInline?: csstype.InsetInlineProperty<string | number> | undefined insetInlineEnd?: | csstype.InsetInlineEndProperty<string | number> | undefined insetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined isolation?: csstype.IsolationProperty | undefined justifyContent?: string | undefined justifyItems?: string | undefined justifySelf?: string | undefined justifyTracks?: string | undefined left?: csstype.LeftProperty<string | number> | undefined letterSpacing?: | csstype.LetterSpacingProperty<string | number> | undefined lineBreak?: csstype.LineBreakProperty | undefined lineHeight?: csstype.LineHeightProperty<string | number> | undefined lineHeightStep?: | csstype.LineHeightStepProperty<string | number> | undefined listStyleImage?: string | undefined listStylePosition?: csstype.ListStylePositionProperty | undefined listStyleType?: string | undefined marginBlock?: csstype.MarginBlockProperty<string | number> | undefined marginBlockEnd?: | csstype.MarginBlockEndProperty<string | number> | undefined marginBlockStart?: | csstype.MarginBlockStartProperty<string | number> | undefined marginBottom?: csstype.MarginBottomProperty<string | number> | undefined marginInline?: csstype.MarginInlineProperty<string | number> | undefined marginInlineEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined marginInlineStart?: | csstype.MarginInlineStartProperty<string | number> | undefined marginLeft?: csstype.MarginLeftProperty<string | number> | undefined marginRight?: csstype.MarginRightProperty<string | number> | undefined marginTop?: csstype.MarginTopProperty<string | number> | undefined maskBorderMode?: csstype.MaskBorderModeProperty | undefined maskBorderOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined maskBorderRepeat?: string | undefined maskBorderSlice?: csstype.MaskBorderSliceProperty | undefined maskBorderSource?: string | undefined maskBorderWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined maskClip?: string | undefined maskComposite?: string | undefined maskImage?: string | undefined maskMode?: string | undefined maskOrigin?: string | undefined maskPosition?: csstype.MaskPositionProperty<string | number> | undefined maskRepeat?: string | undefined maskSize?: csstype.MaskSizeProperty<string | number> | undefined maskType?: csstype.MaskTypeProperty | undefined mathStyle?: csstype.MathStyleProperty | undefined maxBlockSize?: csstype.MaxBlockSizeProperty<string | number> | undefined maxHeight?: csstype.MaxHeightProperty<string | number> | undefined maxInlineSize?: | csstype.MaxInlineSizeProperty<string | number> | undefined maxLines?: csstype.MaxLinesProperty | undefined maxWidth?: csstype.MaxWidthProperty<string | number> | undefined minBlockSize?: csstype.MinBlockSizeProperty<string | number> | undefined minHeight?: csstype.MinHeightProperty<string | number> | undefined minInlineSize?: | csstype.MinInlineSizeProperty<string | number> | undefined minWidth?: csstype.MinWidthProperty<string | number> | undefined mixBlendMode?: csstype.MixBlendModeProperty | undefined motionDistance?: | csstype.OffsetDistanceProperty<string | number> | undefined motionPath?: string | undefined motionRotation?: string | undefined objectFit?: csstype.ObjectFitProperty | undefined objectPosition?: | csstype.ObjectPositionProperty<string | number> | undefined offsetAnchor?: csstype.OffsetAnchorProperty<string | number> | undefined offsetDistance?: | csstype.OffsetDistanceProperty<string | number> | undefined offsetPath?: string | undefined offsetRotate?: string | undefined offsetRotation?: string | undefined opacity?: csstype.OpacityProperty | undefined order?: csstype.GlobalsNumber | undefined orphans?: csstype.GlobalsNumber | undefined outlineColor?: string | undefined outlineOffset?: | csstype.OutlineOffsetProperty<string | number> | undefined outlineStyle?: string | undefined outlineWidth?: csstype.OutlineWidthProperty<string | number> | undefined overflowAnchor?: csstype.OverflowAnchorProperty | undefined overflowBlock?: csstype.OverflowBlockProperty | undefined overflowClipBox?: csstype.OverflowClipBoxProperty | undefined overflowClipMargin?: | csstype.OverflowClipMarginProperty<string | number> | undefined overflowInline?: csstype.OverflowInlineProperty | undefined overflowWrap?: csstype.OverflowWrapProperty | undefined overflowX?: csstype.OverflowXProperty | undefined overflowY?: csstype.OverflowYProperty | undefined overscrollBehaviorBlock?: | csstype.OverscrollBehaviorBlockProperty | undefined overscrollBehaviorInline?: | csstype.OverscrollBehaviorInlineProperty | undefined overscrollBehaviorX?: csstype.OverscrollBehaviorXProperty | undefined overscrollBehaviorY?: csstype.OverscrollBehaviorYProperty | undefined paddingBlock?: csstype.PaddingBlockProperty<string | number> | undefined paddingBlockEnd?: | csstype.PaddingBlockEndProperty<string | number> | undefined paddingBlockStart?: | csstype.PaddingBlockStartProperty<string | number> | undefined paddingBottom?: | csstype.PaddingBottomProperty<string | number> | undefined paddingInline?: | csstype.PaddingInlineProperty<string | number> | undefined paddingInlineEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined paddingInlineStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined paddingLeft?: csstype.PaddingLeftProperty<string | number> | undefined paddingRight?: csstype.PaddingRightProperty<string | number> | undefined paddingTop?: csstype.PaddingTopProperty<string | number> | undefined pageBreakAfter?: csstype.PageBreakAfterProperty | undefined pageBreakBefore?: csstype.PageBreakBeforeProperty | undefined pageBreakInside?: csstype.PageBreakInsideProperty | undefined paintOrder?: string | undefined perspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined placeContent?: string | undefined pointerEvents?: csstype.PointerEventsProperty | undefined position?: csstype.PositionProperty | undefined quotes?: string | undefined resize?: csstype.ResizeProperty | undefined right?: csstype.RightProperty<string | number> | undefined rowGap?: csstype.RowGapProperty<string | number> | undefined rubyAlign?: csstype.RubyAlignProperty | undefined rubyMerge?: csstype.RubyMergeProperty | undefined rubyPosition?: string | undefined scrollBehavior?: csstype.ScrollBehaviorProperty | undefined scrollMargin?: csstype.ScrollMarginProperty<string | number> | undefined scrollMarginBlock?: | csstype.ScrollMarginBlockProperty<string | number> | undefined scrollMarginBlockEnd?: | csstype.ScrollMarginBlockEndProperty<string | number> | undefined scrollMarginBlockStart?: | csstype.ScrollMarginBlockStartProperty<string | number> | undefined scrollMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollMarginInline?: | csstype.ScrollMarginInlineProperty<string | number> | undefined scrollMarginInlineEnd?: | csstype.ScrollMarginInlineEndProperty<string | number> | undefined scrollMarginInlineStart?: | csstype.ScrollMarginInlineStartProperty<string | number> | undefined scrollMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollPadding?: | csstype.ScrollPaddingProperty<string | number> | undefined scrollPaddingBlock?: | csstype.ScrollPaddingBlockProperty<string | number> | undefined scrollPaddingBlockEnd?: | csstype.ScrollPaddingBlockEndProperty<string | number> | undefined scrollPaddingBlockStart?: | csstype.ScrollPaddingBlockStartProperty<string | number> | undefined scrollPaddingBottom?: | csstype.ScrollPaddingBottomProperty<string | number> | undefined scrollPaddingInline?: | csstype.ScrollPaddingInlineProperty<string | number> | undefined scrollPaddingInlineEnd?: | csstype.ScrollPaddingInlineEndProperty<string | number> | undefined scrollPaddingInlineStart?: | csstype.ScrollPaddingInlineStartProperty<string | number> | undefined scrollPaddingLeft?: | csstype.ScrollPaddingLeftProperty<string | number> | undefined scrollPaddingRight?: | csstype.ScrollPaddingRightProperty<string | number> | undefined scrollPaddingTop?: | csstype.ScrollPaddingTopProperty<string | number> | undefined scrollSnapAlign?: string | undefined scrollSnapMargin?: | csstype.ScrollMarginProperty<string | number> | undefined scrollSnapMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollSnapMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollSnapMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollSnapMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollSnapStop?: csstype.ScrollSnapStopProperty | undefined scrollSnapType?: string | undefined scrollbarColor?: string | undefined scrollbarGutter?: string | undefined scrollbarWidth?: csstype.ScrollbarWidthProperty | undefined shapeImageThreshold?: csstype.ShapeImageThresholdProperty | undefined shapeMargin?: csstype.ShapeMarginProperty<string | number> | undefined shapeOutside?: string | undefined tabSize?: csstype.TabSizeProperty<string | number> | undefined tableLayout?: csstype.TableLayoutProperty | undefined textAlign?: csstype.TextAlignProperty | undefined textAlignLast?: csstype.TextAlignLastProperty | undefined textCombineUpright?: string | undefined textDecorationColor?: string | undefined textDecorationLine?: string | undefined textDecorationSkip?: string | undefined textDecorationSkipInk?: | csstype.TextDecorationSkipInkProperty | undefined textDecorationStyle?: csstype.TextDecorationStyleProperty | undefined textDecorationThickness?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textDecorationWidth?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textEmphasisColor?: string | undefined textEmphasisPosition?: string | undefined textEmphasisStyle?: string | undefined textIndent?: csstype.TextIndentProperty<string | number> | undefined textJustify?: csstype.TextJustifyProperty | undefined textOrientation?: csstype.TextOrientationProperty | undefined textOverflow?: string | undefined textRendering?: csstype.TextRenderingProperty | undefined textShadow?: string | undefined textSizeAdjust?: string | undefined textTransform?: csstype.TextTransformProperty | undefined textUnderlineOffset?: | csstype.TextUnderlineOffsetProperty<string | number> | undefined textUnderlinePosition?: string | undefined top?: csstype.TopProperty<string | number> | undefined touchAction?: string | undefined transitionDelay?: string | undefined transitionDuration?: string | undefined transitionProperty?: string | undefined transitionTimingFunction?: string | undefined translate?: csstype.TranslateProperty<string | number> | undefined unicodeBidi?: csstype.UnicodeBidiProperty | undefined userSelect?: csstype.UserSelectProperty | undefined verticalAlign?: | csstype.VerticalAlignProperty<string | number> | undefined visibility?: csstype.VisibilityProperty | undefined whiteSpace?: csstype.WhiteSpaceProperty | undefined widows?: csstype.GlobalsNumber | undefined width?: csstype.WidthProperty<string | number> | undefined willChange?: string | undefined wordBreak?: csstype.WordBreakProperty | undefined wordSpacing?: csstype.WordSpacingProperty<string | number> | undefined wordWrap?: csstype.WordWrapProperty | undefined writingMode?: csstype.WritingModeProperty | undefined zIndex?: csstype.ZIndexProperty | undefined zoom?: csstype.ZoomProperty | undefined all?: csstype.Globals | undefined animation?: csstype.AnimationProperty | undefined background?: csstype.BackgroundProperty<string | number> | undefined backgroundPosition?: | csstype.BackgroundPositionProperty<string | number> | undefined border?: csstype.BorderProperty<string | number> | undefined borderBlock?: csstype.BorderBlockProperty<string | number> | undefined borderBlockEnd?: | csstype.BorderBlockEndProperty<string | number> | undefined borderBlockStart?: | csstype.BorderBlockStartProperty<string | number> | undefined borderBottom?: csstype.BorderBottomProperty<string | number> | undefined borderColor?: string | undefined borderImage?: csstype.BorderImageProperty | undefined borderInline?: csstype.BorderInlineProperty<string | number> | undefined borderInlineEnd?: | csstype.BorderInlineEndProperty<string | number> | undefined borderInlineStart?: | csstype.BorderInlineStartProperty<string | number> | undefined borderLeft?: csstype.BorderLeftProperty<string | number> | undefined borderRadius?: csstype.BorderRadiusProperty<string | number> | undefined borderRight?: csstype.BorderRightProperty<string | number> | undefined borderStyle?: string | undefined borderTop?: csstype.BorderTopProperty<string | number> | undefined borderWidth?: csstype.BorderWidthProperty<string | number> | undefined columnRule?: csstype.ColumnRuleProperty<string | number> | undefined columns?: csstype.ColumnsProperty<string | number> | undefined flex?: csstype.FlexProperty<string | number> | undefined flexFlow?: string | undefined font?: string | undefined gap?: csstype.GapProperty<string | number> | undefined grid?: string | undefined gridArea?: csstype.GridAreaProperty | undefined gridColumn?: csstype.GridColumnProperty | undefined gridRow?: csstype.GridRowProperty | undefined gridTemplate?: string | undefined lineClamp?: csstype.LineClampProperty | undefined listStyle?: string | undefined margin?: csstype.MarginProperty<string | number> | undefined mask?: csstype.MaskProperty<string | number> | undefined maskBorder?: csstype.MaskBorderProperty | undefined motion?: csstype.OffsetProperty<string | number> | undefined offset?: csstype.OffsetProperty<string | number> | undefined outline?: csstype.OutlineProperty<string | number> | undefined overflow?: string | undefined overscrollBehavior?: string | undefined padding?: csstype.PaddingProperty<string | number> | undefined placeItems?: string | undefined placeSelf?: string | undefined textDecoration?: | csstype.TextDecorationProperty<string | number> | undefined textEmphasis?: string | undefined MozAnimationDelay?: string | undefined MozAnimationDirection?: string | undefined MozAnimationDuration?: string | undefined MozAnimationFillMode?: string | undefined MozAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined MozAnimationName?: string | undefined MozAnimationPlayState?: string | undefined MozAnimationTimingFunction?: string | undefined MozAppearance?: csstype.MozAppearanceProperty | undefined MozBackfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined MozBorderBottomColors?: string | undefined MozBorderEndColor?: string | undefined MozBorderEndStyle?: csstype.BorderInlineEndStyleProperty | undefined MozBorderEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined MozBorderLeftColors?: string | undefined MozBorderRightColors?: string | undefined MozBorderStartColor?: string | undefined MozBorderStartStyle?: csstype.BorderInlineStartStyleProperty | undefined MozBorderTopColors?: string | undefined MozBoxSizing?: csstype.BoxSizingProperty | undefined MozColumnCount?: csstype.ColumnCountProperty | undefined MozColumnFill?: csstype.ColumnFillProperty | undefined MozColumnGap?: csstype.ColumnGapProperty<string | number> | undefined MozColumnRuleColor?: string | undefined MozColumnRuleStyle?: string | undefined MozColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined MozColumnWidth?: | csstype.ColumnWidthProperty<string | number> | undefined MozContextProperties?: string | undefined MozFontFeatureSettings?: string | undefined MozFontLanguageOverride?: string | undefined MozHyphens?: csstype.HyphensProperty | undefined MozImageRegion?: string | undefined MozMarginEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined MozMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined MozOrient?: csstype.MozOrientProperty | undefined MozOsxFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined MozPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined MozPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined MozPerspective?: | csstype.PerspectiveProperty<string | number> | undefined MozPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined MozStackSizing?: csstype.MozStackSizingProperty | undefined MozTabSize?: csstype.TabSizeProperty<string | number> | undefined MozTextBlink?: csstype.MozTextBlinkProperty | undefined MozTextSizeAdjust?: string | undefined MozTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined MozTransformStyle?: csstype.TransformStyleProperty | undefined MozTransitionDelay?: string | undefined MozTransitionDuration?: string | undefined MozTransitionProperty?: string | undefined MozTransitionTimingFunction?: string | undefined MozUserFocus?: csstype.MozUserFocusProperty | undefined MozUserModify?: csstype.MozUserModifyProperty | undefined MozUserSelect?: csstype.UserSelectProperty | undefined MozWindowDragging?: csstype.MozWindowDraggingProperty | undefined MozWindowShadow?: csstype.MozWindowShadowProperty | undefined msAccelerator?: csstype.MsAcceleratorProperty | undefined msAlignSelf?: string | undefined msBlockProgression?: csstype.MsBlockProgressionProperty | undefined msContentZoomChaining?: | csstype.MsContentZoomChainingProperty | undefined msContentZoomLimitMax?: string | undefined msContentZoomLimitMin?: string | undefined msContentZoomSnapPoints?: string | undefined msContentZoomSnapType?: | csstype.MsContentZoomSnapTypeProperty | undefined msContentZooming?: csstype.MsContentZoomingProperty | undefined msFilter?: string | undefined msFlexDirection?: csstype.FlexDirectionProperty | undefined msFlexPositive?: csstype.GlobalsNumber | undefined msFlowFrom?: string | undefined msFlowInto?: string | undefined msGridColumns?: | csstype.MsGridColumnsProperty<string | number> | undefined msGridRows?: csstype.MsGridRowsProperty<string | number> | undefined msHighContrastAdjust?: csstype.MsHighContrastAdjustProperty | undefined msHyphenateLimitChars?: | csstype.MsHyphenateLimitCharsProperty | undefined msHyphenateLimitLines?: | csstype.MsHyphenateLimitLinesProperty | undefined msHyphenateLimitZone?: | csstype.MsHyphenateLimitZoneProperty<string | number> | undefined msHyphens?: csstype.HyphensProperty | undefined msImeAlign?: csstype.MsImeAlignProperty | undefined msJustifySelf?: string | undefined msLineBreak?: csstype.LineBreakProperty | undefined msOrder?: csstype.GlobalsNumber | undefined msOverflowStyle?: csstype.MsOverflowStyleProperty | undefined msOverflowX?: csstype.OverflowXProperty | undefined msOverflowY?: csstype.OverflowYProperty | undefined msScrollChaining?: csstype.MsScrollChainingProperty | undefined msScrollLimitXMax?: | csstype.MsScrollLimitXMaxProperty<string | number> | undefined msScrollLimitXMin?: | csstype.MsScrollLimitXMinProperty<string | number> | undefined msScrollLimitYMax?: | csstype.MsScrollLimitYMaxProperty<string | number> | undefined msScrollLimitYMin?: | csstype.MsScrollLimitYMinProperty<string | number> | undefined msScrollRails?: csstype.MsScrollRailsProperty | undefined msScrollSnapPointsX?: string | undefined msScrollSnapPointsY?: string | undefined msScrollSnapType?: csstype.MsScrollSnapTypeProperty | undefined msScrollTranslation?: csstype.MsScrollTranslationProperty | undefined msScrollbar3dlightColor?: string | undefined msScrollbarArrowColor?: string | undefined msScrollbarBaseColor?: string | undefined msScrollbarDarkshadowColor?: string | undefined msScrollbarFaceColor?: string | undefined msScrollbarHighlightColor?: string | undefined msScrollbarShadowColor?: string | undefined msTextAutospace?: csstype.MsTextAutospaceProperty | undefined msTextCombineHorizontal?: string | undefined msTextOverflow?: string | undefined msTouchAction?: string | undefined msTouchSelect?: csstype.MsTouchSelectProperty | undefined msTransform?: string | undefined msTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined msTransitionDelay?: string | undefined msTransitionDuration?: string | undefined msTransitionProperty?: string | undefined msTransitionTimingFunction?: string | undefined msUserSelect?: csstype.MsUserSelectProperty | undefined msWordBreak?: csstype.WordBreakProperty | undefined msWrapFlow?: csstype.MsWrapFlowProperty | undefined msWrapMargin?: csstype.MsWrapMarginProperty<string | number> | undefined msWrapThrough?: csstype.MsWrapThroughProperty | undefined msWritingMode?: csstype.WritingModeProperty | undefined WebkitAlignContent?: string | undefined WebkitAlignItems?: string | undefined WebkitAlignSelf?: string | undefined WebkitAnimationDelay?: string | undefined WebkitAnimationDirection?: string | undefined WebkitAnimationDuration?: string | undefined WebkitAnimationFillMode?: string | undefined WebkitAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined WebkitAnimationName?: string | undefined WebkitAnimationPlayState?: string | undefined WebkitAnimationTimingFunction?: string | undefined WebkitAppearance?: csstype.WebkitAppearanceProperty | undefined WebkitBackdropFilter?: string | undefined WebkitBackfaceVisibility?: | csstype.BackfaceVisibilityProperty | undefined WebkitBackgroundClip?: string | undefined WebkitBackgroundOrigin?: string | undefined WebkitBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined WebkitBorderBeforeColor?: string | undefined WebkitBorderBeforeStyle?: string | undefined WebkitBorderBeforeWidth?: | csstype.WebkitBorderBeforeWidthProperty<string | number> | undefined WebkitBorderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined WebkitBorderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined WebkitBorderImageSlice?: csstype.BorderImageSliceProperty | undefined WebkitBorderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined WebkitBorderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined WebkitBoxDecorationBreak?: | csstype.BoxDecorationBreakProperty | undefined WebkitBoxReflect?: | csstype.WebkitBoxReflectProperty<string | number> | undefined WebkitBoxShadow?: string | undefined WebkitBoxSizing?: csstype.BoxSizingProperty | undefined WebkitClipPath?: string | undefined WebkitColumnCount?: csstype.ColumnCountProperty | undefined WebkitColumnFill?: csstype.ColumnFillProperty | undefined WebkitColumnGap?: csstype.ColumnGapProperty<string | number> | undefined WebkitColumnRuleColor?: string | undefined WebkitColumnRuleStyle?: string | undefined WebkitColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined WebkitColumnSpan?: csstype.ColumnSpanProperty | undefined WebkitColumnWidth?: | csstype.ColumnWidthProperty<string | number> | undefined WebkitFilter?: string | undefined WebkitFlexBasis?: csstype.FlexBasisProperty<string | number> | undefined WebkitFlexDirection?: csstype.FlexDirectionProperty | undefined WebkitFlexGrow?: csstype.GlobalsNumber | undefined WebkitFlexShrink?: csstype.GlobalsNumber | undefined WebkitFlexWrap?: csstype.FlexWrapProperty | undefined WebkitFontFeatureSettings?: string | undefined WebkitFontKerning?: csstype.FontKerningProperty | undefined WebkitFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined WebkitFontVariantLigatures?: string | undefined WebkitHyphens?: csstype.HyphensProperty | undefined WebkitJustifyContent?: string | undefined WebkitLineBreak?: csstype.LineBreakProperty | undefined WebkitLineClamp?: csstype.WebkitLineClampProperty | undefined WebkitMarginEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined WebkitMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined WebkitMaskAttachment?: string | undefined WebkitMaskBoxImageOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined WebkitMaskBoxImageRepeat?: string | undefined WebkitMaskBoxImageSlice?: csstype.MaskBorderSliceProperty | undefined WebkitMaskBoxImageSource?: string | undefined WebkitMaskBoxImageWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined WebkitMaskClip?: string | undefined WebkitMaskComposite?: string | undefined WebkitMaskImage?: string | undefined WebkitMaskOrigin?: string | undefined WebkitMaskPosition?: | csstype.WebkitMaskPositionProperty<string | number> | undefined WebkitMaskPositionX?: | csstype.WebkitMaskPositionXProperty<string | number> | undefined WebkitMaskPositionY?: | csstype.WebkitMaskPositionYProperty<string | number> | undefined WebkitMaskRepeat?: string | undefined WebkitMaskRepeatX?: csstype.WebkitMaskRepeatXProperty | undefined WebkitMaskRepeatY?: csstype.WebkitMaskRepeatYProperty | undefined WebkitMaskSize?: | csstype.WebkitMaskSizeProperty<string | number> | undefined WebkitMaxInlineSize?: | csstype.MaxInlineSizeProperty<string | number> | undefined WebkitOrder?: csstype.GlobalsNumber | undefined WebkitOverflowScrolling?: | csstype.WebkitOverflowScrollingProperty | undefined WebkitPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined WebkitPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined WebkitPerspective?: | csstype.PerspectiveProperty<string | number> | undefined WebkitPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined WebkitPrintColorAdjust?: csstype.ColorAdjustProperty | undefined WebkitRubyPosition?: string | undefined WebkitScrollSnapType?: string | undefined WebkitShapeMargin?: | csstype.ShapeMarginProperty<string | number> | undefined WebkitTapHighlightColor?: string | undefined WebkitTextCombine?: string | undefined WebkitTextDecorationColor?: string | undefined WebkitTextDecorationLine?: string | undefined WebkitTextDecorationSkip?: string | undefined WebkitTextDecorationStyle?: | csstype.TextDecorationStyleProperty | undefined WebkitTextEmphasisColor?: string | undefined WebkitTextEmphasisPosition?: string | undefined WebkitTextEmphasisStyle?: string | undefined WebkitTextFillColor?: string | undefined WebkitTextOrientation?: csstype.TextOrientationProperty | undefined WebkitTextSizeAdjust?: string | undefined WebkitTextStrokeColor?: string | undefined WebkitTextStrokeWidth?: | csstype.WebkitTextStrokeWidthProperty<string | number> | undefined WebkitTextUnderlinePosition?: string | undefined WebkitTouchCallout?: csstype.WebkitTouchCalloutProperty | undefined WebkitTransform?: string | undefined WebkitTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined WebkitTransformStyle?: csstype.TransformStyleProperty | undefined WebkitTransitionDelay?: string | undefined WebkitTransitionDuration?: string | undefined WebkitTransitionProperty?: string | undefined WebkitTransitionTimingFunction?: string | undefined WebkitUserModify?: csstype.WebkitUserModifyProperty | undefined WebkitUserSelect?: csstype.UserSelectProperty | undefined WebkitWritingMode?: csstype.WritingModeProperty | undefined MozAnimation?: csstype.AnimationProperty | undefined MozBorderImage?: csstype.BorderImageProperty | undefined MozColumnRule?: csstype.ColumnRuleProperty<string | number> | undefined MozColumns?: csstype.ColumnsProperty<string | number> | undefined MozTransition?: string | undefined msContentZoomLimit?: string | undefined msContentZoomSnap?: string | undefined msFlex?: csstype.FlexProperty<string | number> | undefined msScrollLimit?: string | undefined msScrollSnapX?: string | undefined msScrollSnapY?: string | undefined msTransition?: string | undefined WebkitAnimation?: csstype.AnimationProperty | undefined WebkitBorderBefore?: | csstype.WebkitBorderBeforeProperty<string | number> | undefined WebkitBorderImage?: csstype.BorderImageProperty | undefined WebkitBorderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined WebkitColumnRule?: | csstype.ColumnRuleProperty<string | number> | undefined WebkitColumns?: csstype.ColumnsProperty<string | number> | undefined WebkitFlex?: csstype.FlexProperty<string | number> | undefined WebkitFlexFlow?: string | undefined WebkitMask?: csstype.WebkitMaskProperty<string | number> | undefined WebkitMaskBoxImage?: csstype.MaskBorderProperty | undefined WebkitTextEmphasis?: string | undefined WebkitTextStroke?: | csstype.WebkitTextStrokeProperty<string | number> | undefined WebkitTransition?: string | undefined azimuth?: string | undefined boxAlign?: csstype.BoxAlignProperty | undefined boxDirection?: csstype.BoxDirectionProperty | undefined boxFlex?: csstype.GlobalsNumber | undefined boxFlexGroup?: csstype.GlobalsNumber | undefined boxLines?: csstype.BoxLinesProperty | undefined boxOrdinalGroup?: csstype.GlobalsNumber | undefined boxOrient?: csstype.BoxOrientProperty | undefined boxPack?: csstype.BoxPackProperty | undefined clip?: string | undefined fontVariantAlternates?: string | undefined gridColumnGap?: | csstype.GridColumnGapProperty<string | number> | undefined gridGap?: csstype.GridGapProperty<string | number> | undefined gridRowGap?: csstype.GridRowGapProperty<string | number> | undefined imeMode?: csstype.ImeModeProperty | undefined offsetBlock?: csstype.InsetBlockProperty<string | number> | undefined offsetBlockEnd?: | csstype.InsetBlockEndProperty<string | number> | undefined offsetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined offsetInline?: csstype.InsetInlineProperty<string | number> | undefined offsetInlineEnd?: | csstype.InsetInlineEndProperty<string | number> | undefined offsetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined scrollSnapCoordinate?: | csstype.ScrollSnapCoordinateProperty<string | number> | undefined scrollSnapDestination?: | csstype.ScrollSnapDestinationProperty<string | number> | undefined scrollSnapPointsX?: string | undefined scrollSnapPointsY?: string | undefined scrollSnapTypeX?: csstype.ScrollSnapTypeXProperty | undefined scrollSnapTypeY?: csstype.ScrollSnapTypeYProperty | undefined scrollbarTrackColor?: string | undefined KhtmlBoxAlign?: csstype.BoxAlignProperty | undefined KhtmlBoxDirection?: csstype.BoxDirectionProperty | undefined KhtmlBoxFlex?: csstype.GlobalsNumber | undefined KhtmlBoxFlexGroup?: csstype.GlobalsNumber | undefined KhtmlBoxLines?: csstype.BoxLinesProperty | undefined KhtmlBoxOrdinalGroup?: csstype.GlobalsNumber | undefined KhtmlBoxOrient?: csstype.BoxOrientProperty | undefined KhtmlBoxPack?: csstype.BoxPackProperty | undefined KhtmlLineBreak?: csstype.LineBreakProperty | undefined KhtmlOpacity?: csstype.OpacityProperty | undefined KhtmlUserSelect?: csstype.UserSelectProperty | undefined MozBackgroundClip?: string | undefined MozBackgroundInlinePolicy?: | csstype.BoxDecorationBreakProperty | undefined MozBackgroundOrigin?: string | undefined MozBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined MozBinding?: string | undefined MozBorderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined MozBorderRadiusBottomleft?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined MozBorderRadiusBottomright?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined MozBorderRadiusTopleft?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined MozBorderRadiusTopright?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined MozBoxAlign?: csstype.BoxAlignProperty | undefined MozBoxDirection?: csstype.BoxDirectionProperty | undefined MozBoxFlex?: csstype.GlobalsNumber | undefined MozBoxOrdinalGroup?: csstype.GlobalsNumber | undefined MozBoxOrient?: csstype.BoxOrientProperty | undefined MozBoxPack?: csstype.BoxPackProperty | undefined MozBoxShadow?: string | undefined MozFloatEdge?: csstype.MozFloatEdgeProperty | undefined MozForceBrokenImageIcon?: csstype.GlobalsNumber | undefined MozOpacity?: csstype.OpacityProperty | undefined MozOutline?: csstype.OutlineProperty<string | number> | undefined MozOutlineColor?: string | undefined MozOutlineRadius?: | csstype.MozOutlineRadiusProperty<string | number> | undefined MozOutlineRadiusBottomleft?: | csstype.MozOutlineRadiusBottomleftProperty<string | number> | undefined MozOutlineRadiusBottomright?: | csstype.MozOutlineRadiusBottomrightProperty<string | number> | undefined MozOutlineRadiusTopleft?: | csstype.MozOutlineRadiusTopleftProperty<string | number> | undefined MozOutlineRadiusTopright?: | csstype.MozOutlineRadiusToprightProperty<string | number> | undefined MozOutlineStyle?: string | undefined MozOutlineWidth?: | csstype.OutlineWidthProperty<string | number> | undefined MozTextAlignLast?: csstype.TextAlignLastProperty | undefined MozTextDecorationColor?: string | undefined MozTextDecorationLine?: string | undefined MozTextDecorationStyle?: csstype.TextDecorationStyleProperty | undefined MozUserInput?: csstype.MozUserInputProperty | undefined msImeMode?: csstype.ImeModeProperty | undefined msScrollbarTrackColor?: string | undefined OAnimation?: csstype.AnimationProperty | undefined OAnimationDelay?: string | undefined OAnimationDirection?: string | undefined OAnimationDuration?: string | undefined OAnimationFillMode?: string | undefined OAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined OAnimationName?: string | undefined OAnimationPlayState?: string | undefined OAnimationTimingFunction?: string | undefined OBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined OBorderImage?: csstype.BorderImageProperty | undefined OObjectFit?: csstype.ObjectFitProperty | undefined OObjectPosition?: | csstype.ObjectPositionProperty<string | number> | undefined OTabSize?: csstype.TabSizeProperty<string | number> | undefined OTextOverflow?: string | undefined OTransform?: string | undefined OTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined OTransition?: string | undefined OTransitionDelay?: string | undefined OTransitionDuration?: string | undefined OTransitionProperty?: string | undefined OTransitionTimingFunction?: string | undefined WebkitBoxAlign?: csstype.BoxAlignProperty | undefined WebkitBoxDirection?: csstype.BoxDirectionProperty | undefined WebkitBoxFlex?: csstype.GlobalsNumber | undefined WebkitBoxFlexGroup?: csstype.GlobalsNumber | undefined WebkitBoxLines?: csstype.BoxLinesProperty | undefined WebkitBoxOrdinalGroup?: csstype.GlobalsNumber | undefined WebkitBoxOrient?: csstype.BoxOrientProperty | undefined WebkitBoxPack?: csstype.BoxPackProperty | undefined WebkitScrollSnapPointsX?: string | undefined WebkitScrollSnapPointsY?: string | undefined alignmentBaseline?: csstype.AlignmentBaselineProperty | undefined baselineShift?: | csstype.BaselineShiftProperty<string | number> | undefined clipRule?: csstype.ClipRuleProperty | undefined colorInterpolation?: csstype.ColorInterpolationProperty | undefined colorRendering?: csstype.ColorRenderingProperty | undefined dominantBaseline?: csstype.DominantBaselineProperty | undefined fill?: string | undefined fillOpacity?: csstype.GlobalsNumber | undefined fillRule?: csstype.FillRuleProperty | undefined floodColor?: string | undefined floodOpacity?: csstype.GlobalsNumber | undefined glyphOrientationVertical?: | csstype.GlyphOrientationVerticalProperty | undefined lightingColor?: string | undefined marker?: string | undefined markerEnd?: string | undefined markerMid?: string | undefined markerStart?: string | undefined shapeRendering?: csstype.ShapeRenderingProperty | undefined stopColor?: string | undefined stopOpacity?: csstype.GlobalsNumber | undefined stroke?: string | undefined strokeDasharray?: | csstype.StrokeDasharrayProperty<string | number> | undefined strokeDashoffset?: | csstype.StrokeDashoffsetProperty<string | number> | undefined strokeLinecap?: csstype.StrokeLinecapProperty | undefined strokeLinejoin?: csstype.StrokeLinejoinProperty | undefined strokeMiterlimit?: csstype.GlobalsNumber | undefined strokeOpacity?: csstype.GlobalsNumber | undefined strokeWidth?: csstype.StrokeWidthProperty<string | number> | undefined textAnchor?: csstype.TextAnchorProperty | undefined vectorEffect?: csstype.VectorEffectProperty | undefined } | { innerHTML?: string | undefined class?: any style?: | string | { alignContent?: string | undefined alignItems?: string | undefined alignSelf?: string | undefined alignTracks?: string | undefined animationDelay?: string | undefined animationDirection?: string | undefined animationDuration?: string | undefined animationFillMode?: string | undefined animationIterationCount?: | csstype.AnimationIterationCountProperty | undefined animationName?: string | undefined animationPlayState?: string | undefined animationTimingFunction?: string | undefined appearance?: csstype.AppearanceProperty | undefined aspectRatio?: string | undefined backdropFilter?: string | undefined backfaceVisibility?: | csstype.BackfaceVisibilityProperty | undefined backgroundAttachment?: string | undefined backgroundBlendMode?: string | undefined backgroundClip?: string | undefined backgroundColor?: string | undefined backgroundImage?: string | undefined backgroundOrigin?: string | undefined backgroundPositionX?: | csstype.BackgroundPositionXProperty<string | number> | undefined backgroundPositionY?: | csstype.BackgroundPositionYProperty<string | number> | undefined backgroundRepeat?: string | undefined backgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined blockOverflow?: string | undefined blockSize?: csstype.BlockSizeProperty<string | number> | undefined borderBlockColor?: string | undefined borderBlockEndColor?: string | undefined borderBlockEndStyle?: | csstype.BorderBlockEndStyleProperty | undefined borderBlockEndWidth?: | csstype.BorderBlockEndWidthProperty<string | number> | undefined borderBlockStartColor?: string | undefined borderBlockStartStyle?: | csstype.BorderBlockStartStyleProperty | undefined borderBlockStartWidth?: | csstype.BorderBlockStartWidthProperty<string | number> | undefined borderBlockStyle?: csstype.BorderBlockStyleProperty | undefined borderBlockWidth?: | csstype.BorderBlockWidthProperty<string | number> | undefined borderBottomColor?: string | undefined borderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined borderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined borderBottomStyle?: csstype.BorderBottomStyleProperty | undefined borderBottomWidth?: | csstype.BorderBottomWidthProperty<string | number> | undefined borderCollapse?: csstype.BorderCollapseProperty | undefined borderEndEndRadius?: | csstype.BorderEndEndRadiusProperty<string | number> | undefined borderEndStartRadius?: | csstype.BorderEndStartRadiusProperty<string | number> | undefined borderImageOutset?: | csstype.BorderImageOutsetProperty<string | number> | undefined borderImageRepeat?: string | undefined borderImageSlice?: csstype.BorderImageSliceProperty | undefined borderImageSource?: string | undefined borderImageWidth?: | csstype.BorderImageWidthProperty<string | number> | undefined borderInlineColor?: string | undefined borderInlineEndColor?: string | undefined borderInlineEndStyle?: | csstype.BorderInlineEndStyleProperty | undefined borderInlineEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined borderInlineStartColor?: string | undefined borderInlineStartStyle?: | csstype.BorderInlineStartStyleProperty | undefined borderInlineStartWidth?: | csstype.BorderInlineStartWidthProperty<string | number> | undefined borderInlineStyle?: csstype.BorderInlineStyleProperty | undefined borderInlineWidth?: | csstype.BorderInlineWidthProperty<string | number> | undefined borderLeftColor?: string | undefined borderLeftStyle?: csstype.BorderLeftStyleProperty | undefined borderLeftWidth?: | csstype.BorderLeftWidthProperty<string | number> | undefined borderRightColor?: string | undefined borderRightStyle?: csstype.BorderRightStyleProperty | undefined borderRightWidth?: | csstype.BorderRightWidthProperty<string | number> | undefined borderSpacing?: | csstype.BorderSpacingProperty<string | number> | undefined borderStartEndRadius?: | csstype.BorderStartEndRadiusProperty<string | number> | undefined borderStartStartRadius?: | csstype.BorderStartStartRadiusProperty<string | number> | undefined borderTopColor?: string | undefined borderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined borderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined borderTopStyle?: csstype.BorderTopStyleProperty | undefined borderTopWidth?: | csstype.BorderTopWidthProperty<string | number> | undefined bottom?: csstype.BottomProperty<string | number> | undefined boxDecorationBreak?: | csstype.BoxDecorationBreakProperty | undefined boxShadow?: string | undefined boxSizing?: csstype.BoxSizingProperty | undefined breakAfter?: csstype.BreakAfterProperty | undefined breakBefore?: csstype.BreakBeforeProperty | undefined breakInside?: csstype.BreakInsideProperty | undefined captionSide?: csstype.CaptionSideProperty | undefined caretColor?: string | undefined clear?: csstype.ClearProperty | undefined clipPath?: string | undefined color?: string | undefined colorAdjust?: csstype.ColorAdjustProperty | undefined colorScheme?: string | undefined columnCount?: csstype.ColumnCountProperty | undefined columnFill?: csstype.ColumnFillProperty | undefined columnGap?: csstype.ColumnGapProperty<string | number> | undefined columnRuleColor?: string | undefined columnRuleStyle?: string | undefined columnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined columnSpan?: csstype.ColumnSpanProperty | undefined columnWidth?: | csstype.ColumnWidthProperty<string | number> | undefined contain?: string | undefined content?: string | undefined contentVisibility?: csstype.ContentVisibilityProperty | undefined counterIncrement?: string | undefined counterReset?: string | undefined counterSet?: string | undefined cursor?: string | undefined direction?: csstype.DirectionProperty | undefined display?: string | undefined emptyCells?: csstype.EmptyCellsProperty | undefined filter?: string | undefined flexBasis?: csstype.FlexBasisProperty<string | number> | undefined flexDirection?: csstype.FlexDirectionProperty | undefined flexGrow?: csstype.GlobalsNumber | undefined flexShrink?: csstype.GlobalsNumber | undefined flexWrap?: csstype.FlexWrapProperty | undefined float?: csstype.FloatProperty | undefined fontFamily?: string | undefined fontFeatureSettings?: string | undefined fontKerning?: csstype.FontKerningProperty | undefined fontLanguageOverride?: string | undefined fontOpticalSizing?: csstype.FontOpticalSizingProperty | undefined fontSize?: csstype.FontSizeProperty<string | number> | undefined fontSizeAdjust?: csstype.FontSizeAdjustProperty | undefined fontSmooth?: | csstype.FontSmoothProperty<string | number> | undefined fontStretch?: string | undefined fontStyle?: string | undefined fontSynthesis?: string | undefined fontVariant?: string | undefined fontVariantCaps?: csstype.FontVariantCapsProperty | undefined fontVariantEastAsian?: string | undefined fontVariantLigatures?: string | undefined fontVariantNumeric?: string | undefined fontVariantPosition?: | csstype.FontVariantPositionProperty | undefined fontVariationSettings?: string | undefined fontWeight?: csstype.FontWeightProperty | undefined forcedColorAdjust?: csstype.ForcedColorAdjustProperty | undefined gridAutoColumns?: | csstype.GridAutoColumnsProperty<string | number> | undefined gridAutoFlow?: string | undefined gridAutoRows?: | csstype.GridAutoRowsProperty<string | number> | undefined gridColumnEnd?: csstype.GridColumnEndProperty | undefined gridColumnStart?: csstype.GridColumnStartProperty | undefined gridRowEnd?: csstype.GridRowEndProperty | undefined gridRowStart?: csstype.GridRowStartProperty | undefined gridTemplateAreas?: string | undefined gridTemplateColumns?: | csstype.GridTemplateColumnsProperty<string | number> | undefined gridTemplateRows?: | csstype.GridTemplateRowsProperty<string | number> | undefined hangingPunctuation?: string | undefined height?: csstype.HeightProperty<string | number> | undefined hyphens?: csstype.HyphensProperty | undefined imageOrientation?: string | undefined imageRendering?: csstype.ImageRenderingProperty | undefined imageResolution?: string | undefined initialLetter?: csstype.InitialLetterProperty | undefined inlineSize?: | csstype.InlineSizeProperty<string | number> | undefined inset?: csstype.InsetProperty<string | number> | undefined insetBlock?: | csstype.InsetBlockProperty<string | number> | undefined insetBlockEnd?: | csstype.InsetBlockEndProperty<string | number> | undefined insetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined insetInline?: | csstype.InsetInlineProperty<string | number> | undefined insetInlineEnd?: | csstype.InsetInlineEndProperty<string | number> | undefined insetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined isolation?: csstype.IsolationProperty | undefined justifyContent?: string | undefined justifyItems?: string | undefined justifySelf?: string | undefined justifyTracks?: string | undefined left?: csstype.LeftProperty<string | number> | undefined letterSpacing?: | csstype.LetterSpacingProperty<string | number> | undefined lineBreak?: csstype.LineBreakProperty | undefined lineHeight?: | csstype.LineHeightProperty<string | number> | undefined lineHeightStep?: | csstype.LineHeightStepProperty<string | number> | undefined listStyleImage?: string | undefined listStylePosition?: csstype.ListStylePositionProperty | undefined listStyleType?: string | undefined marginBlock?: | csstype.MarginBlockProperty<string | number> | undefined marginBlockEnd?: | csstype.MarginBlockEndProperty<string | number> | undefined marginBlockStart?: | csstype.MarginBlockStartProperty<string | number> | undefined marginBottom?: | csstype.MarginBottomProperty<string | number> | undefined marginInline?: | csstype.MarginInlineProperty<string | number> | undefined marginInlineEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined marginInlineStart?: | csstype.MarginInlineStartProperty<string | number> | undefined marginLeft?: | csstype.MarginLeftProperty<string | number> | undefined marginRight?: | csstype.MarginRightProperty<string | number> | undefined marginTop?: csstype.MarginTopProperty<string | number> | undefined maskBorderMode?: csstype.MaskBorderModeProperty | undefined maskBorderOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined maskBorderRepeat?: string | undefined maskBorderSlice?: csstype.MaskBorderSliceProperty | undefined maskBorderSource?: string | undefined maskBorderWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined maskClip?: string | undefined maskComposite?: string | undefined maskImage?: string | undefined maskMode?: string | undefined maskOrigin?: string | undefined maskPosition?: | csstype.MaskPositionProperty<string | number> | undefined maskRepeat?: string | undefined maskSize?: csstype.MaskSizeProperty<string | number> | undefined maskType?: csstype.MaskTypeProperty | undefined mathStyle?: csstype.MathStyleProperty | undefined maxBlockSize?: | csstype.MaxBlockSizeProperty<string | number> | undefined maxHeight?: csstype.MaxHeightProperty<string | number> | undefined maxInlineSize?: | csstype.MaxInlineSizeProperty<string | number> | undefined maxLines?: csstype.MaxLinesProperty | undefined maxWidth?: csstype.MaxWidthProperty<string | number> | undefined minBlockSize?: | csstype.MinBlockSizeProperty<string | number> | undefined minHeight?: csstype.MinHeightProperty<string | number> | undefined minInlineSize?: | csstype.MinInlineSizeProperty<string | number> | undefined minWidth?: csstype.MinWidthProperty<string | number> | undefined mixBlendMode?: csstype.MixBlendModeProperty | undefined motionDistance?: | csstype.OffsetDistanceProperty<string | number> | undefined motionPath?: string | undefined motionRotation?: string | undefined objectFit?: csstype.ObjectFitProperty | undefined objectPosition?: | csstype.ObjectPositionProperty<string | number> | undefined offsetAnchor?: | csstype.OffsetAnchorProperty<string | number> | undefined offsetDistance?: | csstype.OffsetDistanceProperty<string | number> | undefined offsetPath?: string | undefined offsetRotate?: string | undefined offsetRotation?: string | undefined opacity?: csstype.OpacityProperty | undefined order?: csstype.GlobalsNumber | undefined orphans?: csstype.GlobalsNumber | undefined outlineColor?: string | undefined outlineOffset?: | csstype.OutlineOffsetProperty<string | number> | undefined outlineStyle?: string | undefined outlineWidth?: | csstype.OutlineWidthProperty<string | number> | undefined overflowAnchor?: csstype.OverflowAnchorProperty | undefined overflowBlock?: csstype.OverflowBlockProperty | undefined overflowClipBox?: csstype.OverflowClipBoxProperty | undefined overflowClipMargin?: | csstype.OverflowClipMarginProperty<string | number> | undefined overflowInline?: csstype.OverflowInlineProperty | undefined overflowWrap?: csstype.OverflowWrapProperty | undefined overflowX?: csstype.OverflowXProperty | undefined overflowY?: csstype.OverflowYProperty | undefined overscrollBehaviorBlock?: | csstype.OverscrollBehaviorBlockProperty | undefined overscrollBehaviorInline?: | csstype.OverscrollBehaviorInlineProperty | undefined overscrollBehaviorX?: | csstype.OverscrollBehaviorXProperty | undefined overscrollBehaviorY?: | csstype.OverscrollBehaviorYProperty | undefined paddingBlock?: | csstype.PaddingBlockProperty<string | number> | undefined paddingBlockEnd?: | csstype.PaddingBlockEndProperty<string | number> | undefined paddingBlockStart?: | csstype.PaddingBlockStartProperty<string | number> | undefined paddingBottom?: | csstype.PaddingBottomProperty<string | number> | undefined paddingInline?: | csstype.PaddingInlineProperty<string | number> | undefined paddingInlineEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined paddingInlineStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined paddingLeft?: | csstype.PaddingLeftProperty<string | number> | undefined paddingRight?: | csstype.PaddingRightProperty<string | number> | undefined paddingTop?: | csstype.PaddingTopProperty<string | number> | undefined pageBreakAfter?: csstype.PageBreakAfterProperty | undefined pageBreakBefore?: csstype.PageBreakBeforeProperty | undefined pageBreakInside?: csstype.PageBreakInsideProperty | undefined paintOrder?: string | undefined perspective?: | csstype.PerspectiveProperty<string | number> | undefined perspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined placeContent?: string | undefined pointerEvents?: csstype.PointerEventsProperty | undefined position?: csstype.PositionProperty | undefined quotes?: string | undefined resize?: csstype.ResizeProperty | undefined right?: csstype.RightProperty<string | number> | undefined rotate?: string | undefined rowGap?: csstype.RowGapProperty<string | number> | undefined rubyAlign?: csstype.RubyAlignProperty | undefined rubyMerge?: csstype.RubyMergeProperty | undefined rubyPosition?: string | undefined scale?: csstype.ScaleProperty | undefined scrollBehavior?: csstype.ScrollBehaviorProperty | undefined scrollMargin?: | csstype.ScrollMarginProperty<string | number> | undefined scrollMarginBlock?: | csstype.ScrollMarginBlockProperty<string | number> | undefined scrollMarginBlockEnd?: | csstype.ScrollMarginBlockEndProperty<string | number> | undefined scrollMarginBlockStart?: | csstype.ScrollMarginBlockStartProperty<string | number> | undefined scrollMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollMarginInline?: | csstype.ScrollMarginInlineProperty<string | number> | undefined scrollMarginInlineEnd?: | csstype.ScrollMarginInlineEndProperty<string | number> | undefined scrollMarginInlineStart?: | csstype.ScrollMarginInlineStartProperty<string | number> | undefined scrollMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollPadding?: | csstype.ScrollPaddingProperty<string | number> | undefined scrollPaddingBlock?: | csstype.ScrollPaddingBlockProperty<string | number> | undefined scrollPaddingBlockEnd?: | csstype.ScrollPaddingBlockEndProperty<string | number> | undefined scrollPaddingBlockStart?: | csstype.ScrollPaddingBlockStartProperty<string | number> | undefined scrollPaddingBottom?: | csstype.ScrollPaddingBottomProperty<string | number> | undefined scrollPaddingInline?: | csstype.ScrollPaddingInlineProperty<string | number> | undefined scrollPaddingInlineEnd?: | csstype.ScrollPaddingInlineEndProperty<string | number> | undefined scrollPaddingInlineStart?: | csstype.ScrollPaddingInlineStartProperty<string | number> | undefined scrollPaddingLeft?: | csstype.ScrollPaddingLeftProperty<string | number> | undefined scrollPaddingRight?: | csstype.ScrollPaddingRightProperty<string | number> | undefined scrollPaddingTop?: | csstype.ScrollPaddingTopProperty<string | number> | undefined scrollSnapAlign?: string | undefined scrollSnapMargin?: | csstype.ScrollMarginProperty<string | number> | undefined scrollSnapMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollSnapMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollSnapMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollSnapMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollSnapStop?: csstype.ScrollSnapStopProperty | undefined scrollSnapType?: string | undefined scrollbarColor?: string | undefined scrollbarGutter?: string | undefined scrollbarWidth?: csstype.ScrollbarWidthProperty | undefined shapeImageThreshold?: | csstype.ShapeImageThresholdProperty | undefined shapeMargin?: | csstype.ShapeMarginProperty<string | number> | undefined shapeOutside?: string | undefined tabSize?: csstype.TabSizeProperty<string | number> | undefined tableLayout?: csstype.TableLayoutProperty | undefined textAlign?: csstype.TextAlignProperty | undefined textAlignLast?: csstype.TextAlignLastProperty | undefined textCombineUpright?: string | undefined textDecorationColor?: string | undefined textDecorationLine?: string | undefined textDecorationSkip?: string | undefined textDecorationSkipInk?: | csstype.TextDecorationSkipInkProperty | undefined textDecorationStyle?: | csstype.TextDecorationStyleProperty | undefined textDecorationThickness?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textDecorationWidth?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textEmphasisColor?: string | undefined textEmphasisPosition?: string | undefined textEmphasisStyle?: string | undefined textIndent?: | csstype.TextIndentProperty<string | number> | undefined textJustify?: csstype.TextJustifyProperty | undefined textOrientation?: csstype.TextOrientationProperty | undefined textOverflow?: string | undefined textRendering?: csstype.TextRenderingProperty | undefined textShadow?: string | undefined textSizeAdjust?: string | undefined textTransform?: csstype.TextTransformProperty | undefined textUnderlineOffset?: | csstype.TextUnderlineOffsetProperty<string | number> | undefined textUnderlinePosition?: string | undefined top?: csstype.TopProperty<string | number> | undefined touchAction?: string | undefined transform?: string | undefined transformBox?: csstype.TransformBoxProperty | undefined transformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined transformStyle?: csstype.TransformStyleProperty | undefined transitionDelay?: string | undefined transitionDuration?: string | undefined transitionProperty?: string | undefined transitionTimingFunction?: string | undefined translate?: csstype.TranslateProperty<string | number> | undefined unicodeBidi?: csstype.UnicodeBidiProperty | undefined userSelect?: csstype.UserSelectProperty | undefined verticalAlign?: | csstype.VerticalAlignProperty<string | number> | undefined visibility?: csstype.VisibilityProperty | undefined whiteSpace?: csstype.WhiteSpaceProperty | undefined widows?: csstype.GlobalsNumber | undefined width?: csstype.WidthProperty<string | number> | undefined willChange?: string | undefined wordBreak?: csstype.WordBreakProperty | undefined wordSpacing?: | csstype.WordSpacingProperty<string | number> | undefined wordWrap?: csstype.WordWrapProperty | undefined writingMode?: csstype.WritingModeProperty | undefined zIndex?: csstype.ZIndexProperty | undefined zoom?: csstype.ZoomProperty | undefined all?: csstype.Globals | undefined animation?: csstype.AnimationProperty | undefined background?: | csstype.BackgroundProperty<string | number> | undefined backgroundPosition?: | csstype.BackgroundPositionProperty<string | number> | undefined border?: csstype.BorderProperty<string | number> | undefined borderBlock?: | csstype.BorderBlockProperty<string | number> | undefined borderBlockEnd?: | csstype.BorderBlockEndProperty<string | number> | undefined borderBlockStart?: | csstype.BorderBlockStartProperty<string | number> | undefined borderBottom?: | csstype.BorderBottomProperty<string | number> | undefined borderColor?: string | undefined borderImage?: csstype.BorderImageProperty | undefined borderInline?: | csstype.BorderInlineProperty<string | number> | undefined borderInlineEnd?: | csstype.BorderInlineEndProperty<string | number> | undefined borderInlineStart?: | csstype.BorderInlineStartProperty<string | number> | undefined borderLeft?: | csstype.BorderLeftProperty<string | number> | undefined borderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined borderRight?: | csstype.BorderRightProperty<string | number> | undefined borderStyle?: string | undefined borderTop?: csstype.BorderTopProperty<string | number> | undefined borderWidth?: | csstype.BorderWidthProperty<string | number> | undefined columnRule?: | csstype.ColumnRuleProperty<string | number> | undefined columns?: csstype.ColumnsProperty<string | number> | undefined flex?: csstype.FlexProperty<string | number> | undefined flexFlow?: string | undefined font?: string | undefined gap?: csstype.GapProperty<string | number> | undefined grid?: string | undefined gridArea?: csstype.GridAreaProperty | undefined gridColumn?: csstype.GridColumnProperty | undefined gridRow?: csstype.GridRowProperty | undefined gridTemplate?: string | undefined lineClamp?: csstype.LineClampProperty | undefined listStyle?: string | undefined margin?: csstype.MarginProperty<string | number> | undefined mask?: csstype.MaskProperty<string | number> | undefined maskBorder?: csstype.MaskBorderProperty | undefined motion?: csstype.OffsetProperty<string | number> | undefined offset?: csstype.OffsetProperty<string | number> | undefined outline?: csstype.OutlineProperty<string | number> | undefined overflow?: string | undefined overscrollBehavior?: string | undefined padding?: csstype.PaddingProperty<string | number> | undefined placeItems?: string | undefined placeSelf?: string | undefined textDecoration?: | csstype.TextDecorationProperty<string | number> | undefined textEmphasis?: string | undefined transition?: string | undefined MozAnimationDelay?: string | undefined MozAnimationDirection?: string | undefined MozAnimationDuration?: string | undefined MozAnimationFillMode?: string | undefined MozAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined MozAnimationName?: string | undefined MozAnimationPlayState?: string | undefined MozAnimationTimingFunction?: string | undefined MozAppearance?: csstype.MozAppearanceProperty | undefined MozBackfaceVisibility?: | csstype.BackfaceVisibilityProperty | undefined MozBorderBottomColors?: string | undefined MozBorderEndColor?: string | undefined MozBorderEndStyle?: | csstype.BorderInlineEndStyleProperty | undefined MozBorderEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined MozBorderLeftColors?: string | undefined MozBorderRightColors?: string | undefined MozBorderStartColor?: string | undefined MozBorderStartStyle?: | csstype.BorderInlineStartStyleProperty | undefined MozBorderTopColors?: string | undefined MozBoxSizing?: csstype.BoxSizingProperty | undefined MozColumnCount?: csstype.ColumnCountProperty | undefined MozColumnFill?: csstype.ColumnFillProperty | undefined MozColumnGap?: | csstype.ColumnGapProperty<string | number> | undefined MozColumnRuleColor?: string | undefined MozColumnRuleStyle?: string | undefined MozColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined MozColumnWidth?: | csstype.ColumnWidthProperty<string | number> | undefined MozContextProperties?: string | undefined MozFontFeatureSettings?: string | undefined MozFontLanguageOverride?: string | undefined MozHyphens?: csstype.HyphensProperty | undefined MozImageRegion?: string | undefined MozMarginEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined MozMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined MozOrient?: csstype.MozOrientProperty | undefined MozOsxFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined MozPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined MozPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined MozPerspective?: | csstype.PerspectiveProperty<string | number> | undefined MozPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined MozStackSizing?: csstype.MozStackSizingProperty | undefined MozTabSize?: csstype.TabSizeProperty<string | number> | undefined MozTextBlink?: csstype.MozTextBlinkProperty | undefined MozTextSizeAdjust?: string | undefined MozTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined MozTransformStyle?: csstype.TransformStyleProperty | undefined MozTransitionDelay?: string | undefined MozTransitionDuration?: string | undefined MozTransitionProperty?: string | undefined MozTransitionTimingFunction?: string | undefined MozUserFocus?: csstype.MozUserFocusProperty | undefined MozUserModify?: csstype.MozUserModifyProperty | undefined MozUserSelect?: csstype.UserSelectProperty | undefined MozWindowDragging?: csstype.MozWindowDraggingProperty | undefined MozWindowShadow?: csstype.MozWindowShadowProperty | undefined msAccelerator?: csstype.MsAcceleratorProperty | undefined msAlignSelf?: string | undefined msBlockProgression?: | csstype.MsBlockProgressionProperty | undefined msContentZoomChaining?: | csstype.MsContentZoomChainingProperty | undefined msContentZoomLimitMax?: string | undefined msContentZoomLimitMin?: string | undefined msContentZoomSnapPoints?: string | undefined msContentZoomSnapType?: | csstype.MsContentZoomSnapTypeProperty | undefined msContentZooming?: csstype.MsContentZoomingProperty | undefined msFilter?: string | undefined msFlexDirection?: csstype.FlexDirectionProperty | undefined msFlexPositive?: csstype.GlobalsNumber | undefined msFlowFrom?: string | undefined msFlowInto?: string | undefined msGridColumns?: | csstype.MsGridColumnsProperty<string | number> | undefined msGridRows?: | csstype.MsGridRowsProperty<string | number> | undefined msHighContrastAdjust?: | csstype.MsHighContrastAdjustProperty | undefined msHyphenateLimitChars?: | csstype.MsHyphenateLimitCharsProperty | undefined msHyphenateLimitLines?: | csstype.MsHyphenateLimitLinesProperty | undefined msHyphenateLimitZone?: | csstype.MsHyphenateLimitZoneProperty<string | number> | undefined msHyphens?: csstype.HyphensProperty | undefined msImeAlign?: csstype.MsImeAlignProperty | undefined msJustifySelf?: string | undefined msLineBreak?: csstype.LineBreakProperty | undefined msOrder?: csstype.GlobalsNumber | undefined msOverflowStyle?: csstype.MsOverflowStyleProperty | undefined msOverflowX?: csstype.OverflowXProperty | undefined msOverflowY?: csstype.OverflowYProperty | undefined msScrollChaining?: csstype.MsScrollChainingProperty | undefined msScrollLimitXMax?: | csstype.MsScrollLimitXMaxProperty<string | number> | undefined msScrollLimitXMin?: | csstype.MsScrollLimitXMinProperty<string | number> | undefined msScrollLimitYMax?: | csstype.MsScrollLimitYMaxProperty<string | number> | undefined msScrollLimitYMin?: | csstype.MsScrollLimitYMinProperty<string | number> | undefined msScrollRails?: csstype.MsScrollRailsProperty | undefined msScrollSnapPointsX?: string | undefined msScrollSnapPointsY?: string | undefined msScrollSnapType?: csstype.MsScrollSnapTypeProperty | undefined msScrollTranslation?: | csstype.MsScrollTranslationProperty | undefined msScrollbar3dlightColor?: string | undefined msScrollbarArrowColor?: string | undefined msScrollbarBaseColor?: string | undefined msScrollbarDarkshadowColor?: string | undefined msScrollbarFaceColor?: string | undefined msScrollbarHighlightColor?: string | undefined msScrollbarShadowColor?: string | undefined msTextAutospace?: csstype.MsTextAutospaceProperty | undefined msTextCombineHorizontal?: string | undefined msTextOverflow?: string | undefined msTouchAction?: string | undefined msTouchSelect?: csstype.MsTouchSelectProperty | undefined msTransform?: string | undefined msTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined msTransitionDelay?: string | undefined msTransitionDuration?: string | undefined msTransitionProperty?: string | undefined msTransitionTimingFunction?: string | undefined msUserSelect?: csstype.MsUserSelectProperty | undefined msWordBreak?: csstype.WordBreakProperty | undefined msWrapFlow?: csstype.MsWrapFlowProperty | undefined msWrapMargin?: | csstype.MsWrapMarginProperty<string | number> | undefined msWrapThrough?: csstype.MsWrapThroughProperty | undefined msWritingMode?: csstype.WritingModeProperty | undefined WebkitAlignContent?: string | undefined WebkitAlignItems?: string | undefined WebkitAlignSelf?: string | undefined WebkitAnimationDelay?: string | undefined WebkitAnimationDirection?: string | undefined WebkitAnimationDuration?: string | undefined WebkitAnimationFillMode?: string | undefined WebkitAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined WebkitAnimationName?: string | undefined WebkitAnimationPlayState?: string | undefined WebkitAnimationTimingFunction?: string | undefined WebkitAppearance?: csstype.WebkitAppearanceProperty | undefined WebkitBackdropFilter?: string | undefined WebkitBackfaceVisibility?: | csstype.BackfaceVisibilityProperty | undefined WebkitBackgroundClip?: string | undefined WebkitBackgroundOrigin?: string | undefined WebkitBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined WebkitBorderBeforeColor?: string | undefined WebkitBorderBeforeStyle?: string | undefined WebkitBorderBeforeWidth?: | csstype.WebkitBorderBeforeWidthProperty<string | number> | undefined WebkitBorderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined WebkitBorderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined WebkitBorderImageSlice?: | csstype.BorderImageSliceProperty | undefined WebkitBorderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined WebkitBorderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined WebkitBoxDecorationBreak?: | csstype.BoxDecorationBreakProperty | undefined WebkitBoxReflect?: | csstype.WebkitBoxReflectProperty<string | number> | undefined WebkitBoxShadow?: string | undefined WebkitBoxSizing?: csstype.BoxSizingProperty | undefined WebkitClipPath?: string | undefined WebkitColumnCount?: csstype.ColumnCountProperty | undefined WebkitColumnFill?: csstype.ColumnFillProperty | undefined WebkitColumnGap?: | csstype.ColumnGapProperty<string | number> | undefined WebkitColumnRuleColor?: string | undefined WebkitColumnRuleStyle?: string | undefined WebkitColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined WebkitColumnSpan?: csstype.ColumnSpanProperty | undefined WebkitColumnWidth?: | csstype.ColumnWidthProperty<string | number> | undefined WebkitFilter?: string | undefined WebkitFlexBasis?: | csstype.FlexBasisProperty<string | number> | undefined WebkitFlexDirection?: csstype.FlexDirectionProperty | undefined WebkitFlexGrow?: csstype.GlobalsNumber | undefined WebkitFlexShrink?: csstype.GlobalsNumber | undefined WebkitFlexWrap?: csstype.FlexWrapProperty | undefined WebkitFontFeatureSettings?: string | undefined WebkitFontKerning?: csstype.FontKerningProperty | undefined WebkitFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined WebkitFontVariantLigatures?: string | undefined WebkitHyphens?: csstype.HyphensProperty | undefined WebkitJustifyContent?: string | undefined WebkitLineBreak?: csstype.LineBreakProperty | undefined WebkitLineClamp?: csstype.WebkitLineClampProperty | undefined WebkitMarginEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined WebkitMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined WebkitMaskAttachment?: string | undefined WebkitMaskBoxImageOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined WebkitMaskBoxImageRepeat?: string | undefined WebkitMaskBoxImageSlice?: | csstype.MaskBorderSliceProperty | undefined WebkitMaskBoxImageSource?: string | undefined WebkitMaskBoxImageWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined WebkitMaskClip?: string | undefined WebkitMaskComposite?: string | undefined WebkitMaskImage?: string | undefined WebkitMaskOrigin?: string | undefined WebkitMaskPosition?: | csstype.WebkitMaskPositionProperty<string | number> | undefined WebkitMaskPositionX?: | csstype.WebkitMaskPositionXProperty<string | number> | undefined WebkitMaskPositionY?: | csstype.WebkitMaskPositionYProperty<string | number> | undefined WebkitMaskRepeat?: string | undefined WebkitMaskRepeatX?: csstype.WebkitMaskRepeatXProperty | undefined WebkitMaskRepeatY?: csstype.WebkitMaskRepeatYProperty | undefined WebkitMaskSize?: | csstype.WebkitMaskSizeProperty<string | number> | undefined WebkitMaxInlineSize?: | csstype.MaxInlineSizeProperty<string | number> | undefined WebkitOrder?: csstype.GlobalsNumber | undefined WebkitOverflowScrolling?: | csstype.WebkitOverflowScrollingProperty | undefined WebkitPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined WebkitPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined WebkitPerspective?: | csstype.PerspectiveProperty<string | number> | undefined WebkitPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined WebkitPrintColorAdjust?: csstype.ColorAdjustProperty | undefined WebkitRubyPosition?: string | undefined WebkitScrollSnapType?: string | undefined WebkitShapeMargin?: | csstype.ShapeMarginProperty<string | number> | undefined WebkitTapHighlightColor?: string | undefined WebkitTextCombine?: string | undefined WebkitTextDecorationColor?: string | undefined WebkitTextDecorationLine?: string | undefined WebkitTextDecorationSkip?: string | undefined WebkitTextDecorationStyle?: | csstype.TextDecorationStyleProperty | undefined WebkitTextEmphasisColor?: string | undefined WebkitTextEmphasisPosition?: string | undefined WebkitTextEmphasisStyle?: string | undefined WebkitTextFillColor?: string | undefined WebkitTextOrientation?: | csstype.TextOrientationProperty | undefined WebkitTextSizeAdjust?: string | undefined WebkitTextStrokeColor?: string | undefined WebkitTextStrokeWidth?: | csstype.WebkitTextStrokeWidthProperty<string | number> | undefined WebkitTextUnderlinePosition?: string | undefined WebkitTouchCallout?: | csstype.WebkitTouchCalloutProperty | undefined WebkitTransform?: string | undefined WebkitTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined WebkitTransformStyle?: csstype.TransformStyleProperty | undefined WebkitTransitionDelay?: string | undefined WebkitTransitionDuration?: string | undefined WebkitTransitionProperty?: string | undefined WebkitTransitionTimingFunction?: string | undefined WebkitUserModify?: csstype.WebkitUserModifyProperty | undefined WebkitUserSelect?: csstype.UserSelectProperty | undefined WebkitWritingMode?: csstype.WritingModeProperty | undefined MozAnimation?: csstype.AnimationProperty | undefined MozBorderImage?: csstype.BorderImageProperty | undefined MozColumnRule?: | csstype.ColumnRuleProperty<string | number> | undefined MozColumns?: csstype.ColumnsProperty<string | number> | undefined MozTransition?: string | undefined msContentZoomLimit?: string | undefined msContentZoomSnap?: string | undefined msFlex?: csstype.FlexProperty<string | number> | undefined msScrollLimit?: string | undefined msScrollSnapX?: string | undefined msScrollSnapY?: string | undefined msTransition?: string | undefined WebkitAnimation?: csstype.AnimationProperty | undefined WebkitBorderBefore?: | csstype.WebkitBorderBeforeProperty<string | number> | undefined WebkitBorderImage?: csstype.BorderImageProperty | undefined WebkitBorderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined WebkitColumnRule?: | csstype.ColumnRuleProperty<string | number> | undefined WebkitColumns?: | csstype.ColumnsProperty<string | number> | undefined WebkitFlex?: csstype.FlexProperty<string | number> | undefined WebkitFlexFlow?: string | undefined WebkitMask?: | csstype.WebkitMaskProperty<string | number> | undefined WebkitMaskBoxImage?: csstype.MaskBorderProperty | undefined WebkitTextEmphasis?: string | undefined WebkitTextStroke?: | csstype.WebkitTextStrokeProperty<string | number> | undefined WebkitTransition?: string | undefined azimuth?: string | undefined boxAlign?: csstype.BoxAlignProperty | undefined boxDirection?: csstype.BoxDirectionProperty | undefined boxFlex?: csstype.GlobalsNumber | undefined boxFlexGroup?: csstype.GlobalsNumber | undefined boxLines?: csstype.BoxLinesProperty | undefined boxOrdinalGroup?: csstype.GlobalsNumber | undefined boxOrient?: csstype.BoxOrientProperty | undefined boxPack?: csstype.BoxPackProperty | undefined clip?: string | undefined fontVariantAlternates?: string | undefined gridColumnGap?: | csstype.GridColumnGapProperty<string | number> | undefined gridGap?: csstype.GridGapProperty<string | number> | undefined gridRowGap?: | csstype.GridRowGapProperty<string | number> | undefined imeMode?: csstype.ImeModeProperty | undefined offsetBlock?: | csstype.InsetBlockProperty<string | number> | undefined offsetBlockEnd?: | csstype.InsetBlockEndProperty<string | number> | undefined offsetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined offsetInline?: | csstype.InsetInlineProperty<string | number> | undefined offsetInlineEnd?: | csstype.InsetInlineEndProperty<string | number> | undefined offsetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined scrollSnapCoordinate?: | csstype.ScrollSnapCoordinateProperty<string | number> | undefined scrollSnapDestination?: | csstype.ScrollSnapDestinationProperty<string | number> | undefined scrollSnapPointsX?: string | undefined scrollSnapPointsY?: string | undefined scrollSnapTypeX?: csstype.ScrollSnapTypeXProperty | undefined scrollSnapTypeY?: csstype.ScrollSnapTypeYProperty | undefined scrollbarTrackColor?: string | undefined KhtmlBoxAlign?: csstype.BoxAlignProperty | undefined KhtmlBoxDirection?: csstype.BoxDirectionProperty | undefined KhtmlBoxFlex?: csstype.GlobalsNumber | undefined KhtmlBoxFlexGroup?: csstype.GlobalsNumber | undefined KhtmlBoxLines?: csstype.BoxLinesProperty | undefined KhtmlBoxOrdinalGroup?: csstype.GlobalsNumber | undefined KhtmlBoxOrient?: csstype.BoxOrientProperty | undefined KhtmlBoxPack?: csstype.BoxPackProperty | undefined KhtmlLineBreak?: csstype.LineBreakProperty | undefined KhtmlOpacity?: csstype.OpacityProperty | undefined KhtmlUserSelect?: csstype.UserSelectProperty | undefined MozBackgroundClip?: string | undefined MozBackgroundInlinePolicy?: | csstype.BoxDecorationBreakProperty | undefined MozBackgroundOrigin?: string | undefined MozBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined MozBinding?: string | undefined MozBorderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined MozBorderRadiusBottomleft?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined MozBorderRadiusBottomright?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined MozBorderRadiusTopleft?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined MozBorderRadiusTopright?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined MozBoxAlign?: csstype.BoxAlignProperty | undefined MozBoxDirection?: csstype.BoxDirectionProperty | undefined MozBoxFlex?: csstype.GlobalsNumber | undefined MozBoxOrdinalGroup?: csstype.GlobalsNumber | undefined MozBoxOrient?: csstype.BoxOrientProperty | undefined MozBoxPack?: csstype.BoxPackProperty | undefined MozBoxShadow?: string | undefined MozFloatEdge?: csstype.MozFloatEdgeProperty | undefined MozForceBrokenImageIcon?: csstype.GlobalsNumber | undefined MozOpacity?: csstype.OpacityProperty | undefined MozOutline?: csstype.OutlineProperty<string | number> | undefined MozOutlineColor?: string | undefined MozOutlineRadius?: | csstype.MozOutlineRadiusProperty<string | number> | undefined MozOutlineRadiusBottomleft?: | csstype.MozOutlineRadiusBottomleftProperty<string | number> | undefined MozOutlineRadiusBottomright?: | csstype.MozOutlineRadiusBottomrightProperty<string | number> | undefined MozOutlineRadiusTopleft?: | csstype.MozOutlineRadiusTopleftProperty<string | number> | undefined MozOutlineRadiusTopright?: | csstype.MozOutlineRadiusToprightProperty<string | number> | undefined MozOutlineStyle?: string | undefined MozOutlineWidth?: | csstype.OutlineWidthProperty<string | number> | undefined MozTextAlignLast?: csstype.TextAlignLastProperty | undefined MozTextDecorationColor?: string | undefined MozTextDecorationLine?: string | undefined MozTextDecorationStyle?: | csstype.TextDecorationStyleProperty | undefined MozUserInput?: csstype.MozUserInputProperty | undefined msImeMode?: csstype.ImeModeProperty | undefined msScrollbarTrackColor?: string | undefined OAnimation?: csstype.AnimationProperty | undefined OAnimationDelay?: string | undefined OAnimationDirection?: string | undefined OAnimationDuration?: string | undefined OAnimationFillMode?: string | undefined OAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined OAnimationName?: string | undefined OAnimationPlayState?: string | undefined OAnimationTimingFunction?: string | undefined OBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined OBorderImage?: csstype.BorderImageProperty | undefined OObjectFit?: csstype.ObjectFitProperty | undefined OObjectPosition?: | csstype.ObjectPositionProperty<string | number> | undefined OTabSize?: csstype.TabSizeProperty<string | number> | undefined OTextOverflow?: string | undefined OTransform?: string | undefined OTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined OTransition?: string | undefined OTransitionDelay?: string | undefined OTransitionDuration?: string | undefined OTransitionProperty?: string | undefined OTransitionTimingFunction?: string | undefined WebkitBoxAlign?: csstype.BoxAlignProperty | undefined WebkitBoxDirection?: csstype.BoxDirectionProperty | undefined WebkitBoxFlex?: csstype.GlobalsNumber | undefined WebkitBoxFlexGroup?: csstype.GlobalsNumber | undefined WebkitBoxLines?: csstype.BoxLinesProperty | undefined WebkitBoxOrdinalGroup?: csstype.GlobalsNumber | undefined WebkitBoxOrient?: csstype.BoxOrientProperty | undefined WebkitBoxPack?: csstype.BoxPackProperty | undefined WebkitScrollSnapPointsX?: string | undefined WebkitScrollSnapPointsY?: string | undefined alignmentBaseline?: csstype.AlignmentBaselineProperty | undefined baselineShift?: | csstype.BaselineShiftProperty<string | number> | undefined clipRule?: csstype.ClipRuleProperty | undefined colorInterpolation?: | csstype.ColorInterpolationProperty | undefined colorRendering?: csstype.ColorRenderingProperty | undefined dominantBaseline?: csstype.DominantBaselineProperty | undefined fill?: string | undefined fillOpacity?: csstype.GlobalsNumber | undefined fillRule?: csstype.FillRuleProperty | undefined floodColor?: string | undefined floodOpacity?: csstype.GlobalsNumber | undefined glyphOrientationVertical?: | csstype.GlyphOrientationVerticalProperty | undefined lightingColor?: string | undefined marker?: string | undefined markerEnd?: string | undefined markerMid?: string | undefined markerStart?: string | undefined shapeRendering?: csstype.ShapeRenderingProperty | undefined stopColor?: string | undefined stopOpacity?: csstype.GlobalsNumber | undefined stroke?: string | undefined strokeDasharray?: | csstype.StrokeDasharrayProperty<string | number> | undefined strokeDashoffset?: | csstype.StrokeDashoffsetProperty<string | number> | undefined strokeLinecap?: csstype.StrokeLinecapProperty | undefined strokeLinejoin?: csstype.StrokeLinejoinProperty | undefined strokeMiterlimit?: csstype.GlobalsNumber | undefined strokeOpacity?: csstype.GlobalsNumber | undefined strokeWidth?: | csstype.StrokeWidthProperty<string | number> | undefined textAnchor?: csstype.TextAnchorProperty | undefined vectorEffect?: csstype.VectorEffectProperty | undefined } | undefined color?: string | undefined height?: (string | number) | undefined id?: string | undefined lang?: string | undefined max?: (string | number) | undefined media?: string | undefined method?: string | undefined min?: (string | number) | undefined name?: string | undefined target?: string | undefined type?: string | undefined width?: (string | number) | undefined role?: string | undefined tabindex?: (string | number) | undefined 'accent-height'?: (string | number) | undefined accumulate?: 'none' | 'sum' | undefined additive?: 'replace' | 'sum' | undefined 'alignment-baseline'?: | 'alphabetic' | 'hanging' | 'ideographic' | 'mathematical' | 'inherit' | 'baseline' | 'auto' | 'middle' | 'after-edge' | 'before-edge' | 'central' | 'text-after-edge' | 'text-before-edge' | undefined allowReorder?: 'no' | 'yes' | undefined alphabetic?: (string | number) | undefined amplitude?: (string | number) | undefined 'arabic-form'?: | 'initial' | 'medial' | 'terminal' | 'isolated' | undefined ascent?: (string | number) | undefined attributeName?: string | undefined attributeType?: string | undefined autoReverse?: (string | number) | undefined azimuth?: (string | number) | undefined baseFrequency?: (string | number) | undefined 'baseline-shift'?: (string | number) | undefined baseProfile?: (string | number) | undefined bbox?: (string | number) | undefined begin?: (string | number) | undefined bias?: (string | number) | undefined by?: (string | number) | undefined calcMode?: (string | number) | undefined 'cap-height'?: (string | number) | undefined clip?: (string | number) | undefined 'clip-path'?: string | undefined clipPathUnits?: (string | number) | undefined 'clip-rule'?: (string | number) | undefined 'color-interpolation'?: (string | number) | undefined 'color-interpolation-filters'?: | 'inherit' | 'auto' | 'linearRGB' | 'sRGB' | undefined 'color-profile'?: (string | number) | undefined 'color-rendering'?: (string | number) | undefined contentScriptType?: (string | number) | undefined contentStyleType?: (string | number) | undefined cursor?: (string | number) | undefined cx?: (string | number) | undefined cy?: (string | number) | undefined d?: string | undefined decelerate?: (string | number) | undefined descent?: (string | number) | undefined diffuseConstant?: (string | number) | undefined direction?: (string | number) | undefined display?: (string | number) | undefined divisor?: (string | number) | undefined 'dominant-baseline'?: (string | number) | undefined dur?: (string | number) | undefined dx?: (string | number) | undefined dy?: (string | number) | undefined edgeMode?: (string | number) | undefined elevation?: (string | number) | undefined 'enable-background'?: (string | number) | undefined end?: (string | number) | undefined exponent?: (string | number) | undefined externalResourcesRequired?: (string | number) | undefined fill?: string | undefined 'fill-opacity'?: (string | number) | undefined 'fill-rule'?: 'inherit' | 'evenodd' | 'nonzero' | undefined filter?: string | undefined filterRes?: (string | number) | undefined filterUnits?: (string | number) | undefined 'flood-color'?: (string | number) | undefined 'flood-opacity'?: (string | number) | undefined focusable?: (string | number) | undefined 'font-family'?: string | undefined 'font-size'?: (string | number) | undefined 'font-size-adjust'?: (string | number) | undefined 'font-stretch'?: (string | number) | undefined 'font-style'?: (string | number) | undefined 'font-variant'?: (string | number) | undefined 'font-weight'?: (string | number) | undefined format?: (string | number) | undefined from?: (string | number) | undefined fx?: (string | number) | undefined fy?: (string | number) | undefined g1?: (string | number) | undefined g2?: (string | number) | undefined 'glyph-name'?: (string | number) | undefined 'glyph-orientation-horizontal'?: (string | number) | undefined 'glyph-orientation-vertical'?: (string | number) | undefined glyphRef?: (string | number) | undefined gradientTransform?: string | undefined gradientUnits?: string | undefined hanging?: (string | number) | undefined 'horiz-adv-x'?: (string | number) | undefined 'horiz-origin-x'?: (string | number) | undefined href?: string | undefined ideographic?: (string | number) | undefined 'image-rendering'?: (string | number) | undefined in2?: (string | number) | undefined in?: string | undefined intercept?: (string | number) | undefined k1?: (string | number) | undefined k2?: (string | number) | undefined k3?: (string | number) | undefined k4?: (string | number) | undefined k?: (string | number) | undefined kernelMatrix?: (string | number) | undefined kernelUnitLength?: (string | number) | undefined kerning?: (string | number) | undefined keyPoints?: (string | number) | undefined keySplines?: (string | number) | undefined keyTimes?: (string | number) | undefined lengthAdjust?: (string | number) | undefined 'letter-spacing'?: (string | number) | undefined 'lighting-color'?: (string | number) | undefined limitingConeAngle?: (string | number) | undefined local?: (string | number) | undefined 'marker-end'?: string | undefined markerHeight?: (string | number) | undefined 'marker-mid'?: string | undefined 'marker-start'?: string | undefined markerUnits?: (string | number) | undefined markerWidth?: (string | number) | undefined mask?: string | undefined maskContentUnits?: (string | number) | undefined maskUnits?: (string | number) | undefined mathematical?: (string | number) | undefined mode?: (string | number) | undefined numOctaves?: (string | number) | undefined offset?: (string | number) | undefined opacity?: (string | number) | undefined operator?: (string | number) | undefined order?: (string | number) | undefined orient?: (string | number) | undefined orientation?: (string | number) | undefined origin?: (string | number) | undefined overflow?: (string | number) | undefined 'overline-position'?: (string | number) | undefined 'overline-thickness'?: (string | number) | undefined 'paint-order'?: (string | number) | undefined 'panose-1'?: (string | number) | undefined pathLength?: (string | number) | undefined patternContentUnits?: string | undefined patternTransform?: (string | number) | undefined patternUnits?: string | undefined 'pointer-events'?: (string | number) | undefined points?: string | undefined pointsAtX?: (string | number) | undefined pointsAtY?: (string | number) | undefined pointsAtZ?: (string | number) | undefined preserveAlpha?: (string | number) | undefined preserveAspectRatio?: string | undefined primitiveUnits?: (string | number) | undefined r?: (string | number) | undefined radius?: (string | number) | undefined refX?: (string | number) | undefined refY?: (string | number) | undefined renderingIntent?: (string | number) | undefined repeatCount?: (string | number) | undefined repeatDur?: (string | number) | undefined requiredExtensions?: (string | number) | undefined requiredFeatures?: (string | number) | undefined restart?: (string | number) | undefined result?: string | undefined rotate?: (string | number) | undefined rx?: (string | number) | undefined ry?: (string | number) | undefined scale?: (string | number) | undefined seed?: (string | number) | undefined 'shape-rendering'?: (string | number) | undefined slope?: (string | number) | undefined spacing?: (string | number) | undefined specularConstant?: (string | number) | undefined specularExponent?: (string | number) | undefined speed?: (string | number) | undefined spreadMethod?: string | undefined startOffset?: (string | number) | undefined stdDeviation?: (string | number) | undefined stemh?: (string | number) | undefined stemv?: (string | number) | undefined stitchTiles?: (string | number) | undefined 'stop-color'?: string | undefined 'stop-opacity'?: (string | number) | undefined 'strikethrough-position'?: (string | number) | undefined 'strikethrough-thickness'?: (string | number) | undefined string?: (string | number) | undefined stroke?: string | undefined 'stroke-dasharray'?: (string | number) | undefined 'stroke-dashoffset'?: (string | number) | undefined 'stroke-linecap'?: 'inherit' | 'round' | 'butt' | 'square' | undefined 'stroke-linejoin'?: 'inherit' | 'round' | 'bevel' | 'miter' | undefined 'stroke-miterlimit'?: (string | number) | undefined 'stroke-opacity'?: (string | number) | undefined 'stroke-width'?: (string | number) | undefined surfaceScale?: (string | number) | undefined systemLanguage?: (string | number) | undefined tableValues?: (string | number) | undefined targetX?: (string | number) | undefined targetY?: (string | number) | undefined 'text-anchor'?: string | undefined 'text-decoration'?: (string | number) | undefined textLength?: (string | number) | undefined 'text-rendering'?: (string | number) | undefined to?: (string | number) | undefined transform?: string | undefined u1?: (string | number) | undefined u2?: (string | number) | undefined 'underline-position'?: (string | number) | undefined 'underline-thickness'?: (string | number) | undefined unicode?: (string | number) | undefined 'unicode-bidi'?: (string | number) | undefined 'unicode-range'?: (string | number) | undefined 'unitsPer-em'?: (string | number) | undefined 'v-alphabetic'?: (string | number) | undefined values?: string | undefined 'vector-effect'?: (string | number) | undefined version?: string | undefined 'vert-adv-y'?: (string | number) | undefined 'vert-origin-x'?: (string | number) | undefined 'vert-origin-y'?: (string | number) | undefined 'v-hanging'?: (string | number) | undefined 'v-ideographic'?: (string | number) | undefined viewBox?: string | undefined viewTarget?: (string | number) | undefined visibility?: (string | number) | undefined 'v-mathematical'?: (string | number) | undefined widths?: (string | number) | undefined 'word-spacing'?: (string | number) | undefined 'writing-mode'?: (string | number) | undefined x1?: (string | number) | undefined x2?: (string | number) | undefined x?: (string | number) | undefined xChannelSelector?: string | undefined 'x-height'?: (string | number) | undefined xlinkActuate?: string | undefined xlinkArcrole?: string | undefined xlinkHref?: string | undefined xlinkRole?: string | undefined xlinkShow?: string | undefined xlinkTitle?: string | undefined xlinkType?: string | undefined xmlns?: string | undefined y1?: (string | number) | undefined y2?: (string | number) | undefined y?: (string | number) | undefined yChannelSelector?: string | undefined z?: (string | number) | undefined zoomAndPan?: string | undefined 'aria-activedescendant'?: string | undefined 'aria-atomic'?: (boolean | 'false' | 'true') | undefined 'aria-autocomplete'?: 'both' | 'none' | 'inline' | 'list' | undefined 'aria-busy'?: (boolean | 'false' | 'true') | undefined 'aria-checked'?: 'mixed' | (boolean | 'false' | 'true') | undefined 'aria-colcount'?: (string | number) | undefined 'aria-colindex'?: (string | number) | undefined 'aria-colspan'?: (string | number) | undefined 'aria-controls'?: string | undefined 'aria-current'?: | 'page' | (boolean | 'false' | 'true') | 'step' | 'location' | 'date' | 'time' | undefined 'aria-describedby'?: string | undefined 'aria-details'?: string | undefined 'aria-disabled'?: (boolean | 'false' | 'true') | undefined 'aria-dropeffect'?: | 'link' | 'none' | 'copy' | 'move' | 'execute' | 'popup' | undefined 'aria-errormessage'?: string | undefined 'aria-expanded'?: (boolean | 'false' | 'true') | undefined 'aria-flowto'?: string | undefined 'aria-grabbed'?: (boolean | 'false' | 'true') | undefined 'aria-haspopup'?: | 'grid' | 'listbox' | 'menu' | (boolean | 'false' | 'true') | 'tree' | 'dialog' | undefined 'aria-hidden'?: (boolean | 'false' | 'true') | undefined 'aria-invalid'?: | (boolean | 'false' | 'true') | 'grammar' | 'spelling' | undefined 'aria-keyshortcuts'?: string | undefined 'aria-label'?: string | undefined 'aria-labelledby'?: string | undefined 'aria-level'?: (string | number) | undefined 'aria-live'?: 'off' | 'assertive' | 'polite' | undefined 'aria-modal'?: (boolean | 'false' | 'true') | undefined 'aria-multiline'?: (boolean | 'false' | 'true') | undefined 'aria-multiselectable'?: (boolean | 'false' | 'true') | undefined 'aria-orientation'?: 'horizontal' | 'vertical' | undefined 'aria-owns'?: string | undefined 'aria-placeholder'?: string | undefined 'aria-posinset'?: (string | number) | undefined 'aria-pressed'?: 'mixed' | (boolean | 'false' | 'true') | undefined 'aria-readonly'?: (boolean | 'false' | 'true') | undefined 'aria-relevant'?: | 'all' | 'text' | 'additions' | 'additions text' | 'removals' | undefined 'aria-required'?: (boolean | 'false' | 'true') | undefined 'aria-roledescription'?: string | undefined 'aria-rowcount'?: (string | number) | undefined 'aria-rowindex'?: (string | number) | undefined 'aria-rowspan'?: (string | number) | undefined 'aria-selected'?: (boolean | 'false' | 'true') | undefined 'aria-setsize'?: (string | number) | undefined 'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other' | undefined 'aria-valuemax'?: (string | number) | undefined 'aria-valuemin'?: (string | number) | undefined 'aria-valuenow'?: (string | number) | undefined 'aria-valuetext'?: string | undefined onCopy?: ((payload: ClipboardEvent) => void) | undefined onCut?: ((payload: ClipboardEvent) => void) | undefined onPaste?: ((payload: ClipboardEvent) => void) | undefined onCompositionend?: ((payload: CompositionEvent) => void) | undefined onCompositionstart?: ((payload: CompositionEvent) => void) | undefined onCompositionupdate?: ((payload: CompositionEvent) => void) | undefined onDrag?: ((payload: DragEvent) => void) | undefined onDragend?: ((payload: DragEvent) => void) | undefined onDragenter?: ((payload: DragEvent) => void) | undefined onDragexit?: ((payload: DragEvent) => void) | undefined onDragleave?: ((payload: DragEvent) => void) | undefined onDragover?: ((payload: DragEvent) => void) | undefined onDragstart?: ((payload: DragEvent) => void) | undefined onDrop?: ((payload: DragEvent) => void) | undefined onFocus?: ((payload: FocusEvent) => void) | undefined onFocusin?: ((payload: FocusEvent) => void) | undefined onFocusout?: ((payload: FocusEvent) => void) | undefined onBlur?: ((payload: FocusEvent) => void) | undefined onChange?: ((payload: Event) => void) | undefined onBeforeinput?: ((payload: Event) => void) | undefined onInput?: ((payload: Event) => void) | undefined onReset?: ((payload: Event) => void) | undefined onSubmit?: ((payload: Event) => void) | undefined onInvalid?: ((payload: Event) => void) | undefined onLoad?: ((payload: Event) => void) | undefined onError?: ((payload: Event) => void) | undefined onKeydown?: ((payload: KeyboardEvent) => void) | undefined onKeypress?: ((payload: KeyboardEvent) => void) | undefined onKeyup?: ((payload: KeyboardEvent) => void) | undefined onAuxclick?: ((payload: MouseEvent) => void) | undefined onClick?: ((payload: MouseEvent) => void) | undefined onContextmenu?: ((payload: MouseEvent) => void) | undefined onDblclick?: ((payload: MouseEvent) => void) | undefined onMousedown?: ((payload: MouseEvent) => void) | undefined onMouseenter?: ((payload: MouseEvent) => void) | undefined onMouseleave?: ((payload: MouseEvent) => void) | undefined onMousemove?: ((payload: MouseEvent) => void) | undefined onMouseout?: ((payload: MouseEvent) => void) | undefined onMouseover?: ((payload: MouseEvent) => void) | undefined onMouseup?: ((payload: MouseEvent) => void) | undefined onAbort?: ((payload: Event) => void) | undefined onCanplay?: ((payload: Event) => void) | undefined onCanplaythrough?: ((payload: Event) => void) | undefined onDurationchange?: ((payload: Event) => void) | undefined onEmptied?: ((payload: Event) => void) | undefined onEncrypted?: ((payload: Event) => void) | undefined onEnded?: ((payload: Event) => void) | undefined onLoadeddata?: ((payload: Event) => void) | undefined onLoadedmetadata?: ((payload: Event) => void) | undefined onLoadstart?: ((payload: Event) => void) | undefined onPause?: ((payload: Event) => void) | undefined onPlay?: ((payload: Event) => void) | undefined onPlaying?: ((payload: Event) => void) | undefined onProgress?: ((payload: Event) => void) | undefined onRatechange?: ((payload: Event) => void) | undefined onSeeked?: ((payload: Event) => void) | undefined onSeeking?: ((payload: Event) => void) | undefined onStalled?: ((payload: Event) => void) | undefined onSuspend?: ((payload: Event) => void) | undefined onTimeupdate?: ((payload: Event) => void) | undefined onVolumechange?: ((payload: Event) => void) | undefined onWaiting?: ((payload: Event) => void) | undefined onSelect?: ((payload: Event) => void) | undefined onScroll?: ((payload: UIEvent) => void) | undefined onTouchcancel?: ((payload: TouchEvent) => void) | undefined onTouchend?: ((payload: TouchEvent) => void) | undefined onTouchmove?: ((payload: TouchEvent) => void) | undefined onTouchstart?: ((payload: TouchEvent) => void) | undefined onPointerdown?: ((payload: PointerEvent) => void) | undefined onPointermove?: ((payload: PointerEvent) => void) | undefined onPointerup?: ((payload: PointerEvent) => void) | undefined onPointercancel?: ((payload: PointerEvent) => void) | undefined onPointerenter?: ((payload: PointerEvent) => void) | undefined onPointerleave?: ((payload: PointerEvent) => void) | undefined onPointerover?: ((payload: PointerEvent) => void) | undefined onPointerout?: ((payload: PointerEvent) => void) | undefined onWheel?: ((payload: WheelEvent) => void) | undefined onAnimationstart?: ((payload: AnimationEvent) => void) | undefined onAnimationend?: ((payload: AnimationEvent) => void) | undefined onAnimationiteration?: ((payload: AnimationEvent) => void) | undefined onTransitionend?: ((payload: TransitionEvent) => void) | undefined onTransitionstart?: ((payload: TransitionEvent) => void) | undefined } | { x?: string | number | undefined y?: string | number | undefined z?: string | number | undefined translateX?: string | number | undefined translateY?: string | number | undefined translateZ?: string | number | undefined rotate?: string | number | undefined rotateX?: string | number | undefined rotateY?: string | number | undefined rotateZ?: string | number | undefined scale?: string | number | undefined scaleX?: string | number | undefined scaleY?: string | number | undefined scaleZ?: string | number | undefined skew?: string | number | undefined skewX?: string | number | undefined skewY?: string | number | undefined originX?: string | number | undefined originY?: string | number | undefined originZ?: string | number | undefined perspective?: string | number | undefined transformPerspective?: string | number | undefined } | { pathLength?: number | undefined pathOffset?: number | undefined pathSpacing?: number | undefined } style: { alignContent?: string | undefined alignItems?: string | undefined alignSelf?: string | undefined alignTracks?: string | undefined animationDelay?: string | undefined animationDirection?: string | undefined animationDuration?: string | undefined animationFillMode?: string | undefined animationIterationCount?: | csstype.AnimationIterationCountProperty | undefined animationName?: string | undefined animationPlayState?: string | undefined animationTimingFunction?: string | undefined appearance?: csstype.AppearanceProperty | undefined aspectRatio?: string | undefined backdropFilter?: string | undefined backfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined backgroundAttachment?: string | undefined backgroundBlendMode?: string | undefined backgroundClip?: string | undefined backgroundColor?: string | undefined backgroundImage?: string | undefined backgroundOrigin?: string | undefined backgroundPositionX?: | csstype.BackgroundPositionXProperty<string | number> | undefined backgroundPositionY?: | csstype.BackgroundPositionYProperty<string | number> | undefined backgroundRepeat?: string | undefined backgroundSize?: csstype.BackgroundSizeProperty<string | number> | undefined blockOverflow?: string | undefined blockSize?: csstype.BlockSizeProperty<string | number> | undefined borderBlockColor?: string | undefined borderBlockEndColor?: string | undefined borderBlockEndStyle?: csstype.BorderBlockEndStyleProperty | undefined borderBlockEndWidth?: | csstype.BorderBlockEndWidthProperty<string | number> | undefined borderBlockStartColor?: string | undefined borderBlockStartStyle?: csstype.BorderBlockStartStyleProperty | undefined borderBlockStartWidth?: | csstype.BorderBlockStartWidthProperty<string | number> | undefined borderBlockStyle?: csstype.BorderBlockStyleProperty | undefined borderBlockWidth?: | csstype.BorderBlockWidthProperty<string | number> | undefined borderBottomColor?: string | undefined borderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined borderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined borderBottomStyle?: csstype.BorderBottomStyleProperty | undefined borderBottomWidth?: | csstype.BorderBottomWidthProperty<string | number> | undefined borderCollapse?: csstype.BorderCollapseProperty | undefined borderEndEndRadius?: | csstype.BorderEndEndRadiusProperty<string | number> | undefined borderEndStartRadius?: | csstype.BorderEndStartRadiusProperty<string | number> | undefined borderImageOutset?: | csstype.BorderImageOutsetProperty<string | number> | undefined borderImageRepeat?: string | undefined borderImageSlice?: csstype.BorderImageSliceProperty | undefined borderImageSource?: string | undefined borderImageWidth?: | csstype.BorderImageWidthProperty<string | number> | undefined borderInlineColor?: string | undefined borderInlineEndColor?: string | undefined borderInlineEndStyle?: csstype.BorderInlineEndStyleProperty | undefined borderInlineEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined borderInlineStartColor?: string | undefined borderInlineStartStyle?: csstype.BorderInlineStartStyleProperty | undefined borderInlineStartWidth?: | csstype.BorderInlineStartWidthProperty<string | number> | undefined borderInlineStyle?: csstype.BorderInlineStyleProperty | undefined borderInlineWidth?: | csstype.BorderInlineWidthProperty<string | number> | undefined borderLeftColor?: string | undefined borderLeftStyle?: csstype.BorderLeftStyleProperty | undefined borderLeftWidth?: | csstype.BorderLeftWidthProperty<string | number> | undefined borderRightColor?: string | undefined borderRightStyle?: csstype.BorderRightStyleProperty | undefined borderRightWidth?: | csstype.BorderRightWidthProperty<string | number> | undefined borderSpacing?: csstype.BorderSpacingProperty<string | number> | undefined borderStartEndRadius?: | csstype.BorderStartEndRadiusProperty<string | number> | undefined borderStartStartRadius?: | csstype.BorderStartStartRadiusProperty<string | number> | undefined borderTopColor?: string | undefined borderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined borderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined borderTopStyle?: csstype.BorderTopStyleProperty | undefined borderTopWidth?: csstype.BorderTopWidthProperty<string | number> | undefined bottom?: csstype.BottomProperty<string | number> | undefined boxDecorationBreak?: csstype.BoxDecorationBreakProperty | undefined boxShadow?: string | undefined boxSizing?: csstype.BoxSizingProperty | undefined breakAfter?: csstype.BreakAfterProperty | undefined breakBefore?: csstype.BreakBeforeProperty | undefined breakInside?: csstype.BreakInsideProperty | undefined captionSide?: csstype.CaptionSideProperty | undefined caretColor?: string | undefined clear?: csstype.ClearProperty | undefined clipPath?: string | undefined color?: string | undefined colorAdjust?: csstype.ColorAdjustProperty | undefined colorScheme?: string | undefined columnCount?: csstype.ColumnCountProperty | undefined columnFill?: csstype.ColumnFillProperty | undefined columnGap?: csstype.ColumnGapProperty<string | number> | undefined columnRuleColor?: string | undefined columnRuleStyle?: string | undefined columnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined columnSpan?: csstype.ColumnSpanProperty | undefined columnWidth?: csstype.ColumnWidthProperty<string | number> | undefined contain?: string | undefined content?: string | undefined contentVisibility?: csstype.ContentVisibilityProperty | undefined counterIncrement?: string | undefined counterReset?: string | undefined counterSet?: string | undefined cursor?: string | undefined direction?: csstype.DirectionProperty | undefined display?: string | undefined emptyCells?: csstype.EmptyCellsProperty | undefined filter?: string | undefined flexBasis?: csstype.FlexBasisProperty<string | number> | undefined flexDirection?: csstype.FlexDirectionProperty | undefined flexGrow?: csstype.GlobalsNumber | undefined flexShrink?: csstype.GlobalsNumber | undefined flexWrap?: csstype.FlexWrapProperty | undefined float?: csstype.FloatProperty | undefined fontFamily?: string | undefined fontFeatureSettings?: string | undefined fontKerning?: csstype.FontKerningProperty | undefined fontLanguageOverride?: string | undefined fontOpticalSizing?: csstype.FontOpticalSizingProperty | undefined fontSize?: csstype.FontSizeProperty<string | number> | undefined fontSizeAdjust?: csstype.FontSizeAdjustProperty | undefined fontSmooth?: csstype.FontSmoothProperty<string | number> | undefined fontStretch?: string | undefined fontStyle?: string | undefined fontSynthesis?: string | undefined fontVariant?: string | undefined fontVariantCaps?: csstype.FontVariantCapsProperty | undefined fontVariantEastAsian?: string | undefined fontVariantLigatures?: string | undefined fontVariantNumeric?: string | undefined fontVariantPosition?: csstype.FontVariantPositionProperty | undefined fontVariationSettings?: string | undefined fontWeight?: csstype.FontWeightProperty | undefined forcedColorAdjust?: csstype.ForcedColorAdjustProperty | undefined gridAutoColumns?: | csstype.GridAutoColumnsProperty<string | number> | undefined gridAutoFlow?: string | undefined gridAutoRows?: csstype.GridAutoRowsProperty<string | number> | undefined gridColumnEnd?: csstype.GridColumnEndProperty | undefined gridColumnStart?: csstype.GridColumnStartProperty | undefined gridRowEnd?: csstype.GridRowEndProperty | undefined gridRowStart?: csstype.GridRowStartProperty | undefined gridTemplateAreas?: string | undefined gridTemplateColumns?: | csstype.GridTemplateColumnsProperty<string | number> | undefined gridTemplateRows?: | csstype.GridTemplateRowsProperty<string | number> | undefined hangingPunctuation?: string | undefined height?: csstype.HeightProperty<string | number> | undefined hyphens?: csstype.HyphensProperty | undefined imageOrientation?: string | undefined imageRendering?: csstype.ImageRenderingProperty | undefined imageResolution?: string | undefined initialLetter?: csstype.InitialLetterProperty | undefined inlineSize?: csstype.InlineSizeProperty<string | number> | undefined inset?: csstype.InsetProperty<string | number> | undefined insetBlock?: csstype.InsetBlockProperty<string | number> | undefined insetBlockEnd?: csstype.InsetBlockEndProperty<string | number> | undefined insetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined insetInline?: csstype.InsetInlineProperty<string | number> | undefined insetInlineEnd?: csstype.InsetInlineEndProperty<string | number> | undefined insetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined isolation?: csstype.IsolationProperty | undefined justifyContent?: string | undefined justifyItems?: string | undefined justifySelf?: string | undefined justifyTracks?: string | undefined left?: csstype.LeftProperty<string | number> | undefined letterSpacing?: csstype.LetterSpacingProperty<string | number> | undefined lineBreak?: csstype.LineBreakProperty | undefined lineHeight?: csstype.LineHeightProperty<string | number> | undefined lineHeightStep?: csstype.LineHeightStepProperty<string | number> | undefined listStyleImage?: string | undefined listStylePosition?: csstype.ListStylePositionProperty | undefined listStyleType?: string | undefined marginBlock?: csstype.MarginBlockProperty<string | number> | undefined marginBlockEnd?: csstype.MarginBlockEndProperty<string | number> | undefined marginBlockStart?: | csstype.MarginBlockStartProperty<string | number> | undefined marginBottom?: csstype.MarginBottomProperty<string | number> | undefined marginInline?: csstype.MarginInlineProperty<string | number> | undefined marginInlineEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined marginInlineStart?: | csstype.MarginInlineStartProperty<string | number> | undefined marginLeft?: csstype.MarginLeftProperty<string | number> | undefined marginRight?: csstype.MarginRightProperty<string | number> | undefined marginTop?: csstype.MarginTopProperty<string | number> | undefined maskBorderMode?: csstype.MaskBorderModeProperty | undefined maskBorderOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined maskBorderRepeat?: string | undefined maskBorderSlice?: csstype.MaskBorderSliceProperty | undefined maskBorderSource?: string | undefined maskBorderWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined maskClip?: string | undefined maskComposite?: string | undefined maskImage?: string | undefined maskMode?: string | undefined maskOrigin?: string | undefined maskPosition?: csstype.MaskPositionProperty<string | number> | undefined maskRepeat?: string | undefined maskSize?: csstype.MaskSizeProperty<string | number> | undefined maskType?: csstype.MaskTypeProperty | undefined mathStyle?: csstype.MathStyleProperty | undefined maxBlockSize?: csstype.MaxBlockSizeProperty<string | number> | undefined maxHeight?: csstype.MaxHeightProperty<string | number> | undefined maxInlineSize?: csstype.MaxInlineSizeProperty<string | number> | undefined maxLines?: csstype.MaxLinesProperty | undefined maxWidth?: csstype.MaxWidthProperty<string | number> | undefined minBlockSize?: csstype.MinBlockSizeProperty<string | number> | undefined minHeight?: csstype.MinHeightProperty<string | number> | undefined minInlineSize?: csstype.MinInlineSizeProperty<string | number> | undefined minWidth?: csstype.MinWidthProperty<string | number> | undefined mixBlendMode?: csstype.MixBlendModeProperty | undefined motionDistance?: csstype.OffsetDistanceProperty<string | number> | undefined motionPath?: string | undefined motionRotation?: string | undefined objectFit?: csstype.ObjectFitProperty | undefined objectPosition?: csstype.ObjectPositionProperty<string | number> | undefined offsetAnchor?: csstype.OffsetAnchorProperty<string | number> | undefined offsetDistance?: csstype.OffsetDistanceProperty<string | number> | undefined offsetPath?: string | undefined offsetRotate?: string | undefined offsetRotation?: string | undefined opacity?: csstype.OpacityProperty | undefined order?: csstype.GlobalsNumber | undefined orphans?: csstype.GlobalsNumber | undefined outlineColor?: string | undefined outlineOffset?: csstype.OutlineOffsetProperty<string | number> | undefined outlineStyle?: string | undefined outlineWidth?: csstype.OutlineWidthProperty<string | number> | undefined overflowAnchor?: csstype.OverflowAnchorProperty | undefined overflowBlock?: csstype.OverflowBlockProperty | undefined overflowClipBox?: csstype.OverflowClipBoxProperty | undefined overflowClipMargin?: | csstype.OverflowClipMarginProperty<string | number> | undefined overflowInline?: csstype.OverflowInlineProperty | undefined overflowWrap?: csstype.OverflowWrapProperty | undefined overflowX?: csstype.OverflowXProperty | undefined overflowY?: csstype.OverflowYProperty | undefined overscrollBehaviorBlock?: | csstype.OverscrollBehaviorBlockProperty | undefined overscrollBehaviorInline?: | csstype.OverscrollBehaviorInlineProperty | undefined overscrollBehaviorX?: csstype.OverscrollBehaviorXProperty | undefined overscrollBehaviorY?: csstype.OverscrollBehaviorYProperty | undefined paddingBlock?: csstype.PaddingBlockProperty<string | number> | undefined paddingBlockEnd?: | csstype.PaddingBlockEndProperty<string | number> | undefined paddingBlockStart?: | csstype.PaddingBlockStartProperty<string | number> | undefined paddingBottom?: csstype.PaddingBottomProperty<string | number> | undefined paddingInline?: csstype.PaddingInlineProperty<string | number> | undefined paddingInlineEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined paddingInlineStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined paddingLeft?: csstype.PaddingLeftProperty<string | number> | undefined paddingRight?: csstype.PaddingRightProperty<string | number> | undefined paddingTop?: csstype.PaddingTopProperty<string | number> | undefined pageBreakAfter?: csstype.PageBreakAfterProperty | undefined pageBreakBefore?: csstype.PageBreakBeforeProperty | undefined pageBreakInside?: csstype.PageBreakInsideProperty | undefined paintOrder?: string | undefined perspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined placeContent?: string | undefined pointerEvents?: csstype.PointerEventsProperty | undefined position?: csstype.PositionProperty | undefined quotes?: string | undefined resize?: csstype.ResizeProperty | undefined right?: csstype.RightProperty<string | number> | undefined rowGap?: csstype.RowGapProperty<string | number> | undefined rubyAlign?: csstype.RubyAlignProperty | undefined rubyMerge?: csstype.RubyMergeProperty | undefined rubyPosition?: string | undefined scrollBehavior?: csstype.ScrollBehaviorProperty | undefined scrollMargin?: csstype.ScrollMarginProperty<string | number> | undefined scrollMarginBlock?: | csstype.ScrollMarginBlockProperty<string | number> | undefined scrollMarginBlockEnd?: | csstype.ScrollMarginBlockEndProperty<string | number> | undefined scrollMarginBlockStart?: | csstype.ScrollMarginBlockStartProperty<string | number> | undefined scrollMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollMarginInline?: | csstype.ScrollMarginInlineProperty<string | number> | undefined scrollMarginInlineEnd?: | csstype.ScrollMarginInlineEndProperty<string | number> | undefined scrollMarginInlineStart?: | csstype.ScrollMarginInlineStartProperty<string | number> | undefined scrollMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollPadding?: csstype.ScrollPaddingProperty<string | number> | undefined scrollPaddingBlock?: | csstype.ScrollPaddingBlockProperty<string | number> | undefined scrollPaddingBlockEnd?: | csstype.ScrollPaddingBlockEndProperty<string | number> | undefined scrollPaddingBlockStart?: | csstype.ScrollPaddingBlockStartProperty<string | number> | undefined scrollPaddingBottom?: | csstype.ScrollPaddingBottomProperty<string | number> | undefined scrollPaddingInline?: | csstype.ScrollPaddingInlineProperty<string | number> | undefined scrollPaddingInlineEnd?: | csstype.ScrollPaddingInlineEndProperty<string | number> | undefined scrollPaddingInlineStart?: | csstype.ScrollPaddingInlineStartProperty<string | number> | undefined scrollPaddingLeft?: | csstype.ScrollPaddingLeftProperty<string | number> | undefined scrollPaddingRight?: | csstype.ScrollPaddingRightProperty<string | number> | undefined scrollPaddingTop?: | csstype.ScrollPaddingTopProperty<string | number> | undefined scrollSnapAlign?: string | undefined scrollSnapMargin?: csstype.ScrollMarginProperty<string | number> | undefined scrollSnapMarginBottom?: | csstype.ScrollMarginBottomProperty<string | number> | undefined scrollSnapMarginLeft?: | csstype.ScrollMarginLeftProperty<string | number> | undefined scrollSnapMarginRight?: | csstype.ScrollMarginRightProperty<string | number> | undefined scrollSnapMarginTop?: | csstype.ScrollMarginTopProperty<string | number> | undefined scrollSnapStop?: csstype.ScrollSnapStopProperty | undefined scrollSnapType?: string | undefined scrollbarColor?: string | undefined scrollbarGutter?: string | undefined scrollbarWidth?: csstype.ScrollbarWidthProperty | undefined shapeImageThreshold?: csstype.ShapeImageThresholdProperty | undefined shapeMargin?: csstype.ShapeMarginProperty<string | number> | undefined shapeOutside?: string | undefined tabSize?: csstype.TabSizeProperty<string | number> | undefined tableLayout?: csstype.TableLayoutProperty | undefined textAlign?: csstype.TextAlignProperty | undefined textAlignLast?: csstype.TextAlignLastProperty | undefined textCombineUpright?: string | undefined textDecorationColor?: string | undefined textDecorationLine?: string | undefined textDecorationSkip?: string | undefined textDecorationSkipInk?: csstype.TextDecorationSkipInkProperty | undefined textDecorationStyle?: csstype.TextDecorationStyleProperty | undefined textDecorationThickness?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textDecorationWidth?: | csstype.TextDecorationThicknessProperty<string | number> | undefined textEmphasisColor?: string | undefined textEmphasisPosition?: string | undefined textEmphasisStyle?: string | undefined textIndent?: csstype.TextIndentProperty<string | number> | undefined textJustify?: csstype.TextJustifyProperty | undefined textOrientation?: csstype.TextOrientationProperty | undefined textOverflow?: string | undefined textRendering?: csstype.TextRenderingProperty | undefined textShadow?: string | undefined textSizeAdjust?: string | undefined textTransform?: csstype.TextTransformProperty | undefined textUnderlineOffset?: | csstype.TextUnderlineOffsetProperty<string | number> | undefined textUnderlinePosition?: string | undefined top?: csstype.TopProperty<string | number> | undefined touchAction?: string | undefined transitionDelay?: string | undefined transitionDuration?: string | undefined transitionProperty?: string | undefined transitionTimingFunction?: string | undefined translate?: csstype.TranslateProperty<string | number> | undefined unicodeBidi?: csstype.UnicodeBidiProperty | undefined userSelect?: csstype.UserSelectProperty | undefined verticalAlign?: csstype.VerticalAlignProperty<string | number> | undefined visibility?: csstype.VisibilityProperty | undefined whiteSpace?: csstype.WhiteSpaceProperty | undefined widows?: csstype.GlobalsNumber | undefined width?: csstype.WidthProperty<string | number> | undefined willChange?: string | undefined wordBreak?: csstype.WordBreakProperty | undefined wordSpacing?: csstype.WordSpacingProperty<string | number> | undefined wordWrap?: csstype.WordWrapProperty | undefined writingMode?: csstype.WritingModeProperty | undefined zIndex?: csstype.ZIndexProperty | undefined zoom?: csstype.ZoomProperty | undefined all?: csstype.Globals | undefined animation?: csstype.AnimationProperty | undefined background?: csstype.BackgroundProperty<string | number> | undefined backgroundPosition?: | csstype.BackgroundPositionProperty<string | number> | undefined border?: csstype.BorderProperty<string | number> | undefined borderBlock?: csstype.BorderBlockProperty<string | number> | undefined borderBlockEnd?: csstype.BorderBlockEndProperty<string | number> | undefined borderBlockStart?: | csstype.BorderBlockStartProperty<string | number> | undefined borderBottom?: csstype.BorderBottomProperty<string | number> | undefined borderColor?: string | undefined borderImage?: csstype.BorderImageProperty | undefined borderInline?: csstype.BorderInlineProperty<string | number> | undefined borderInlineEnd?: | csstype.BorderInlineEndProperty<string | number> | undefined borderInlineStart?: | csstype.BorderInlineStartProperty<string | number> | undefined borderLeft?: csstype.BorderLeftProperty<string | number> | undefined borderRadius?: csstype.BorderRadiusProperty<string | number> | undefined borderRight?: csstype.BorderRightProperty<string | number> | undefined borderStyle?: string | undefined borderTop?: csstype.BorderTopProperty<string | number> | undefined borderWidth?: csstype.BorderWidthProperty<string | number> | undefined columnRule?: csstype.ColumnRuleProperty<string | number> | undefined columns?: csstype.ColumnsProperty<string | number> | undefined flex?: csstype.FlexProperty<string | number> | undefined flexFlow?: string | undefined font?: string | undefined gap?: csstype.GapProperty<string | number> | undefined grid?: string | undefined gridArea?: csstype.GridAreaProperty | undefined gridColumn?: csstype.GridColumnProperty | undefined gridRow?: csstype.GridRowProperty | undefined gridTemplate?: string | undefined lineClamp?: csstype.LineClampProperty | undefined listStyle?: string | undefined margin?: csstype.MarginProperty<string | number> | undefined mask?: csstype.MaskProperty<string | number> | undefined maskBorder?: csstype.MaskBorderProperty | undefined motion?: csstype.OffsetProperty<string | number> | undefined offset?: csstype.OffsetProperty<string | number> | undefined outline?: csstype.OutlineProperty<string | number> | undefined overflow?: string | undefined overscrollBehavior?: string | undefined padding?: csstype.PaddingProperty<string | number> | undefined placeItems?: string | undefined placeSelf?: string | undefined textDecoration?: csstype.TextDecorationProperty<string | number> | undefined textEmphasis?: string | undefined MozAnimationDelay?: string | undefined MozAnimationDirection?: string | undefined MozAnimationDuration?: string | undefined MozAnimationFillMode?: string | undefined MozAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined MozAnimationName?: string | undefined MozAnimationPlayState?: string | undefined MozAnimationTimingFunction?: string | undefined MozAppearance?: csstype.MozAppearanceProperty | undefined MozBackfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined MozBorderBottomColors?: string | undefined MozBorderEndColor?: string | undefined MozBorderEndStyle?: csstype.BorderInlineEndStyleProperty | undefined MozBorderEndWidth?: | csstype.BorderInlineEndWidthProperty<string | number> | undefined MozBorderLeftColors?: string | undefined MozBorderRightColors?: string | undefined MozBorderStartColor?: string | undefined MozBorderStartStyle?: csstype.BorderInlineStartStyleProperty | undefined MozBorderTopColors?: string | undefined MozBoxSizing?: csstype.BoxSizingProperty | undefined MozColumnCount?: csstype.ColumnCountProperty | undefined MozColumnFill?: csstype.ColumnFillProperty | undefined MozColumnGap?: csstype.ColumnGapProperty<string | number> | undefined MozColumnRuleColor?: string | undefined MozColumnRuleStyle?: string | undefined MozColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined MozColumnWidth?: csstype.ColumnWidthProperty<string | number> | undefined MozContextProperties?: string | undefined MozFontFeatureSettings?: string | undefined MozFontLanguageOverride?: string | undefined MozHyphens?: csstype.HyphensProperty | undefined MozImageRegion?: string | undefined MozMarginEnd?: csstype.MarginInlineEndProperty<string | number> | undefined MozMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined MozOrient?: csstype.MozOrientProperty | undefined MozOsxFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined MozPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined MozPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined MozPerspective?: csstype.PerspectiveProperty<string | number> | undefined MozPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined MozStackSizing?: csstype.MozStackSizingProperty | undefined MozTabSize?: csstype.TabSizeProperty<string | number> | undefined MozTextBlink?: csstype.MozTextBlinkProperty | undefined MozTextSizeAdjust?: string | undefined MozTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined MozTransformStyle?: csstype.TransformStyleProperty | undefined MozTransitionDelay?: string | undefined MozTransitionDuration?: string | undefined MozTransitionProperty?: string | undefined MozTransitionTimingFunction?: string | undefined MozUserFocus?: csstype.MozUserFocusProperty | undefined MozUserModify?: csstype.MozUserModifyProperty | undefined MozUserSelect?: csstype.UserSelectProperty | undefined MozWindowDragging?: csstype.MozWindowDraggingProperty | undefined MozWindowShadow?: csstype.MozWindowShadowProperty | undefined msAccelerator?: csstype.MsAcceleratorProperty | undefined msAlignSelf?: string | undefined msBlockProgression?: csstype.MsBlockProgressionProperty | undefined msContentZoomChaining?: csstype.MsContentZoomChainingProperty | undefined msContentZoomLimitMax?: string | undefined msContentZoomLimitMin?: string | undefined msContentZoomSnapPoints?: string | undefined msContentZoomSnapType?: csstype.MsContentZoomSnapTypeProperty | undefined msContentZooming?: csstype.MsContentZoomingProperty | undefined msFilter?: string | undefined msFlexDirection?: csstype.FlexDirectionProperty | undefined msFlexPositive?: csstype.GlobalsNumber | undefined msFlowFrom?: string | undefined msFlowInto?: string | undefined msGridColumns?: csstype.MsGridColumnsProperty<string | number> | undefined msGridRows?: csstype.MsGridRowsProperty<string | number> | undefined msHighContrastAdjust?: csstype.MsHighContrastAdjustProperty | undefined msHyphenateLimitChars?: csstype.MsHyphenateLimitCharsProperty | undefined msHyphenateLimitLines?: csstype.MsHyphenateLimitLinesProperty | undefined msHyphenateLimitZone?: | csstype.MsHyphenateLimitZoneProperty<string | number> | undefined msHyphens?: csstype.HyphensProperty | undefined msImeAlign?: csstype.MsImeAlignProperty | undefined msJustifySelf?: string | undefined msLineBreak?: csstype.LineBreakProperty | undefined msOrder?: csstype.GlobalsNumber | undefined msOverflowStyle?: csstype.MsOverflowStyleProperty | undefined msOverflowX?: csstype.OverflowXProperty | undefined msOverflowY?: csstype.OverflowYProperty | undefined msScrollChaining?: csstype.MsScrollChainingProperty | undefined msScrollLimitXMax?: | csstype.MsScrollLimitXMaxProperty<string | number> | undefined msScrollLimitXMin?: | csstype.MsScrollLimitXMinProperty<string | number> | undefined msScrollLimitYMax?: | csstype.MsScrollLimitYMaxProperty<string | number> | undefined msScrollLimitYMin?: | csstype.MsScrollLimitYMinProperty<string | number> | undefined msScrollRails?: csstype.MsScrollRailsProperty | undefined msScrollSnapPointsX?: string | undefined msScrollSnapPointsY?: string | undefined msScrollSnapType?: csstype.MsScrollSnapTypeProperty | undefined msScrollTranslation?: csstype.MsScrollTranslationProperty | undefined msScrollbar3dlightColor?: string | undefined msScrollbarArrowColor?: string | undefined msScrollbarBaseColor?: string | undefined msScrollbarDarkshadowColor?: string | undefined msScrollbarFaceColor?: string | undefined msScrollbarHighlightColor?: string | undefined msScrollbarShadowColor?: string | undefined msTextAutospace?: csstype.MsTextAutospaceProperty | undefined msTextCombineHorizontal?: string | undefined msTextOverflow?: string | undefined msTouchAction?: string | undefined msTouchSelect?: csstype.MsTouchSelectProperty | undefined msTransform?: string | undefined msTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined msTransitionDelay?: string | undefined msTransitionDuration?: string | undefined msTransitionProperty?: string | undefined msTransitionTimingFunction?: string | undefined msUserSelect?: csstype.MsUserSelectProperty | undefined msWordBreak?: csstype.WordBreakProperty | undefined msWrapFlow?: csstype.MsWrapFlowProperty | undefined msWrapMargin?: csstype.MsWrapMarginProperty<string | number> | undefined msWrapThrough?: csstype.MsWrapThroughProperty | undefined msWritingMode?: csstype.WritingModeProperty | undefined WebkitAlignContent?: string | undefined WebkitAlignItems?: string | undefined WebkitAlignSelf?: string | undefined WebkitAnimationDelay?: string | undefined WebkitAnimationDirection?: string | undefined WebkitAnimationDuration?: string | undefined WebkitAnimationFillMode?: string | undefined WebkitAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined WebkitAnimationName?: string | undefined WebkitAnimationPlayState?: string | undefined WebkitAnimationTimingFunction?: string | undefined WebkitAppearance?: csstype.WebkitAppearanceProperty | undefined WebkitBackdropFilter?: string | undefined WebkitBackfaceVisibility?: csstype.BackfaceVisibilityProperty | undefined WebkitBackgroundClip?: string | undefined WebkitBackgroundOrigin?: string | undefined WebkitBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined WebkitBorderBeforeColor?: string | undefined WebkitBorderBeforeStyle?: string | undefined WebkitBorderBeforeWidth?: | csstype.WebkitBorderBeforeWidthProperty<string | number> | undefined WebkitBorderBottomLeftRadius?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined WebkitBorderBottomRightRadius?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined WebkitBorderImageSlice?: csstype.BorderImageSliceProperty | undefined WebkitBorderTopLeftRadius?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined WebkitBorderTopRightRadius?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined WebkitBoxDecorationBreak?: csstype.BoxDecorationBreakProperty | undefined WebkitBoxReflect?: | csstype.WebkitBoxReflectProperty<string | number> | undefined WebkitBoxShadow?: string | undefined WebkitBoxSizing?: csstype.BoxSizingProperty | undefined WebkitClipPath?: string | undefined WebkitColumnCount?: csstype.ColumnCountProperty | undefined WebkitColumnFill?: csstype.ColumnFillProperty | undefined WebkitColumnGap?: csstype.ColumnGapProperty<string | number> | undefined WebkitColumnRuleColor?: string | undefined WebkitColumnRuleStyle?: string | undefined WebkitColumnRuleWidth?: | csstype.ColumnRuleWidthProperty<string | number> | undefined WebkitColumnSpan?: csstype.ColumnSpanProperty | undefined WebkitColumnWidth?: csstype.ColumnWidthProperty<string | number> | undefined WebkitFilter?: string | undefined WebkitFlexBasis?: csstype.FlexBasisProperty<string | number> | undefined WebkitFlexDirection?: csstype.FlexDirectionProperty | undefined WebkitFlexGrow?: csstype.GlobalsNumber | undefined WebkitFlexShrink?: csstype.GlobalsNumber | undefined WebkitFlexWrap?: csstype.FlexWrapProperty | undefined WebkitFontFeatureSettings?: string | undefined WebkitFontKerning?: csstype.FontKerningProperty | undefined WebkitFontSmoothing?: | csstype.FontSmoothProperty<string | number> | undefined WebkitFontVariantLigatures?: string | undefined WebkitHyphens?: csstype.HyphensProperty | undefined WebkitJustifyContent?: string | undefined WebkitLineBreak?: csstype.LineBreakProperty | undefined WebkitLineClamp?: csstype.WebkitLineClampProperty | undefined WebkitMarginEnd?: | csstype.MarginInlineEndProperty<string | number> | undefined WebkitMarginStart?: | csstype.MarginInlineStartProperty<string | number> | undefined WebkitMaskAttachment?: string | undefined WebkitMaskBoxImageOutset?: | csstype.MaskBorderOutsetProperty<string | number> | undefined WebkitMaskBoxImageRepeat?: string | undefined WebkitMaskBoxImageSlice?: csstype.MaskBorderSliceProperty | undefined WebkitMaskBoxImageSource?: string | undefined WebkitMaskBoxImageWidth?: | csstype.MaskBorderWidthProperty<string | number> | undefined WebkitMaskClip?: string | undefined WebkitMaskComposite?: string | undefined WebkitMaskImage?: string | undefined WebkitMaskOrigin?: string | undefined WebkitMaskPosition?: | csstype.WebkitMaskPositionProperty<string | number> | undefined WebkitMaskPositionX?: | csstype.WebkitMaskPositionXProperty<string | number> | undefined WebkitMaskPositionY?: | csstype.WebkitMaskPositionYProperty<string | number> | undefined WebkitMaskRepeat?: string | undefined WebkitMaskRepeatX?: csstype.WebkitMaskRepeatXProperty | undefined WebkitMaskRepeatY?: csstype.WebkitMaskRepeatYProperty | undefined WebkitMaskSize?: csstype.WebkitMaskSizeProperty<string | number> | undefined WebkitMaxInlineSize?: | csstype.MaxInlineSizeProperty<string | number> | undefined WebkitOrder?: csstype.GlobalsNumber | undefined WebkitOverflowScrolling?: | csstype.WebkitOverflowScrollingProperty | undefined WebkitPaddingEnd?: | csstype.PaddingInlineEndProperty<string | number> | undefined WebkitPaddingStart?: | csstype.PaddingInlineStartProperty<string | number> | undefined WebkitPerspective?: csstype.PerspectiveProperty<string | number> | undefined WebkitPerspectiveOrigin?: | csstype.PerspectiveOriginProperty<string | number> | undefined WebkitPrintColorAdjust?: csstype.ColorAdjustProperty | undefined WebkitRubyPosition?: string | undefined WebkitScrollSnapType?: string | undefined WebkitShapeMargin?: csstype.ShapeMarginProperty<string | number> | undefined WebkitTapHighlightColor?: string | undefined WebkitTextCombine?: string | undefined WebkitTextDecorationColor?: string | undefined WebkitTextDecorationLine?: string | undefined WebkitTextDecorationSkip?: string | undefined WebkitTextDecorationStyle?: csstype.TextDecorationStyleProperty | undefined WebkitTextEmphasisColor?: string | undefined WebkitTextEmphasisPosition?: string | undefined WebkitTextEmphasisStyle?: string | undefined WebkitTextFillColor?: string | undefined WebkitTextOrientation?: csstype.TextOrientationProperty | undefined WebkitTextSizeAdjust?: string | undefined WebkitTextStrokeColor?: string | undefined WebkitTextStrokeWidth?: | csstype.WebkitTextStrokeWidthProperty<string | number> | undefined WebkitTextUnderlinePosition?: string | undefined WebkitTouchCallout?: csstype.WebkitTouchCalloutProperty | undefined WebkitTransform?: string | undefined WebkitTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined WebkitTransformStyle?: csstype.TransformStyleProperty | undefined WebkitTransitionDelay?: string | undefined WebkitTransitionDuration?: string | undefined WebkitTransitionProperty?: string | undefined WebkitTransitionTimingFunction?: string | undefined WebkitUserModify?: csstype.WebkitUserModifyProperty | undefined WebkitUserSelect?: csstype.UserSelectProperty | undefined WebkitWritingMode?: csstype.WritingModeProperty | undefined MozAnimation?: csstype.AnimationProperty | undefined MozBorderImage?: csstype.BorderImageProperty | undefined MozColumnRule?: csstype.ColumnRuleProperty<string | number> | undefined MozColumns?: csstype.ColumnsProperty<string | number> | undefined MozTransition?: string | undefined msContentZoomLimit?: string | undefined msContentZoomSnap?: string | undefined msFlex?: csstype.FlexProperty<string | number> | undefined msScrollLimit?: string | undefined msScrollSnapX?: string | undefined msScrollSnapY?: string | undefined msTransition?: string | undefined WebkitAnimation?: csstype.AnimationProperty | undefined WebkitBorderBefore?: | csstype.WebkitBorderBeforeProperty<string | number> | undefined WebkitBorderImage?: csstype.BorderImageProperty | undefined WebkitBorderRadius?: | csstype.BorderRadiusProperty<string | number> | undefined WebkitColumnRule?: csstype.ColumnRuleProperty<string | number> | undefined WebkitColumns?: csstype.ColumnsProperty<string | number> | undefined WebkitFlex?: csstype.FlexProperty<string | number> | undefined WebkitFlexFlow?: string | undefined WebkitMask?: csstype.WebkitMaskProperty<string | number> | undefined WebkitMaskBoxImage?: csstype.MaskBorderProperty | undefined WebkitTextEmphasis?: string | undefined WebkitTextStroke?: | csstype.WebkitTextStrokeProperty<string | number> | undefined WebkitTransition?: string | undefined azimuth?: string | undefined boxAlign?: csstype.BoxAlignProperty | undefined boxDirection?: csstype.BoxDirectionProperty | undefined boxFlex?: csstype.GlobalsNumber | undefined boxFlexGroup?: csstype.GlobalsNumber | undefined boxLines?: csstype.BoxLinesProperty | undefined boxOrdinalGroup?: csstype.GlobalsNumber | undefined boxOrient?: csstype.BoxOrientProperty | undefined boxPack?: csstype.BoxPackProperty | undefined clip?: string | undefined fontVariantAlternates?: string | undefined gridColumnGap?: csstype.GridColumnGapProperty<string | number> | undefined gridGap?: csstype.GridGapProperty<string | number> | undefined gridRowGap?: csstype.GridRowGapProperty<string | number> | undefined imeMode?: csstype.ImeModeProperty | undefined offsetBlock?: csstype.InsetBlockProperty<string | number> | undefined offsetBlockEnd?: csstype.InsetBlockEndProperty<string | number> | undefined offsetBlockStart?: | csstype.InsetBlockStartProperty<string | number> | undefined offsetInline?: csstype.InsetInlineProperty<string | number> | undefined offsetInlineEnd?: | csstype.InsetInlineEndProperty<string | number> | undefined offsetInlineStart?: | csstype.InsetInlineStartProperty<string | number> | undefined scrollSnapCoordinate?: | csstype.ScrollSnapCoordinateProperty<string | number> | undefined scrollSnapDestination?: | csstype.ScrollSnapDestinationProperty<string | number> | undefined scrollSnapPointsX?: string | undefined scrollSnapPointsY?: string | undefined scrollSnapTypeX?: csstype.ScrollSnapTypeXProperty | undefined scrollSnapTypeY?: csstype.ScrollSnapTypeYProperty | undefined scrollbarTrackColor?: string | undefined KhtmlBoxAlign?: csstype.BoxAlignProperty | undefined KhtmlBoxDirection?: csstype.BoxDirectionProperty | undefined KhtmlBoxFlex?: csstype.GlobalsNumber | undefined KhtmlBoxFlexGroup?: csstype.GlobalsNumber | undefined KhtmlBoxLines?: csstype.BoxLinesProperty | undefined KhtmlBoxOrdinalGroup?: csstype.GlobalsNumber | undefined KhtmlBoxOrient?: csstype.BoxOrientProperty | undefined KhtmlBoxPack?: csstype.BoxPackProperty | undefined KhtmlLineBreak?: csstype.LineBreakProperty | undefined KhtmlOpacity?: csstype.OpacityProperty | undefined KhtmlUserSelect?: csstype.UserSelectProperty | undefined MozBackgroundClip?: string | undefined MozBackgroundInlinePolicy?: csstype.BoxDecorationBreakProperty | undefined MozBackgroundOrigin?: string | undefined MozBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined MozBinding?: string | undefined MozBorderRadius?: csstype.BorderRadiusProperty<string | number> | undefined MozBorderRadiusBottomleft?: | csstype.BorderBottomLeftRadiusProperty<string | number> | undefined MozBorderRadiusBottomright?: | csstype.BorderBottomRightRadiusProperty<string | number> | undefined MozBorderRadiusTopleft?: | csstype.BorderTopLeftRadiusProperty<string | number> | undefined MozBorderRadiusTopright?: | csstype.BorderTopRightRadiusProperty<string | number> | undefined MozBoxAlign?: csstype.BoxAlignProperty | undefined MozBoxDirection?: csstype.BoxDirectionProperty | undefined MozBoxFlex?: csstype.GlobalsNumber | undefined MozBoxOrdinalGroup?: csstype.GlobalsNumber | undefined MozBoxOrient?: csstype.BoxOrientProperty | undefined MozBoxPack?: csstype.BoxPackProperty | undefined MozBoxShadow?: string | undefined MozFloatEdge?: csstype.MozFloatEdgeProperty | undefined MozForceBrokenImageIcon?: csstype.GlobalsNumber | undefined MozOpacity?: csstype.OpacityProperty | undefined MozOutline?: csstype.OutlineProperty<string | number> | undefined MozOutlineColor?: string | undefined MozOutlineRadius?: | csstype.MozOutlineRadiusProperty<string | number> | undefined MozOutlineRadiusBottomleft?: | csstype.MozOutlineRadiusBottomleftProperty<string | number> | undefined MozOutlineRadiusBottomright?: | csstype.MozOutlineRadiusBottomrightProperty<string | number> | undefined MozOutlineRadiusTopleft?: | csstype.MozOutlineRadiusTopleftProperty<string | number> | undefined MozOutlineRadiusTopright?: | csstype.MozOutlineRadiusToprightProperty<string | number> | undefined MozOutlineStyle?: string | undefined MozOutlineWidth?: csstype.OutlineWidthProperty<string | number> | undefined MozTextAlignLast?: csstype.TextAlignLastProperty | undefined MozTextDecorationColor?: string | undefined MozTextDecorationLine?: string | undefined MozTextDecorationStyle?: csstype.TextDecorationStyleProperty | undefined MozUserInput?: csstype.MozUserInputProperty | undefined msImeMode?: csstype.ImeModeProperty | undefined msScrollbarTrackColor?: string | undefined OAnimation?: csstype.AnimationProperty | undefined OAnimationDelay?: string | undefined OAnimationDirection?: string | undefined OAnimationDuration?: string | undefined OAnimationFillMode?: string | undefined OAnimationIterationCount?: | csstype.AnimationIterationCountProperty | undefined OAnimationName?: string | undefined OAnimationPlayState?: string | undefined OAnimationTimingFunction?: string | undefined OBackgroundSize?: | csstype.BackgroundSizeProperty<string | number> | undefined OBorderImage?: csstype.BorderImageProperty | undefined OObjectFit?: csstype.ObjectFitProperty | undefined OObjectPosition?: | csstype.ObjectPositionProperty<string | number> | undefined OTabSize?: csstype.TabSizeProperty<string | number> | undefined OTextOverflow?: string | undefined OTransform?: string | undefined OTransformOrigin?: | csstype.TransformOriginProperty<string | number> | undefined OTransition?: string | undefined OTransitionDelay?: string | undefined OTransitionDuration?: string | undefined OTransitionProperty?: string | undefined OTransitionTimingFunction?: string | undefined WebkitBoxAlign?: csstype.BoxAlignProperty | undefined WebkitBoxDirection?: csstype.BoxDirectionProperty | undefined WebkitBoxFlex?: csstype.GlobalsNumber | undefined WebkitBoxFlexGroup?: csstype.GlobalsNumber | undefined WebkitBoxLines?: csstype.BoxLinesProperty | undefined WebkitBoxOrdinalGroup?: csstype.GlobalsNumber | undefined WebkitBoxOrient?: csstype.BoxOrientProperty | undefined WebkitBoxPack?: csstype.BoxPackProperty | undefined WebkitScrollSnapPointsX?: string | undefined WebkitScrollSnapPointsY?: string | undefined alignmentBaseline?: csstype.AlignmentBaselineProperty | undefined baselineShift?: csstype.BaselineShiftProperty<string | number> | undefined clipRule?: csstype.ClipRuleProperty | undefined colorInterpolation?: csstype.ColorInterpolationProperty | undefined colorRendering?: csstype.ColorRenderingProperty | undefined dominantBaseline?: csstype.DominantBaselineProperty | undefined fill?: string | undefined fillOpacity?: csstype.GlobalsNumber | undefined fillRule?: csstype.FillRuleProperty | undefined floodColor?: string | undefined floodOpacity?: csstype.GlobalsNumber | undefined glyphOrientationVertical?: | csstype.GlyphOrientationVerticalProperty | undefined lightingColor?: string | undefined marker?: string | undefined markerEnd?: string | undefined markerMid?: string | undefined markerStart?: string | undefined shapeRendering?: csstype.ShapeRenderingProperty | undefined stopColor?: string | undefined stopOpacity?: csstype.GlobalsNumber | undefined stroke?: string | undefined strokeDasharray?: | csstype.StrokeDasharrayProperty<string | number> | undefined strokeDashoffset?: | csstype.StrokeDashoffsetProperty<string | number> | undefined strokeLinecap?: csstype.StrokeLinecapProperty | undefined strokeLinejoin?: csstype.StrokeLinejoinProperty | undefined strokeMiterlimit?: csstype.GlobalsNumber | undefined strokeOpacity?: csstype.GlobalsNumber | undefined strokeWidth?: csstype.StrokeWidthProperty<string | number> | undefined textAnchor?: csstype.TextAnchorProperty | undefined vectorEffect?: csstype.VectorEffectProperty | undefined } transform: { x?: string | number | undefined y?: string | number | undefined z?: string | number | undefined translateX?: string | number | undefined translateY?: string | number | undefined translateZ?: string | number | undefined rotate?: string | number | undefined rotateX?: string | number | undefined rotateY?: string | number | undefined rotateZ?: string | number | undefined scale?: string | number | undefined scaleX?: string | number | undefined scaleY?: string | number | undefined scaleZ?: string | number | undefined skew?: string | number | undefined skewX?: string | number | undefined skewY?: string | number | undefined originX?: string | number | undefined originY?: string | number | undefined originZ?: string | number | undefined perspective?: string | number | undefined transformPerspective?: string | number | undefined } stop: () => void } declare function useMotions(): MotionInstanceBindings<MotionVariants> /** * A Composable holding all the ongoing transitions in a local reference. */ declare function useMotionTransitions(): MotionTransitions /** * A Composable handling variants selection and features. * * @param variants * @param initial * @param options */ declare function useMotionVariants<T extends MotionVariants>( variants?: MaybeRef<T>, ): { state: vue_demi.ComputedRef<Variant | undefined> variant: Ref<keyof T> } declare type UseSpringOptions = Partial<Spring> & { target?: MaybeRef$1<PermissiveTarget> } declare function useSpring( values: Partial<PermissiveMotionProperties>, spring?: UseSpringOptions, ): SpringControls /** * Check whether an object is a Motion Instance or not. * * Can be useful while building packages based on @vueuse/motion. * * @param obj * @returns bool */ declare function isMotionInstance(obj: any): obj is MotionInstance /** * Convert a string to a slug. * * Source: https://gist.github.com/hagemann/382adfc57adbd5af078dc93feef01fe1 * Credits: @hagemann * * Edited to transform camel naming to slug with `-`. * * @param str */ declare function slugify(string: string): string /** * Reactive prefers-reduced-motion. * * @param options */ declare function useReducedMotion(options?: { window?: Window }): Ref<boolean> export { CustomValueType, Easing, EasingFunction, Inertia, Keyframes, KeyframesTarget, MakeCustomValueType, MakeKeyframes, MotionControls, directive as MotionDirective, MotionInstance, MotionInstanceBindings, MotionPlugin, MotionPluginOptions, MotionProperties, MotionTarget, MotionTransitions, MotionValuesMap, MotionVariants, Omit, Orchestration, PassiveEffect, PermissiveMotionProperties, PermissiveTarget, PermissiveTransitionDefinition, PopmotionTransitionProps, PropertiesKeys, Props, Repeat, ResolvedKeyframesTarget, ResolvedSingleTarget, ResolvedValueTarget, SVGPathProperties, SingleTarget, Spring, SpringControls, StartAnimation, StopAnimation, StyleProperties, Subscriber, Target, TargetAndTransition, TargetResolver, TargetWithKeyframes, TransformProperties, Transformer, Transition, TransitionDefinition, TransitionMap, Tween, UseMotionOptions, ValueTarget, Variant, fade, fadeVisible, isMotionInstance, pop, popVisible, reactiveStyle, reactiveTransform, rollBottom, rollLeft, rollRight, rollTop, rollVisibleBottom, rollVisibleLeft, rollVisibleRight, rollVisibleTop, slideBottom, slideLeft, slideRight, slideTop, slideVisibleBottom, slideVisibleLeft, slideVisibleRight, slideVisibleTop, slugify, useElementStyle, useElementTransform, useMotion, useMotionControls, useMotionProperties, useMotionTransitions, useMotionVariants, useMotions, useReducedMotion, useSpring, } <file_sep>/*! * @vueuse/motion v1.6.0 * (c) 2021 * @license MIT */ import { set, del, unref, ref, computed, watch, nextTick, reactive, isRef, } from 'vue-demi' import { isObject, unrefElement, useEventListener, useIntersectionObserver, noop, isNumber, useMediaQuery, } from '@vueuse/core' import { tryOnUnmounted, isFunction } from '@vueuse/shared' import { velocityPerSecond, inertia, animate, cubicBezier, linear, easeIn, easeInOut, easeOut, circIn, circInOut, circOut, backIn, backInOut, backOut, anticipate, bounceIn, bounceInOut, bounceOut, } from 'popmotion' const motionState = {} /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i] for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p] } return t } return __assign.apply(this, arguments) } function __rest(s, e) { var t = {} for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p] if (s != null && typeof Object.getOwnPropertySymbols === 'function') for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if ( e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]) ) t[p[i]] = s[p[i]] } return t } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value) }) } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)) } catch (e) { reject(e) } } function rejected(value) { try { step(generator['throw'](value)) } catch (e) { reject(e) } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected) } step((generator = generator.apply(thisArg, _arguments || [])).next()) }) } var defaultTimestep = (1 / 60) * 1000 var getCurrentTime = typeof performance !== 'undefined' ? function () { return performance.now() } : function () { return Date.now() } var onNextFrame = typeof window !== 'undefined' ? function (callback) { return window.requestAnimationFrame(callback) } : function (callback) { return setTimeout(function () { return callback(getCurrentTime()) }, defaultTimestep) } function createRenderStep(runNextFrame) { var toRun = [] var toRunNextFrame = [] var numToRun = 0 var isProcessing = false var toKeepAlive = new WeakSet() var step = { schedule: function (callback, keepAlive, immediate) { if (keepAlive === void 0) { keepAlive = false } if (immediate === void 0) { immediate = false } var addToCurrentFrame = immediate && isProcessing var buffer = addToCurrentFrame ? toRun : toRunNextFrame if (keepAlive) toKeepAlive.add(callback) if (buffer.indexOf(callback) === -1) { buffer.push(callback) if (addToCurrentFrame && isProcessing) numToRun = toRun.length } return callback }, cancel: function (callback) { var index = toRunNextFrame.indexOf(callback) if (index !== -1) toRunNextFrame.splice(index, 1) toKeepAlive.delete(callback) }, process: function (frameData) { var _a isProcessing = true ;(_a = [toRunNextFrame, toRun]), (toRun = _a[0]), (toRunNextFrame = _a[1]) toRunNextFrame.length = 0 numToRun = toRun.length if (numToRun) { for (var i = 0; i < numToRun; i++) { var callback = toRun[i] callback(frameData) if (toKeepAlive.has(callback)) { step.schedule(callback) runNextFrame() } } } isProcessing = false }, } return step } var maxElapsed = 40 var useDefaultElapsed = true var runNextFrame = false var isProcessing = false var frame = { delta: 0, timestamp: 0, } var stepsOrder = ['read', 'update', 'preRender', 'render', 'postRender'] var steps = /*#__PURE__*/ stepsOrder.reduce(function (acc, key) { acc[key] = createRenderStep(function () { return (runNextFrame = true) }) return acc }, {}) var sync = /*#__PURE__*/ stepsOrder.reduce(function (acc, key) { var step = steps[key] acc[key] = function (process, keepAlive, immediate) { if (keepAlive === void 0) { keepAlive = false } if (immediate === void 0) { immediate = false } if (!runNextFrame) startLoop() return step.schedule(process, keepAlive, immediate) } return acc }, {}) var processStep = function (stepId) { return steps[stepId].process(frame) } var processFrame = function (timestamp) { runNextFrame = false frame.delta = useDefaultElapsed ? defaultTimestep : Math.max(Math.min(timestamp - frame.timestamp, maxElapsed), 1) frame.timestamp = timestamp isProcessing = true stepsOrder.forEach(processStep) isProcessing = false if (runNextFrame) { useDefaultElapsed = false onNextFrame(processFrame) } } var startLoop = function () { runNextFrame = true useDefaultElapsed = true if (!isProcessing) onNextFrame(processFrame) } var getFrameData = function () { return frame } /** * A generic subscription manager. */ class SubscriptionManager { constructor() { this.subscriptions = new Set() } add(handler) { this.subscriptions.add(handler) return () => void this.subscriptions.delete(handler) } notify( /** * Using ...args would be preferable but it's array creation and this * might be fired every frame. */ a, b, c, ) { if (!this.subscriptions.size) return for (const handler of this.subscriptions) { handler(a, b, c) } } clear() { this.subscriptions.clear() } } const isFloat = (value) => { return !isNaN(parseFloat(value)) } /** * `MotionValue` is used to track the state and velocity of motion values. */ class MotionValue { /** * @param init - The initiating value * @param config - Optional configuration options */ constructor(init) { /** * Duration, in milliseconds, since last updating frame. */ this.timeDelta = 0 /** * Timestamp of the last time this `MotionValue` was updated. */ this.lastUpdated = 0 /** * Functions to notify when the `MotionValue` updates. */ this.updateSubscribers = new SubscriptionManager() /** * Tracks whether this value can output a velocity. */ this.canTrackVelocity = false /** * Update and notify `MotionValue` subscribers. * * @param v * @param render */ this.updateAndNotify = (v) => { // Update values this.prev = this.current this.current = v // Get frame data const { delta, timestamp } = getFrameData() // Update timestamp if (this.lastUpdated !== timestamp) { this.timeDelta = delta this.lastUpdated = timestamp } // Schedule velocity check post frame render sync.postRender(this.scheduleVelocityCheck) // Update subscribers this.updateSubscribers.notify(this.current) } /** * Schedule a velocity check for the next frame. */ this.scheduleVelocityCheck = () => sync.postRender(this.velocityCheck) /** * Updates `prev` with `current` if the value hasn't been updated this frame. * This ensures velocity calculations return `0`. */ this.velocityCheck = ({ timestamp }) => { if (!this.canTrackVelocity) this.canTrackVelocity = isFloat(this.current) if (timestamp !== this.lastUpdated) { this.prev = this.current } } this.prev = this.current = init this.canTrackVelocity = isFloat(this.current) } /** * Adds a function that will be notified when the `MotionValue` is updated. * * It returns a function that, when called, will cancel the subscription. */ onChange(subscription) { return this.updateSubscribers.add(subscription) } clearListeners() { this.updateSubscribers.clear() } /** * Sets the state of the `MotionValue`. * * @param v * @param render */ set(v) { this.updateAndNotify(v) } /** * Returns the latest state of `MotionValue` * * @returns - The latest state of `MotionValue` */ get() { return this.current } /** * Get previous value. * * @returns - The previous latest state of `MotionValue` */ getPrevious() { return this.prev } /** * Returns the latest velocity of `MotionValue` * * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. */ getVelocity() { // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful return this.canTrackVelocity ? // These casts could be avoided if parseFloat would be typed better velocityPerSecond( parseFloat(this.current) - parseFloat(this.prev), this.timeDelta, ) : 0 } /** * Registers a new animation to control this `MotionValue`. Only one * animation can drive a `MotionValue` at one time. */ start(animation) { this.stop() return new Promise((resolve) => { const { stop } = animation(resolve) this.stopAnimation = stop }).then(() => this.clearAnimation()) } /** * Stop the currently active animation. */ stop() { if (this.stopAnimation) this.stopAnimation() this.clearAnimation() } /** * Returns `true` if this value is currently animating. */ isAnimating() { return !!this.stopAnimation } /** * Clear the current animation reference. */ clearAnimation() { this.stopAnimation = null } /** * Destroy and clean up subscribers to this `MotionValue`. */ destroy() { this.updateSubscribers.clear() this.stop() } } function getMotionValue(init) { return new MotionValue(init) } const { isArray } = Array function useMotionValues() { const motionValues = {} const stop = (keys) => { // Destroy key closure const destroyKey = (key) => { if (!motionValues[key]) return motionValues[key].stop() motionValues[key].destroy() del(motionValues, key) } // Check if keys argument is defined if (keys) { if (isArray(keys)) { // If `keys` are an array, loop on specified keys and destroy them keys.forEach(destroyKey) } else { // If `keys` is a string, destroy the specified one destroyKey(keys) } } else { // No keys specified, destroy all animations Object.keys(motionValues).forEach(destroyKey) } } const get = (key, from, target) => { if (motionValues[key]) return motionValues[key] // Create motion value const motionValue = getMotionValue(from) // Set motion properties mapping motionValue.onChange((v) => { set(target, key, v) }) // Set instance motion value set(motionValues, key, motionValue) return motionValue } // Ensure everything is cleared on unmount tryOnUnmounted(stop) return { motionValues, get, stop, } } var clamp = function (min, max) { return function (v) { return Math.max(Math.min(v, max), min) } } var sanitize = function (v) { return v % 1 ? Number(v.toFixed(5)) : v } var floatRegex = /(-)?([\d]*\.?[\d])+/g var colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi var singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i function isString(v) { return typeof v === 'string' } var number = { test: function (v) { return typeof v === 'number' }, parse: parseFloat, transform: function (v) { return v }, } var alpha = __assign(__assign({}, number), { transform: clamp(0, 1) }) var scale = __assign(__assign({}, number), { default: 1 }) var createUnitType = function (unit) { return { test: function (v) { return isString(v) && v.endsWith(unit) && v.split(' ').length === 1 }, parse: parseFloat, transform: function (v) { return '' + v + unit }, } } var degrees = createUnitType('deg') var percent = createUnitType('%') var px = createUnitType('px') var progressPercentage = __assign(__assign({}, percent), { parse: function (v) { return percent.parse(v) / 100 }, transform: function (v) { return percent.transform(v * 100) }, }) var isColorString = function (type, testProp) { return function (v) { return Boolean( (isString(v) && singleColorRegex.test(v) && v.startsWith(type)) || (testProp && Object.prototype.hasOwnProperty.call(v, testProp)), ) } } var splitColor = function (aName, bName, cName) { return function (v) { var _a if (!isString(v)) return v var _b = v.match(floatRegex), a = _b[0], b = _b[1], c = _b[2], alpha = _b[3] return ( (_a = {}), (_a[aName] = parseFloat(a)), (_a[bName] = parseFloat(b)), (_a[cName] = parseFloat(c)), (_a.alpha = alpha !== undefined ? parseFloat(alpha) : 1), _a ) } } var hsla = { test: isColorString('hsl', 'hue'), parse: splitColor('hue', 'saturation', 'lightness'), transform: function (_a) { var hue = _a.hue, saturation = _a.saturation, lightness = _a.lightness, _b = _a.alpha, alpha$1 = _b === void 0 ? 1 : _b return ( 'hsla(' + Math.round(hue) + ', ' + percent.transform(sanitize(saturation)) + ', ' + percent.transform(sanitize(lightness)) + ', ' + sanitize(alpha.transform(alpha$1)) + ')' ) }, } var clampRgbUnit = clamp(0, 255) var rgbUnit = __assign(__assign({}, number), { transform: function (v) { return Math.round(clampRgbUnit(v)) }, }) var rgba = { test: isColorString('rgb', 'red'), parse: splitColor('red', 'green', 'blue'), transform: function (_a) { var red = _a.red, green = _a.green, blue = _a.blue, _b = _a.alpha, alpha$1 = _b === void 0 ? 1 : _b return ( 'rgba(' + rgbUnit.transform(red) + ', ' + rgbUnit.transform(green) + ', ' + rgbUnit.transform(blue) + ', ' + sanitize(alpha.transform(alpha$1)) + ')' ) }, } function parseHex(v) { var r = '' var g = '' var b = '' var a = '' if (v.length > 5) { r = v.substr(1, 2) g = v.substr(3, 2) b = v.substr(5, 2) a = v.substr(7, 2) } else { r = v.substr(1, 1) g = v.substr(2, 1) b = v.substr(3, 1) a = v.substr(4, 1) r += r g += g b += b a += a } return { red: parseInt(r, 16), green: parseInt(g, 16), blue: parseInt(b, 16), alpha: a ? parseInt(a, 16) / 255 : 1, } } var hex = { test: isColorString('#'), parse: parseHex, transform: rgba.transform, } var color = { test: function (v) { return rgba.test(v) || hex.test(v) || hsla.test(v) }, parse: function (v) { if (rgba.test(v)) { return rgba.parse(v) } else if (hsla.test(v)) { return hsla.parse(v) } else { return hex.parse(v) } }, transform: function (v) { return isString(v) ? v : v.hasOwnProperty('red') ? rgba.transform(v) : hsla.transform(v) }, } var colorToken = '${c}' var numberToken = '${n}' function test(v) { var _a, _b, _c, _d return ( isNaN(v) && isString(v) && ((_b = (_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = v.match(colorRegex)) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0 ) } function analyse(v) { var values = [] var numColors = 0 var colors = v.match(colorRegex) if (colors) { numColors = colors.length v = v.replace(colorRegex, colorToken) values.push.apply(values, colors.map(color.parse)) } var numbers = v.match(floatRegex) if (numbers) { v = v.replace(floatRegex, numberToken) values.push.apply(values, numbers.map(number.parse)) } return { values: values, numColors: numColors, tokenised: v } } function parse(v) { return analyse(v).values } function createTransformer(v) { var _a = analyse(v), values = _a.values, numColors = _a.numColors, tokenised = _a.tokenised var numValues = values.length return function (v) { var output = tokenised for (var i = 0; i < numValues; i++) { output = output.replace( i < numColors ? colorToken : numberToken, i < numColors ? color.transform(v[i]) : sanitize(v[i]), ) } return output } } var convertNumbersToZero = function (v) { return typeof v === 'number' ? 0 : v } function getAnimatableNone$1(v) { var parsed = parse(v) var transformer = createTransformer(v) return transformer(parsed.map(convertNumbersToZero)) } var complex = { test: test, parse: parse, createTransformer: createTransformer, getAnimatableNone: getAnimatableNone$1, } var maxDefaults = new Set(['brightness', 'contrast', 'saturate', 'opacity']) function applyDefaultFilter(v) { var _a = v.slice(0, -1).split('('), name = _a[0], value = _a[1] if (name === 'drop-shadow') return v var number = (value.match(floatRegex) || [])[0] if (!number) return v var unit = value.replace(number, '') var defaultValue = maxDefaults.has(name) ? 1 : 0 if (number !== value) defaultValue *= 100 return name + '(' + defaultValue + unit + ')' } var functionRegex = /([a-z-]*)\(.*?\)/g var filter = __assign(__assign({}, complex), { getAnimatableNone: function (v) { var functions = v.match(functionRegex) return functions ? functions.map(applyDefaultFilter).join(' ') : v }, }) const isKeyframesTarget = (v) => { return Array.isArray(v) } const underDampedSpring = () => ({ type: 'spring', stiffness: 500, damping: 25, restDelta: 0.5, restSpeed: 10, }) const criticallyDampedSpring = (to) => ({ type: 'spring', stiffness: 550, damping: to === 0 ? 2 * Math.sqrt(550) : 30, restDelta: 0.01, restSpeed: 10, }) const overDampedSpring = (to) => ({ type: 'spring', stiffness: 550, damping: to === 0 ? 100 : 30, restDelta: 0.01, restSpeed: 10, }) const linearTween = () => ({ type: 'keyframes', ease: 'linear', duration: 300, }) const keyframes = (values) => ({ type: 'keyframes', duration: 800, values, }) const defaultTransitions = { default: overDampedSpring, x: underDampedSpring, y: underDampedSpring, z: underDampedSpring, rotate: underDampedSpring, rotateX: underDampedSpring, rotateY: underDampedSpring, rotateZ: underDampedSpring, scaleX: criticallyDampedSpring, scaleY: criticallyDampedSpring, scale: criticallyDampedSpring, backgroundColor: linearTween, color: linearTween, opacity: linearTween, } const getDefaultTransition = (valueKey, to) => { let transitionFactory if (isKeyframesTarget(to)) { transitionFactory = keyframes } else { transitionFactory = defaultTransitions[valueKey] || defaultTransitions.default } return Object.assign({ to }, transitionFactory(to)) } /** * ValueType for ints */ const int = Object.assign(Object.assign({}, number), { transform: Math.round }) const valueTypes = { // Color props color, backgroundColor: color, outlineColor: color, fill: color, stroke: color, // Border props borderColor: color, borderTopColor: color, borderRightColor: color, borderBottomColor: color, borderLeftColor: color, borderWidth: px, borderTopWidth: px, borderRightWidth: px, borderBottomWidth: px, borderLeftWidth: px, borderRadius: px, radius: px, borderTopLeftRadius: px, borderTopRightRadius: px, borderBottomRightRadius: px, borderBottomLeftRadius: px, // Positioning props width: px, maxWidth: px, height: px, maxHeight: px, size: px, top: px, right: px, bottom: px, left: px, // Spacing props padding: px, paddingTop: px, paddingRight: px, paddingBottom: px, paddingLeft: px, margin: px, marginTop: px, marginRight: px, marginBottom: px, marginLeft: px, // Transform props rotate: degrees, rotateX: degrees, rotateY: degrees, rotateZ: degrees, scale, scaleX: scale, scaleY: scale, scaleZ: scale, skew: degrees, skewX: degrees, skewY: degrees, distance: px, translateX: px, translateY: px, translateZ: px, x: px, y: px, z: px, perspective: px, transformPerspective: px, opacity: alpha, originX: progressPercentage, originY: progressPercentage, originZ: px, // Misc zIndex: int, filter, WebkitFilter: filter, // SVG fillOpacity: alpha, strokeOpacity: alpha, numOctaves: int, } /** * Return the value type for a key. * * @param key */ const getValueType = (key) => valueTypes[key] /** * Transform the value using its value type, or return the value. * * @param value * @param type */ const getValueAsType = (value, type) => { return type && typeof value === 'number' && type.transform ? type.transform(value) : value } /** * Get default animatable * * @param key * @param value */ function getAnimatableNone(key, value) { let defaultValueType = getValueType(key) if (defaultValueType !== filter) defaultValueType = complex // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target return defaultValueType.getAnimatableNone ? defaultValueType.getAnimatableNone(value) : undefined } // Easing map from popmotion const easingLookup = { linear, easeIn, easeInOut, easeOut, circIn, circInOut, circOut, backIn, backInOut, backOut, anticipate, bounceIn, bounceInOut, bounceOut, } /** * Transform easing definition to easing function. * * @param definition */ const easingDefinitionToFunction = (definition) => { if (Array.isArray(definition)) { const [x1, y1, x2, y2] = definition return cubicBezier(x1, y1, x2, y2) } else if (typeof definition === 'string') { return easingLookup[definition] } return definition } /** * Create an easing array * * @param ease */ const isEasingArray = (ease) => { return Array.isArray(ease) && typeof ease[0] !== 'number' } /** * Check if a value is animatable. Examples: * * ✅: 100, "100px", "#fff" * ❌: "block", "url(2.jpg)" * @param value * * @internal */ const isAnimatable = (key, value) => { // If the list of keys tat might be non-animatable grows, replace with Set if (key === 'zIndex') return false // If it's a number or a keyframes array, we can animate it. We might at some point // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this, // but for now lets leave it like this for performance reasons if (typeof value === 'number' || Array.isArray(value)) return true if ( typeof value === 'string' && // It's animatable if we have a string complex.test(value) && // And it contains numbers and/or colors !value.startsWith('url(') // Unless it starts with "url(" ) { return true } return false } /** * Hydrate keyframes from transition options. * * @param options */ function hydrateKeyframes(options) { if (Array.isArray(options.to) && options.to[0] === null) { options.to = [...options.to] options.to[0] = options.from } return options } /** * Convert Transition type into Popmotion-compatible options. */ function convertTransitionToAnimationOptions(_a) { var { ease, times, delay } = _a, transition = __rest(_a, ['ease', 'times', 'delay']) const options = Object.assign({}, transition) if (times) options['offset'] = times // Map easing names to Popmotion's easing functions if (ease) { options['ease'] = isEasingArray(ease) ? ease.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease) } // Map delay to elapsed from Popmotion if (delay) { options['elapsed'] = -delay } return options } /** * Get PopMotion animation options from Transition definition * * @param transition * @param options * @param key */ function getPopmotionAnimationOptions(transition, options, key) { if (Array.isArray(options.to)) { if (!transition.duration) transition.duration = 800 } hydrateKeyframes(options) // Get a default transition if none is determined to be defined. if (!isTransitionDefined(transition)) { transition = Object.assign( Object.assign({}, transition), getDefaultTransition(key, options.to), ) } return Object.assign( Object.assign({}, options), convertTransitionToAnimationOptions(transition), ) } /** * Decide whether a transition is defined on a given Transition. * This filters out orchestration options and returns true * if any options are left. */ function isTransitionDefined(_a) { var transition = __rest(_a, [ 'delay', 'repeat', 'repeatType', 'repeatDelay', 'from', ]) return !!Object.keys(transition).length } /** * Get the transition definition for the current value. * * First search for transition nested definition (key or default), * then fallback on the main transition definition itself. * * @param transition * @param key */ function getValueTransition(transition, key) { return transition[key] || transition['default'] || transition } /** * Get the animation function populated with variant values. */ function getAnimation(key, value, target, transition, onComplete) { // Get key transition or fallback values const valueTransition = getValueTransition(transition, key) // Get origin let origin = valueTransition.from === null || valueTransition.from === undefined ? value.get() : valueTransition.from // Is target animatable const isTargetAnimatable = isAnimatable(key, target) // If we're trying to animate from "none", try and get an animatable version // of the target. This could be improved to work both ways. if (origin === 'none' && isTargetAnimatable && typeof target === 'string') { origin = getAnimatableNone(key, target) } // Is origin animatable const isOriginAnimatable = isAnimatable(key, origin) /** * Start the animation. */ function start(complete) { const options = { from: origin, to: target, velocity: transition.velocity ? transition.velocity : value.getVelocity(), onUpdate: (v) => value.set(v), } return valueTransition.type === 'inertia' || valueTransition.type === 'decay' ? inertia(Object.assign(Object.assign({}, options), valueTransition)) : animate( Object.assign( Object.assign( {}, getPopmotionAnimationOptions(valueTransition, options, key), ), { onUpdate: (v) => { options.onUpdate(v) if (valueTransition.onUpdate) valueTransition.onUpdate(v) }, onComplete: () => { if (transition.onComplete) transition.onComplete() if (onComplete) onComplete() if (complete) complete() }, }, ), ) } /** * Set value without transition. */ function set(complete) { value.set(target) if (transition.onComplete) transition.onComplete() if (onComplete) onComplete() if (complete) complete() return { stop: () => {} } } return !isOriginAnimatable || !isTargetAnimatable || valueTransition.type === false ? set : start } /** * A Composable holding all the ongoing transitions in a local reference. */ function useMotionTransitions() { const { motionValues, stop, get } = useMotionValues() const push = (key, value, target, transition = {}, onComplete) => { // Get the `from` key from target const from = target[key] // Get motion value for the target key const motionValue = get(key, from, target) // Sets the value immediately if specified if (transition && transition.immediate) { motionValue.set(value) return } // Create animation const animation = getAnimation( key, motionValue, value, transition, onComplete, ) // Start animation motionValue.start(animation) } return { motionValues, stop, push } } /** * A Composable handling motion controls, pushing resolved variant to useMotionTransitions manager. * * @param transform * @param style * @param currentVariant */ function useMotionControls( motionProperties, variants = {}, { push, stop } = useMotionTransitions(), ) { // Variants as ref const _variants = unref(variants) const getVariantFromKey = (variant) => { if (!_variants || !_variants[variant]) { throw new Error(`The variant ${variant} does not exist.`) } return _variants[variant] } const apply = (variant) => { // If variant is a key, try to resolve it if (typeof variant === 'string') { variant = getVariantFromKey(variant) } // Return Promise chain return Promise.all( Object.entries(variant).map(([key, value]) => { // Skip transition key if (key === 'transition') return return new Promise((resolve) => { push( key, value, motionProperties, variant.transition || getDefaultTransition(key, variant[key]), resolve, ) }) }), ) } const set = (variant) => { // Get variant data from parameter let variantData = isObject(variant) ? variant : getVariantFromKey(variant) // Set in chain Object.entries(variantData).forEach(([key, value]) => { // Skip transition key if (key === 'transition') return push(key, value, motionProperties, { immediate: true, }) }) } const leave = (done) => __awaiter(this, void 0, void 0, function* () { let leaveVariant if (_variants) { if (_variants.leave) { leaveVariant = _variants.leave } if (!_variants.leave && _variants.initial) { leaveVariant = _variants.initial } } if (!leaveVariant) { done() return } yield apply(leaveVariant) done() }) return { apply, set, stopTransitions: stop, leave, } } const isBrowser = typeof window !== 'undefined' const supportsPointerEvents = () => isBrowser && window.onpointerdown === null const supportsTouchEvents = () => isBrowser && window.ontouchstart === null const supportsMouseEvents = () => isBrowser && window.onmousedown === null function registerEventListeners({ target, state, variants, apply }) { const _variants = unref(variants) // State const hovered = ref(false) const tapped = ref(false) const focused = ref(false) const mutableKeys = computed(() => { let result = [] if (!_variants) return result if (_variants.hovered) { result = [...result, ...Object.keys(_variants.hovered)] } if (_variants.tapped) { result = [...result, ...Object.keys(_variants.tapped)] } if (_variants.focused) { result = [...result, ...Object.keys(_variants.focused)] } return result }) const computedProperties = computed(() => { const result = {} Object.assign(result, state.value) if (hovered.value && _variants.hovered) { Object.assign(result, _variants.hovered) } if (tapped.value && _variants.tapped) { Object.assign(result, _variants.tapped) } if (focused.value && _variants.focused) { Object.assign(result, _variants.focused) } for (const key in result) { if (!mutableKeys.value.includes(key)) delete result[key] } return result }) watch( () => unrefElement(target), (el) => { if (!el || !_variants) return // Hovered if (_variants.hovered) { useEventListener(el, 'mouseenter', () => { hovered.value = true }) useEventListener(el, 'mouseleave', () => { hovered.value = false tapped.value = false }) useEventListener(el, 'mouseout', () => { hovered.value = false tapped.value = false }) } // Tapped if (_variants.tapped) { // Mouse if (supportsMouseEvents()) { useEventListener(el, 'mousedown', () => { tapped.value = true }) useEventListener(el, 'mouseup', () => { tapped.value = false }) } // Pointer if (supportsPointerEvents()) { useEventListener(el, 'pointerdown', () => { tapped.value = true }) useEventListener(el, 'pointerup', () => { tapped.value = false }) } // Touch if (supportsTouchEvents()) { useEventListener(el, 'touchstart', () => { tapped.value = true }) useEventListener(el, 'touchend', () => { tapped.value = false }) } } // Focused if (_variants.focused) { useEventListener(el, 'focus', () => { focused.value = true }) useEventListener(el, 'blur', () => { focused.value = false }) } }, { immediate: true, }, ) // Watch local computed variant, apply it dynamically watch(computedProperties, (newVal) => { apply(newVal) }) } function registerLifeCycleHooks({ target, variants, variant }) { const _variants = unref(variants) const stop = watch( () => target, () => { // Lifecycle hooks bindings if (_variants && _variants.enter) { // Set initial before the element is mounted if (_variants.initial) variant.value = 'initial' // Set enter animation, once the element is mounted nextTick(() => (variant.value = 'enter')) } }, { immediate: true, flush: 'pre', }, ) return { stop } } function registerVariantsSync({ state, apply }) { // Watch for variant changes and apply the new one const stop = watch( state, (newVal) => { if (newVal) apply(newVal) }, { immediate: true, }, ) return { stop } } function registerVisibilityHooks({ target, variants, variant }) { const _variants = unref(variants) let _stopObserver = noop const _stopWatcher = watch( () => unrefElement(target), (el) => { if (!el) return // Bind intersection observer on target _stopObserver = useIntersectionObserver( target, ([{ isIntersecting }]) => { if (_variants && _variants.visible) { if (isIntersecting) { variant.value = 'visible' } else { variant.value = 'initial' } } }, ).stop }, { immediate: true, }, ) /** * Stop both the watcher and the intersection observer. */ const stop = () => { _stopObserver() _stopWatcher() } return { stop, } } /** * A Composable executing resolved variants features from variants declarations. * * Supports: * - lifeCycleHooks: Bind the motion hooks to the component lifecycle hooks. * * @param variant * @param variants * @param options */ function useMotionFeatures( instance, options = { syncVariants: true, lifeCycleHooks: true, visibilityHooks: true, eventListeners: true, }, ) { // Lifecycle hooks bindings if (options.lifeCycleHooks) { registerLifeCycleHooks(instance) } if (options.syncVariants) { registerVariantsSync(instance) } // Visibility hooks if (options.visibilityHooks) { registerVisibilityHooks(instance) } // Event listeners if (options.eventListeners) { registerEventListeners(instance) } } /** * Reactive style object implementing all native CSS properties. * * @param props */ function reactiveStyle(props = {}) { // Reactive StyleProperties object const state = reactive(Object.assign({}, props)) const style = ref({}) // Reactive DOM Element compatible `style` object bound to state watch( state, () => { // Init result object const result = {} for (const [key, value] of Object.entries(state)) { // Get value type for key const valueType = getValueType(key) // Get value as type for key const valueAsType = getValueAsType(value, valueType) // Append the computed style to result object result[key] = valueAsType } style.value = result }, { immediate: true, deep: true, }, ) return { state, style, } } /** * A list of all transformable axes. We'll use this list to generated a version * of each axes for each transform. */ const transformAxes = ['', 'X', 'Y', 'Z'] /** * An ordered array of each transformable value. By default, transform values * will be sorted to this order. */ const order = ['perspective', 'translate', 'scale', 'rotate', 'skew'] /** * Generate a list of every possible transform key. */ const transformProps = ['transformPerspective', 'x', 'y', 'z'] order.forEach((operationKey) => { transformAxes.forEach((axesKey) => { const key = operationKey + axesKey transformProps.push(key) }) }) /** * A quick lookup for transform props. */ const transformPropSet = new Set(transformProps) function isTransformProp(key) { return transformPropSet.has(key) } /** * A quick lookup for transform origin props */ const transformOriginProps = new Set(['originX', 'originY', 'originZ']) function isTransformOriginProp(key) { return transformOriginProps.has(key) } /** * A Composable giving access to a StyleProperties object, and binding the generated style object to a target. * * @param target */ function useElementStyle(target, onInit) { // Transform cache available before the element is mounted let _cache // Local target cache as we need to resolve the element from PermissiveTarget let _target = undefined // Create a reactive style object const { state, style } = reactiveStyle() // Sync existing style from supplied element const stopInitWatch = watch( () => unrefElement(target), (el) => { if (!el) return _target = el // Loop on style keys for (const key of Object.keys(valueTypes)) { if ( el.style[key] === null || el.style[key] === '' || isTransformProp(key) || isTransformOriginProp(key) ) continue // Append a defined key to the local StyleProperties state object set(state, key, el.style[key]) } // If cache is present, init the target with the current cached value if (_cache) { Object.entries(_cache).forEach(([key, value]) => set(el.style, key, value), ) } if (onInit) onInit(state) }, { immediate: true, }, ) // Sync reactive style to element const stopSyncWatch = watch( style, (newVal) => { // Add the current value to the cache so it is set on target creation if (!_target) { _cache = newVal return } // Append the state object to the target style properties for (const key in newVal) set(_target.style, key, newVal[key]) }, { immediate: true, }, ) // Stop watchers const stop = () => { stopInitWatch() stopSyncWatch() } return { style: state, stop, } } /** * Aliases translate key for simpler API integration. */ const translateAlias = { x: 'translateX', y: 'translateY', z: 'translateZ', } /** * Reactive transform string implementing all native CSS transform properties. * * @param props * @param enableHardwareAcceleration */ function reactiveTransform(props = {}, enableHardwareAcceleration = true) { // Reactive TransformProperties object const state = reactive(Object.assign({}, props)) const transform = ref('') watch( state, (newVal) => { // Init result let result = '' let hasHardwareAcceleration = false // Use translate3d by default has a better GPU optimization // And corrects scaling discrete behaviors if (enableHardwareAcceleration && (newVal.x || newVal.y || newVal.z)) { const str = [newVal.x || 0, newVal.y || 0, newVal.z || 0] .map(px.transform) .join(',') result += `translate3d(${str}) ` hasHardwareAcceleration = true } // Loop on defined TransformProperties state keys for (const [key, value] of Object.entries(newVal)) { if ( enableHardwareAcceleration && (key === 'x' || key === 'y' || key === 'z') ) continue // Get value type for key const valueType = getValueType(key) // Get value as type for key const valueAsType = getValueAsType(value, valueType) // Append the computed transform key to result string result += `${translateAlias[key] || key}(${valueAsType}) ` } if (enableHardwareAcceleration && !hasHardwareAcceleration) { result += `translateZ(0px) ` } transform.value = result.trim() }, { immediate: true, deep: true, }, ) return { state, transform, } } /** * Return an object from a transform string. * * @param str */ function parseTransform(transform) { // Split transform string. const transforms = transform.trim().split(/\) |\)/) // Handle "initial", "inherit", "unset". if (transforms.length === 1) { return {} } const parseValues = (value) => { // If value is ending with px or deg, return it as a number if (value.endsWith('px') || value.endsWith('deg')) return parseFloat(value) // Return as number if (isNaN(Number(value))) return Number(value) // Parsing impossible, return as string return value } // Reduce the result to an object and return it return transforms.reduce((acc, transform) => { if (!transform) return acc const [name, transformValue] = transform.split('(') const valueArray = transformValue.split(',') const values = valueArray.map((val) => { return parseValues(val.endsWith(')') ? val.replace(')', '') : val.trim()) }) const value = values.length === 1 ? values[0] : values return Object.assign(Object.assign({}, acc), { [name]: value }) }, {}) } /** * Sets the state from a parsed transform string. * * Used in useElementTransform init to restore element transform string in cases it does exists. * * @param state * @param transform */ function stateFromTransform(state, transform) { Object.entries(parseTransform(transform)).forEach(([key, value]) => { // Get value w/o unit, as unit is applied later on value = parseFloat(value) // Axes reference for loops const axes = ['x', 'y', 'z'] // Handle translate3d and scale3d if (key === 'translate3d') { // Loop on parsed scale / translate definition value.forEach((axisValue, index) => { set(state, axes[index], axisValue) }) return } // Sync translateX on X if (key === 'translateX') { set(state, 'x', value) return } // Sync translateY on Y if (key === 'translateY') { set(state, 'y', value) return } // Sync translateZ on Z if (key === 'translateZ') { set(state, 'z', value) return } // Set raw value set(state, key, value) }) } /** * A Composable giving access to a TransformProperties object, and binding the generated transform string to a target. * * @param target */ function useElementTransform(target, onInit) { // Transform cache available before the element is mounted let _cache // Local target cache as we need to resolve the element from PermissiveTarget let _target = undefined // Create a reactive transform object const { state, transform } = reactiveTransform() // Cache transform until the element is alive and we can bind to it const stopInitWatch = watch( () => unrefElement(target), (el) => { if (!el) return _target = el // Parse transform properties and applies them to the current state if (el.style.transform) stateFromTransform(state, el.style.transform) // If cache is present, init the target with the current cached value if (_cache) { el.style.transform = _cache } if (onInit) onInit(state) }, { immediate: true, }, ) // Sync reactive transform to element const stopSyncWatch = watch( transform, (newValue) => { // Add the current value to the cache so it is set on target creation if (!_target) { _cache = newValue return } // Set the transform string on the target _target.style.transform = newValue }, { immediate: true, }, ) // Stop watchers const stop = () => { stopInitWatch() stopSyncWatch() } return { transform: state, stop, } } /** * A Composable giving access to both `transform` and `style`objects for a single element. * * @param target */ function useMotionProperties(target, defaultValues) { // Local motion properties const motionProperties = reactive({}) // Local mass setter const apply = (values) => { Object.entries(values).forEach(([key, value]) => { set(motionProperties, key, value) }) } // Target element style object const { style, stop: stopStyleWatchers } = useElementStyle(target, apply) // Target element transform object const { transform, stop: stopTransformWatchers } = useElementTransform( target, apply, ) // Watch local object and apply styling accordingly const stopPropertiesWatch = watch( motionProperties, (newVal) => { Object.entries(newVal).forEach(([key, value]) => { const target = isTransformProp(key) ? transform : style if (target[key] && target[key] === value) return set(target, key, value) }) }, { immediate: true, deep: true, }, ) // Apply default values once target is available const stopInitWatch = watch( () => unrefElement(target), (el) => { if (!el) return if (defaultValues) apply(defaultValues) }, { immediate: true, }, ) // Stop watchers const stop = () => { stopStyleWatchers() stopTransformWatchers() stopPropertiesWatch() stopInitWatch() } return { motionProperties, style, transform, stop, } } /** * A Composable handling variants selection and features. * * @param variants * @param initial * @param options */ function useMotionVariants(variants = {}) { // Unref variants const _variants = unref(variants) // Current variant string const variant = ref() // Current variant state const state = computed(() => { if (!variant.value) return return _variants[variant.value] }) return { state, variant, } } /** * A Vue Composable that put your components in motion. * * @docs https://motion.vueuse.js.org * * @param target * @param variants * @param options */ function useMotion(target, variants = {}, options) { // Reactive styling and transform const { motionProperties } = useMotionProperties(target) // Variants manager const { variant, state } = useMotionVariants(variants) // Motion controls, synchronized with motion properties and variants const controls = useMotionControls(motionProperties, variants) // Create motion instance const instance = Object.assign( { target, variant, variants, state, motionProperties }, controls, ) // Bind features useMotionFeatures(instance, options) return instance } const directivePropsKeys = [ 'initial', 'enter', 'leave', 'visible', 'hovered', 'tapped', 'focused', 'delay', ] const resolveVariants = (node, variantsRef) => { // This is done to achieve compat with Vue 2 & 3 // node.props = Vue 3 element props location // node.data.attrs = Vue 2 element props location const target = node.props ? node.props // @ts-expect-error : node.data && node.data.attrs // @ts-expect-error ? node.data.attrs : {} if (target) { if (target['variants'] && isObject(target['variants'])) { // If variant are passed through a single object reference, initialize with it variantsRef.value = Object.assign( Object.assign({}, variantsRef.value), target['variants'], ) } // Loop on directive prop keys, add them to the local variantsRef if defined directivePropsKeys.forEach((key) => { if (key === 'delay') { if (target && target[key] && isNumber(target[key])) { const delay = target[key] if (variantsRef && variantsRef.value) { if (variantsRef.value.enter) { if (!variantsRef.value.enter.transition) { variantsRef.value.enter.transition = {} } variantsRef.value.enter.transition = Object.assign( Object.assign({}, variantsRef.value.enter.transition), { delay }, ) } if (variantsRef.value.visible) { if (!variantsRef.value.visible.transition) { variantsRef.value.visible.transition = {} } variantsRef.value.visible.transition = Object.assign( Object.assign({}, variantsRef.value.visible.transition), { delay }, ) } } } return } if (target && target[key] && isObject(target[key])) { variantsRef.value[key] = target[key] } }) } } const directive = (variants) => { const register = (el, binding, node) => { // Initialize variants with argument const variantsRef = ref(variants || {}) // Resolve variants from node props resolveVariants(node, variantsRef) // Create motion instance const motionInstance = useMotion(el, variantsRef) // Set the global state reference if the name is set through v-motion="`value`" if (binding.value) set(motionState, binding.value, motionInstance) } const unregister = (_, binding, __) => { // Check if motion state has the current element as reference if (binding.value && motionState[binding.value]) del(motionState, binding.value) } return { // Vue 3 Directive Hooks created: register, unmounted: unregister, // Vue 2 Directive Hooks // For Nuxt & Vue 2 compatibility // @ts-expect-error bind: register, unbind: unregister, } } const fade = { initial: { opacity: 0, }, enter: { opacity: 1, }, } const fadeVisible = { initial: { opacity: 0, }, visible: { opacity: 1, }, } const pop = { initial: { scale: 0, opacity: 0, }, enter: { scale: 1, opacity: 1, }, } const popVisible = { initial: { scale: 0, opacity: 0, }, visible: { scale: 1, opacity: 1, }, } // Roll from left const rollLeft = { initial: { x: -100, rotate: 90, opacity: 0, }, enter: { x: 0, rotate: 0, opacity: 1, }, } const rollVisibleLeft = { initial: { x: -100, rotate: 90, opacity: 0, }, visible: { x: 0, rotate: 0, opacity: 1, }, } // Roll from right const rollRight = { initial: { x: 100, rotate: -90, opacity: 0, }, enter: { x: 0, rotate: 0, opacity: 1, }, } const rollVisibleRight = { initial: { x: 100, rotate: -90, opacity: 0, }, visible: { x: 0, rotate: 0, opacity: 1, }, } // Roll from top const rollTop = { initial: { y: -100, rotate: -90, opacity: 0, }, enter: { y: 0, rotate: 0, opacity: 1, }, } const rollVisibleTop = { initial: { y: -100, rotate: -90, opacity: 0, }, visible: { y: 0, rotate: 0, opacity: 1, }, } // Roll from bottom const rollBottom = { initial: { y: 100, rotate: 90, opacity: 0, }, enter: { y: 0, rotate: 0, opacity: 1, }, } const rollVisibleBottom = { initial: { y: 100, rotate: 90, opacity: 0, }, visible: { y: 0, rotate: 0, opacity: 1, }, } // Slide from left const slideLeft = { initial: { x: -100, opacity: 0, }, enter: { x: 0, opacity: 1, }, } const slideVisibleLeft = { initial: { x: -100, opacity: 0, }, visible: { x: 0, opacity: 1, }, } // Slide from right const slideRight = { initial: { x: 100, opacity: 0, }, enter: { x: 0, opacity: 1, }, } const slideVisibleRight = { initial: { x: 100, opacity: 0, }, visible: { x: 0, opacity: 1, }, } // Slide from top const slideTop = { initial: { y: -100, opacity: 0, }, enter: { y: 0, opacity: 1, }, } const slideVisibleTop = { initial: { y: -100, opacity: 0, }, visible: { y: 0, opacity: 1, }, } // Slide from bottom const slideBottom = { initial: { y: 100, opacity: 0, }, enter: { y: 0, opacity: 1, }, } const slideVisibleBottom = { initial: { y: 100, opacity: 0, }, visible: { y: 0, opacity: 1, }, } var presets = /*#__PURE__*/ Object.freeze({ __proto__: null, fade: fade, fadeVisible: fadeVisible, pop: pop, popVisible: popVisible, rollBottom: rollBottom, rollLeft: rollLeft, rollRight: rollRight, rollTop: rollTop, rollVisibleBottom: rollVisibleBottom, rollVisibleLeft: rollVisibleLeft, rollVisibleRight: rollVisibleRight, rollVisibleTop: rollVisibleTop, slideBottom: slideBottom, slideLeft: slideLeft, slideRight: slideRight, slideTop: slideTop, slideVisibleBottom: slideVisibleBottom, slideVisibleLeft: slideVisibleLeft, slideVisibleRight: slideVisibleRight, slideVisibleTop: slideVisibleTop, }) /** * Convert a string to a slug. * * Source: https://gist.github.com/hagemann/382adfc57adbd5af078dc93feef01fe1 * Credits: @hagemann * * Edited to transform camel naming to slug with `-`. * * @param str */ function slugify(string) { const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;' const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------' const p = new RegExp(a.split('').join('|'), 'g') return string .toString() .replace(/[A-Z]/g, (s) => '-' + s) // Camel to slug .toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(p, (c) => b.charAt(a.indexOf(c))) // Replace special characters .replace(/&/g, '-and-') // Replace & with 'and' .replace(/[^\w\-]+/g, '') // Remove all non-word characters .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, '') // Trim - from end of text } const MotionPlugin = { install(app, options) { // Register default `v-motion` directive app.directive('motion', directive()) // Register presets if (!options || (options && !options.excludePresets)) { for (const key in presets) { // Get preset variants const preset = presets[key] // Register the preset `v-motion-${key}` directive app.directive(`motion-${slugify(key)}`, directive(preset)) } } // Register plugin-wise directives if (options && options.directives) { // Loop on options, create a custom directive for each definition for (const key in options.directives) { // Get directive variants const variants = options.directives[key] // Development warning, showing definitions missing `initial` key if (!variants.initial && true) { console.warn( `Your directive v-motion-${key} is missing initial variant!`, ) } // Register the custom `v-motion-${key}` directive app.directive(`motion-${key}`, directive(variants)) } } }, } function useMotions() { return motionState } function useSpring(values, spring) { const { stop, get } = useMotionValues() return { values, stop, set: (properties) => Promise.all( Object.entries(properties).map(([key, value]) => { const motionValue = get(key, values[key], values) return motionValue.start((onComplete) => { const options = Object.assign( { type: 'spring' }, spring || getDefaultTransition(key, value), ) return animate( Object.assign( { from: motionValue.get(), to: value, velocity: motionValue.getVelocity(), onUpdate: (v) => motionValue.set(v), onComplete, }, options, ), ) }) }), ), } } /** * Check whether an object is a Motion Instance or not. * * Can be useful while building packages based on @vueuse/motion. * * @param obj * @returns bool */ function isMotionInstance(obj) { const _obj = obj return ( _obj.apply !== undefined && isFunction(_obj.apply) && _obj.set !== undefined && isFunction(_obj.set) && _obj.stopTransitions !== undefined && isFunction(_obj.stopTransitions) && _obj.target !== undefined && isRef(_obj.target) ) } /** * Reactive prefers-reduced-motion. * * @param options */ function useReducedMotion(options = {}) { return useMediaQuery('(prefers-reduced-motion: reduce)', options) } export { directive as MotionDirective, MotionPlugin, fade, fadeVisible, isMotionInstance, pop, popVisible, reactiveStyle, reactiveTransform, rollBottom, rollLeft, rollRight, rollTop, rollVisibleBottom, rollVisibleLeft, rollVisibleRight, rollVisibleTop, slideBottom, slideLeft, slideRight, slideTop, slideVisibleBottom, slideVisibleLeft, slideVisibleRight, slideVisibleTop, slugify, useElementStyle, useElementTransform, useMotion, useMotionControls, useMotionProperties, useMotionTransitions, useMotionVariants, useMotions, useReducedMotion, useSpring, } <file_sep>import { noop, unrefElement, useIntersectionObserver } from '@vueuse/core' import { unref, watch } from 'vue-demi' import { MotionInstance, MotionVariants } from '../types' export function registerVisibilityHooks<T extends MotionVariants>({ target, variants, variant, }: MotionInstance<T>) { const _variants = unref(variants) let _stopObserver: () => void = noop const _stopWatcher = watch( () => unrefElement(target), (el) => { if (!el) return // Bind intersection observer on target _stopObserver = useIntersectionObserver( target, ([{ isIntersecting }]) => { if (_variants && _variants.visible) { if (isIntersecting) { variant.value = 'visible' } else { variant.value = 'initial' } } }, ).stop }, { immediate: true, }, ) /** * Stop both the watcher and the intersection observer. */ const stop = () => { _stopObserver() _stopWatcher() } return { stop, } } <file_sep>import { MaybeRef } from '@vueuse/core' import { MotionInstance, MotionVariants, PermissiveTarget, UseMotionOptions, } from './types' import { useMotionControls } from './useMotionControls' import { useMotionFeatures } from './useMotionFeatures' import { useMotionProperties } from './useMotionProperties' import { useMotionVariants } from './useMotionVariants' /** * A Vue Composable that put your components in motion. * * @docs https://motion.vueuse.js.org * * @param target * @param variants * @param options */ export function useMotion<T extends MotionVariants>( target: MaybeRef<PermissiveTarget>, variants: MaybeRef<T> = {} as MaybeRef<T>, options?: UseMotionOptions, ) { // Reactive styling and transform const { motionProperties } = useMotionProperties(target) // Variants manager const { variant, state } = useMotionVariants<T>(variants) // Motion controls, synchronized with motion properties and variants const controls = useMotionControls<T>(motionProperties, variants) // Create motion instance const instance: MotionInstance<T> = { target, variant, variants, state, motionProperties, ...controls, } // Bind features useMotionFeatures(instance, options) return instance } <file_sep>import { del as __del, Directive, DirectiveBinding, ref, set as __set, VNode, } from 'vue-demi' import { motionState } from '../features/state' import { MotionVariants } from '../types' import { useMotion } from '../useMotion' import { resolveVariants } from '../utils/directive' export const directive = ( variants?: MotionVariants, ): Directive<HTMLElement | SVGElement> => { const register = ( el: HTMLElement | SVGElement, binding: DirectiveBinding, node: VNode< any, HTMLElement | SVGElement, { [key: string]: any } >, ) => { // Initialize variants with argument const variantsRef = ref<MotionVariants>(variants || {}) // Resolve variants from node props resolveVariants(node, variantsRef) // Create motion instance const motionInstance = useMotion(el, variantsRef) // Set the global state reference if the name is set through v-motion="`value`" if (binding.value) __set(motionState, binding.value, motionInstance) } const unregister = ( _: HTMLElement | SVGElement, binding: DirectiveBinding, __: VNode< any, HTMLElement | SVGElement, { [key: string]: any } >, ) => { // Check if motion state has the current element as reference if (binding.value && motionState[binding.value]) __del(motionState, binding.value) } return { // Vue 3 Directive Hooks created: register, unmounted: unregister, // Vue 2 Directive Hooks // For Nuxt & Vue 2 compatibility // @ts-expect-error bind: register, unbind: unregister, } } export default directive <file_sep>import { unrefElement, useEventListener } from '@vueuse/core' import { computed, ref, unref, watch } from 'vue-demi' import { MotionInstance, MotionVariants } from '../types' import { supportsMouseEvents, supportsPointerEvents, supportsTouchEvents, } from '../utils/events' export function registerEventListeners<T extends MotionVariants>({ target, state, variants, apply, }: MotionInstance<T>) { const _variants = unref(variants) // State const hovered = ref(false) const tapped = ref(false) const focused = ref(false) const mutableKeys = computed(() => { let result: string[] = [] if (!_variants) return result if (_variants.hovered) { result = [...result, ...Object.keys(_variants.hovered)] } if (_variants.tapped) { result = [...result, ...Object.keys(_variants.tapped)] } if (_variants.focused) { result = [...result, ...Object.keys(_variants.focused)] } return result }) const computedProperties = computed(() => { const result = {} Object.assign(result, state.value) if (hovered.value && _variants.hovered) { Object.assign(result, _variants.hovered) } if (tapped.value && _variants.tapped) { Object.assign(result, _variants.tapped) } if (focused.value && _variants.focused) { Object.assign(result, _variants.focused) } for (const key in result) { if (!mutableKeys.value.includes(key)) delete result[key] } return result }) watch( () => unrefElement(target), (el) => { if (!el || !_variants) return // Hovered if (_variants.hovered) { useEventListener(el as EventTarget, 'mouseenter', () => { hovered.value = true }) useEventListener(el as EventTarget, 'mouseleave', () => { hovered.value = false tapped.value = false }) useEventListener(el as EventTarget, 'mouseout', () => { hovered.value = false tapped.value = false }) } // Tapped if (_variants.tapped) { // Mouse if (supportsMouseEvents()) { useEventListener(el as EventTarget, 'mousedown', () => { tapped.value = true }) useEventListener(el as EventTarget, 'mouseup', () => { tapped.value = false }) } // Pointer if (supportsPointerEvents()) { useEventListener(el as EventTarget, 'pointerdown', () => { tapped.value = true }) useEventListener(el as EventTarget, 'pointerup', () => { tapped.value = false }) } // Touch if (supportsTouchEvents()) { useEventListener(el as EventTarget, 'touchstart', () => { tapped.value = true }) useEventListener(el as EventTarget, 'touchend', () => { tapped.value = false }) } } // Focused if (_variants.focused) { useEventListener(el as EventTarget, 'focus', () => { focused.value = true }) useEventListener(el as EventTarget, 'blur', () => { focused.value = false }) } }, { immediate: true, }, ) // Watch local computed variant, apply it dynamically watch(computedProperties, (newVal) => { apply(newVal) }) } <file_sep>import { registerEventListeners } from './features/eventListeners' import { registerLifeCycleHooks } from './features/lifeCycleHooks' import { registerVariantsSync } from './features/syncVariants' import { registerVisibilityHooks } from './features/visibilityHooks' import { MotionInstance, MotionVariants, UseMotionOptions } from './types' /** * A Composable executing resolved variants features from variants declarations. * * Supports: * - lifeCycleHooks: Bind the motion hooks to the component lifecycle hooks. * * @param variant * @param variants * @param options */ export function useMotionFeatures<T extends MotionVariants>( instance: MotionInstance<T>, options: UseMotionOptions = { syncVariants: true, lifeCycleHooks: true, visibilityHooks: true, eventListeners: true, }, ) { // Lifecycle hooks bindings if (options.lifeCycleHooks) { registerLifeCycleHooks(instance) } if (options.syncVariants) { registerVariantsSync(instance) } // Visibility hooks if (options.visibilityHooks) { registerVisibilityHooks(instance) } // Event listeners if (options.eventListeners) { registerEventListeners(instance) } } <file_sep>/*! * @vueuse/motion v1.6.0 * (c) 2021 * @license MIT */ var VueuseMotion = (function (t, e, n, r, i) { 'use strict' const s = {} /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var o = function () { return (o = Object.assign || function (t) { for (var e, n = 1, r = arguments.length; n < r; n++) for (var i in (e = arguments[n])) Object.prototype.hasOwnProperty.call(e, i) && (t[i] = e[i]) return t }).apply(this, arguments) } function a(t, e) { var n = {} for (var r in t) Object.prototype.hasOwnProperty.call(t, r) && e.indexOf(r) < 0 && (n[r] = t[r]) if (null != t && 'function' == typeof Object.getOwnPropertySymbols) { var i = 0 for (r = Object.getOwnPropertySymbols(t); i < r.length; i++) e.indexOf(r[i]) < 0 && Object.prototype.propertyIsEnumerable.call(t, r[i]) && (n[r[i]] = t[r[i]]) } return n } function c(t, e, n, r) { return new (n || (n = Promise))(function (i, s) { function o(t) { try { c(r.next(t)) } catch (t) { s(t) } } function a(t) { try { c(r.throw(t)) } catch (t) { s(t) } } function c(t) { var e t.done ? i(t.value) : ((e = t.value), e instanceof n ? e : new n(function (t) { t(e) })).then(o, a) } c((r = r.apply(t, e || [])).next()) }) } var u = (1 / 60) * 1e3, l = 'undefined' != typeof performance ? function () { return performance.now() } : function () { return Date.now() }, p = 'undefined' != typeof window ? function (t) { return window.requestAnimationFrame(t) } : function (t) { return setTimeout(function () { return t(l()) }, u) } var f = !0, d = !1, m = !1, v = { delta: 0, timestamp: 0 }, y = ['read', 'update', 'preRender', 'render', 'postRender'], h = y.reduce(function (t, e) { return ( (t[e] = (function (t) { var e = [], n = [], r = 0, i = !1, s = new WeakSet(), o = { schedule: function (t, o, a) { void 0 === o && (o = !1), void 0 === a && (a = !1) var c = a && i, u = c ? e : n return ( o && s.add(t), -1 === u.indexOf(t) && (u.push(t), c && i && (r = e.length)), t ) }, cancel: function (t) { var e = n.indexOf(t) ;-1 !== e && n.splice(e, 1), s.delete(t) }, process: function (a) { var c if ( ((i = !0), (e = (c = [n, e])[0]), ((n = c[1]).length = 0), (r = e.length)) ) for (var u = 0; u < r; u++) { var l = e[u] l(a), s.has(l) && (o.schedule(l), t()) } i = !1 }, } return o })(function () { return (d = !0) })), t ) }, {}), b = y.reduce(function (t, e) { var n = h[e] return ( (t[e] = function (t, e, r) { return ( void 0 === e && (e = !1), void 0 === r && (r = !1), d || w(), n.schedule(t, e, r) ) }), t ) }, {}), g = function (t) { return h[t].process(v) }, O = function (t) { ;(d = !1), (v.delta = f ? u : Math.max(Math.min(t - v.timestamp, 40), 1)), (v.timestamp = t), (m = !0), y.forEach(g), (m = !1), d && ((f = !1), p(O)) }, w = function () { ;(d = !0), (f = !0), m || p(O) } class j { constructor() { this.subscriptions = new Set() } add(t) { return ( this.subscriptions.add(t), () => { this.subscriptions.delete(t) } ) } notify(t, e, n) { if (this.subscriptions.size) for (const r of this.subscriptions) r(t, e, n) } clear() { this.subscriptions.clear() } } const x = (t) => !isNaN(parseFloat(t)) class k { constructor(t) { ;(this.timeDelta = 0), (this.lastUpdated = 0), (this.updateSubscribers = new j()), (this.canTrackVelocity = !1), (this.updateAndNotify = (t) => { ;(this.prev = this.current), (this.current = t) const { delta: e, timestamp: n } = v this.lastUpdated !== n && ((this.timeDelta = e), (this.lastUpdated = n)), b.postRender(this.scheduleVelocityCheck), this.updateSubscribers.notify(this.current) }), (this.scheduleVelocityCheck = () => b.postRender(this.velocityCheck)), (this.velocityCheck = ({ timestamp: t }) => { this.canTrackVelocity || (this.canTrackVelocity = x(this.current)), t !== this.lastUpdated && (this.prev = this.current) }), (this.prev = this.current = t), (this.canTrackVelocity = x(this.current)) } onChange(t) { return this.updateSubscribers.add(t) } clearListeners() { this.updateSubscribers.clear() } set(t) { this.updateAndNotify(t) } get() { return this.current } getPrevious() { return this.prev } getVelocity() { return this.canTrackVelocity ? i.velocityPerSecond( parseFloat(this.current) - parseFloat(this.prev), this.timeDelta, ) : 0 } start(t) { return ( this.stop(), new Promise((e) => { const { stop: n } = t(e) this.stopAnimation = n }).then(() => this.clearAnimation()) ) } stop() { this.stopAnimation && this.stopAnimation(), this.clearAnimation() } isAnimating() { return !!this.stopAnimation } clearAnimation() { this.stopAnimation = null } destroy() { this.updateSubscribers.clear(), this.stop() } } const { isArray: V } = Array function E() { const t = {}, n = (n) => { const r = (n) => { t[n] && (t[n].stop(), t[n].destroy(), e.del(t, n)) } n ? (V(n) ? n.forEach(r) : r(n)) : Object.keys(t).forEach(r) } return ( r.tryOnUnmounted(n), { motionValues: t, get: (n, r, i) => { if (t[n]) return t[n] const s = new k(r) return ( s.onChange((t) => { e.set(i, n, t) }), e.set(t, n, s), s ) }, stop: n, } ) } var A = function (t, e) { return function (n) { return Math.max(Math.min(n, e), t) } }, T = function (t) { return t % 1 ? Number(t.toFixed(5)) : t }, L = /(-)?([\d]*\.?[\d])+/g, C = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi, I = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i function R(t) { return 'string' == typeof t } var P = { test: function (t) { return 'number' == typeof t }, parse: parseFloat, transform: function (t) { return t }, }, M = o(o({}, P), { transform: A(0, 1) }), S = o(o({}, P), { default: 1 }), z = function (t) { return { test: function (e) { return R(e) && e.endsWith(t) && 1 === e.split(' ').length }, parse: parseFloat, transform: function (e) { return '' + e + t }, } }, F = z('deg'), B = z('%'), N = z('px'), W = o(o({}, B), { parse: function (t) { return B.parse(t) / 100 }, transform: function (t) { return B.transform(100 * t) }, }), U = function (t, e) { return function (n) { return Boolean( (R(n) && I.test(n) && n.startsWith(t)) || (e && Object.prototype.hasOwnProperty.call(n, e)), ) } }, X = function (t, e, n) { return function (r) { var i if (!R(r)) return r var s = r.match(L), o = s[1], a = s[2], c = s[3] return ( ((i = {})[t] = parseFloat(s[0])), (i[e] = parseFloat(o)), (i[n] = parseFloat(a)), (i.alpha = void 0 !== c ? parseFloat(c) : 1), i ) } }, Y = { test: U('hsl', 'hue'), parse: X('hue', 'saturation', 'lightness'), transform: function (t) { var e = t.saturation, n = t.lightness, r = t.alpha, i = void 0 === r ? 1 : r return ( 'hsla(' + Math.round(t.hue) + ', ' + B.transform(T(e)) + ', ' + B.transform(T(n)) + ', ' + T(M.transform(i)) + ')' ) }, }, Z = A(0, 255), D = o(o({}, P), { transform: function (t) { return Math.round(Z(t)) }, }), $ = { test: U('rgb', 'red'), parse: X('red', 'green', 'blue'), transform: function (t) { var e = t.green, n = t.blue, r = t.alpha, i = void 0 === r ? 1 : r return ( 'rgba(' + D.transform(t.red) + ', ' + D.transform(e) + ', ' + D.transform(n) + ', ' + T(M.transform(i)) + ')' ) }, } var _ = { test: U('#'), parse: function (t) { var e = '', n = '', r = '', i = '' return ( t.length > 5 ? ((e = t.substr(1, 2)), (n = t.substr(3, 2)), (r = t.substr(5, 2)), (i = t.substr(7, 2))) : ((e = t.substr(1, 1)), (n = t.substr(2, 1)), (r = t.substr(3, 1)), (i = t.substr(4, 1)), (e += e), (n += n), (r += r), (i += i)), { red: parseInt(e, 16), green: parseInt(n, 16), blue: parseInt(r, 16), alpha: i ? parseInt(i, 16) / 255 : 1, } ) }, transform: $.transform, }, H = { test: function (t) { return $.test(t) || _.test(t) || Y.test(t) }, parse: function (t) { return $.test(t) ? $.parse(t) : Y.test(t) ? Y.parse(t) : _.parse(t) }, transform: function (t) { return R(t) ? t : t.hasOwnProperty('red') ? $.transform(t) : Y.transform(t) }, }, q = '${c}', Q = '${n}' function G(t) { var e = [], n = 0, r = t.match(C) r && ((n = r.length), (t = t.replace(C, q)), e.push.apply(e, r.map(H.parse))) var i = t.match(L) return ( i && ((t = t.replace(L, Q)), e.push.apply(e, i.map(P.parse))), { values: e, numColors: n, tokenised: t } ) } function J(t) { return G(t).values } function K(t) { var e = G(t), n = e.numColors, r = e.tokenised, i = e.values.length return function (t) { for (var e = r, s = 0; s < i; s++) e = e.replace(s < n ? q : Q, s < n ? H.transform(t[s]) : T(t[s])) return e } } var tt = function (t) { return 'number' == typeof t ? 0 : t } var et = { test: function (t) { var e, n, r, i return ( isNaN(t) && R(t) && (null !== (n = null === (e = t.match(L)) || void 0 === e ? void 0 : e.length) && void 0 !== n ? n : 0) + (null !== (i = null === (r = t.match(C)) || void 0 === r ? void 0 : r.length) && void 0 !== i ? i : 0) > 0 ) }, parse: J, createTransformer: K, getAnimatableNone: function (t) { var e = J(t) return K(t)(e.map(tt)) }, }, nt = new Set(['brightness', 'contrast', 'saturate', 'opacity']) function rt(t) { var e = t.slice(0, -1).split('('), n = e[0], r = e[1] if ('drop-shadow' === n) return t var i = (r.match(L) || [])[0] if (!i) return t var s = r.replace(i, ''), o = nt.has(n) ? 1 : 0 return i !== r && (o *= 100), n + '(' + o + s + ')' } var it = /([a-z-]*)\(.*?\)/g, st = o(o({}, et), { getAnimatableNone: function (t) { var e = t.match(it) return e ? e.map(rt).join(' ') : t }, }) const ot = () => ({ type: 'spring', stiffness: 500, damping: 25, restDelta: 0.5, restSpeed: 10, }), at = (t) => ({ type: 'spring', stiffness: 550, damping: 0 === t ? 2 * Math.sqrt(550) : 30, restDelta: 0.01, restSpeed: 10, }), ct = () => ({ type: 'keyframes', ease: 'linear', duration: 300 }), ut = (t) => ({ type: 'keyframes', duration: 800, values: t }), lt = { default: (t) => ({ type: 'spring', stiffness: 550, damping: 0 === t ? 100 : 30, restDelta: 0.01, restSpeed: 10, }), x: ot, y: ot, z: ot, rotate: ot, rotateX: ot, rotateY: ot, rotateZ: ot, scaleX: at, scaleY: at, scale: at, backgroundColor: ct, color: ct, opacity: ct, }, pt = (t, e) => { let n return ( (n = Array.isArray(e) ? ut : lt[t] || lt.default), Object.assign({ to: e }, n(e)) ) }, ft = Object.assign(Object.assign({}, P), { transform: Math.round }), dt = { color: H, backgroundColor: H, outlineColor: H, fill: H, stroke: H, borderColor: H, borderTopColor: H, borderRightColor: H, borderBottomColor: H, borderLeftColor: H, borderWidth: N, borderTopWidth: N, borderRightWidth: N, borderBottomWidth: N, borderLeftWidth: N, borderRadius: N, radius: N, borderTopLeftRadius: N, borderTopRightRadius: N, borderBottomRightRadius: N, borderBottomLeftRadius: N, width: N, maxWidth: N, height: N, maxHeight: N, size: N, top: N, right: N, bottom: N, left: N, padding: N, paddingTop: N, paddingRight: N, paddingBottom: N, paddingLeft: N, margin: N, marginTop: N, marginRight: N, marginBottom: N, marginLeft: N, rotate: F, rotateX: F, rotateY: F, rotateZ: F, scale: S, scaleX: S, scaleY: S, scaleZ: S, skew: F, skewX: F, skewY: F, distance: N, translateX: N, translateY: N, translateZ: N, x: N, y: N, z: N, perspective: N, transformPerspective: N, opacity: M, originX: W, originY: W, originZ: N, zIndex: ft, filter: st, WebkitFilter: st, fillOpacity: M, strokeOpacity: M, numOctaves: ft, }, mt = (t) => dt[t], vt = (t, e) => e && 'number' == typeof t && e.transform ? e.transform(t) : t const yt = { linear: i.linear, easeIn: i.easeIn, easeInOut: i.easeInOut, easeOut: i.easeOut, circIn: i.circIn, circInOut: i.circInOut, circOut: i.circOut, backIn: i.backIn, backInOut: i.backInOut, backOut: i.backOut, anticipate: i.anticipate, bounceIn: i.bounceIn, bounceInOut: i.bounceInOut, bounceOut: i.bounceOut, }, ht = (t) => { if (Array.isArray(t)) { const [e, n, r, s] = t return i.cubicBezier(e, n, r, s) } return 'string' == typeof t ? yt[t] : t }, bt = (t, e) => 'zIndex' !== t && (!('number' != typeof e && !Array.isArray(e)) || !('string' != typeof e || !et.test(e) || e.startsWith('url('))) function gt(t) { var { ease: e, times: n, delay: r } = t, i = a(t, ['ease', 'times', 'delay']) const s = Object.assign({}, i) return ( n && (s.offset = n), e && (s.ease = ((t) => Array.isArray(t) && 'number' != typeof t[0])(e) ? e.map(ht) : ht(e)), r && (s.elapsed = -r), s ) } function Ot(t, e, n) { return ( Array.isArray(e.to) && (t.duration || (t.duration = 800)), (function (t) { Array.isArray(t.to) && null === t.to[0] && ((t.to = [...t.to]), (t.to[0] = t.from)) })(e), (function (t) { var e = a(t, ['delay', 'repeat', 'repeatType', 'repeatDelay', 'from']) return !!Object.keys(e).length })(t) || (t = Object.assign(Object.assign({}, t), pt(n, e.to))), Object.assign(Object.assign({}, e), gt(t)) ) } function wt(t, e, n, r, s) { const o = (function (t, e) { return t[e] || t.default || t })(r, t) let a = null == o.from ? e.get() : o.from const c = bt(t, n) 'none' === a && c && 'string' == typeof n && (a = (function (t, e) { let n = mt(t) return ( n !== st && (n = et), n.getAnimatableNone ? n.getAnimatableNone(e) : void 0 ) })(t, n)) return bt(t, a) && c && !1 !== o.type ? function (c) { const u = { from: a, to: n, velocity: r.velocity ? r.velocity : e.getVelocity(), onUpdate: (t) => e.set(t), } return 'inertia' === o.type || 'decay' === o.type ? i.inertia(Object.assign(Object.assign({}, u), o)) : i.animate( Object.assign(Object.assign({}, Ot(o, u, t)), { onUpdate: (t) => { u.onUpdate(t), o.onUpdate && o.onUpdate(t) }, onComplete: () => { r.onComplete && r.onComplete(), s && s(), c && c() }, }), ) } : function (t) { return ( e.set(n), r.onComplete && r.onComplete(), s && s(), t && t(), { stop: () => {} } ) } } function jt() { const { motionValues: t, stop: e, get: n } = E() return { motionValues: t, stop: e, push: (t, e, r, i = {}, s) => { const o = n(t, r[t], r) if (i && i.immediate) return void o.set(e) const a = wt(t, o, e, i, s) o.start(a) }, } } function xt(t, r = {}, { push: i, stop: s } = jt()) { const o = e.unref(r), a = (t) => { if (!o || !o[t]) throw new Error(`The variant ${t} does not exist.`) return o[t] }, u = (e) => ( 'string' == typeof e && (e = a(e)), Promise.all( Object.entries(e).map(([n, r]) => { if ('transition' !== n) return new Promise((s) => { i(n, r, t, e.transition || pt(n, e[n]), s) }) }), ) ) return { apply: u, set: (e) => { let r = n.isObject(e) ? e : a(e) Object.entries(r).forEach(([e, n]) => { 'transition' !== e && i(e, n, t, { immediate: !0 }) }) }, stopTransitions: s, leave: (t) => c(this, void 0, void 0, function* () { let e o && (o.leave && (e = o.leave), !o.leave && o.initial && (e = o.initial)), e ? (yield u(e), t()) : t() }), } } const kt = 'undefined' != typeof window function Vt({ target: t, state: r, variants: i, apply: s }) { const o = e.unref(i), a = e.ref(!1), c = e.ref(!1), u = e.ref(!1), l = e.computed(() => { let t = [] return o ? (o.hovered && (t = [...t, ...Object.keys(o.hovered)]), o.tapped && (t = [...t, ...Object.keys(o.tapped)]), o.focused && (t = [...t, ...Object.keys(o.focused)]), t) : t }), p = e.computed(() => { const t = {} Object.assign(t, r.value), a.value && o.hovered && Object.assign(t, o.hovered), c.value && o.tapped && Object.assign(t, o.tapped), u.value && o.focused && Object.assign(t, o.focused) for (const e in t) l.value.includes(e) || delete t[e] return t }) e.watch( () => n.unrefElement(t), (t) => { t && o && (o.hovered && (n.useEventListener(t, 'mouseenter', () => { a.value = !0 }), n.useEventListener(t, 'mouseleave', () => { ;(a.value = !1), (c.value = !1) }), n.useEventListener(t, 'mouseout', () => { ;(a.value = !1), (c.value = !1) })), o.tapped && (kt && null === window.onmousedown && (n.useEventListener(t, 'mousedown', () => { c.value = !0 }), n.useEventListener(t, 'mouseup', () => { c.value = !1 })), kt && null === window.onpointerdown && (n.useEventListener(t, 'pointerdown', () => { c.value = !0 }), n.useEventListener(t, 'pointerup', () => { c.value = !1 })), kt && null === window.ontouchstart && (n.useEventListener(t, 'touchstart', () => { c.value = !0 }), n.useEventListener(t, 'touchend', () => { c.value = !1 }))), o.focused && (n.useEventListener(t, 'focus', () => { u.value = !0 }), n.useEventListener(t, 'blur', () => { u.value = !1 }))) }, { immediate: !0 }, ), e.watch(p, (t) => { s(t) }) } function Et( t, r = { syncVariants: !0, lifeCycleHooks: !0, visibilityHooks: !0, eventListeners: !0, }, ) { r.lifeCycleHooks && (function ({ target: t, variants: n, variant: r }) { const i = e.unref(n) e.watch( () => t, () => { i && i.enter && (i.initial && (r.value = 'initial'), e.nextTick(() => (r.value = 'enter'))) }, { immediate: !0, flush: 'pre' }, ) })(t), r.syncVariants && (function ({ state: t, apply: n }) { e.watch( t, (t) => { t && n(t) }, { immediate: !0 }, ) })(t), r.visibilityHooks && (function ({ target: t, variants: r, variant: i }) { const s = e.unref(r) let o = n.noop const a = e.watch( () => n.unrefElement(t), (e) => { e && (o = n.useIntersectionObserver(t, ([{ isIntersecting: t }]) => { s && s.visible && (i.value = t ? 'visible' : 'initial') }).stop) }, { immediate: !0 }, ) })(t), r.eventListeners && Vt(t) } function At(t = {}) { const n = e.reactive(Object.assign({}, t)), r = e.ref({}) return ( e.watch( n, () => { const t = {} for (const [e, r] of Object.entries(n)) { const n = mt(e), i = vt(r, n) t[e] = i } r.value = t }, { immediate: !0, deep: !0 }, ), { state: n, style: r } ) } const Tt = ['', 'X', 'Y', 'Z'], Lt = ['transformPerspective', 'x', 'y', 'z'] ;['perspective', 'translate', 'scale', 'rotate', 'skew'].forEach((t) => { Tt.forEach((e) => { Lt.push(t + e) }) }) const Ct = new Set(Lt) function It(t) { return Ct.has(t) } const Rt = new Set(['originX', 'originY', 'originZ']) function Pt(t) { return Rt.has(t) } function Mt(t, r) { let i, s const { state: o, style: a } = At(), c = e.watch( () => n.unrefElement(t), (t) => { if (t) { s = t for (const n of Object.keys(dt)) null === t.style[n] || '' === t.style[n] || It(n) || Pt(n) || e.set(o, n, t.style[n]) i && Object.entries(i).forEach(([n, r]) => e.set(t.style, n, r)), r && r(o) } }, { immediate: !0 }, ), u = e.watch( a, (t) => { if (s) for (const n in t) e.set(s.style, n, t[n]) else i = t }, { immediate: !0 }, ) return { style: o, stop: () => { c(), u() }, } } const St = { x: 'translateX', y: 'translateY', z: 'translateZ' } function zt(t = {}, n = !0) { const r = e.reactive(Object.assign({}, t)), i = e.ref('') return ( e.watch( r, (t) => { let e = '', r = !1 if (n && (t.x || t.y || t.z)) { ;(e += `translate3d(${[t.x || 0, t.y || 0, t.z || 0] .map(N.transform) .join(',')}) `), (r = !0) } for (const [r, i] of Object.entries(t)) { if (n && ('x' === r || 'y' === r || 'z' === r)) continue const t = mt(r), s = vt(i, t) e += `${St[r] || r}(${s}) ` } n && !r && (e += 'translateZ(0px) '), (i.value = e.trim()) }, { immediate: !0, deep: !0 }, ), { state: r, transform: i } ) } function Ft(t) { const e = t.trim().split(/\) |\)/) if (1 === e.length) return {} return e.reduce((t, e) => { if (!e) return t const [n, r] = e.split('('), i = r .split(',') .map((t) => ((t) => t.endsWith('px') || t.endsWith('deg') ? parseFloat(t) : isNaN(Number(t)) ? Number(t) : t)(t.endsWith(')') ? t.replace(')', '') : t.trim()), ), s = 1 === i.length ? i[0] : i return Object.assign(Object.assign({}, t), { [n]: s }) }, {}) } function Bt(t, r) { let i, s const { state: o, transform: a } = zt(), c = e.watch( () => n.unrefElement(t), (t) => { t && ((s = t), t.style.transform && (function (t, n) { Object.entries(Ft(n)).forEach(([n, r]) => { r = parseFloat(r) const i = ['x', 'y', 'z'] 'translate3d' !== n ? e.set( t, 'translateX' !== n ? 'translateY' !== n ? 'translateZ' !== n ? n : 'z' : 'y' : 'x', r, ) : r.forEach((n, r) => { e.set(t, i[r], n) }) }) })(o, t.style.transform), i && (t.style.transform = i), r && r(o)) }, { immediate: !0 }, ), u = e.watch( a, (t) => { s ? (s.style.transform = t) : (i = t) }, { immediate: !0 }, ) return { transform: o, stop: () => { c(), u() }, } } function Nt(t, r) { const i = e.reactive({}), s = (t) => { Object.entries(t).forEach(([t, n]) => { e.set(i, t, n) }) }, { style: o, stop: a } = Mt(t, s), { transform: c, stop: u } = Bt(t, s), l = e.watch( i, (t) => { Object.entries(t).forEach(([t, n]) => { const r = It(t) ? c : o ;(r[t] && r[t] === n) || e.set(r, t, n) }) }, { immediate: !0, deep: !0 }, ), p = e.watch( () => n.unrefElement(t), (t) => { t && r && s(r) }, { immediate: !0 }, ) return { motionProperties: i, style: o, transform: c, stop: () => { a(), u(), l(), p() }, } } function Wt(t = {}) { const n = e.unref(t), r = e.ref() return { state: e.computed(() => { if (r.value) return n[r.value] }), variant: r, } } function Ut(t, e = {}, n) { const { motionProperties: r } = Nt(t), { variant: i, state: s } = Wt(e), o = xt(r, e), a = Object.assign( { target: t, variant: i, variants: e, state: s, motionProperties: r }, o, ) return Et(a, n), a } const Xt = [ 'initial', 'enter', 'leave', 'visible', 'hovered', 'tapped', 'focused', 'delay', ], Yt = (t) => { const r = (r, i, o) => { const a = e.ref(t || {}) ;((t, e) => { const r = t.props ? t.props : t.data && t.data.attrs ? t.data.attrs : {} r && (r.variants && n.isObject(r.variants) && (e.value = Object.assign( Object.assign({}, e.value), r.variants, )), Xt.forEach((t) => { if ('delay' !== t) r && r[t] && n.isObject(r[t]) && (e.value[t] = r[t]) else if (r && r[t] && n.isNumber(r[t])) { const n = r[t] e && e.value && (e.value.enter && (e.value.enter.transition || (e.value.enter.transition = {}), (e.value.enter.transition = Object.assign( Object.assign({}, e.value.enter.transition), { delay: n }, ))), e.value.visible && (e.value.visible.transition || (e.value.visible.transition = {}), (e.value.visible.transition = Object.assign( Object.assign({}, e.value.visible.transition), { delay: n }, )))) } })) })(o, a) const c = Ut(r, a) i.value && e.set(s, i.value, c) }, i = (t, n, r) => { n.value && s[n.value] && e.del(s, n.value) } return { created: r, unmounted: i, bind: r, unbind: i } }, Zt = { initial: { opacity: 0 }, enter: { opacity: 1 } }, Dt = { initial: { opacity: 0 }, visible: { opacity: 1 } }, $t = { initial: { scale: 0, opacity: 0 }, enter: { scale: 1, opacity: 1 } }, _t = { initial: { scale: 0, opacity: 0 }, visible: { scale: 1, opacity: 1 }, }, Ht = { initial: { x: -100, rotate: 90, opacity: 0 }, enter: { x: 0, rotate: 0, opacity: 1 }, }, qt = { initial: { x: -100, rotate: 90, opacity: 0 }, visible: { x: 0, rotate: 0, opacity: 1 }, }, Qt = { initial: { x: 100, rotate: -90, opacity: 0 }, enter: { x: 0, rotate: 0, opacity: 1 }, }, Gt = { initial: { x: 100, rotate: -90, opacity: 0 }, visible: { x: 0, rotate: 0, opacity: 1 }, }, Jt = { initial: { y: -100, rotate: -90, opacity: 0 }, enter: { y: 0, rotate: 0, opacity: 1 }, }, Kt = { initial: { y: -100, rotate: -90, opacity: 0 }, visible: { y: 0, rotate: 0, opacity: 1 }, }, te = { initial: { y: 100, rotate: 90, opacity: 0 }, enter: { y: 0, rotate: 0, opacity: 1 }, }, ee = { initial: { y: 100, rotate: 90, opacity: 0 }, visible: { y: 0, rotate: 0, opacity: 1 }, }, ne = { initial: { x: -100, opacity: 0 }, enter: { x: 0, opacity: 1 } }, re = { initial: { x: -100, opacity: 0 }, visible: { x: 0, opacity: 1 } }, ie = { initial: { x: 100, opacity: 0 }, enter: { x: 0, opacity: 1 } }, se = { initial: { x: 100, opacity: 0 }, visible: { x: 0, opacity: 1 } }, oe = { initial: { y: -100, opacity: 0 }, enter: { y: 0, opacity: 1 } }, ae = { initial: { y: -100, opacity: 0 }, visible: { y: 0, opacity: 1 } }, ce = { initial: { y: 100, opacity: 0 }, enter: { y: 0, opacity: 1 } }, ue = { initial: { y: 100, opacity: 0 }, visible: { y: 0, opacity: 1 } } var le = Object.freeze({ __proto__: null, fade: Zt, fadeVisible: Dt, pop: $t, popVisible: _t, rollBottom: te, rollLeft: Ht, rollRight: Qt, rollTop: Jt, rollVisibleBottom: ee, rollVisibleLeft: qt, rollVisibleRight: Gt, rollVisibleTop: Kt, slideBottom: ce, slideLeft: ne, slideRight: ie, slideTop: oe, slideVisibleBottom: ue, slideVisibleLeft: re, slideVisibleRight: se, slideVisibleTop: ae, }) function pe(t) { const e = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;', n = new RegExp(e.split('').join('|'), 'g') return t .toString() .replace(/[A-Z]/g, (t) => '-' + t) .toLowerCase() .replace(/\s+/g, '-') .replace(n, (t) => 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------'.charAt( e.indexOf(t), ), ) .replace(/&/g, '-and-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-') .replace(/^-+/, '') .replace(/-+$/, '') } const fe = { install(t, e) { if ((t.directive('motion', Yt()), !e || (e && !e.excludePresets))) for (const e in le) { const n = le[e] t.directive(`motion-${pe(e)}`, Yt(n)) } if (e && e.directives) for (const n in e.directives) { const r = e.directives[n] 0, t.directive(`motion-${n}`, Yt(r)) } }, } return ( (t.MotionDirective = Yt), (t.MotionPlugin = fe), (t.fade = Zt), (t.fadeVisible = Dt), (t.isMotionInstance = function (t) { const n = t return ( void 0 !== n.apply && r.isFunction(n.apply) && void 0 !== n.set && r.isFunction(n.set) && void 0 !== n.stopTransitions && r.isFunction(n.stopTransitions) && void 0 !== n.target && e.isRef(n.target) ) }), (t.pop = $t), (t.popVisible = _t), (t.reactiveStyle = At), (t.reactiveTransform = zt), (t.rollBottom = te), (t.rollLeft = Ht), (t.rollRight = Qt), (t.rollTop = Jt), (t.rollVisibleBottom = ee), (t.rollVisibleLeft = qt), (t.rollVisibleRight = Gt), (t.rollVisibleTop = Kt), (t.slideBottom = ce), (t.slideLeft = ne), (t.slideRight = ie), (t.slideTop = oe), (t.slideVisibleBottom = ue), (t.slideVisibleLeft = re), (t.slideVisibleRight = se), (t.slideVisibleTop = ae), (t.slugify = pe), (t.useElementStyle = Mt), (t.useElementTransform = Bt), (t.useMotion = Ut), (t.useMotionControls = xt), (t.useMotionProperties = Nt), (t.useMotionTransitions = jt), (t.useMotionVariants = Wt), (t.useMotions = function () { return s }), (t.useReducedMotion = function (t = {}) { return n.useMediaQuery('(prefers-reduced-motion: reduce)', t) }), (t.useSpring = function (t, e) { const { stop: n, get: r } = E() return { values: t, stop: n, set: (n) => Promise.all( Object.entries(n).map(([n, s]) => { const o = r(n, t[n], t) return o.start((t) => { const r = Object.assign({ type: 'spring' }, e || pt(n, s)) return i.animate( Object.assign( { from: o.get(), to: s, velocity: o.getVelocity(), onUpdate: (t) => o.set(t), onComplete: t, }, r, ), ) }) }), ), } }), Object.defineProperty(t, '__esModule', { value: !0 }), t ) })({}, VueDemi, VueUse, shared, popmotion)
f2bbf6f5e695839ed570aa5c9aad7e2e8c1d426b
[ "JavaScript", "TypeScript" ]
9
TypeScript
patrickdaley/motion
a18db1f3c313eb812ede779a5ca943dc8afca02f
d45a44661f5410952b257edf14a4d57abf638261
refs/heads/master
<repo_name>brandohardesty/Showcase<file_sep>/README.md # Showcase This is sample code from my Data Structures course. # DoublyLinkedList.py This is a sample from a lab where I was required to implement a doubly linked list with operations including insert, deletion, addition, etc. # MixedFraction.py This is an object that I created for several labs. It inherits the Fraction class, not from the python standard library. I implemented class members such as numerators, denomenators, and whole numbers. The functions include rich comparison operators and overridden arithmetic operators. # Fraction.py This is an object that I created for labs using MixedFraction.py. The fraction class is the parent of MixedFraction and includes similar class members like numerators and denominators. It includes rich comparison operators and overridden arithetic operators. # cStack.py Here I implemented the stack data structure built on top of a list. I include functionallities such as peek, pop, and push. # cQueue.py Here I implemented the queue data structure built on top of a list. I include functionalities such as enqueue and dequeue. # binheap.py This is an implementation of a binary heap structure. I use this structure for building a priority queue in lab 7 to decrease the big o on ciertian operations. # InfixPostfix.py In this lab, I had to convert infix expressions to postfix expressions and then further evaluate them in another file Postfixevaluation.py # Postfixevaluation.py Here I evaluate the postfix expressions created in InfixPostfix.py # Binary and AVL Tree This is currently being graded and I will upload when I recieve a grade. <file_sep>/primeFact.py __author__ = "<NAME>" def sieve(n = int(1e7)): """ builds a list of primes less than n :param n: limit on our primes :return: reverse ordered list of primes less than n """ multiples = set() primes = [2] for i in range(3,n+1,2): if i not in multiples: primes.append(i) multiples.update(f for f in range(i*i,n+1,i)) return primes[::-1] def largestPrimeFactor(n,primes): """ :param n: :param primes: list of primes between 0 and n :return: the largest prime factor """ for i in primes: if n % i == 0: return i return -1 def primeFactors(n, primes): factors = [largestPrimeFactor(n, primes)] r = n i = 0 while factors[i] > 0: r = r // factors[i] i += 1 factors.append(largestPrimeFactor(r, primes)) factors.pop() product = 1 for p in factors: product *= p if product == n: return factors else: factors.insert(0,n//product) return factors def displayFactors(n,factors): out = '' if factors[0] > 1e14: out = 'Warning {:,m} is too large to guarantee all factors are prime\n' if factors[0] == n: out = '{:,d} is prime'.format(n) def main(): #primes = sieve() #dataFile = open('datfile1','r') #nums = [] #nums = dataFile.readlines() print(largestPrimeFactor(100,sieve(9))) print(primeFactors(83*2,sieve(9))) if __name__ == '__main__': main() <file_sep>/Fraction.py __author__ = '<NAME>' from primeFact import sieve,primeFactors class Fraction(object): def __init__(self, top, bottom=1): """ Constructor for MixedFraction. Initializes num and den after reducing top / bottom by their gcd. :param top: numerator :param bottom: denominator """ g = self.gcd(top, bottom) self.num = top // g self.den = bottom // g @staticmethod def gcd(m, n): """ Euclid's Division Algorithm to find the greatest common denominator (gcd) of two integers. <http://people.uncw.edu/tompkinsj/133/proofs/quotientRemainderTheorem.htm> :param m: an int :param n: an int :return: the greatest common denominator of m and n """ while m % n != 0: m, n = n, m % n return n @classmethod def from_string(cls,f): n = f[:f.index("/")] d = f[f.index("/") + 1:] return cls(int(n),int(d)) def __str__(self): """ String representation of this fraction. :return: 'num / den' """ return '{}/{}'.format(str(self.num), str(self.den)) def __float__(self): result = self.num/self.den return result def __add__(self, other): """ Adds this fraction to the input parameter (also a Fraction or FixedFraction (possibly a MixedFraction). For the MixedFraction case, Fraction is moved to second operand so MixedFraction handles the addition (arithmetic promotion is required). :param other a Fraction, FixedFraction, or MixedFraction :return Fraction(n, d) """ n = self.num * other.den + self.den * other.num d = self.den * other.den return Fraction(n, d) def __sub__(self,other): """ This is going to subtract another fraction from this fraction. :param other: The fraction subtracting this fraction :return: a fraction resulting from the subtraction """ n = self.num * other.den - self.den * other.num d = self.den * other.den return Fraction(n,d) def __pow__(self, exp): """ Multiplies this fraction by itself exp times. :param exp: the exponent to be applied :return: Fraction(n, d) after exponentiation """ n = self.num ** exp d = self.den ** exp return Fraction(n, d) def __truediv__(self, other): """ Divides a fraction by another fraction :param other: another fraction :return: a resulting fraction from the division """ n = (self.num * other.den) d = (self.den * other.num) return Fraction(n,d) def __sub__(self,other): """ Subtracts "other" fraction from this fraction :param other: another fraction :return: a resulting fraction from the subtraction """ n = (self.num * other.den) - (other.num * self.den) d = (self.den * other.den) return Fraction(n,d) def __mul__(self,other): """ Multiplies this fraction by another fraction :param other: another fraction :return: a resulting fraction from the multiplication """ n = (self.num * other.num) d = (self.den * other.den) return Fraction(n,d) def __eq__(self,other): """ Test if two fractions are equivalent :param other: a fraction to test equivalency :return: boolean either true or false """ f1 = float(self.num/self.den) f2 = float(other.num/other.den) if(f1 == f2): return True else: return False def __ne__(self,other): """ Test if two fractions aren't equivalent :param other:a fraction to test equivalency :return: boolean either true or false """ f1 = float(self.num / self.den) f2 = float(other.num / other.den) if (not(f1 == f2)): return True else: return False def __lt__(self,other): """ Test if the current fraction is less than the other fraction :param other: another fraction :return: boolean true or false """ f1 = float(self.num / self.den) f2 = float(other.num / other.den) if (f1 < f2): return True else: return False def __gt__(self,other): """ Test if the current fraction is greater than the other fraction :param other: another fraction :return: boolean true or false """ f1 = float(self.num / self.den) f2 = float(other.num / other.den) if (f1 > f2): return True else: return False def __ge__(self,other): """ Test if the current fraction is greater than or equal to the other fraction :param other: another fraction :return: boolean true or false """ f1 = float(self.num / self.den) f2 = float(other.num / other.den) if (f1 >= f2): return True else: return False def __le__(self,other): """ Test if the current fraction is less than or equal to another fraction :param other: another fraction :return: boolean true or false """ f1 = float(self.num / self.den) f2 = float(other.num / other.den) if (f1 <= f2): return True else: return False def __abs__(self): tempNum = self.num if(self.num < 0): tempNum *= -1 else: pass return Fraction(tempNum,self.den) def primeFactorsOfFrac(self): n = sieve(max(self.num,self.den)) factOfNum = primeFactors(self.num,n) factOfDen = primeFactors(self.den,n) return (factOfNum,factOfDen) <file_sep>/cQueue.py import DoublyLinkedList __author__ = "<NAME>" class Queue: def __init__(self): """ Creates a new Queue """ self.queue = DoublyLinkedList.DoublyLinkedList() def is_empty(self): """ Test if the Queue is empty :return: True or False """ return self.queue.size == 0 def size(self): """ Gives the size of the Queue :return: the number of elements in the queue """ return self.queue.size def enqueue(self,value): """ Adds a node object to the front of the queue :param value: The value :return: nothing """ self.queue.addFront(value) def dequeue(self): """ Remove the last object in the queue :return: The last value in the queue """ return self.queue.removeRear() <file_sep>/cStack.py import DoublyLinkedList __author__ = "<NAME>" class Stack: def __init__(self): """ Creates a new stack """ self.stack = DoublyLinkedList.DoublyLinkedList() def isEmpty(self): """ Test if the stack is empty :return: True or false """ return self.stack.size == 0 def size(self): """ Gives the size of the stack :return: The number of elements in the stack """ return self.stack.size def push(self,value): """ Adds a node to the rear of the stack :param value: The object you want to add :return: nothing """ self.stack.addRear(value) def pop(self): """ Removes the last item on the stack :return: the value of the last item """ if self.isEmpty(): raise Exception return self.stack.removeRear() def peek(self): """ Looks at the last item on the stack :return: the value of the last item on the stack """ return self.stack.atIndex(self.stack.size-1) <file_sep>/InfixPostfix.py __author__ = "<NAME>" import cStack import DoublyLinkedList import MixedFraction def infixToPostfix(infixexpr): prec = {} prec["^"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = cStack.Stack() postfixList = [] tokenList = infixexpr.split(" ") for token in tokenList: if token.isnumeric() or token.isalpha() or token.count(".") == 1 or (token.count("/") == 1 and len(token) > 1): postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': try: postfixList.append(topToken) topToken = opStack.pop() except Exception: print("Bad expession: {}".format(infixexpr)) break else: try: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) except KeyError: print("Key Error: {}".format(infixexpr)) break opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList) def main(): print(infixToPostfix("A * B + C ^ D")) print(infixToPostfix("( 4.4 + 4.6 ) ^ ( 2 / ( 1 + 3 ) )")) print(infixToPostfix("( 2 ^ 20 ) ^ ( 2 / ( 1 + 3 ) )")) print(infixToPostfix("A * B ) + ( C ^ D )")) print(infixToPostfix("( A * B ) + (C ^ D )")) print(infixToPostfix("7 + 9 * 8 / 4 ^ 2")) print(infixToPostfix("( 17 + 9 ) * 3 / ( 5 - 3 ) ^ 4")) if __name__ == "__main__": main() <file_sep>/lab7.py __author__ = '<NAME>, <NAME> modified by <NAME> and student' import MixedFraction import random import math import binheap import csv import time class Node: def __init__(self, initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self, newdata): self.data = newdata def setNext(self, newnext): self.next = newnext class Queue23: def __init__(self): self.head = None def search(self, item): current = self.head found = False stop = False while current is not None and not found and not stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: current = current.getNext() return found def add(self, item): current = self.head previous = None stop = False while current is not None and not stop: if current.getData() > item: stop = True else: previous = current current = current.getNext() temp = Node(item) if previous is None: temp.setNext(self.head) self.head = temp else: temp.setNext(current) previous.setNext(temp) def isEmpty(self): """ Returns True if the priority queue is empty, False otherwise.""" return self.head is None def size(self): """ Returns the current size of the priority queue.""" current = self.head count = 0 while current is not None: count = count + 1 current = current.getNext() return count def insert(self, k): self.add(k) def findMin(self): """ Finds and returns the minimum value in the priority queue. :return: the object with the minimum value """ return self.head.getData() def delMin(self): """ Removes and returns the minimum value in the priority queue. Catches the potential IndexError. :return: minimum value in the priority queue, None if attempted on an empty heap """ retval = None try: retval = self.head.getData() self.head = self.head.next except IndexError: return None return retval def buildPriorityQueue(self, alist): """ Builds an otherwise empty priority queue from the list parameter. :param alist: A list of comparable objects. :return: None """ blist = list(alist) blist.sort() pNode = Node(blist[0]) self.head = pNode del blist[0] for i in range(len(blist)): t = Node(blist[0]) pNode.next = t pNode = t del blist[0] class Queue12: def __init__(self): self.items = [] def isEmpty(self): """ Returns True if the priority queue is empty, False otherwise.""" return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): """ Returns the current size of the priority queue.""" return len(self.items) def insert(self, k): """ inserts k into the priority queue so the priority is maintained :param k: :return: None """ self.items.append(k) self.items.sort() def findMin(self): """ Finds and returns the minimum value in the priority queue. :return: the object with the minimum value """ return self.items[0] def delMin(self): """ Removes and returns the minimum value in the priority queue. Catches the potential IndexError. :return: minimum value in the priority queue, None if attempted on an empty heap """ retval = None try: retval = self.items[0] del self.items[0] except IndexError: return None return retval def buildPriorityQueue(self, alist): """ Builds an otherwise empty priority queue from the list parameter. :param alist: A list of comparable objects. :return: None """ self.items = alist self.items.sort() def generateDataSet(): randomMixedFractions = list() for i in range(40000): randomMixedFractions.append(MixedFraction.MixedFraction(random.randint(1,100),random.randint(1,100))) dataSets = {"10k":[],"20k":[],"30k":[],"40k":[]} dataSets["10k"] = randomMixedFractions[:10000] dataSets["20k"] = randomMixedFractions[:20000] dataSets["30k"] = randomMixedFractions[:30000] dataSets["40k"] = randomMixedFractions[:40000] return dataSets def getData(dataList): minimum = min(dataList) maximum = max(dataList) totalListVal = MixedFraction.MixedFraction(0,1) for i in dataList: totalListVal += i avg = totalListVal/MixedFraction.MixedFraction(len(dataList),1) delta = MixedFraction.MixedFraction(0,1) deltaList = list() realAvg = 0 for i in range(len(dataList)): delta = dataList[i] - avg if(delta == MixedFraction.MixedFraction(0,1)): realAvg = dataList[i] deltaList.append(abs(delta)) else: deltaList.append(abs(delta)) realAvg = dataList[deltaList.index(min(deltaList))] return (minimum,maximum,realAvg) def timeOperations(data): listQ = Queue12() linkedQ = Queue23() binQ = binheap.BinHeap() keys = ["10k","20k","30k","40k"] with open("table.csv", "w") as file: nList = [10000, 20000, 30000, 40000] writer = csv.writer(file) writer.writerow(["listQ", "linkedQ", "binQ"]) for i in keys: listQ.buildPriorityQueue(data[i]) linkedQ.buildPriorityQueue(data[i]) binQ.buildPriorityQueue(data[i]) st = time.clock() listQ.findMin() sp = time.clock() listQT = sp - st st = time.clock() linkedQ.findMin() sp = time.clock() linkedQT = sp - st st = time.clock() binQ.findMin() sp = time.clock() binQT = sp - st writer.writerow([listQT,linkedQT,binQT]) with open("insert.csv", "w") as file: nList = [10000, 20000, 30000, 40000] insertWriter = csv.writer(file) insertWriter.writerow(["listQ", "linkedQ", "binQ"]) for i in keys: listQ.buildPriorityQueue(data[i]) linkedQ.buildPriorityQueue(data[i]) binQ.buildPriorityQueue(data[i]) avgE = getData(data[i])[2] st = time.clock() listQ.insert(avgE) sp = time.clock() listQT = sp - st st = time.clock() linkedQ.insert(avgE) sp = time.clock() linkedQT = sp - st st = time.clock() binQ.insert(avgE) sp = time.clock() binQT = sp - st insertWriter.writerow([listQT,linkedQT,binQT]) with open("del.csv", "w") as file: nList = [10000, 20000, 30000, 40000] delWriter = csv.writer(file) delWriter.writerow(["listQ", "linkedQ", "binQ"]) for i in keys: listQ.buildPriorityQueue(data[i]) linkedQ.buildPriorityQueue(data[i]) binQ.buildPriorityQueue(data[i]) st = time.clock() listQ.delMin() sp = time.clock() listQT = sp - st st = time.clock() linkedQ.delMin() sp = time.clock() linkedQT = sp - st st = time.clock() binQ.delMin() sp = time.clock() binQT = sp - st delWriter.writerow([listQT,linkedQT,binQT]) #finding minimum test 10k through 40k def main(): timeOperations(generateDataSet()) pass if __name__ == '__main__': main() <file_sep>/MixedFraction.py from Fraction import Fraction __author__ = '<NAME>' class MixedFraction (Fraction): def __init__(self, top, bottom=1): """ Initializes num and den after reducing top / bottom by their gcd by invoking super. Adds fields whole and n, initialized to 0. If num > den, assigns the quotient to whole and the remainder to n. :param top: numerator :param bottom: denominator """ super().__init__(top, bottom) self.whole = 0 self.n = 0 if self.num >= self.den: self.whole = self.num // self.den self.n = self.num % self.den def __str__(self): """ String representation of this fraction. Empty strings are used in place of 0. :return: whole num / den :: num / den :: whole """ if self.whole == 0: return super().__str__() elif self.n == 0: return str(self.whole) return '{} {}/{}'.format(str(self.whole), str(self.n), str(self.den)) def __add__(self, other): """ Adds this fraction to the input parameter (also a Fraction (possibly a MixedFraction). :param other Fraction or MixedFraction :return MixedFraction(n, d) """ n = self.num * other.den + self.den * other.num d = self.den * other.den return MixedFraction(n, d) def __sub__(self, other): """ Subtracts the input parameter (also a Fraction (possibly a MixedFraction) from this fraction. :param other Fraction or MixedFraction :return MixedFraction(n, d) """ n = (self.num * other.den) - (self.den * other.num) d = self.den * other.den return MixedFraction(n,d) def __mul__(self,other): """ Multiplies a mixed fraction by another mixed fraction or fraction :param other: another fraction or mixed fraction :return: the resulting mixed fraction from the multiplication """ n = (self.num) * (other.num) d = (self.den * other.den) return MixedFraction(n,d) def __truediv__(self,other): """ Divides a mixed fraction by another mixed fraction or a fraction :param other: another fraction or mixed fraction :return: the resulting mixed fraction from the division """ n = (self.num) * other.den d = (self.den * other.num) return MixedFraction(n,d) def __pow__(self, exp): """ Multiplies this fraction by itself exp times. :param exp: the exponent to be applied :return: MixedFraction(n, d) after exponentiation """ f = super().__pow__(exp) return MixedFraction(f.num, f.den) @classmethod def from_string(cls,f): if (f.count(" ") == 1): w = f[:f.index(" ")] n = f[f.index(" ") + 1:f.index("/")] d = f[f.index("/")+1:] return cls(int(w) * int(d) + int(n), int(d)) if(f.count(" ") == 0): n = f[:f.index("/")] d = f[f.index("/") + 1:] return cls(int(n),int(d)) <file_sep>/lab6_quicksorts.py import os import sys from urllib.request import urlopen import matplotlib.pyplot as plt from time import clock import math import random __author__ = '<NAME>' def plot(data_map, title, xlabel='N', ylabel='time - seconds'): """ Plots the two sets of data (minimum 8 datapoints) in the dictionary data_map using its keys as labels :param data_map: a dictionary containing the x data points and two sets of y data points :param title: Map heading :param xlabel: abscissa axis :param ylabel: ordinate axis :return: None """ labels = list(data_map.keys()) plt.title(title) x = data_map[labels[0]] y1 = data_map[labels[1]] y2 = data_map[labels[2]] plt.plot(x, y1, label=labels[1], color='g') plt.plot(x,y2, label=labels[2], color='b') plt.xlabel(xlabel) plt.ylabel(ylabel) plt.text(x[2], y1[2], 'f({0:,}) = {1:.2}\nn = {0:,}'.format(x[2], y1[2]), color='g') # n, f(n) plt.text(x[5], y1[5], 'f({:,}) = {:.2}\n= {:.2}f(n) '.format(x[5], y1[5], y1[5]/y1[2]), color='g') # n, f(2n)/f(n) plt.text(x[0], y2[0], 'f({0:,}) = {1:.2}\nn = {0:,}'.format(x[0], y2[0]), color='b') # n, f(n) plt.text(x[7], y2[7], 'f({:,}) = {:.2}\n= {:.2}f(n) '.format(x[7], y2[7], y2[7] / y2[0]), color='b') # n, f(8n)/f(n) plt.legend() plt.show() def get_from_web(web_addr, save=True): """ Retrieves and saves the resource located at the provided URL :param web_addr: URL :param save: default Boolean saves to a file in a directory named data :return: a list of strs created from space delimited str tokens in the web resource """ response = urlopen(web_addr).read() # urlopen creates the connection # read returns a bytes object file_name = web_addr[web_addr.rfind('/') + 1:] if not os.path.exists('data'): os.makedirs('data') if save: with open('data/' + file_name, 'wb') as f: f.write(response) return response.decode().split() def quicksort(xlist): qsort(xlist, 0, len(xlist)-1) def qsort(xlist, L, R): i = L j = R ip = L + (R - L) // 2 # index of middle element p = xlist[ip] # pivot element in the middle while i <= j: while xlist[i] < p: i += 1 while xlist[j] > p: j -= 1 if i <= j: # swap and increment i, decrement j xlist[i], xlist[j] = xlist[j], xlist[i] i += 1 j -= 1 if L < j: # sort left list qsort(xlist, L, j) if i < R: # sort right list qsort(xlist, i, R) def bquickSort(alist): bquickSortHelper(alist,0,len(alist)-1) def bquickSortHelper(alist,first,last): if first<last: splitpoint = partition2(alist,first,last) bquickSortHelper(alist,first,splitpoint-1) bquickSortHelper(alist,splitpoint+1,last) def partition2(alist,first,last): pivotvalue = alist[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and alist[leftmark] <= pivotvalue: leftmark = leftmark + 1 while alist[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark -1 if rightmark < leftmark: done = True else: temp = alist[leftmark] alist[leftmark] = alist[rightmark] alist[rightmark] = temp temp = alist[first] alist[first] = alist[rightmark] alist[rightmark] = temp return rightmark def genData(): file = open('data.txt','w') set1 = [-1*(i**2) for i in range(-50,51)] set2 = [i for i in range(50,0-1)] for x in range(0,51): set2.append(x) file.write('Data Set 1\n') for x in range(len(set1)): file.write(str(set1[x])+'\n') file.write('Data Set 2\n') for x in range(len(set2)): file.write(str(set2[x])+'\n') return (set1,set2) def main(start, data, func, title): data_sorted = sorted(data, reverse=True) data_map = {'x':[], 'randomized data':[], 'sorted data':[]} print('\n{}'.format(title)) temp = 0 temp2 = 0 step = start end = start + 8*step + 1 for n in range(start, end, step): ulist = data[:n] slist = data_sorted[:n] expected = temp * (n ** 2) expected2 = temp2 * (n * math.log10(n)) start1 = clock() func(ulist) time1 = clock() - start1 temp2 = time1 / (n * math.log10(n)) start2 = clock() func(slist) time2 = clock() - start2 temp = time2 / (n**2) data_map['x'].append(n) data_map['randomized data'].append(time1) data_map['sorted data'].append(time2) x = data_map['x'] y1 = data_map['randomized data'] y2 = data_map['sorted data'] analyze_data(x, y1, 'green') analyze_data(x, y2, 'blue') plot(data_map, title) def analyze_data(x, y, color='green'): if color is 'blue': print('Sorted {}'.format(color)) else: print('Unsorted {}'.format(color)) print('f({0:,}) = {1:.2}, n = {0:,}'.format(x[2], y[2])) print('f({:,}) = {:.2}, = {:.2}f(n) '.format(x[5], y[5], y[5] / y[2])) print('f({0:,}) = {1:.2}, n = {0:,}'.format(x[0], y[0])) print('f({:,}) = {:.2}, = {:.2}f(n) '.format(x[7], y[7], y[7] / y[0])) if y[5]/y[2] < 1.5 or y[7]/y[0] < 6 : # output ratio for doubled input less than double print('The {} graph is better than linear? \n \ Expected: f(2n) ≅ 2*f(n), f(8n) ≅ 8*f(n)'.format(color)) elif round(y[5]/y[2]) == 2 or round(y[7]/y[0]) == 8: # output ratio for doubled input is also double print('The {} graph appears to be linear. \n \ Expected: f(2n) ≅ 2*f(n), f(8n) ≅ 8*f(n)'.format(color)) elif round(y[5]/y[2]) >= 3 and round(y[7]/y[0]) > 32: # output ratio for double input is quadratic, for 8*input it is 64f(n) print('****The {} graph may be quadratic. \n \ Expected: f(2n) ≅ 4*f(n), f(8n) ≅ 64*f(n) ****\n'.format(color)) elif round(y[5]/y[2]) >= 4 or round(y[7]/y[0]) >= 64: # output ratio for doubled input is quadratic, for 8 * input it is 64f(n) print('**************The {} graph appears to be quadratic. \n \ Expected: f(2n) ≅ 4*f(n), f(8n) ≅ 64*f(n) **************\n'.format(color)) def conclusions(): ans1 = """ The list is being partitioned the maximum amount of times if you pivot on the endpoints of the dataset. The reason the sort runs the maximum amount of times is because the list only gets smaller by one each run. """ print('\nDiscussion regarding the dataset size limitations exhibited using "quickSort - first element pivot" in Step 1.\n\t{}'.format(ans1)) ans2 = """ Actual (6.2e-05)/30^2 = (expected time)/60^2" Expected Time calculation = 2.48e-4 and the actual time was 2.2e-4 so the calculations are accurate.""" print('Calculations for Step 2 showing actual vs expected performance of "quicksort - middle pivot"\n\t{}'.format(ans2)) ans3 = """ I generated a data set where the data increased until the middle was the maximum value. The decreased from the middle value to the end of the data set. This allows for decreasing the list size by 1 each run.""" print('Design particulars for your datasets created in Step 2.\n\t{}'.format(ans3)) ans4 = """ Yes, my generated data set degrades the run time to n^2 because it results in the maximum number of runs.""" print('Does the middle pivot solve the quicksort degradation problem?\n\t{}'.format(ans4)) if __name__ == '__main__': data = get_from_web('http://people.uncw.edu/tompkinsj/231/resources/dictionary.txt') print("""This Lab test various quicksort algorithms using particular datasets to show graphically that the algorithm may degrade to O(n**2) given the right conditions.""") print("""In the second part, we attempt to degrade quicksort with middle pivot using different combinations of datasets since it efficiently handled presorted data sets.""") print("Initial dataset: type {}, type element {}, first element {}, last element {}, size {:,}.". format(type(data), type(data[0]), data[0], data[-1], len(data))) main(50, data, bquickSort, 'Unsorted vs Sorted Quick Sorts - middle pivot') start_size = 50 # invoke main with a start_size appropriate for the recursive first pivot quickSort, same data, new function name, and new title main(start_size,data, quicksort, 'Unsorted vs Sorted Quick Sorts - first element pivot') # populate data with the return value from your dataset building function which builds and saves dataset to data folder title = ' ' # invoke main with a modified title datatup = genData() main(10,datatup[0], bquickSort, 'Unsorted {} vs Sorted {} - middle pivot'.format(title,title)) conclusions() <file_sep>/DoublyLinkedList.py __author__ = "<NAME>" class DoublyLinkedNode: """ A single node in a doubly-linked list. Contains 3 instance variables: data: The value stored at the node. prev: A pointer to the previous node in the linked list. next: A pointer to the next node in the linked list. """ def __init__(self, value): """ Initializes a node by setting its data to value and prev and next to None. :return: The reference for self. """ self.data = value self.prev = None self.next = None class DoublyLinkedList: """ The doubly-linked list class has 3 instance variables: head: The first node in the list. tail: The last node in the list. size: How many nodes are in the list. """ def __init__(self): """ The constructor sets head and tail to None and the size to zero. :return: The reference for self. """ self.head = None self.tail = None self.size = 0 def addFront(self, value): """ Creates a new node (with data = value) and puts it in the front of the list. :return: None """ newNode = DoublyLinkedNode(value) if (self.size == 0): self.head = newNode self.tail = newNode self.size = 1 else: newNode.next = self.head self.head.prev = newNode self.head = newNode self.size += 1 def addRear(self, value): """ Creates a new node (with data = value) and puts it in the rear of the list. :return: None """ newNode = DoublyLinkedNode(value) if (self.size == 0): self.head = newNode self.tail = newNode self.size = 1 else: newNode.prev = self.tail self.tail.next = newNode self.tail = newNode self.size += 1 def removeFront(self): """ Removes the node in the front of the list. :return: The data in the deleted node. """ value = self.head.data self.head = self.head.next if self.head != None: self.head.prev = None self.size -= 1 return value def removeRear(self): """ Removes the node in the rear of the list. :return: The data in the deleted node. """ value = self.tail.data self.tail = self.tail.prev if self.tail != None: self.tail.next = None self.size -= 1 return value def printItOut(self): """ Prints out the list from head to tail all on one line. :return: None """ temp = self.head while temp != None: print(temp.data, end=" ") temp = temp.next print() def printInReverse(self): """ Prints out the list from tail to head all on one line. :return: None """ temp = self.tail while temp != None: print(temp.data, end=" ") temp = temp.prev print() def atIndex(self, index): """ Retrieves the data of the item at index. :param index: The index of the item to retrieve. :return: Returns the data of the item. """ count = 0 temp = self.head while count < index: count += 1 temp = temp.next if not temp: return None return temp.data def indexOf(self,value): for i in range(self.size): if (value == self.atIndex(i)): return i return -1 def insertAt(self,index,value): newNode = DoublyLinkedNode(value) temp = self.head for i in range(index): temp = temp.next if(index == 0): self.addFront(value) elif(index == (self.size)): self.addRear(value) else: temp.prev.next = newNode newNode.prev = temp.prev temp.prev = newNode newNode.next = temp self.size += 1 def removeAt(self,index): temp = self.head for i in range(index): temp = temp.next if(index == 0): return self.removeFront() elif(index == (self.size-1)): return self.removeRear() else: print(self.size) value = temp.data temp.prev.next = temp.next temp.next.prev = temp.prev self.size -= 1 return value def main(): dll = DoublyLinkedList() dll.addRear(5) dll.addRear(2) dll.addRear(25) dll.addRear(-4) dll.insertAt(2,7) dll.printItOut() x = dll.removeAt(2) dll.printItOut() print("\tThe item removed was {}.".format(x)) x = dll.removeAt(0) dll.printItOut() print("\tThe item removed was {}.".format(x)) x = dll.removeAt(2) dll.printItOut() print("\tThe item removed was {}.".format(x)) # optionally print() dll = DoublyLinkedList() dll.addRear(1) dll.addRear(2) dll.addRear(4) dll.addRear(25) dll.addRear(35) dll.printItOut() for i in range(dll.size): y = dll.atIndex(i) yIndex = dll.indexOf(y) print('The value at index {:d} is {} for which indexOf({}) returned {}.'.format(i,y,y,yIndex)) print('indexOf(-10) is {}'.format(dll.indexOf(-10))) print('The dll size is {}.'.format(dll.size)) if __name__ == '__main__': main() <file_sep>/Postfixevaluation.py __author__ = "<NAME>" from InfixPostfix import infixToPostfix import DoublyLinkedList import cStack import MixedFraction postfixExpressions = ['4.4 4.6 + 2 1 3 + / ^', '2 20 ^ 2 1 3 + / ^', '2 20 + 2 1 3 + + *', '2 -1 3 + -'] infixExpressions = ["7 + 9 * 8 - 4 ^ 2", "7 + 9 * 8 / 4 ^ 2", "( 17 + 9 ) * 3 / ( 5 - 3 ) ^ 4", "7.5 + 9 - 1.8 / 4 ^ 2.5"] def evaluatePost(exp): stack = cStack.Stack() tokenList = exp.split(" ") for i in tokenList: try: if(i.count("/") == 1 and len(i) > 1): stack.push(float(MixedFraction.MixedFraction.from_string(i))) else: i = float(i) stack.push(i) except: if (i in "*/+-^"): b = stack.pop() a = stack.pop() if (i == "*"): stack.push(a * b) elif (i == "/"): stack.push(a / b) elif (i == "+"): stack.push(a + b) elif (i == "-"): stack.push(a - b) elif (i == "^"): stack.push(a ** b) return stack.peek() def main(): for i in postfixExpressions: result = evaluatePost(i) out = "{} = {}".format(i,result) print(out) for i in infixExpressions: c = infixToPostfix(i) result = evaluatePost(c) out = "{} = {}".format(i, result) print(out) if __name__ == "__main__": main() <file_sep>/binheap.py __author__ = '<NAME>, <NAME> modified by <NAME>' class BinHeap: def __init__(self): self.heapList = [0] self.currentSize = 0 def insert(self, k): """ inserts k into the priority queue so the priority is maintained :param k: :return: None """ self.heapList.append(k) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) def findMin(self): """ Finds and returns the minimum value in the priority queue. :return: the object with the minimum value """ return self.heapList[1] def delMin(self): """ Removes and returns the minimum value in the priority queue. Catches the potential IndexError. :return: minimum value in the priority queue, None if attempted on an empty heap """ retval = None try: retval = self.heapList[1] self.heapList[1] = self.heapList[self.currentSize] self.currentSize = self.currentSize - 1 self.heapList.pop() self.percDown(1) except IndexError: pass return retval def isEmpty(self): """ Returns True if the priority queue is empty, False otherwise.""" return self.currentSize == 0 def size(self): """ Returns the current size of the priority queue.""" return self.currentSize def buildPriorityQueue(self, alist): """ Builds an otherwise empty priority queue from the list parameter. :param alist: A list of comparable objects. :return: None """ i = len(alist) // 2 self.currentSize = len(alist) self.heapList = [0] + alist[:] while (i > 0): self.percDown(i) i = i - 1 def percUp(self, i): """ Percolates an item, at index i, as far up in the tree as it needs to go to maintain the heap property :param i: the index of the item :return: None """ while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i = i // 2 def percDown(self,i): """ Invoked by delMin and buildPriorityQueue. Invokes minChild. Since the heap property requires that the root of the tree be the smallest item in the tree, finding the minimum item is easy. The hard part of delMin is restoring full compliance with the heap structure and heap order properties after the root has been removed. We can restore our heap in two steps. First, we will restore the root item by taking the last item in the list and moving it to the root position. Moving the last item maintains our heap structure property. However, we have probably destroyed the heap order property of our binary heap. Second, we will restore the heap order property by pushing the new root node down the tree to its proper position. :param i: :return: None """ while (i * 2) <= self.currentSize: mc = self.minChild(i) if self.heapList[i] > self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc def minChild(self,i): """ Invoked by percDown. If there is only one child, its index is returned. If there are two children, then the smaller childs index is returned. :param i: index of the parent :return: the index of the minimum child """ if i * 2 + 1 > self.currentSize: return i * 2 else: if self.heapList[i*2] < self.heapList[i*2+1]: return i * 2 else: return i * 2 + 1 def main(): print('Invoking BinHeap()') bh = BinHeap() print('Size: {}, isEmpty(): {}, delMin(): {}'.format(bh.size(), bh.isEmpty(), bh.delMin())) data = [9,5,6,2,3] print('Invoking buildPriorityQueue({}) which invokes percDown from the middle of the list to the top.'.format(data)) bh.buildPriorityQueue(data) x = -5 print('Invoking insert({0}) which appends {0} to the heap then invokes percUp.'.format(x)) bh.insert(x) print('Size: {}, isEmpty(): {}'.format(bh.size(), bh.isEmpty())) print('''while bh.size() > 0: invoking delMin(), which stores the min value for later return, places the last element first, reduces the size, pops the end then invokes percDown''') while bh.size() > 0: print(bh.delMin()) if __name__ == '__main__': main()
cde9d877f3308e0087ccb60917e19592f13ee0fd
[ "Markdown", "Python" ]
12
Markdown
brandohardesty/Showcase
4b60e9989020160a1688e81d590f63517ec0978c
17a9cc469790b807d6c379b3f14f5e968c5765a2
refs/heads/main
<file_sep>const canvas = document.querySelector('canvas#cv'); const ctx = canvas.getContext('2d'); canvas.width = canvas.offsetWidth; canvas.height = canvas.offsetHeight; console.log(canvas.width, canvas.height); class Calculator { relX(x) { return (0 - ((canvas.width / 2) - x)); } relY(y) { return ((canvas.height / 2) - y); } calFromRelX(relX) { return (canvas.width / 2) + relX; } calFromRelY(relY) { return (canvas.height / 2) - relY; } } class Star extends Calculator { x = Math.random() * (canvas.width - 200) + 100; y = Math.random() * (canvas.height - 200) + 100; size = Math.random() * 3 + 1; multiplier = 1.03; isOutSide = false; update() { if ((this.x > -100 && this.x < canvas.width + 100) && (this.y > -100 && this.y < canvas.height + 100)) { ctx.fillStyle = 'white'; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); let relX = super.relX(this.x); let relY = super.relY(this.y); relX *= this.multiplier; relY *= this.multiplier; this.x = super.calFromRelX(relX); this.y = super.calFromRelY(relY); this.multiplier += 0.00001; } else { if (!this.isOutSide) { array.push(new Star()); this.isOutSide = true; if (array.length > 100) { array.shift(); } } } } } let array = []; for (let i = 0; i < 20; i++) { array.push(new Star()); } function animate() { ctx.fillStyle = "rgba(0, 0, 0, 0.5)"; ctx.beginPath(); ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fill(); ctx.closePath(); array.forEach(el => {el.update()}) requestAnimationFrame(animate); } animate();<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Space</title> <link rel="stylesheet" href="style.css"> </head> <body> <canvas id="cv"></canvas> <script src="graphicEngine.js"></script> </body> </html>
dae1ac5edcacd2906ef84e825a8111f849296b41
[ "JavaScript", "Markdown" ]
2
JavaScript
CaptSiro/SpaceTravel
97b74746aae6fdd2ff7b2abea6f03ecd61bd51e0
1c62876c5286da6f7b27107a44e3d33cf9d00bd8
refs/heads/master
<repo_name>a2iKnGWq/XRhun-test<file_sep>/XR/application.py from flask import Flask, flash, jsonify, redirect, render_template, request # Configure application app = Flask(__name__) # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True # Ensure responses aren't cached @app.after_request def after_request(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response @app.route("/", methods=["GET"]) #["GET", "POST"] def index(): """Show portfolio""" return render_template("home.html") @app.route("/void", methods=["GET"]) def voidfunc(): """Show portfolio""" return render_template("void.html") @app.route("/cards", methods=["GET"]) def cards(): """Show portfolio""" return render_template("cards.html") @app.route("/FAQ", methods=["GET"]) def FAQ(): """Show portfolio""" return render_template("FAQ.html")
ef77baa7ea5da1315ea352a73e57bc9fcd307776
[ "Python" ]
1
Python
a2iKnGWq/XRhun-test
8d8ff941c672f52ffb84cd813efbcbd6313b89b1
defd036ad0e74444a91a8ed51cc3c9a20f80dd75
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public class TarriffModel { public string Id { get; set; } public string Name { get; set; } public decimal PricePerUnit { get; set; } } } <file_sep>using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Common.ISubscriptionsServices { public interface ISubscriptionServices { void MakeSubscription(Subscriptions subcription); List<Subscriptions> GetAllSubscription(); List<Subscriptions> GetCustomerSubscription(string customerId); Subscriptions FindSubscription(string customerId); void CancelSubcription(string id); List<Subscriptions> CheckActiveSubscription(string customerId); string UpdateSubscription(Subscriptions modifiedSubscription); } } <file_sep>using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace EDSCustomerPortal.Services.IServices { public interface IAuthenticationService { string RegisterUser(CustomerModel model); CustomerModel GetCustomerByEmail(string email); CustomerModel GetCustomerById(string customerId); string RegisterSubscription(ElectricityTariffPayment electricityTariffPayment); ElectricityTariffPayment ViewCustomerSubscriptionByMeterNumber(string meterNumber); void DeleteSubscription(string metreId); } } <file_sep>using EDSCustomerPortal.Menu; using System; namespace EDSCustomerPortal { class Program { static void Main(string[] args) { MenuNav menuNav = new MenuNav(); menuNav.PageMenu(); } } } <file_sep>using ElectricityDigitalSystem.AgentServices.IServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.AgentServices { public class AgentServices : AgentServicesAPI, IAgentServices { public string RegisterAgent(AgentsModel agent) { if (agent == null) { throw new ArgumentNullException(nameof(agent)); } //This will Handle registration of an Agent else { fileService.Database.Agents.Add(agent); fileService.SaveChanges(); return agent.Id == null ? "Failed" : "Success"; } } public AgentsModel GetAgentById(string agentId) { AgentsModel foundAgent = fileService.Database.Agents.Find(c => c.Id == agentId); if (foundAgent != null) { return foundAgent; } return null; } //Find Agent via Email public AgentsModel GetAgentByEmail(string email) { AgentsModel foundAgentEmail = fileService.Database.Agents.Find(c => c.EmailAddress == email); if (foundAgentEmail != null) { return foundAgentEmail; } return null; } public string UpdateAgent(AgentsModel modifiedAgent) { AgentsModel foundAgent = this.GetAgentById(modifiedAgent.Id); if (foundAgent != null) { //fileService.Database.Customers.IndexOf(foundCustomer); //fileService.Database.Customers.Insert(indexOfFoundCustomer, foundCustomer); fileService.SaveChanges(); return "SUCCESS"; } return "FAILURE NOT FOUND"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EDSAgentPortal.Validation { public class Security { public static string ReadPassword(char mask) { const int ENTER = 13, BACKSP = 8, CTRLBACKSP = 127; int[] FILTERED = { 0, 27, 9, 10 /*, 32 space, if you care */ }; // const var pass = new Stack<char>(); char chr = (char)0; while ((chr = System.Console.ReadKey(true).KeyChar) != ENTER) { if (chr == BACKSP) { if (pass.Count > 0) { System.Console.Write("\b \b"); pass.Pop(); } } else if (chr == CTRLBACKSP) { while (pass.Count > 0) { System.Console.Write("\b \b"); pass.Pop(); } } else if (FILTERED.Count(x => chr == x) > 0) { } else { pass.Push((char)chr); System.Console.Write(mask); } } System.Console.WriteLine(); return new string(pass.Reverse().ToArray()); } public static string ReadPassword() { return ReadPassword('*'); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public class Subscriptions { public string Id { get; set; } public decimal Amount { get; set; } public string TariffId { get; set; } public string CustomerId { get; set; } public string AgentId { get; set; } public DateTime SubcriptionDateTime { get; set; } = DateTime.Now; public string SubscriptionStatus { get; set; } } } <file_sep>using EDSAgentPortal.AgentMenu; using ElectricityDigitalSystem.Common; using ElectricityDigitalSystem.Common.ISubscriptionsServices; using System; namespace EDSAgentPortal { class Program { static void Main(string[] args) { ITariffServices tariffServices = new TariffServices(); tariffServices.AddTariffToService(); AgentMenuNav agentMenuNav = new AgentMenuNav(); agentMenuNav.PageMenuNav(); } } } <file_sep>using EDSAgentPortal.AgentMenu.AgentLogInMenu; using EDSAgentPortal.Validation; using ElectricityDigitalSystem.AgentServices; using ElectricityDigitalSystem.AgentServices.IServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSAgentPortal.AgentMenu { public class AgentMenu { readonly IAgentServices agentServices = new AgentServices(); readonly AgentMenuNav agentMenuNav = new AgentMenuNav(); readonly ValidationClass validation = new ValidationClass(); readonly LogInMenuNav loginMenuNav = new LogInMenuNav(); public void RegisterAgent() { Dictionary<string, string> navItemDIc = new Dictionary<string, string>(); List<string> navigationItems = new List<string> { "FirstName", "LastName", "Email", "Password", "PhoneNumber" }; Console.Clear(); Console.WriteLine("Please Provide your Details : "); for (int i = 0; i < navigationItems.Count; i++) { Console.Write($"Enter your {navigationItems[i]} : "); var value = Console.ReadLine(); while (string.IsNullOrEmpty(value)) { Console.WriteLine($"{navigationItems[i]} cannot be left blank"); Console.Write($"{navigationItems[i]} : "); value = Console.ReadLine(); } navItemDIc.Add(navigationItems[i], value); } string FirstName, LastName, Email, Password, PhoneNumber; FirstName = navItemDIc["FirstName"]; LastName = navItemDIc["LastName"]; Email = navItemDIc["Email"]; Password = navItemDIc["Password"]; PhoneNumber = navItemDIc["PhoneNumber"]; ulong number = validation.CheckPhoneNumber(PhoneNumber); AgentsModel model = new AgentsModel { FirstName = FirstName, LastName = LastName, EmailAddress = Email, Password = <PASSWORD>, PhoneNumber = number.ToString("00000000000"), }; string registrationResponds = agentServices.RegisterAgent(model); if (registrationResponds == "Success") { Console.WriteLine(); Console.WriteLine("Registration Successful"); Console.WriteLine("Redirecting you to Home Page...."); Thread.Sleep(3000); } else Console.WriteLine("An Error occured While Trying to Create your Account Please try Again"); agentMenuNav.PageMenuNav(); } public void LoginAgent() { string Email, Password; Console.Clear(); Console.WriteLine("Please Login with your Email and Password"); Console.Write($"Please Enter your Email : "); Email = Console.ReadLine(); Console.Write($"Please Enter your Password : "); Password = <PASSWORD>(); var agent = agentServices.GetAgentByEmail(Email); if (agent == null) { Console.WriteLine("No Email Found"); Thread.Sleep(3000); agentMenuNav.PageMenuNav(); } else { if (agent.Password != <PASSWORD>) { Console.WriteLine("Invalid Login Credentials \nPlease Create an Account!"); Thread.Sleep(3000); agentMenuNav.PageMenuNav(); } else { //call the loginPageNav loginMenuNav.LogInPageMenuNav(agent.Id, agent.FirstName, agent.LastName); } } } } } <file_sep># Team-Saturn-ElectricityDigitalSystem Team Project Done by Ekene, Sarah and Michael and supervised by Soji Problem : The government of Nigeria wants to make power Generation and Management / Distribution easy for its citizens. Previously , Customers had to Go Directly to the offices of the discos ( distribution companies) to refill their Bill. But now The Government wants that process to become easy. For this reason they have come to Your team to come up with a solution. Using The Pillars Of Object Oriented Programming learned over the past few weeks, write a software program That the Disco Company Agents can Use To Register a New Customer Into the System/ Remove a Customer From the System / Update a Customer’s information Accept And Process Payments from a Customer For a particular Electricity Tariff subscription and Store that Information on the Customer in their Database View the Personal/ Electricity Tariff Information related to a Customer. Modify the Information for an Electrify Power Tariff Plan(i.e Price per Units of Electricity) Also, Write another simple Software Program That the Customer can Use To Register into the System. Subscribe for an Electricity Tariff Unsubscribe from an Electricity Tariff Update personal Information Notes : When A Customer has Subscribed for an electricity tariff, it should reflect in the Agents Application Database. Hints Use a persistent storage type (most likely Text file or Json File) as your database Create a Library and Two Console Applications (one for the agent and one for the customer) The Two Console Applications should be serviced from the common Library. Ie (add a reference to the Library project inside both console apps) The Library should be smart enough to separate namespaces that are only peculiar to the Customer application or to the Agent Application. -Only the Library should be able to read/write to the database. The service layers can also stay inside the Library project (as namespaces) Your program should be interactive. When you want to run your program, to run the customer app, just change your starting point to the program.cs file of the customer console app, Alternatively when you want to run the Agent Application, change your starting point to the Program.cs file for the Agent app <file_sep>using EDSAgentPortal.Validation; using ElectricityDigitalSystem.AgentServices; using ElectricityDigitalSystem.AgentServices.IServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSAgentPortal.AgentMenu.AgentLogInMenu.CustomerPortfolio { public class CustomerPortMenu { readonly IAgentCustomerServices agentCustomerServices = new AgentCustomerServices(); readonly ValidationClass validation = new ValidationClass(); readonly CustomerPortMenuNav customerPortMenuNav = new CustomerPortMenuNav(); public void RegisterCustomer(string registeringAgent) { Dictionary<string, string> navItemDIc = new Dictionary<string, string>(); List<string> navigationItems = new List<string> { "FirstName", "LastName", "Email", "Password", "PhoneNumber" }; Console.Clear(); Console.WriteLine("Please Provide your Details : "); for (int i = 0; i < navigationItems.Count; i++) { Console.Write($"Enter your {navigationItems[i]} : "); var value = Console.ReadLine(); while (string.IsNullOrEmpty(value)) { Console.WriteLine($"{navigationItems[i]} cannot be left blank"); Console.Write($"{navigationItems[i]} : "); value = Console.ReadLine(); } navItemDIc.Add(navigationItems[i], value); } string FirstName, LastName, Email, Password, PhoneNumber; FirstName = navItemDIc["FirstName"]; LastName = navItemDIc["LastName"]; Email = navItemDIc["Email"]; Password = navItemDIc["Password"]; PhoneNumber = navItemDIc["PhoneNumber"]; ulong number = validation.CheckPhoneNumber(PhoneNumber); CustomerModel model = new CustomerModel { FirstName = FirstName, LastName = LastName, EmailAddress = Email, Password = <PASSWORD>, PhoneNumber = number.ToString("00000000000"), AgentId = registeringAgent }; string registrationResponds = agentCustomerServices.RegisterCustomer(model); if (registrationResponds == "Success") { Console.WriteLine(); Console.WriteLine("Registration Successful"); Console.WriteLine("Redirecting you to Home Page...."); Thread.Sleep(3000); customerPortMenuNav.CustomerPortPageMenuNav(registeringAgent); } else { Console.WriteLine("An Error occured While Trying to Create your Account Please try Again"); customerPortMenuNav.CustomerPortPageMenuNav(registeringAgent); } } public void ViewCustomerInfo() { string result = EmailCheck(); if (result == "Failed") { Console.WriteLine("No Valid Email Found"); Thread.Sleep(3000); } else { Console.WriteLine(); Console.WriteLine($"{"Full Name",-20} : {agentCustomerServices.GetCustomerByEmail(result).FirstName} {agentCustomerServices.GetCustomerByEmail(result).LastName}"); Console.WriteLine($"{"Email Address",-20} : {agentCustomerServices.GetCustomerByEmail(result).EmailAddress} "); Console.WriteLine($"{"Phone Number",-20} : {agentCustomerServices.GetCustomerByEmail(result).PhoneNumber} "); Console.WriteLine($"{"Meter Number",-20} : {agentCustomerServices.GetCustomerByEmail(result).MeterNumber} "); Console.WriteLine($"{"Registered Agent Id",-20} : {agentCustomerServices.GetCustomerByEmail(result).AgentId} "); Console.WriteLine($"{"Created Date Time",-20} : {agentCustomerServices.GetCustomerByEmail(result).CreatedDateTime} "); Console.WriteLine($"{"Modified Date Time",-20} : {agentCustomerServices.GetCustomerByEmail(result).ModifiedDateTime} "); Console.ReadKey(); } } public void ViewAllRegisteredCustomer() { var values = agentCustomerServices.GetAllRegisteredCustomer(); if (values == null) { Console.WriteLine("No Customer Registered!!!!"); } else { foreach (var item in values) { Console.WriteLine(); Console.WriteLine($"{"Full Name",-20} : {item.FirstName} {item.LastName}"); Console.WriteLine($"{"Email Address",-20} : {item.EmailAddress} "); Console.WriteLine($"{"Phone Number",-20} : {item.PhoneNumber} "); Console.WriteLine($"{"Meter Number",-20} : {item.MeterNumber} "); Console.WriteLine($"{"Registered Agent Id",-20} : {item.AgentId} "); Console.WriteLine($"{"Created Date Time",-20} : {item.CreatedDateTime} "); Console.WriteLine($"{"Modified Date Time",-20} : {item.ModifiedDateTime} "); } Console.ReadKey(); } } public void UpdatePersonalInfo() { string result = EmailCheck(); if (result == "Failed") { Console.WriteLine("No Valid Email Found"); Thread.Sleep(3000); } else { var customerEmail = agentCustomerServices.GetCustomerByEmail(result); bool inputAnother; do { Console.WriteLine($"What would you like to Update?\n 1. First Name 2. Last Name 3. Email Address 4. Phone Number 5. Password"); string response = Console.ReadLine(); switch (response) { case "1": Console.WriteLine("Please enter your new First Name :"); customerEmail.FirstName = Console.ReadLine(); customerEmail.ModifiedDateTime = DateTime.Now; break; case "2": Console.WriteLine("Please enter your new Last Name :"); customerEmail.LastName = Console.ReadLine(); customerEmail.ModifiedDateTime = DateTime.Now; break; case "3": Console.WriteLine("Please enter your new Email Address :"); customerEmail.EmailAddress = Console.ReadLine(); customerEmail.ModifiedDateTime = DateTime.Now; break; case "4": Console.WriteLine("Please enter your new Phone Number :"); customerEmail.PhoneNumber = Console.ReadLine(); customerEmail.ModifiedDateTime = DateTime.Now; break; case "5": Console.WriteLine("Please enter your new Password :"); customerEmail.Password = Console.ReadLine(); customerEmail.ModifiedDateTime = DateTime.Now; break; } Console.WriteLine("Would you like to update another information? (Y/N)"); var continueEditing = Console.ReadLine(); if (continueEditing.ToLower() == "y") { inputAnother = true; } else { inputAnother = false; } } while (inputAnother); agentCustomerServices.UpdateCustomer(customerEmail); Console.WriteLine("Successful!!!"); Thread.Sleep(3000); } } private string EmailCheck() { Console.Clear(); Console.WriteLine("Please Can I have the Email you used in Registering :"); Console.Write("The Email Address : "); string email = Console.ReadLine(); while (string.IsNullOrEmpty(email)) { Console.Write("Please Enter an Email Address : "); email = Console.ReadLine(); } var customer = agentCustomerServices.GetCustomerByEmail(email); if (customer == null) { return "Failed"; } else { return customer.EmailAddress; } } } } <file_sep>using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Common.ISubscriptionsServices { public interface ITariffServices { void AddTariffToService(); void PushToDb(TarriffModel model); List<TarriffModel> GetAllTariff(); TarriffModel GetTarriffByName(string name); TarriffModel GetTarriffById(string id); } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public class CustomerModel : BaseUserModel { readonly Random meterNumber = new Random(); public CustomerModel() { this.Id = "CUS-" + Guid.NewGuid().ToString(); this.MeterNumber = ($"EDS-{meterNumber.Next(100000000, 999999999)}"); } public string MeterNumber { get; set; } public string AgentId { get; set; } public string Password { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public class ElectricityTariffPayment { public string MeterNumber { get; set; } public string TariffId { get; set; } public string PricePerUnit { get; set; } public string AmountPaid { get; set; } public string NumberOfUnit { get; set; } public DateTime DateOfPayment { get; set; } = DateTime.Now; } } <file_sep>using ElectricityDigitalSystem.AgentServices; using ElectricityDigitalSystem.AgentServices.IServices; using ElectricityDigitalSystem.Common; using ElectricityDigitalSystem.Common.ISubscriptionsServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSAgentPortal.AgentMenu.AgentLogInMenu.CustomerPortfolio { public class AgentCustomerSubscriptions { readonly ISubscriptionServices subscriptionServices = new SubscriptionServices(); readonly ITariffServices tariffServices = new TariffServices(); readonly IAgentCustomerServices agentCustomerServices = new AgentCustomerServices(); readonly CustomerPortMenuNav customerPortMenuNav = new CustomerPortMenuNav(); decimal t1, t2, t3, t4 = default; string a1, a2, a3, a4 = default; public void CancelCustomerSubscription() { Console.Clear(); Console.WriteLine("Would you like to cancel your active subscription?\n1 : Yes\n2 : No"); var entry = Console.ReadLine(); switch (entry) { case "1": CancelSub(); break; case "2": Console.WriteLine("Processing..."); Thread.Sleep(3000); break; default: CancelCustomerSubscription(); break; } } public void CancelSub() { Console.Clear(); var userEmailCheck = EmailCheck(); if (userEmailCheck == "Failed") { Console.WriteLine("No Valid Email Found"); Thread.Sleep(3000); } else { var customerToBeSubscribeID = agentCustomerServices.GetCustomerByEmail(userEmailCheck).Id; var activeSub = subscriptionServices.CheckActiveSubscription(customerToBeSubscribeID); if (activeSub.Count == 0) { Console.WriteLine("\nYou do not have an Active subscription"); Thread.Sleep(3000); } else { foreach (var item in activeSub) { item.SubscriptionStatus = "Inactive"; subscriptionServices.UpdateSubscription(item); Console.WriteLine("\nSubscription cancelled successfully"); } Thread.Sleep(3000); } } } public void MakeSubscription(string registeringAgent) { Console.Clear(); var userEmailCheck = EmailCheck(); if (userEmailCheck == "Failed") { Console.WriteLine("No Valid Email Found"); Thread.Sleep(3000); } else { var customerToBeSubscribeID = agentCustomerServices.GetCustomerByEmail(userEmailCheck).Id; var activeSub = subscriptionServices.CheckActiveSubscription(customerToBeSubscribeID); if (activeSub.Count != 0) { //Show all Tariff Console.WriteLine("You currently have an active subscription \nBuying a new Subscription will deactivate your previous subscription"); Console.WriteLine("1 : Continue \n2 : Back to Home "); string entry = Console.ReadLine(); switch (entry) { case "1": MakeSubscriptionPayment(registeringAgent, customerToBeSubscribeID); break; case "2": customerPortMenuNav.CustomerPortPageMenuNav(registeringAgent); break; default: MakeSubscription(registeringAgent); break; } } else { MakeSubscriptionPayment(registeringAgent, customerToBeSubscribeID); } } } private void MakeSubscriptionPayment(string registeringAgent, string customerToBeSubscribeID) { Console.Clear(); var tariffs = tariffServices.GetAllTariff(); Console.WriteLine("We have four Tariffs"); Console.WriteLine("\nTariff Name Tariff Price"); for (var i = 0; i < tariffs.Count; i++) { Console.Write($"{i + 1} : {tariffs[i].Name} #{tariffs[i].PricePerUnit} \n"); if (i == 0) { t1 = tariffs[i].PricePerUnit; a1 = tariffs[i].Id; } else if (i == 1) { t2 = tariffs[i].PricePerUnit; a2 = tariffs[i].Id; } else if (i == 2) { t3 = tariffs[i].PricePerUnit; a3 = tariffs[i].Id; } else if (i == 3) { t4 = tariffs[i].PricePerUnit; ; a4 = tariffs[i].Id; } } Console.WriteLine(); string userInput = Console.ReadLine(); Console.Clear(); int amountToBuy; switch (userInput) { case "1": Console.WriteLine("How many units would you like to purchase?"); string firstInput = Console.ReadLine(); while (!int.TryParse(firstInput, out amountToBuy)) { Console.WriteLine("Invalid Input\nHow many units would you like to purchase?"); firstInput = Console.ReadLine(); } CalculateTotalUnit(amountToBuy, t1, a1, registeringAgent, customerToBeSubscribeID); break; case "2": Console.WriteLine("How many units would you like to purchase?"); string secondInput = Console.ReadLine(); while (!int.TryParse(secondInput, out amountToBuy)) { Console.WriteLine("Invalid Input\nHow many units would you like to purchase?"); secondInput = Console.ReadLine(); } CalculateTotalUnit(amountToBuy, t2, a2, registeringAgent, customerToBeSubscribeID); break; case "3": Console.WriteLine("How many units would you like to purchase?"); string thirdInput = Console.ReadLine(); while (!int.TryParse(thirdInput, out amountToBuy)) { Console.WriteLine("Invalid Input\nHow many units would you like to purchase?"); thirdInput = Console.ReadLine(); } CalculateTotalUnit(amountToBuy, t3, a3, registeringAgent, customerToBeSubscribeID); break; case "4": Console.WriteLine("How many units would you like to purchase?"); string fourthInput = Console.ReadLine(); while (!int.TryParse(fourthInput, out amountToBuy)) { Console.WriteLine("Invalid Input\nHow many units would you like to purchase?"); fourthInput = Console.ReadLine(); } CalculateTotalUnit(amountToBuy, t4, a4, registeringAgent, customerToBeSubscribeID); break; default: MakeSubscriptionPayment(registeringAgent, customerToBeSubscribeID); break; } } private void CalculateTotalUnit(int unitToBePurchased, decimal pricePerUnit, string tariffId, string registeringAgent, string customerToBeSubscribeID) { decimal totalAmountPurchased = Convert.ToDecimal(unitToBePurchased) * pricePerUnit; Console.WriteLine($"You are about to pay #{totalAmountPurchased} \nDo you want to proceed? \n1 : Yes\n2 : No "); string entry = Console.ReadLine(); switch (entry) { case "1": Console.WriteLine($"You have Successfully purchased {unitToBePurchased} Units"); var sub = subscriptionServices.CheckActiveSubscription(customerToBeSubscribeID); foreach (var item in sub) { item.SubscriptionStatus = "Inactive"; subscriptionServices.UpdateSubscription(item); } Subscriptions subscriptions = new Subscriptions { Id = Guid.NewGuid().ToString(), SubscriptionStatus = "Active", CustomerId = customerToBeSubscribeID, TariffId = tariffId, AgentId = registeringAgent, SubcriptionDateTime = DateTime.Now, Amount = totalAmountPurchased, }; subscriptionServices.MakeSubscription(subscriptions); Console.WriteLine("Successfull!!!"); Thread.Sleep(3000); break; case "2": Console.WriteLine("Cancelled!!!\nRedirecting...."); Thread.Sleep(3000); break; } } public void ViewSubscriptionsHistory() { Console.Clear(); var userEmailCheck = EmailCheck(); if (userEmailCheck == "Failed") { Console.WriteLine("No Valid Email Found"); Thread.Sleep(3000); } else { var customerToBeSubscribeID = agentCustomerServices.GetCustomerByEmail(userEmailCheck).Id; var subscriptions = subscriptionServices.GetCustomerSubscription(customerToBeSubscribeID); string tariffName; if (subscriptions.Count == 0) { Console.WriteLine("You have not made any Subscription"); Thread.Sleep(3000); } else { Console.WriteLine("Subscription History\n"); Console.WriteLine($"{"Tariff Name", -20}\tAmount\t\t\tSubscription Date\t\tSubscription Status\n\n"); foreach (var subscription in subscriptions) { tariffName = subscription.TariffId; var customerTariff = tariffServices.GetTarriffById(tariffName); Console.Write($"{customerTariff.Name, -20}\t#{subscription.Amount}\t\t{subscription.SubcriptionDateTime}\t\t{subscription.SubscriptionStatus}\n"); } Console.ReadKey(); } } } private string EmailCheck() { Console.Clear(); Console.WriteLine("Please Can I have the Email you used in Registering :"); Console.Write("The Email Address : "); string email = Console.ReadLine(); while (string.IsNullOrEmpty(email)) { Console.Write("Please Enter an Email Address : "); email = Console.ReadLine(); } var customer = agentCustomerServices.GetCustomerByEmail(email); if (customer == null) { return "Failed"; } else { return customer.EmailAddress; } } } } <file_sep>using ElectricityDigitalSystem.AgentServices.IServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ElectricityDigitalSystem.AgentServices { public class AgentCustomerServices : AgentServicesAPI, IAgentCustomerServices { public string RegisterCustomer(CustomerModel customer) { if (customer == null) { throw new ArgumentNullException(nameof(customer)); } //This will Handle registration of a customer else { fileService.Database.Customers.Add(customer); fileService.SaveChanges(); return customer.Id == null ? "Failed" : "Success"; } } public CustomerModel GetCustomerById(string customerId) { CustomerModel foundcustomer = fileService.Database.Customers.Find(c => c.Id == customerId); if (foundcustomer != null) { return foundcustomer; } return null; } public List<CustomerModel> GetAllRegisteredCustomer() { var allCustomers = fileService.Database.Customers.ToList(); return allCustomers; } //Find Customer via Email public CustomerModel GetCustomerByEmail(string email) { CustomerModel foundcustomer = fileService.Database.Customers.Find(c => c.EmailAddress == email); if (foundcustomer != null) { return foundcustomer; } return null; } public string UpdateCustomer(CustomerModel modifiedcustomer) { CustomerModel foundCustomer = this.GetCustomerById(modifiedcustomer.Id); if (foundCustomer != null) { //fileService.Database.Customers.IndexOf(foundCustomer); //fileService.Database.Customers.Insert(indexOfFoundCustomer, foundCustomer); fileService.SaveChanges(); return "SUCCESS"; } return "FAILURE NOT FOUND"; } } } <file_sep>using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Data { public class DbContext { public List<AgentsModel> Agents { get; set; } = new List<AgentsModel>(); public List<CustomerModel> Customers { get; set; } = new List<CustomerModel>(); public List<TarriffModel> Tariffs { get; set; } = new List<TarriffModel>(); public List<Subscriptions> Subcriptions { get; set; } = new List<Subscriptions>(); public List<ElectricityTariffPayment> TariffPayments { get; set; } = new List<ElectricityTariffPayment>(); } } <file_sep>using ElectricityDigitalSystem.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ElectricityDigitalSystem.ClientServices { public class CustomerService : ClientServicesAPI { public string RegisterCustomer(CustomerModel customer) { if(customer == null) { throw new ArgumentNullException(nameof(customer)); } //This will Handle registration of a customer else { //customer.Id = "CUS-" + Guid.NewGuid().ToString(); //customer.MeterNumber = "EDS-" + Guid.NewGuid().ToString(); fileService.Database.Customers.Add(customer); fileService.SaveChanges(); return customer.Id; } } public CustomerModel GetCustomerById(string customerId) { CustomerModel foundcustomer = fileService.Database.Customers.Find(c => c.Id == customerId); if (foundcustomer != null) { return foundcustomer; } return null; } //Find Customer via Email public CustomerModel GetCustomerByEmail(string email) { CustomerModel foundcustomer = fileService.Database.Customers.Find(c => c.EmailAddress == email); if (foundcustomer != null) { return foundcustomer; } return null; } public string UpdateCustomer(CustomerModel modifiedcustomer) { CustomerModel foundCustomer = this.GetCustomerById(modifiedcustomer.Id); if (foundCustomer != null) { //fileService.Database.Customers.IndexOf(foundCustomer); //fileService.Database.Customers.Insert(indexOfFoundCustomer, foundCustomer); fileService.SaveChanges(); return "SUCCESS"; } return "FAILURE NOT FOUND"; } public string RegisterCustomerSubcription(ElectricityTariffPayment electricityTariffPayment) { if (electricityTariffPayment == null) { throw new ArgumentNullException(nameof(electricityTariffPayment)); } //This ill Handle registration of a customer else { fileService.Database.TariffPayments.Add(electricityTariffPayment); fileService.SaveChanges(); return electricityTariffPayment.MeterNumber; } } public ElectricityTariffPayment ViewCustomerSubcriptionStatus(string meterNumber) { ElectricityTariffPayment customerMeterNumber = fileService.Database.TariffPayments.Find(c => c.MeterNumber == meterNumber); if (customerMeterNumber != null) { return customerMeterNumber; } return null; } public bool DeleteSubcription(ElectricityTariffPayment electricityTariffPayment) { fileService.Database.TariffPayments.Remove(electricityTariffPayment); fileService.SaveChanges(); return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace EDSAgentPortal.AgentMenu { public class AgentMenuNav { readonly bool appIsRunning = true; public void PageMenuNav() { AgentMenu agentMenu = new AgentMenu(); while (appIsRunning == true) { Console.Clear(); Console.WriteLine("Welcome To EDS AGENT PORTAL."); Console.WriteLine("Choose an Option : \n1. Register \n2. Login \n3. Close the App"); string choice = Console.ReadLine(); switch (choice) { case "1": agentMenu.RegisterAgent(); break; case "2": agentMenu.LoginAgent(); break; case "3": Environment.Exit(0); break; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public class BaseUserModel { public string Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime CreatedDateTime { get; set; } = DateTime.Now; public DateTime ModifiedDateTime { get; set; } = DateTime.Now; public string EmailAddress { get; set; } public string PhoneNumber { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public enum MeterType { SINGLEPHASE = 1, THREEPHASE = 3 } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public class AgentsModel : BaseUserModel { public AgentsModel() => Id = "AGT-" + Guid.NewGuid().ToString(); public string Password { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace EDSAgentPortal.AgentMenu.AgentLogInMenu.AgentPortfolio { public class AgentPortMenuNav { readonly AgentPortMenu agentPortMenu = new AgentPortMenu(); public void AgentPortPageMenuNav(string id, string firstName, string lastName) { bool inLoginPage = true; while (inLoginPage) { Console.Clear(); Console.WriteLine($"Welcome Agent {firstName} {lastName}"); Console.WriteLine("Choose an Option : \n1. View Data \n2. Update Information \n3. Back To LogIn Menu"); string choice = Console.ReadLine(); switch (choice) { case "1": agentPortMenu.ViewAgentData(id); break; case "2": agentPortMenu.UpdatePersonalInfo(id); break; case "3": inLoginPage = false; break; } } } } } <file_sep>using ElectricityDigitalSystem.AgentServices; using ElectricityDigitalSystem.AgentServices.IServices; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSAgentPortal.AgentMenu.AgentLogInMenu.AgentPortfolio { public class AgentPortMenu { readonly IAgentServices agentServices = new AgentServices(); readonly AgentMenuNav agentMenuNav = new AgentMenuNav(); public void ViewAgentData(string id) { Console.WriteLine(); Console.WriteLine($"{"Full Name",-20} : {agentServices.GetAgentById(id).FirstName} {agentServices.GetAgentById(id).LastName}"); Console.WriteLine($"{"Email Address",-20} : {agentServices.GetAgentById(id).EmailAddress} "); Console.WriteLine($"{"Phone Number",-20} : {agentServices.GetAgentById(id).PhoneNumber} "); Console.WriteLine($"{"Created Date Time",-20} : {agentServices.GetAgentById(id).CreatedDateTime} "); Console.WriteLine($"{"Modified Date Time",-20} : {agentServices.GetAgentById(id).ModifiedDateTime} "); Console.ReadKey(); } public void UpdatePersonalInfo(string id) { var customerDetail = agentServices.GetAgentById(id); bool inputAnother; do { Console.WriteLine($"What would you like to Update?\n 1. First Name 2. Last Name 3. Email Address 4. Phone Number 5. Password"); string response = Console.ReadLine(); switch (response) { case "1": Console.WriteLine("Please enter your new First Name :"); customerDetail.FirstName = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "2": Console.WriteLine("Please enter your new Last Name :"); customerDetail.LastName = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "3": Console.WriteLine("Please enter your new Email Address :"); customerDetail.EmailAddress = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "4": Console.WriteLine("Please enter your new Phone Number :"); customerDetail.PhoneNumber = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "5": Console.WriteLine("Please enter your new Password :"); customerDetail.Password = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; } Console.WriteLine("Would you like to update another information? (Y/N)"); var continueEditing = Console.ReadLine(); if (continueEditing.ToLower() == "y") { inputAnother = true; } else { inputAnother = false; } } while (inputAnother); agentServices.UpdateAgent(customerDetail); Console.WriteLine("Successful!!!\nLogging Out...."); Thread.Sleep(2000); agentMenuNav.PageMenuNav(); } } } <file_sep>using ElectricityDigitalSystem.AgentServices; using ElectricityDigitalSystem.Common.ISubscriptionsServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ElectricityDigitalSystem.Common { public class SubscriptionServices : AgentServicesAPI, ISubscriptionServices { public void MakeSubscription(Subscriptions subscription) { fileService.Database.Subcriptions.Add(subscription); fileService.SaveChanges(); } public List<Subscriptions> GetAllSubscription() { var customerSubscription = fileService.Database.Subcriptions.ToList(); return customerSubscription; } public List<Subscriptions> GetCustomerSubscription(string customerId) { var customerSubscription = fileService.Database.Subcriptions.Where(c => c.CustomerId == customerId).ToList(); return customerSubscription; } public Subscriptions FindSubscription(string customerId) { var subscription = fileService.Database.Subcriptions.Find(s => s.CustomerId == customerId); return subscription; } public void CancelSubcription(string id) { var subToCancel = FindSubscription(id); subToCancel.SubscriptionStatus = "InActive"; } public List<Subscriptions> CheckActiveSubscription(string customerId) { var activeSubscription = fileService.Database.Subcriptions.Where(x => x.CustomerId == customerId).ToList(); var Sub = activeSubscription.Where(x => x.SubscriptionStatus == "Active").ToList(); return Sub; } public string UpdateSubscription(Subscriptions modifiedSubscription) { if (modifiedSubscription != null) { // int indexOfCustomer = fileService.Database.Subcriptions.IndexOf(modifiedSubscription); //fileService.database.Customers.Insert(indexOfCustomer, modifiedCustomer); fileService.SaveChanges(); return "SUCCESSFULLY UPDATED"; } return "Failed, Customer not found"; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ElectricityDigitalSystem.Constant { public class FileConstant { public readonly static string DBFOLDER = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.Desktop), "SBSC EDS"); } } <file_sep>using ElectricityDigitalSystem.Data; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.ClientServices { public class ClientServicesAPI { protected JsonFileService fileService = new JsonFileService(); } } <file_sep>using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.AgentServices.IServices { public interface IAgentServices { string RegisterAgent(AgentsModel agent); AgentsModel GetAgentById(string agentId); AgentsModel GetAgentByEmail(string email); string UpdateAgent(AgentsModel modifiedAgent); } } <file_sep>using ElectricityDigitalSystem.AgentServices; using ElectricityDigitalSystem.Common.ISubscriptionsServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ElectricityDigitalSystem.Common { public class TariffServices : AgentServicesAPI, ITariffServices { public void AddTariffToService() { //List<TarriffModel> mockData = new List<TarriffModel>(); TarriffModel tariff1 = new TarriffModel { Id = Guid.NewGuid().ToString(), Name = "Better Home Plan", PricePerUnit = 150.40M, }; TarriffModel tariff2 = new TarriffModel { Id = Guid.NewGuid().ToString(), Name = "Best Home Plan", PricePerUnit = 250.84M, }; TarriffModel tariff3 = new TarriffModel { Id = Guid.NewGuid().ToString(), Name = "Basic Home Plan", PricePerUnit = 120.90M, }; TarriffModel tariff4 = new TarriffModel { Id = Guid.NewGuid().ToString(), Name = "Premium Home Plan", PricePerUnit = 300.60M, }; PushToDb(tariff1); PushToDb(tariff2); PushToDb(tariff3); PushToDb(tariff4); } public void PushToDb(TarriffModel model) { if (fileService.Database.Tariffs.Count <= 3) { fileService.Database.Tariffs.Add(model); fileService.SaveChanges(); } } public List<TarriffModel> GetAllTariff() { var Tariffs = fileService.Database.Tariffs.ToList(); return Tariffs; } public TarriffModel GetTarriffByName(string name) { var tariff = fileService.Database.Tariffs.Find(t => t.Name == name); return tariff; } public TarriffModel GetTarriffById(string id) { var tariff = fileService.Database.Tariffs.Find(t => t.Id == id); return tariff; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace EDSCustomerPortal.Menu { public class LoginMenuNav { readonly LoginMenu loginMenu = new LoginMenu(); public void PageMenu(string id, string firstName, string lastName, string meterNumber) { bool inLoginPage = true; while (inLoginPage) { Console.Clear(); Console.WriteLine($"welcome {firstName} {lastName}"); Console.WriteLine("Welcome To CUSTOMER PORTAL.\n"); Console.WriteLine("Choose an Option : 1. View Data 2. Update Information 3. Make Subscription\n4. Cancel Subscription 5. View Subscription 6. Log Out"); string choice = Console.ReadLine(); switch (choice) { case "1": loginMenu.ViewCustomerData(id); break; case "2": LoginMenu.UpdatePersonalInfo(id); break; case "3": loginMenu.MakeSubscription(meterNumber); break; case "4": loginMenu.CancelSubscription(meterNumber); break; case "5": loginMenu.ViewSubscription(meterNumber); break; case "6": inLoginPage = false; break; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace EDSAgentPortal.AgentMenu.AgentLogInMenu.CustomerPortfolio { public class CustomerPortMenuNav { public void CustomerPortPageMenuNav(string registeringAgent) { CustomerPortMenu customerPortMenu = new CustomerPortMenu(); AgentCustomerSubscriptions agentCustomerSubscriptions = new AgentCustomerSubscriptions(); bool inLoginPage = true; while (inLoginPage) { Console.Clear(); Console.WriteLine("Welcome To AGENT CUSTOMER'S PAGE."); Console.WriteLine("Choose an Option : \n1. Register A Customer \n2. View Customer Details \n3. View All Registered Customer \n4. Update Customers Information \n5. Make Subscription \n6. Cancel Subscription \n7. View Subscription \n8. Go Back To LogIn Page"); string choice = Console.ReadLine(); switch (choice) { case "1": customerPortMenu.RegisterCustomer(registeringAgent); break; case "2": customerPortMenu.ViewCustomerInfo(); break; case "3": customerPortMenu.ViewAllRegisteredCustomer(); break; case "4": customerPortMenu.UpdatePersonalInfo(); break; case "5": agentCustomerSubscriptions.MakeSubscription(registeringAgent); break; case "6": agentCustomerSubscriptions.CancelCustomerSubscription(); break; case "7": agentCustomerSubscriptions.ViewSubscriptionsHistory(); break; case "8": inLoginPage = false; break; } } } } } <file_sep>using EDSCustomerPortal.Services; using EDSCustomerPortal.Services.IServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSCustomerPortal.Menu { public class Menu { readonly MenuNav menuNav = new MenuNav(); readonly IAuthenticationService authenticationService = new AuthenticationService(); readonly LoginMenuNav loginMenuNav = new LoginMenuNav(); public void LoginNavigationPage() { Dictionary<string, string> navItemDic = new Dictionary<string, string>(); List<string> navigationItem = new List<string> { "Email", "Password" }; Console.Clear(); Console.WriteLine("Please Login with your Email and Password"); for (var i = 0; i < navigationItem.Count; i++) { Console.Write($"Please Enter your {navigationItem[i]} : "); var value = Console.ReadLine(); navItemDic.Add(navigationItem[i], value); } string Email, Password; Email = navItemDic["Email"]; Password = navItemDic["Password"]; var customer = authenticationService.GetCustomerByEmail(Email); if (customer == null) { Console.WriteLine("No Email Found"); Thread.Sleep(3000); menuNav.PageMenu(); } else { if (customer.Password != Password) { Console.WriteLine("Invalid Login Credentials Please Try Again"); Thread.Sleep(3000); menuNav.PageMenu(); } else { loginMenuNav.PageMenu(customer.Id, customer.FirstName, customer.LastName, customer.MeterNumber); } } } public void RegistrationNavigationPage() { Dictionary<string, string> navItemDIc = new Dictionary<string, string>(); List<string> navigationItems = new List<string> { "FirstName", "LastName", "Email", "Password", "PhoneNumber" }; Console.Clear(); Console.WriteLine("Please Provide your Details"); for (int i = 0; i < navigationItems.Count; i++) { Console.Write($"Enter your {navigationItems[i]} : "); var value = Console.ReadLine(); navItemDIc.Add(navigationItems[i], value); } string FirstName, LastName, Email, Password, PhoneNumber; FirstName = navItemDIc["FirstName"]; LastName = navItemDIc["LastName"]; Email = navItemDIc["Email"]; Password = navItemDIc["Password"]; // MeterNumber = navItemDIc["MeterNumber"]; PhoneNumber = navItemDIc["PhoneNumber"]; CustomerModel model = new CustomerModel { FirstName = FirstName, LastName = LastName, EmailAddress = Email, Password = <PASSWORD>, // MeterNumber = MeterNumber, PhoneNumber = PhoneNumber, }; string registrationResponds = authenticationService.RegisterUser(model); if (registrationResponds == "Success") { Console.WriteLine("Registration Successful"); Console.WriteLine("Redirecting you to Home Page...."); Thread.Sleep(3000); } else Console.WriteLine("An Error occured While Trying to Create your Account Please try Again"); menuNav.PageMenu(); } } } <file_sep>using EDSCustomerPortal.Services; using EDSCustomerPortal.Services.IServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSCustomerPortal.Menu { public class SubscriptionMenu { readonly IAuthenticationService authenticationService = new AuthenticationService(); public void AddSubscription(string meterId, string tariffId, string pricePerUnit, string billCharged, string numberOfUnit) { Dictionary<string, string> navItemDIc = new Dictionary<string, string>(); List<string> navigationItems = new List<string> { "MeterNumber","TariffId", "PricePerUnit", "AmountPaid", "NumberOfUnit" }; Console.Clear(); navItemDIc.Add(navigationItems[0], meterId); navItemDIc.Add(navigationItems[1], tariffId); navItemDIc.Add(navigationItems[2], pricePerUnit); navItemDIc.Add(navigationItems[3], billCharged); navItemDIc.Add(navigationItems[4], numberOfUnit); string MeterNumber, TariffId, PricePerUnit, NumberOfUnit, AmountPaid; MeterNumber = navItemDIc["MeterNumber"]; TariffId = navItemDIc["TariffId"]; PricePerUnit = navItemDIc["PricePerUnit"]; AmountPaid = navItemDIc["AmountPaid"]; NumberOfUnit = navItemDIc["NumberOfUnit"]; ElectricityTariffPayment electricityTariffPayment = new ElectricityTariffPayment() { MeterNumber = MeterNumber, TariffId = TariffId, PricePerUnit = PricePerUnit, AmountPaid = AmountPaid, NumberOfUnit = NumberOfUnit, }; authenticationService.RegisterSubscription(electricityTariffPayment); //var checkMeterNumberExist = AuthenticationService.ViewCustomerSubscriptionByMeterNumber(MeterNumber); //if (checkMeterNumberExist == null) //{ // AuthenticationService.RegisterSubscription(electricityTariffPayment); //} //else //{ // if (checkMeterNumberExist.MeterNumber == MeterNumber) // { // Console.WriteLine($" Bill Cancelled!!!\nYou're on Subscription... Redirecting..."); // Thread.Sleep(3000); // } // else // { // Console.WriteLine($" Validated!!!\n Payment Successfull!!!"); // AuthenticationService.RegisterSubscription(electricityTariffPayment); // } //} } public void CalculateElectricityBill(string metreId) { double selectedTariffPlan; string tariffId = null; string numberOfUnit; string priceperUnit = null; double billCharged = 0.0d; Console.WriteLine("Enter 1. Single Phase 2. Three Phase"); selectedTariffPlan = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please enter the number of units you want"); numberOfUnit = Console.ReadLine(); switch (selectedTariffPlan) { case 1: Console.WriteLine("You will be charged 25 Naira per Unit."); tariffId = "SP"; priceperUnit = "25"; billCharged = Convert.ToInt32(numberOfUnit) * Convert.ToInt32(priceperUnit); Console.WriteLine($"Your Bill is : {billCharged}\n Click Enter to Validate and Make Payment "); Console.ReadKey(); break; case 2: Console.WriteLine("You will be charged 30 Naira per Unit."); tariffId = "TP"; priceperUnit = "30"; billCharged = Convert.ToInt32(numberOfUnit) * Convert.ToInt32(priceperUnit); Console.WriteLine($"Your Bill is : {billCharged}\n Click Enter to Validate and Make Payment "); Console.ReadKey(); break; } AddSubscription( metreId, tariffId, priceperUnit, billCharged.ToString(), numberOfUnit); } } } <file_sep>using ElectricityDigitalSystem.Data; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.AgentServices { public class AgentServicesAPI { protected JsonFileService fileService = new JsonFileService(); } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace EDSCustomerPortal.Validate { public class Validation { } } <file_sep>using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.AgentServices.IServices { public interface IAgentCustomerServices { string RegisterCustomer(CustomerModel customer); List<CustomerModel> GetAllRegisteredCustomer(); CustomerModel GetCustomerById(string customerId); CustomerModel GetCustomerByEmail(string email); string UpdateCustomer(CustomerModel modifiedcustomer); } } <file_sep>using EDSAgentPortal.AgentMenu.AgentLogInMenu.AgentPortfolio; using EDSAgentPortal.AgentMenu.AgentLogInMenu.CustomerPortfolio; using System; using System.Collections.Generic; using System.Text; namespace EDSAgentPortal.AgentMenu.AgentLogInMenu { public class LogInMenuNav { public void LogInPageMenuNav(string id, string firstName, string lastName) { AgentPortMenuNav agentPortMenuNav = new AgentPortMenuNav(); CustomerPortMenuNav customerPortMenuNav = new CustomerPortMenuNav(); bool inLoginPage = true; while (inLoginPage) { Console.Clear(); Console.WriteLine($"{firstName} {lastName}"); Console.WriteLine("Welcome To AGENT PORTAL.\n"); Console.WriteLine("Choose an Option : \n1. AGENT Dashboard \n2. CUSTOMER Dashboard \n3. Log Out"); string choice = Console.ReadLine(); switch (choice) { case "1": agentPortMenuNav.AgentPortPageMenuNav(id, firstName, lastName); break; case "2": customerPortMenuNav.CustomerPortPageMenuNav(id); break; case "3": inLoginPage = false; break; } } } } } <file_sep>using ElectricityDigitalSystem.Constant; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.Json; namespace ElectricityDigitalSystem.Data { public class JsonFileService { private readonly string jsonFileName = "edsDb.json"; public DbContext Database { get; set; } public JsonFileService() { this.OnInit(); } private void OnInit() { if(!Directory.Exists(FileConstant.DBFOLDER)) { Directory.CreateDirectory(FileConstant.DBFOLDER); } if (!File.Exists(Path.Combine(FileConstant.DBFOLDER, jsonFileName))) { File.Create(Path.Combine(FileConstant.DBFOLDER, jsonFileName)).Close(); this.Database = new DbContext(); } else { //if file exist then read the file from the directory using StreamReader reader = new StreamReader(Path.Combine(FileConstant.DBFOLDER, jsonFileName)); { try { //Read all filecontent from the json file string jsonFileContent = reader.ReadToEnd(); this.Database = JsonSerializer.Deserialize<DbContext>(jsonFileContent); } catch(Exception) { //If the databse is empty instead of throwing an error just create an instance of the database Database = new DbContext(); } } } } public void SaveChanges() { //This will covert the database object in a json and write to a file string newJson = JsonSerializer.Serialize(Database); File.WriteAllText(Path.Combine(FileConstant.DBFOLDER, jsonFileName), newJson); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace EDSCustomerPortal.AppData { public class CustomerApplicationData { public DateTime LastLoginDate { get; set; } public string CurrentCustomerId { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ElectricityDigitalSystem.Models { public class MeterModel { public string Id { get; set; } public string MeterNumber { get; set; } public MeterType Type { get; set; } public string ProductName { get; set; } } } <file_sep>using EDSCustomerPortal.Services; using EDSCustomerPortal.Services.IServices; using ElectricityDigitalSystem.ClientServices; using ElectricityDigitalSystem.Models; using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSCustomerPortal.Menu { public class LoginMenu { readonly SubscriptionMenu subscriptionMenuNav = new SubscriptionMenu(); readonly IAuthenticationService authenticationService = new AuthenticationService(); public void ViewCustomerData(string id) { Console.WriteLine(); Console.WriteLine($"{"Full Name",-20} : {authenticationService.GetCustomerById(id).FirstName} {authenticationService.GetCustomerById(id).LastName}"); Console.WriteLine($"{"Email Address",-20} : {authenticationService.GetCustomerById(id).EmailAddress} "); Console.WriteLine($"{"Phone Number",-20} : {authenticationService.GetCustomerById(id).PhoneNumber} "); Console.WriteLine($"{"Meter Number",-20} : {authenticationService.GetCustomerById(id).MeterNumber} "); Console.WriteLine($"{"Created Date Time", -20} : {authenticationService.GetCustomerById(id).CreatedDateTime} "); Console.WriteLine($"{"Modified Date Time",-20} : {authenticationService.GetCustomerById(id).ModifiedDateTime} "); Console.ReadKey(); } public static void UpdatePersonalInfo(string id) { CustomerService service = new CustomerService(); var customerDetail = service.GetCustomerById(id); //var customerDetail = AuthenticationService.GetCustomerById(id); bool inputAnother; do { Console.WriteLine($"What would you like to Update?\n 1. First Name 2. Last Name 3. Email Address 4. Phone Number 5. Password"); string response = Console.ReadLine(); switch (response) { case "1": Console.WriteLine("Please enter your new First Name :"); customerDetail.FirstName = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "2": Console.WriteLine("Please enter your new Last Name :"); customerDetail.LastName = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "3": Console.WriteLine("Please enter your new Email Address :"); customerDetail.EmailAddress = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "4": Console.WriteLine("Please enter your new Phone Number :"); customerDetail.PhoneNumber = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; case "5": Console.WriteLine("Please enter your new Password :"); customerDetail.Password = Console.ReadLine(); customerDetail.ModifiedDateTime = DateTime.Now; break; } Console.WriteLine("Would you like to update another information? (Y/N)"); var continueEditing = Console.ReadLine(); if (continueEditing.ToLower() == "y") { inputAnother = true; } else { inputAnother = false; } } while (inputAnother); //AuthenticationService.UpdateCustomerData(customerDetail); service.UpdateCustomer(customerDetail); Console.WriteLine("Successful!!!\nLog Out to Effect the Changes...."); Thread.Sleep(3000); } public void ViewSubscription(string meterNumber) { try { Console.WriteLine(); Console.WriteLine($"Details for Meter Number : {meterNumber}"); Console.WriteLine($"{"Tarrif Subscribed To",-25} : {authenticationService.ViewCustomerSubscriptionByMeterNumber(meterNumber).TariffId}"); Console.WriteLine($"{"Price per Unit",-25} : #{authenticationService.ViewCustomerSubscriptionByMeterNumber(meterNumber).PricePerUnit}"); Console.WriteLine($"{"Number of Unit",-25} : {authenticationService.ViewCustomerSubscriptionByMeterNumber(meterNumber).NumberOfUnit}"); Console.WriteLine($"{"Amount Paid",-25} : {authenticationService.ViewCustomerSubscriptionByMeterNumber(meterNumber).AmountPaid}"); Console.WriteLine($"{"Date of Subscription",-25} : {authenticationService.ViewCustomerSubscriptionByMeterNumber(meterNumber).DateOfPayment}"); Console.WriteLine(); Console.ReadKey(); } catch (Exception) { Console.WriteLine("Not Subcribed!!!!\nRedericting...."); Thread.Sleep(3000); } } public void MakeSubscription(string meterId) { try { subscriptionMenuNav.CalculateElectricityBill(meterId); Console.WriteLine($" Validated!!!\n Payment Successfull!!!"); Thread.Sleep(3000); } catch (Exception) { Console.WriteLine("Error!!! Subcription Not Successful.\nRedericting...."); Thread.Sleep(3000); } } public void CancelSubscription(string meterNumber) { try { Console.WriteLine($"Are you sure you want to Cancel Subscription? \nEnter 1. To Continue 2. To Go Back"); string getInput = Console.ReadLine(); switch (getInput) { case "1": authenticationService.DeleteSubscription(meterNumber); Console.WriteLine("Subscription Cancelled.\nRedirecting...."); Thread.Sleep(3000); break; case "2": break; } } catch (Exception) { Console.WriteLine("Not Subcribed!!!!\nRedericting...."); Thread.Sleep(3000); } } } } <file_sep>using EDSCustomerPortal.Services; using ElectricityDigitalSystem.ClientServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace EDSCustomerPortal.Menu { public class MenuNav { bool appIsRunning = true; public void PageMenu() { Menu menu = new Menu(); while (appIsRunning == true) { Console.Clear(); Console.WriteLine("Welcome To EDS CUSTOMER PORTAL."); Console.WriteLine("Choose an Option : \n1. Login \n2. Register \n3. Close the App"); string choice = Console.ReadLine(); switch (choice) { case "1": menu.LoginNavigationPage(); break; case "2": menu.RegistrationNavigationPage(); break; case "3": appIsRunning = false; break; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace EDSAgentPortal.Validation { public class ValidationClass { public ulong CheckPhoneNumber(string password) { ulong number; while (!ulong.TryParse(password, out number)) { Console.WriteLine("Please enter an 11 digit number"); Console.Write("Phone Number : "); password = Console.ReadLine(); } return number; } } } <file_sep>using EDSCustomerPortal.Services.IServices; using ElectricityDigitalSystem.ClientServices; using ElectricityDigitalSystem.Models; using System; using System.Collections.Generic; using System.Text; namespace EDSCustomerPortal.Services { public class AuthenticationService : IAuthenticationService { public string RegisterUser(CustomerModel model) { if(model == null) { throw new ArgumentNullException(nameof(model)); } else { CustomerService service = new CustomerService(); string id = service.RegisterCustomer(model); return id == null ? "Failed" : "Success"; } } public CustomerModel GetCustomerByEmail(string email) { CustomerService service = new CustomerService(); var customerfound = service.GetCustomerByEmail(email); return customerfound; } public CustomerModel GetCustomerById(string customerId) { CustomerService service = new CustomerService(); var customerfound = service.GetCustomerById(customerId); return customerfound; } //Having Issue when I call the Update method from here //public static UpdateCustomerData(CustomerModel model) //{ // CustomerService service = new CustomerService(); // service.UpdateCustomer(model); // return true; //} public string RegisterSubscription(ElectricityTariffPayment electricityTariffPayment) { if (electricityTariffPayment == null ) { throw new ArgumentNullException(nameof(electricityTariffPayment)); } else { CustomerService service = new CustomerService(); string meterNumber = service.RegisterCustomerSubcription(electricityTariffPayment); return meterNumber == null ? "Failed" : "Success"; } } public ElectricityTariffPayment ViewCustomerSubscriptionByMeterNumber(string meterNumber) { CustomerService service = new CustomerService(); var customerMeterNumber = service.ViewCustomerSubcriptionStatus(meterNumber); if (customerMeterNumber == null) { throw new ArgumentNullException(nameof(customerMeterNumber)); } else { return customerMeterNumber; } } public void DeleteSubscription(string metreId) { CustomerService service = new CustomerService(); var customerNumber = service.ViewCustomerSubcriptionStatus(metreId); if (customerNumber == null) { throw new ArgumentNullException(nameof(customerNumber)); } else { service.DeleteSubcription(customerNumber); } } } }
bd2fd52790c74a8d93d9fb6e84bb0be62d83fe9f
[ "Markdown", "C#" ]
44
C#
kenelight4u/Team-Saturn-ElectricityDigitalSystem
351a7d180f8860809b1e842893a2982fcf2c4488
e664b313ed9ee662b1ca2368139761eb944aae2c
refs/heads/master
<repo_name>AnnaSamonii/JavaSeleniumCode<file_sep>/src/test/java/UITestsDay2.java import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class UITestsDay2 { WebDriver driver ; @Test public void test001() { String path = "C:\\Users\\Anushka\\Desktop\\JavaBootCampNov-day1\\src\\test\\Resources\\geckodriver-v0.23.0-win64\\geckodriver.exe"; System.setProperty("webdriver.gecko.driver", path); driver = new FirefoxDriver(); openMainPage(); typeQuery(); submitQuery(); checkResult(); openMainPage(); clickLoginButton(); } private void clickLoginButton() { } private void checkResult() { Boolean isDisplayed = driver.findElement(By.id("resultStats")).isDisplayed(); System.out.println("isDisplayed:" + isDisplayed); } private void submitQuery() { driver.findElement(By.cssSelector(".FPdoLc > center:nth-child(1) > input:nth-child(1)")).click(); } private void typeQuery() { WebElement webElement = driver.findElement(By.cssSelector(".gLFyf")); webElement.sendKeys("Java for Beginners"); } private void openMainPage() { driver.get("http://google.com"); } @Test public void test002() { String path = "C:\\Users\\Anushka\\Desktop\\JavaBootCampNov-day1\\src\\test\\Resources\\chromedriver.exe"; System.setProperty("webdriver.gecko.driver",path); WebDriver driver = new ChromeDriver(); } } <file_sep>/src/test/java/Day2.java import org.testng.annotations.Test; public class Day2 { @Test public void test001() { System.out.println("Welcome to Day 2"); } @Test public void test002() { printString("Test"); } public void printString(String a) { System.out.println(a); } @Test public void test004() { name("Ruchika", "Sinha"); } private void name(String firstName, String lastName) { System.out.println("Name is " + firstName + " " + lastName); } @Test public void test003() { printString(true, "Some Text"); printString(false, "Some Another Text"); } private void printString(Boolean isEnablePrint, String printValue) { if (isEnablePrint) { System.out.println(printValue); } else { System.out.println("False"); } } @Test public void test005() { printNameIfEnabled(true, "Anna", "Gorbenco"); printNameIfEnabled(false, "Anna", "Gorbenco"); } private void printNameIfEnabled(Boolean isEnable, String firstName, String lastName) { if (isEnable) { System.out.println(firstName + " " + lastName); } } @Test public void test006() { checkNumber(9); checkNumber(11); } public void checkNumber(int number) { if (number > 10) { System.out.println("More"); } else { System.out.println(("Less")); } } @Test public void test008() { compareInt(20, 30, 10); compareInt(20, 3, 10); } public void compareInt(int a, int b, int c) { if (a > b) { System.out.println(c); } else { System.out.println("Go to sleep"); } } @Test public void test009() { functionA(true, 10, 5); functionA(false, 10, 20); functionA(true, 10, 20); functionA(false, 20, 10); } private void functionA(boolean isEnable, int a, int b) { if (a > b) { if (isEnable) { System.out.println("Hello World"); } else { System.out.println("buy buy"); } } } @Test public void test010() { int[] array1 = {10, 20, 30, 40}; System.out.println(array1[3]); } @Test public void test011() { int[] array2 = {10, 20, 30, 40, 50, 60, 70}; printIndex(array2, 3); } private void printIndex(int[] arr, int index) { System.out.println(arr[index]); } @Test public void test012() { int[] array2 = {10, 20, 30, 40, 50, 60, 70}; printIndex2(array2, 3); printIndex2(array2, 7); } private void printIndex2(int[] arr, int index) { if (index < arr.length) { System.out.println(arr[index]); } else { System.out.println("Check your Index"); } } @Test public void test013() { int[] array2 = {10, 20, 30, 40, 50, 60, 70}; printIndex3(array2, 3); printIndex3(array2, 7); printIndex3(array2, -7); } private void printIndex3(int[] arr, int index) { if (index < arr.length) { System.out.println(arr[index]); } else { System.out.println("Check your Index"); } } @Test public void test014() { int[] array2 = {10, 20, 30, 40, 50, 60, 70}; printIndex4(array2, 3); printIndex4(array2, 7); printIndex4(array2, -7); } private void printIndex4(int[] arr, int index) { if (index < arr.length && index > +0) { System.out.println(arr[index]); } else { { System.out.println("Check your Index"); } } } @Test public void test015() { int[] array1 = {1, 2, 3, 4, 5, 6}; int[] array2 = {1, 2, 3, 4}; compareSizeOfArrays(array1, array2); } private void compareSizeOfArrays(int array1[], int array2[]) { if (array1.length > array2.length) { System.out.println("array1 has more elements"); } else { System.out.println("array2 has more elements"); } } @Test public void test016() { for (int i = 0; i < 1000; i++) { System.out.println(i); } } @Test public void test017() { int[] array1 = {1, 2, 3, 4, 5, 6, 7}; for (int i = 0; i < array1.length; i++) { System.out.println(array1[i]); } } @Test public void test018() { int[] array1 = {1, 2, 3, 4, 5, 6, 7}; multiplyArrayElements(array1, 5); } private void multiplyArrayElements(int[] array1, int i) { for (int j = 0; j < array1.length; j++) { System.out.println(array1[j] * i); } } @Test public void test019() { int[] array1 = {1, 2, 3, 4, 5}; compareArrayElements(array1, 3); } private void compareArrayElements(int[] array1, int pivot) { for (int i = 0; i < array1.length; i++) { if (array1[i] < pivot) { System.out.println("Element in index" + i + "Is lesser than pivot"); } else { System.out.println("Element in index" + i + "Is lesser than pivot"); } } } @Test public void test020() { int[] arr = {2, 4, 8, 1, 5}; countNumbersLessThanPivot(arr, 3); } private void countNumbersLessThanPivot(int[] array, int pivot) { int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] < pivot) { count++; } } System.out.println(count); } @Test public void test021() { int[] array = {2, 4, 8, 1, 5}; printRev(array); } private void printRev(int[] array) { for (int i = array.length - 1; i >= 0; i--) { System.out.println(array[i]); } } @Test public void test022() throws Exception { int i = 0; for (; i < 5; ) { System.out.println(i); i++; } } @Test public void test023() throws Exception { boolean elementIsNotVisible = true; int i = 0; while (elementIsNotVisible) { System.out.println("Element is not visible"); i++; if (i > 100) { elementIsNotVisible = false; } } } @Test public void test024() throws Exception { int[] integerArray = {2, 0, 1, 3}; for (int eachElement : integerArray) { System.out.println(eachElement); } } @Test public void test025() throws Exception { int i; for (i = 0; i < 5; i++) { if (i >= 7) { break; } System.out.println("Yuhu"); } System.out.println(i); } } <file_sep>/src/test/java/Day3/XPathTests.java package Day3; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class XPathTests { WebDriver driver; String AccountEmail = "<EMAIL>"; String AccountPassword = "<PASSWORD>"; By signinBtn = By.cssSelector(".signin-btn"); @Test public void test001() throws Exception { String path = "C:\\Users\\Anushka\\Desktop\\JavaBootCampNov-day1\\src\\test\\Resources\\geckodriver-v0.23.0-win64\\geckodriver.exe"; System.setProperty("webdriver.gecko.driver", path); driver = new FirefoxDriver(); String url = "https://www.dice.com/dashboard/login"; driver.get(url); //String xPath1 = "/html/body/div/div/form/div/div[1]/div/input"; String xPath1 = "//form/div/div[1]/div/input"; driver.findElement(By.xpath(xPath1)).sendKeys("<EMAIL>"); String xPath2 = "//form/div/div[2]/div/input"; driver.findElement(By.xpath(xPath2)).sendKeys("<PASSWORD>"); String xPath3= "//form/div/div[3]/div/input"; driver.findElement(By.xpath(xPath3)).sendKeys("AccountPassword"); } }
b8b0b3570f4b7e3a9105a95ba223ff0016f82686
[ "Java" ]
3
Java
AnnaSamonii/JavaSeleniumCode
625f9dcfecbb5308eb98a14f29e3e0c68d615c1d
c4100cab129d7d62f0f2a596ed6adabfba6bd97a
refs/heads/master
<repo_name>brizio31/Android.FabTel<file_sep>/FabTel/src/main/java/it/cloudhome/android/fabtel/MySQLiteHelper.java package it.cloudhome.android.fabtel; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class MySQLiteHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "comunicacon.db"; private static final int DATABASE_VERSION = 1; // Database creation sql statement private static final String DATABASE_CREATE1 = "create table utenti " + "(id integer primary key autoincrement, " + " interno text not null, " + " nominativo text not null, " + " chat text not null " + "); "; private static final String DATABASE_CREATE2 = "create table chat_messages " + "(id integer primary key autoincrement," + "chat_from text not null," + "chat_to text not null," + "message text not null," + "timestamp text not null)" + ";"; public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE1); database.execSQL(DATABASE_CREATE2); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS utenti DROP TABLE IF EXISTS chat_messages;"); onCreate(db); } } <file_sep>/settings.gradle include ':FabTel' <file_sep>/FabTel/src/main/java/it/cloudhome/android/fabtel/ClsChatMessage.java package it.cloudhome.android.fabtel; import java.sql.Timestamp; import java.util.Date; public class ClsChatMessage { private String _from,_to,_chatMessage,_timestamp; private int id; public ClsChatMessage(String sFrom, String sTo, String sMessage) { // TODO Auto-generated constructor stub super(); this._from=sFrom; this._to=sTo; this._chatMessage=sMessage; Date now = new Date(); Long ts =now.getTime(); this._timestamp = ts.toString(); } public ClsChatMessage(String sFrom, String sTo, String sMessage,String sTimeStamp) { // TODO Auto-generated constructor stub super(); this._from=sFrom; this._to=sTo; this._chatMessage=sMessage; this._timestamp = sTimeStamp; } public int getId(){return id;} public String getFrom() {return this._from;} public String getTo(){ return this._to;} public String getMessage(){ return this._chatMessage;} public String getTimeStamp(){ return this._timestamp;} @SuppressWarnings("deprecation") public String getDateTime() { Timestamp ts=new Timestamp(Long.valueOf(this._timestamp)); String tmpStr=String.valueOf(ts.getDate())+"/"+String.valueOf(ts.getMonth()+1)+"/"+ String.valueOf(1900+ts.getYear())+" "+String.valueOf(ts.getHours())+":"; String min="0"+String.valueOf(ts.getMinutes()).trim(); min=min.substring(min.length()-2, min.length()); tmpStr += min; min="0"+String.valueOf(ts.getSeconds()).trim(); min=min.substring(min.length()-2, min.length()); tmpStr += ":"+ min; return tmpStr; } public void setId(int id){this.id=id;} public void setFrom(String sFrom){this._from=sFrom;} public void setTo(String sTo){this._to=sTo;} public void setMessage(String message){this._chatMessage=message;} public void setTimeStamp(String ts){this._timestamp=ts;} } <file_sep>/FabTel/src/main/java/it/cloudhome/android/fabtel/SplashScreen.java package it.cloudhome.android.fabtel; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; /** * Created by Fabrizio.Clerici on 06/12/13. */ public class SplashScreen extends Activity { protected int _splashTime = 2000; // time to display the splash screen in ms protected boolean _active=true; private Context ctx; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.v_splash); ctx=this; Thread splashTread = new Thread() { @Override public void run() { try { int waited = 0; while(_active && (waited < _splashTime)) { sleep(100); if(_active) { waited += 100; } } } catch(InterruptedException e) { // do nothing } finally { finish(); Intent i = new Intent(ctx,CentraleMain.class); startActivity(i); } } }; splashTread.start(); } } <file_sep>/FabTel/src/main/java/it/cloudhome/android/fabtel/DBChatMessage.java package it.cloudhome.android.fabtel; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class DBChatMessage { // Database fields private SQLiteDatabase database; private MySQLiteHelper dbHelper; private String[] allColumns = { "id","chat_from","chat_to","message","timestamp" }; public DBChatMessage(Context context) { dbHelper = new MySQLiteHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public List<ClsChatMessage> GetCollection(String filter,String[] filterPar,String order) { return GetCollection(filter, filterPar, order,null); } public List<ClsChatMessage> GetCollection(String filter,String[] filterPar,String order,String limit) { List<ClsChatMessage> msgs = new ArrayList<ClsChatMessage>(); Cursor cursor=database.query("chat_messages", allColumns, filter, filterPar, null, null, order,limit); cursor.moveToFirst(); while (!cursor.isAfterLast()) { ClsChatMessage msg = new ClsChatMessage(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)); msgs.add(msg); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return msgs; } public ClsChatMessage GetByFilter(String filter,String[] filterPar,String order) { Cursor cursor=database.query("chat_messages", allColumns, filter, filterPar, null, null, order); cursor.moveToFirst(); ClsChatMessage msg = new ClsChatMessage(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)); msg.setId(cursor.getInt(0)); // Make sure to close the cursor cursor.close(); return msg; } public void Insert(ClsChatMessage msg) { ContentValues values = new ContentValues(); values.put("chat_from", msg.getFrom()); values.put("chat_to", msg.getTo()); values.put("message", msg.getMessage()); values.put("timestamp", msg.getTimeStamp()); database.insert("chat_messages", null,values); } public void Delete(String id) { database.delete("chat_messages", "id="+id,null); } public void upgradeDB() { this.open(); database.execSQL("DROP TABLE IF EXISTS chat_messages"); String Sql = "create table chat_messages " + "(id integer primary key autoincrement," + "chat_from text not null," + "chat_to text not null," + "message text not null," + "timestamp text not null)" + ";"; database.execSQL(Sql); this.close(); } public void executeSQL(String sql) { // TODO Auto-generated method stub database.execSQL(sql); } } <file_sep>/FabTel/src/main/java/it/cloudhome/android/fabtel/ClsContatto.java package it.cloudhome.android.fabtel; public class ClsContatto { private String nome; private String interno; private String stato; private String chat_address; private int id; public ClsContatto(String nome, String interno, String stato, String chat_address) { // TODO Auto-generated constructor stub super(); this.nome=nome; this.interno=interno; this.stato=stato; this.chat_address=chat_address; } public ClsContatto(String nome, String interno, String chat_address) { // TODO Auto-generated constructor stub super(); this.nome=nome; this.interno=interno; this.stato=""; this.chat_address=chat_address; } public String getNome(){ return this.nome; } public int getId(){return id;} public String getInterno(){ return this.interno;} public String getStato(){ return this.stato;} public String getChatAddress(){ return this.chat_address;} public void setId(int id){this.id=id;} public void setInterno(String interno){this.interno=interno;} public void setNome(String nome){this.nome=nome;} public void setChatAddress(String chat_address){this.chat_address=chat_address;} public void setStato(String stato){this.stato=stato;} public int getImage_old(){ /* if (this.stato.equalsIgnoreCase("ONLINE")) return R.drawable.ico_profilo; if (this.stato.equalsIgnoreCase("BUSY")) return R.drawable.ico_profilo_busy; if (this.stato.equalsIgnoreCase("DND")) return R.drawable.ico_profilo_dnd; if (this.stato.startsWith("DIVERT")) return R.drawable.ico_profilo_out; return R.drawable.ico_profilo_off; */ return R.drawable.ico_profilo; } public int getImage(){ return R.drawable.ico_profilo; } public int getPhoneImage() { //Nuova Funzione Non esegue pi� il controllo sullo stato dell'interno return R.drawable.call_user; } public int getPhoneImage_old(){ /* if (this.stato.equalsIgnoreCase("ONLINE")) return R.drawable.call_user; if (this.stato.equalsIgnoreCase("BUSY")) return R.drawable.call_user_off; */ return R.drawable.call_user; } }
b7e85aea1dbb8370cf8eb5b1957834850cce47b4
[ "Java", "Gradle" ]
6
Java
brizio31/Android.FabTel
0103f477482604b94b4b2f7d3155a85584bffb56
1a22663b06f1a2cd8ff6373cc5ae9a1a566c0a71
refs/heads/master
<file_sep>using System; using System.Data; using System.Data.SqlClient; public partial class write : System.Web.UI.Page { SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ourdb"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { try { if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("insert into BlogPost(Title,Content,Author, BlogDate) values(@title,@content,@author,@date)", con); cmd.Parameters.AddWithValue("@title", txbxTitle.Text); cmd.Parameters.AddWithValue("@content", txbxContent.Text); cmd.Parameters.AddWithValue("@author", txbxAuthor.Text); cmd.Parameters.AddWithValue("@date", System.DateTime.Now); cmd.ExecuteNonQuery(); cmd.Dispose(); Response.Write("done!!!!!!"); } catch (Exception k) { Response.Write(k.Message); //throw; } finally { con.Close(); } } }<file_sep>using System; using System.Data; using System.Data.SqlClient; public partial class details : System.Web.UI.Page { SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ourdb"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString.Get("Id") != null) { DetailsView1.DefaultMode = System.Web.UI.WebControls.DetailsViewMode.ReadOnly; detail(); bindComment(); } } void detail() { try { if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("select * from BlogPost where Id=@id", con); cmd.Parameters.AddWithValue("@id", Request.QueryString["Id"]); SqlDataAdapter adp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adp.Fill(ds); ds.Tables[0].Columns.Add("FormDate", typeof(string)); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { DateTime date = (DateTime)ds.Tables[0].Rows[0]["BlogDate"]; string format = "MMM ddd d, yyyy"; ds.Tables[0].Rows[0]["FormDate"] = date.ToString(format); } DetailsView1.DataSource = ds; DetailsView1.DataBind(); cmd.Dispose(); } catch (Exception k) { Response.Write(k.Message); //throw; } finally { con.Close(); } } void bindComment() { try { if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("select * from Comments where BlogId=@id", con); cmd.Parameters.AddWithValue("@id", Request.QueryString["Id"]); SqlDataAdapter adp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adp.Fill(ds); if (ds.Tables[0].Rows.Count == 0) { GridViewcomment.Visible = false; LabelNoComment.Visible = true; } else { GridViewcomment.Visible = true; LabelNoComment.Visible = false; GridViewcomment.DataSource = ds; GridViewcomment.DataBind(); } } catch (Exception) { throw; } finally { con.Close(); } } protected void Button1_Click(object sender, EventArgs e) { try { if (txbxcomment.Text != txbxcomment.ToolTip.ToString() || txbxcommentauthor.Text != txbxcommentauthor.ToolTip.ToString()) { if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("insert into Comments(BlogId, Comment, Name, Date) values(@bid,@com,@name,@date)", con); cmd.Parameters.AddWithValue("@bid", Request.QueryString["Id"]); cmd.Parameters.AddWithValue("@com", txbxcomment.Text); cmd.Parameters.AddWithValue("@name", txbxcommentauthor.Text); cmd.Parameters.AddWithValue("@date", System.DateTime.Now); cmd.ExecuteNonQuery(); cmd.Dispose(); txbxcomment.Text = String.Empty; txbxcommentauthor.Text = String.Empty; bindComment(); } else { } } catch (Exception) { throw; } finally { con.Close(); } } } <file_sep> News Article using Blogging techniques which is built ASP.NET with the help of MS SQL DB and MS SQL Server 2014 where it is hosted in Microsoft Azure making use of remote SQL Server v12 in which it is remotely published using MS Visual Studio 2015. <file_sep>using System; using System.Data; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ourdb"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { BindBlog(); } void BindBlog() { try { if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("select * from BlogPost order by BlogDate desc ", con); SqlDataAdapter adp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); cmd.Dispose(); } catch (Exception k) { Response.Write(k.Message); //throw; } finally { con.Close(); } } }
591ab4b9cbe224d133919677a6d9ae255065af62
[ "Markdown", "C#" ]
4
C#
ashumeow/newsarticle
d9316ca21cf64ff1886afaa76f145f8bbe8caf89
4ac1476ec5296d6e6d33867195d96330cd66958a
refs/heads/master
<repo_name>jessicaundomiel/QuizApp<file_sep>/app/helpers/application_helper.rb module ApplicationHelper #Here, we'll have a master-list of answers and the user's guess will be checked against that list. def check_answer(answer) citylist = ["Atlanta", "Asheville", "Charlotte", "Raleigh"] #Additional master-lists could be placed here. correct = false citylist.each do |c| if answer == c correct == true end end return correct end # Check to see if the answer, while correct, may have already been guessed and put into the database of answers. def check_for_dup(answer, database) is_dup = false database.each do |d| if answer == d.name is_dup = true end end return is_dup end end
dbf810827e7fc66dfe9eabbfe40b8d464d4c4955
[ "Ruby" ]
1
Ruby
jessicaundomiel/QuizApp
08ff0c654face636f52120bd9998fbc3e552e7ff
6f26c37d79e8dcc1a0141128f40735af09f291b9
refs/heads/master
<repo_name>lamesen/RecruitRestaurantVisitorForecasting<file_sep>/recruit_utils.py """ Contributions from: DSEverything - Mean Mix - Math, Geo, Harmonic (LB 0.493) https://www.kaggle.com/dongxu027/mean-mix-math-geo-harmonic-lb-0-493 JdPaletto - Surprised Yet? - Part2 - (LB: 0.503) https://www.kaggle.com/jdpaletto/surprised-yet-part2-lb-0-503 hklee - weighted mean comparisons, LB 0.497, 1ST https://www.kaggle.com/zeemeen/weighted-mean-comparisons-lb-0-497-1st Also all comments for changes, encouragement, and forked scripts rock Keep the Surprise Going """ import pandas as pd import numpy as np from sklearn import preprocessing, metrics, cluster from sklearn.model_selection import TimeSeriesSplit import statsmodels.api as sm def import_data(): ''' Data munging for Recruit Restaurant Visitor Forecasting competition :return: This function returns two objects. The first is a DataFrame will all data sets contained. The second is a DataFrame that contains aggregated store metrics. ''' # Importing data data = { 'tra': pd.read_csv('./data/air_visit_data.csv'), 'as': pd.read_csv('./data/air_store_info.csv'), 'hs': pd.read_csv('./data/hpg_store_info.csv'), 'ar': pd.read_csv('./data/air_reserve.csv'), 'hr': pd.read_csv('./data/hpg_reserve.csv'), 'id': pd.read_csv('./data/store_id_relation.csv'), 'tes': pd.read_csv('./data/sample_submission.csv'), 'hol': pd.read_csv('./data/date_info.csv').rename(columns={'calendar_date': 'visit_date'}) } # Join HPG id to store relation id; we will be using AirREGI id primarily data['hr'] = pd.merge(data['hr'], data['id'], how='inner', on=['hpg_store_id']) # Date/Time transformations in the AirREGI/HPG reservation data for df in ['ar', 'hr']: data[df]['visit_datetime'] = pd.to_datetime(data[df]['visit_datetime']) data[df]['visit_datetime'] = data[df]['visit_datetime'].dt.date data[df]['reserve_datetime'] = pd.to_datetime(data[df]['reserve_datetime']) data[df]['reserve_datetime'] = data[df]['reserve_datetime'].dt.date data[df]['reserve_datetime_diff'] = data[df].apply(lambda r: (r['visit_datetime'] - r['reserve_datetime']).days, axis=1) tmp1 = data[df].groupby(['air_store_id', 'visit_datetime'], as_index=False)[ ['reserve_datetime_diff', 'reserve_visitors']].sum().rename( columns={'visit_datetime': 'visit_date', 'reserve_datetime_diff': 'rs1', 'reserve_visitors': 'rv1'}) tmp2 = data[df].groupby(['air_store_id', 'visit_datetime'], as_index=False)[ ['reserve_datetime_diff', 'reserve_visitors']].mean().rename( columns={'visit_datetime': 'visit_date', 'reserve_datetime_diff': 'rs2', 'reserve_visitors': 'rv2'}) data[df] = pd.merge(tmp1, tmp2, how='inner', on=['air_store_id', 'visit_date']) # Feature engineering: log(visitors), day of week, week of month, year, month, day, etc. data['tra']['visit_date'] = pd.to_datetime(data['tra']['visit_date']) data['tra']['log_visitors'] = data['tra']['visitors'].apply(np.log) data['tra']['dow'] = data['tra']['visit_date'].dt.dayofweek data['tra']['wom'] = (data['tra']['visit_date'].dt.day - 1) // 7 + 1 data['tra']['year'] = data['tra']['visit_date'].dt.year data['tra']['month'] = data['tra']['visit_date'].dt.month data['tra']['day'] = data['tra']['visit_date'].dt.day data['tra']['visit_date'] = data['tra']['visit_date'].dt.date data['tra']['large_party'] = np.where(data['tra']['visitors'] >= 120, 1., 0.) # Create the same features for the test data data['tes']['visit_date'] = data['tes']['id'].map(lambda x: str(x).split('_')[2]) data['tes']['air_store_id'] = data['tes']['id'].map(lambda x: '_'.join(x.split('_')[:2])) data['tes']['visit_date'] = pd.to_datetime(data['tes']['visit_date']) data['tes']['log_visitors'] = 0 data['tes']['dow'] = data['tes']['visit_date'].dt.dayofweek data['tes']['wom'] = (data['tes']['visit_date'].dt.day - 1) // 7 + 1 data['tes']['year'] = data['tes']['visit_date'].dt.year data['tes']['month'] = data['tes']['visit_date'].dt.month data['tes']['day'] = data['tes']['visit_date'].dt.day data['tes']['visit_date'] = data['tes']['visit_date'].dt.date data['tes']['large_party'] = np.where(data['tes']['visitors'] >= 120, 1., 0.) # Manual differencing by me! We combine train and test so that we can build the full differencing data['tra']['subset'] = 'train' data['tes']['subset'] = 'test' combined = pd.concat([data['tra'], data['tes']]) combined.sort_values(by=['air_store_id', 'visit_date'], inplace=True) combined['visitors_lag1'] = combined.groupby(['air_store_id'])['log_visitors'].shift() combined['visitors_diff1'] = combined.groupby(['air_store_id'])['log_visitors'].diff() combined['visitors_lag2'] = combined.groupby(['air_store_id'])['log_visitors'].shift(2) combined['visitors_diff2'] = combined.groupby(['air_store_id'])['log_visitors'].diff(2) combined['visitors_lag3'] = combined.groupby(['air_store_id'])['log_visitors'].shift(3) combined['visitors_diff3'] = combined.groupby(['air_store_id'])['log_visitors'].diff(3) combined['visitors_lag4'] = combined.groupby(['air_store_id'])['log_visitors'].shift(4) combined['visitors_diff4'] = combined.groupby(['air_store_id'])['log_visitors'].diff(4) combined['visitors_lag5'] = combined.groupby(['air_store_id'])['log_visitors'].shift(5) combined['visitors_diff5'] = combined.groupby(['air_store_id'])['log_visitors'].diff(5) combined['visitors_lag6'] = combined.groupby(['air_store_id'])['log_visitors'].shift(6) combined['visitors_diff6'] = combined.groupby(['air_store_id'])['log_visitors'].diff(6) combined['visitors_lag7'] = combined.groupby(['air_store_id'])['log_visitors'].shift(7) combined['visitors_diff7'] = combined.groupby(['air_store_id'])['log_visitors'].diff(7) # Split train and test again data['tra'] = combined[combined['subset'] == 'train'] data['tra'].drop('subset', axis=1) data['tes'] = combined[combined['subset'] == 'test'] data['tes'].drop('subset', axis=1) # Create unique store data frame for future feature engineering unique_stores = data['tes']['air_store_id'].unique() stores = pd.concat([pd.DataFrame({'air_store_id': unique_stores, 'dow': [i] * len(unique_stores)}) for i in range(7)], axis=0, ignore_index=True).reset_index(drop=True) # Add descriptive statistics by store and day of week: min, mean, median, max and count of visitors tmp = data['tra'].groupby(['air_store_id', 'dow'], as_index=False)['visitors'].min().rename( columns={'visitors': 'min_visitors'}) stores = pd.merge(stores, tmp, how='left', on=['air_store_id', 'dow']) tmp = data['tra'].groupby(['air_store_id', 'dow'], as_index=False)['visitors'].mean().rename( columns={'visitors': 'mean_visitors'}) stores = pd.merge(stores, tmp, how='left', on=['air_store_id', 'dow']) tmp = data['tra'].groupby(['air_store_id', 'dow'], as_index=False)['visitors'].median().rename( columns={'visitors': 'median_visitors'}) stores = pd.merge(stores, tmp, how='left', on=['air_store_id', 'dow']) tmp = data['tra'].groupby(['air_store_id', 'dow'], as_index=False)['visitors'].max().rename( columns={'visitors': 'max_visitors'}) stores = pd.merge(stores, tmp, how='left', on=['air_store_id', 'dow']) tmp = data['tra'].groupby(['air_store_id', 'dow'], as_index=False)['visitors'].count().rename( columns={'visitors': 'count_observations'}) stores = pd.merge(stores, tmp, how='left', on=['air_store_id', 'dow']) stores = pd.merge(stores, data['as'], how='left', on=['air_store_id']) # NEW FEATURES FROM <NAME> (not that useful) stores['air_genre_name'] = stores['air_genre_name'].map(lambda x: str(str(x).replace('/', ' '))) stores['air_area_name'] = stores['air_area_name'].map(lambda x: str(str(x).replace('-', ' '))) # Label encoding for Genre and Area names lbl = preprocessing.LabelEncoder() for i in range(10): stores['air_genre_name' + str(i)] = lbl.fit_transform( stores['air_genre_name'].map(lambda x: str(str(x).split(' ')[i]) if len(str(x).split(' ')) > i else '')) stores['air_area_name' + str(i)] = lbl.fit_transform( stores['air_area_name'].map(lambda x: str(str(x).split(' ')[i]) if len(str(x).split(' ')) > i else '')) stores['air_genre_name'] = lbl.fit_transform(stores['air_genre_name']) stores['air_area_name'] = lbl.fit_transform(stores['air_area_name']) # Location clustering by me! Clustering by latitude and longitude k=8 cluster_stores = cluster_regions(stores[['longitude', 'latitude']], 8) stores['cluster'] = cluster_stores.predict(stores[['longitude', 'latitude']].as_matrix()) # Holiday information added data['hol']['visit_date'] = pd.to_datetime(data['hol']['visit_date']) data['hol']['day_of_week'] = lbl.fit_transform(data['hol']['day_of_week']) data['hol']['visit_date'] = data['hol']['visit_date'].dt.date return data, stores def create_train_test(data, stores, clean=False, predict_large_party=False): ''' :param data: The prepared dataframes built from csv files :param stores: A dataframe of grouped stores and aggregated metrics :param clean: If this is true, we will remove stores and other categorical variables that don't exist in the test set from the training set :param predict_large_party: If this is true we will use logistic regression to try and predict whether a large party (greater than 120) was present on this day :return: Returns a finzalized train and test data frame ''' # Join holiday data train = pd.merge(data['tra'], data['hol'], how='left', on=['visit_date']) test = pd.merge(data['tes'], data['hol'], how='left', on=['visit_date']) # Join store aggregates train = pd.merge(train, stores, how='left', on=['air_store_id', 'dow']) test = pd.merge(test, stores, how='left', on=['air_store_id', 'dow']) # Join the AirREGI and HPG reservation data for df in ['ar', 'hr']: train = pd.merge(train, data[df], how='left', on=['air_store_id', 'visit_date']) test = pd.merge(test, data[df], how='left', on=['air_store_id', 'visit_date']) # Rename the id column train['id'] = train.apply(lambda r: '_'.join([str(r['air_store_id']), str(r['visit_date'])]), axis=1) # Calculate the top level reservation aggregates train['total_reserv_sum'] = train['rv1_x'] + train['rv1_y'] train['total_reserv_mean'] = (train['rv2_x'] + train['rv2_y']) / 2 train['total_reserv_dt_diff_mean'] = (train['rs2_x'] + train['rs2_y']) / 2 test['total_reserv_sum'] = test['rv1_x'] + test['rv1_y'] test['total_reserv_mean'] = (test['rv2_x'] + test['rv2_y']) / 2 test['total_reserv_dt_diff_mean'] = (test['rs2_x'] + test['rs2_y']) / 2 # NEW FEATURES FROM JMBULL not very useful but included nonetheless train['date_int'] = train['visit_date'].apply(lambda x: x.strftime('%Y%m%d')).astype(int) test['date_int'] = test['visit_date'].apply(lambda x: x.strftime('%Y%m%d')).astype(int) train['var_max_lat'] = train['latitude'].max() - train['latitude'] train['var_max_long'] = train['longitude'].max() - train['longitude'] test['var_max_lat'] = test['latitude'].max() - test['latitude'] test['var_max_long'] = test['longitude'].max() - test['longitude'] # NEW FEATURES FROM Georgii Vyshnia not very useful but included nonetheless train['lon_plus_lat'] = train['longitude'] + train['latitude'] test['lon_plus_lat'] = test['longitude'] + test['latitude'] # Label encoding to a simpler store ID lbl = preprocessing.LabelEncoder() train['air_store_id2'] = lbl.fit_transform(train['air_store_id']) test['air_store_id2'] = lbl.transform(test['air_store_id']) # If true run the train_clean function. Details below if clean: train, test = train_clean(train, test) # Fill NaNs with -1 train = train.fillna(-1) test = test.fillna(-1) # If true, use a logistic regression to predict whether the test data set will have a large party or not if predict_large_party: train['large_party'] = np.where(train['visitors'] >= 120, 1., 0.) subset = ['dow', 'wom', 'year', 'month', 'day', 'day_of_week', 'holiday_flg', 'air_genre_name', 'air_area_name', 'air_store_id2', 'cluster', 'min_visitors', 'mean_visitors', 'median_visitors', 'max_visitors', 'count_observations', 'rs1_x', 'rv1_x', 'rs2_x', 'rv2_x', 'rs1_y', 'rv1_y', 'rs2_y', 'rv2_y', 'total_reserv_sum', 'total_reserv_mean', 'total_reserv_dt_diff_mean'] y = train['large_party'] X = train[subset] lr = sm.Logit(y, X) model = lr.fit() test['large_party'] = model.predict(test[subset]) test['large_party'] = np.where(test['large_party'] >= 0.5, 1., 0) return train, test def train_clean(train, test): ''' Remove observations from the training set with categorical_vars that aren't in the test set. Categorical vars to be removed are listed below but include Genre/Area names and store ids as well as the location cluster ''' categorical_vars = ['air_genre_name', 'air_area_name', 'air_store_id2', 'cluster'] for var in categorical_vars: new_train = train[train[var].isin(test[var].unique())] return new_train, test def cluster_regions(df, n_clusters): ''' :param df: Input dataframe :param n_clusters: number of clusters to apply :return: returns the model with which to predict lon/lat clusters ''' X = df[['longitude', 'latitude']].as_matrix() kmeans = cluster.KMeans(n_clusters=n_clusters, init='k-means++', n_init=25, max_iter=1000).fit(X) return kmeans def RMSLE(y, pred): ''' :param y: validation y vector :param pred: y-hat vector :return: returns the root mean squared error; since the predictions are based on log(visitors) we do not need to calculate log of RMSE ''' return metrics.mean_squared_error(y, pred) ** 0.5 def time_series_cv(y, X, input_model): ''' User-defined function to calculate cross validation based on time-series based on https://robjhyndman.com/hyndsight/tscv/ :param y: cv y vector :param X: cv X matrix :param input_model: accepts any type of model with a predict function :return: returns the time-series based cv RMSLE score ''' # Using sci-kit learn we create a time-series specific cv split tscv = TimeSeriesSplit(n_splits=5) results = [] # Iterate over splits, including the past observations each time for train_index, test_index in tscv.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] model = input_model.fit(X_train, y_train) predictions = model.predict(X_test) # Calculate RMSLE results.append(RMSLE(y_test, predictions)) # Return results return results def score_predictions(predictions, name, log=True): ''' User-defined function to create a scoring file based on predictions :param predictions: y-hat vector :param name: file name :param log: Boolean value to signify whether np.exp should be calculated on the y-hat value or not :return: None type returned ''' # Score the file and save scored_df = pd.read_csv('./data/sample_submission.csv') temp_series = pd.Series(predictions) temp_series[temp_series < 0] = 0 if log: scored_df['visitors'] = np.exp(temp_series) else: scored_df['visitors'] = temp_series scored_df.to_csv('./Output/' + name + '.csv', index=False) def predict_iter(train, test, model): ''' For models that use differencing, the test set must be iterated since the calculated y-hat values will influence the differencing :param train: training data :param test: test data :param model: any type of model object with a predict function :return: train and test data sets with y-hat scoring on the test ''' # Save the input data sets so the analyst can see whether the process went as expected train.to_csv('./tmp/train_in.csv') test.to_csv('./tmp/test_in.csv') # Identify the train/test subset so as not to confuse after they are combined train['subset'] = 'train' test['subset'] = 'test' # Combine the train and test set since they are time-series contiguous combined = pd.concat([train, test]) combined.sort_values(by=['air_store_id', 'visit_date'], inplace=True) # Loop the number of unique days in the test set for _ in test.valid_date.unique(): # Create a y-hat vector combined['predictions'] = model.predict(combined) # Calculate log_visitors value on y-hat vector for the test set and leave alone for the training combined['log_visitors'] = combined['predictions'].where(combined['subset'] == 'test', combined['log_visitors']) # Calculate the visitors value based on yhat vector for the test set and leave alone for the training combined['visitors'] = np.exp(combined['predictions'].where(combined['subset'] == 'test', combined['visitors'])) # Re-calculate all of the lag and diff predictors based on the newly predicted log_visitors value combined['visitors_lag1'] = combined.groupby(['air_store_id'])['log_visitors'].shift() combined['visitors_diff1'] = combined.groupby(['air_store_id'])['log_visitors'].diff() combined['visitors_lag2'] = combined.groupby(['air_store_id'])['log_visitors'].shift(2) combined['visitors_diff2'] = combined.groupby(['air_store_id'])['log_visitors'].diff(2) combined['visitors_lag3'] = combined.groupby(['air_store_id'])['log_visitors'].shift(3) combined['visitors_diff3'] = combined.groupby(['air_store_id'])['log_visitors'].diff(3) combined['visitors_lag4'] = combined.groupby(['air_store_id'])['log_visitors'].shift(4) combined['visitors_diff4'] = combined.groupby(['air_store_id'])['log_visitors'].diff(4) combined['visitors_lag5'] = combined.groupby(['air_store_id'])['log_visitors'].shift(5) combined['visitors_diff5'] = combined.groupby(['air_store_id'])['log_visitors'].diff(5) combined['visitors_lag6'] = combined.groupby(['air_store_id'])['log_visitors'].shift(6) combined['visitors_diff6'] = combined.groupby(['air_store_id'])['log_visitors'].diff(6) combined['visitors_lag7'] = combined.groupby(['air_store_id'])['log_visitors'].shift(7) combined['visitors_diff7'] = combined.groupby(['air_store_id'])['log_visitors'].diff(7) # Once the looping is complete, drop the extraneous y-hat vector combined.drop('predictions', axis=1) # Split the train and test data sets and drop the subset column train = combined[combined['subset'] == 'train'] train.drop('subset', axis=1) test = combined[combined['subset'] == 'test'] test.drop('subset', axis=1) # Save the output to a file in order to analyze expectations train.to_csv('./tmp/train_out.csv') test.to_csv('./tmp/test_out.csv') return train, test <file_sep>/h2o_train.py import recruit_utils import pandas as pd import numpy as np import h2o from h2o.automl import H2OAutoML def convert_columns_as_factor(hdf, column_list): list_count = len(column_list) if list_count is 0: return "Error: You don't have a list of binary columns." if (len(hdf.columns)) is 0: return "Error: You don't have any columns in your data frame." for i in range(list_count): try: hdf[column_list[i]] = hdf[column_list[i]].asfactor() print('Column ' + column_list[i] + " is converted into factor/catagorical.") except ValueError: print('Error: ' + str(column_list[i]) + " not found in the data frame.") # Import data into pandas data frames data, stores = recruit_utils.import_data() # Create train and test set train, test = recruit_utils.create_train_test(data, stores, clean=True, predict_large_party=True) # Initialize h2o cluster h2o.init() # Drop un-needed ID variables and target variable transformations train_subset = train.drop(['air_store_id', 'visit_date', 'id', 'air_store_id2', 'visitors'], axis=1) # Create an H2O data frame (HDF) from the pandas data frame h2o_train = h2o.H2OFrame(train_subset) # User-defined function to convert columns to HDF factors convert_columns_as_factor(h2o_train, ['dow', 'wom', 'year', 'month', 'day', 'day_of_week', 'holiday_flg', 'air_genre_name', 'air_area_name', 'air_genre_name0', 'air_genre_name1', 'air_genre_name2', 'air_genre_name3', 'air_genre_name4', 'air_genre_name5', 'air_genre_name6', 'air_genre_name7', 'air_genre_name8', 'air_genre_name9', 'air_area_name0', 'air_area_name1', 'air_area_name2', 'air_area_name3', 'air_area_name4', 'air_area_name5', 'air_area_name6', 'air_area_name7', 'air_area_name8', 'air_area_name9', 'cluster', 'large_party']) # Setup Auto ML to run for approximately 10 hours aml = H2OAutoML(max_runtime_secs=36000) # Train Auto ML aml.train(y="log_visitors", training_frame=h2o_train) # Save results model_path = h2o.save_model(model=aml.leader, path="./tmp/mymodel2", force=True) saved_model = h2o.load_model(model_path) # Output leaderboard lb = aml.leaderboard # Save original train/test data train.to_csv('./tmp/train_in.csv') test.to_csv('./tmp/test_in.csv') # Mark train/test sets train['subset'] = 'train' test['subset'] = 'test' combined = pd.concat([train, test]) combined.sort_values(by=['air_store_id', 'visit_date'], inplace=True) for _ in test.visit_date.unique(): # Set up testing HDF h2o_test = h2o.H2OFrame(combined) convert_columns_as_factor(h2o_test, ['dow', 'wom', 'year', 'month', 'day', 'day_of_week', 'holiday_flg', 'air_genre_name', 'air_area_name', 'air_genre_name0', 'air_genre_name1', 'air_genre_name2', 'air_genre_name3', 'air_genre_name4', 'air_genre_name5', 'air_genre_name6', 'air_genre_name7', 'air_genre_name8', 'air_genre_name9', 'air_area_name0', 'air_area_name1', 'air_area_name2', 'air_area_name3', 'air_area_name4', 'air_area_name5', 'air_area_name6', 'air_area_name7', 'air_area_name8', 'air_area_name9', 'cluster', 'large_party']) # Generate predictions preds = aml.leader.predict(h2o_test) temp_df = h2o.as_list(preds) temp_series = temp_df['predict'] temp_series[temp_series < 0] = 0 combined['predictions'] = temp_series combined['log_visitors'] = combined['predictions'].where(combined['subset'] == 'test', combined['log_visitors']) combined['visitors'] = np.exp(combined['predictions'].where(combined['subset'] == 'test', combined['log_visitors'])) combined['visitors_lag1'] = combined.groupby(['air_store_id'])['log_visitors'].shift() combined['visitors_diff1'] = combined.groupby(['air_store_id'])['log_visitors'].diff() combined['visitors_lag2'] = combined.groupby(['air_store_id'])['log_visitors'].shift(2) combined['visitors_diff2'] = combined.groupby(['air_store_id'])['log_visitors'].diff(2) combined['visitors_lag3'] = combined.groupby(['air_store_id'])['log_visitors'].shift(3) combined['visitors_diff3'] = combined.groupby(['air_store_id'])['log_visitors'].diff(3) combined['visitors_lag4'] = combined.groupby(['air_store_id'])['log_visitors'].shift(4) combined['visitors_diff4'] = combined.groupby(['air_store_id'])['log_visitors'].diff(4) combined['visitors_lag5'] = combined.groupby(['air_store_id'])['log_visitors'].shift(5) combined['visitors_diff5'] = combined.groupby(['air_store_id'])['log_visitors'].diff(5) combined['visitors_lag6'] = combined.groupby(['air_store_id'])['log_visitors'].shift(6) combined['visitors_diff6'] = combined.groupby(['air_store_id'])['log_visitors'].diff(6) combined['visitors_lag7'] = combined.groupby(['air_store_id'])['log_visitors'].shift(7) combined['visitors_diff7'] = combined.groupby(['air_store_id'])['log_visitors'].diff(7) # Score the file and save scored_df = pd.read_csv('./data/sample_submission.csv') scored_final_df = pd.merge(scored_df[['id']], combined[['id', 'visitors']], on='id') scored_final_df.to_csv('./Output/scored_automl.csv', index=False)
5f6fb4f030a577654fda912bf2d3f29632615fa9
[ "Python" ]
2
Python
lamesen/RecruitRestaurantVisitorForecasting
1239fe2c5a6fd40dbc4f0acc8bea7c2a6332363e
4d017af91b18b5ac4c33d9ec8b44e09a1eee8228
refs/heads/master
<repo_name>brenes/lodel20n<file_sep>/config/initializers/decorators.rb ActiveRecord::Base.class_eval do def decorator(format) @__decorators ||= {} @__decorators[format] ||= eval("Decorators::#{self.class.name}::#{format}.new(self)") end end<file_sep>/db/migrate/20111120104353_create_resultados.rb class CreateResultados < ActiveRecord::Migration def change create_table :resultados do |t| t.integer :escrutinio_id t.integer :partido_id t.timestamps end end end <file_sep>/db/migrate/20111120122701_add_fields_to_resultado.rb class AddFieldsToResultado < ActiveRecord::Migration def change add_column :resultados, :escanos, :integer add_column :resultados, :total_votos, :integer add_column :resultados, :pct_votos, :integer end end <file_sep>/app/decorators/decorator.rb module Decorators class Base def initialize(decorated) @decorated = decorated end def method_missing(s, *a) @decorated.send(s, *a) end end end<file_sep>/app/models/escrutinio.rb class Escrutinio < ActiveRecord::Base belongs_to :territorio has_many :resultados scope :final, where(:pct_escrutado => 100) # Los escrutinios tienen este formato # <escrutinio_sitio> # <porciento_escrutado>100</porciento_escrutado> # <nombre_sitio>Barbastro</nombre_sitio> # <ts>0</ts> # <tipo_sitio>5</tipo_sitio> # <votos> # <contabilizados><cantidad>9433</cantidad><porcentaje>77.5</porcentaje></contabilizados> # <abstenciones><cantidad>2738</cantidad><porcentaje>22.5</porcentaje></abstenciones> # <nulos><cantidad>70</cantidad><porcentaje>0.74</porcentaje></nulos> # <blancos><cantidad>113</cantidad><porcentaje>1.21</porcentaje></blancos> # </votos> # <resultados> # <numero_partidos>20</numero_partidos> # <partido> # <id_partido>226</id_partido> # <nombre>PSOE</nombre> # <electos>2</electos> # <votos_numero>4398</votos_numero> # <votos_porciento>46.97</votos_porciento> # </partido> # </resultados> # </escrutinio_sitio> def self.create_from_api territorio, escrutinio_xml hora = escrutinio_xml.xpath("/escrutinio_sitio/ts").first.content hora = (hora == 0) ? nil : Time.at(hora.to_i) escrutinio = Escrutinio.find_by_territorio_id_and_hora(territorio.id, hora) # si tenemos escrutinio de esta hora no lo repetimos return escrutinio unless escrutinio.nil? escrutinio = Escrutinio.create! :territorio_id => territorio.id, :hora => hora, :pct_escrutado => escrutinio_xml.xpath("/escrutinio_sitio/porciento_escrutado").first.content, :total_contabilizados => escrutinio_xml.xpath("/escrutinio_sitio/votos/contabilizados/cantidad").first.content, :pct_contabilizados => escrutinio_xml.xpath("/escrutinio_sitio/votos/contabilizados/porcentaje").first.content, :total_abstenciones => escrutinio_xml.xpath("/escrutinio_sitio/votos/abstenciones/cantidad").first.content, :pct_abstenciones => escrutinio_xml.xpath("/escrutinio_sitio/votos/abstenciones/porcentaje").first.content, :total_nulos => escrutinio_xml.xpath("/escrutinio_sitio/votos/nulos/cantidad").first.content, :pct_nulos => escrutinio_xml.xpath("/escrutinio_sitio/votos/nulos/porcentaje").first.content, :total_blanco => escrutinio_xml.xpath("/escrutinio_sitio/votos/blancos/cantidad").first.content, :pct_blanco => escrutinio_xml.xpath("/escrutinio_sitio/votos/blancos/porcentaje").first.content escrutinio_xml.xpath("/escrutinio_sitio/resultados/partido").each do |resultado_xml| escrutinio.resultados << Resultado.create_from_api(resultado_xml) end escrutinio end def final? pct_escrutado == 100 end def total_votos total_contabilizados + total_abstenciones + total_nulos end end <file_sep>/app/decorators/territorio/html.rb module Decorators::Territorio class Html < Decorators::Base def sidebar end end end<file_sep>/app/controllers/territorios_controller.rb class TerritoriosController < ApplicationController def index @territorio = Territorio.pais.first @escrutinio = @territorio.ultimo_escrutinio @escrutinio_html = Decorators::Escrutinio::Html.new(@escrutinio) @escrutinio_seo = Decorators::Escrutinio::Seo.new(@escrutinio_html) render :action => :show_pais end def show @territorio = Territorio.find(params[:id]) @escrutinio = @territorio.ultimo_escrutinio @escrutinio_html = Decorators::Escrutinio::Html.new(@escrutinio) @escrutinio_seo = Decorators::Escrutinio::Seo.new(@escrutinio_html) render :action => :"show_#{@territorio.descripcion_tipo}" end end <file_sep>/db/migrate/20111120202536_add_pct_escrutado_to_escrutinio.rb class AddPctEscrutadoToEscrutinio < ActiveRecord::Migration def change add_column :escrutinios, :pct_escrutado, :float end end <file_sep>/app/decorators/escrutinio/html.rb module Decorators::Escrutinio class Html < Decorators::Base def titulo @decorated.final? ? "Escrutinio final" : "Escrutinio parcial <>(#{@decorated.pct_escrutado}%)</i>" end def fecha_actualizacion @decorated.final? ? "<p>Datos actualizados por última vez a las #{hora}</p>" : "<p>Datos definitivos</p>" end end end<file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery Dir["app/decorators/*.rb"].each do |path| require_dependency path end Dir["app/decorators/**/*.rb"].each do |path| require_dependency path end I18n.locale = :es end <file_sep>/app/decorators/escrutinio/seo.rb module Decorators::Escrutinio class Seo < Decorators::Base def header_seccion "<h2>#{@decorated.titulo}</h2>" end end end<file_sep>/lib/tasks/api.rake namespace :elpais do desc "Tarea para descargar toda la estructura de territorios" task :descarga_territorios => :environment do VCR.use_cassette("elpais_estructura_#{Settings["year"]}", :record => :new_episodes) do Territorio.delete_all # Creamos el territorio del pais pais = Territorio.find_by_nombre("España") pais ||= Territorio.create! :nombre => "España", :tipo_api => Territorio.TIPOS_API[:pais] # Visitamos la página de El Pais y recorremos l a lista de comunidades Nokogiri::HTML(Net::HTTP.get(URI.parse(pais.pais_url))).xpath("//div[@id='otrasCCAAs']/ul/li/a/@href").each do |id_comunidad| str_id_comunidad = id_comunidad.value.gsub("/", "") uri_comunidad = URI.parse("http://rsl00.epimg.net/elecciones/#{Settings["year"]}/generales/congreso/#{str_id_comunidad}/index.xml2") resultado_comunidad = Nokogiri::XML(Net::HTTP.get uri_comunidad) comunidad = Territorio.create_from_api str_id_comunidad, pais, resultado_comunidad puts "#{str_id_comunidad} " + comunidad.nombre contenido = Nokogiri::HTML(Net::HTTP.get(URI.parse(comunidad.pais_url))) contenido.xpath("//div[@id='otrasCircunscripciones']/ul/li/a/@href").each do |id_provincia| str_id_provincia = id_provincia.value.gsub("/", "").gsub("\.html", "") uri_provincia = URI.parse("http://rsl00.epimg.net/elecciones/#{Settings["year"]}/generales/congreso/#{str_id_comunidad}/#{str_id_provincia}.xml2") resultado_provincia = Nokogiri::XML(Net::HTTP.get uri_provincia) provincia = Territorio.create_from_api str_id_provincia, comunidad, resultado_provincia puts "--- #{str_id_provincia} " + provincia.nombre Nokogiri::HTML(Net::HTTP.get(URI.parse(provincia.pais_url))).xpath("//div[@id='listadoMunicipios']/ul/li/a/@href").each do |id_municipio| str_id_municipio = id_municipio.value.gsub(/^.*\//, "").gsub("\.html", "") uri_municipio = URI.parse("http://rsl00.epimg.net/elecciones/#{Settings["year"]}/generales/congreso/#{str_id_comunidad}/#{str_id_provincia}/#{str_id_municipio}.xml2") resultado_municipio = Nokogiri::XML(Net::HTTP.get uri_municipio) unless resultado_municipio.xpath("/escrutinio_sitio/nombre_sitio").first.nil? municipio = Territorio.create_from_api str_id_municipio, provincia, resultado_municipio puts "------ #{str_id_municipio} " + municipio.nombre end end end end end end desc "Tarea para descargar el escrutinio de los territorios en su estado actual" task :escrutinio => :environment do # Tarda tanto que podemos dejarlo en bucle sin problema while true Territorio.interesantes.each do |t| t.consultar_escrutinio end end end end<file_sep>/app/models/resultado.rb class Resultado < ActiveRecord::Base belongs_to :escrutinio belongs_to :partido # Los resultados tienen este formato # <id_partido>226</id_partido> # <nombre>PSOE</nombre> # <electos>2</electos> # <votos_numero>4398</votos_numero> # <votos_porciento>46.97</votos_porciento> def self.create_from_api resultado_xml id_partido = resultado_xml.xpath("id_partido").first.content partido = Partido.find_or_create_by_id_api(id_partido, :nombre => resultado_xml.xpath("nombre").first.content) Resultado.create! :partido_id => partido.id, :escanos => resultado_xml.xpath("electos").first.nil? ? nil : resultado_xml.xpath("electos").first.content.to_i, :total_votos => resultado_xml.xpath("votos_numero").first.content.to_i, :pct_votos => resultado_xml.xpath("votos_porciento").first.content.to_f end end <file_sep>/app/models/partido.rb class Partido < ActiveRecord::Base has_many :resultados end <file_sep>/app/decorators/territorio/js.rb module Decorators::Territorio class Js < Decorators::Base def distribucion_partidos escrutinio = @decorated.ultimo_escrutinio "var data = #{escrutinio.resultados.map{|r| {:id => r.partido.id, :name => r.pct_votos > 0.5 ? r.partido.nombre : "", :pct => 1 + r.pct_votos*(100-escrutinio.resultados.count)/100}}.to_json}; var w = 600, //width h = 450, //height r = 200, //radius center = 225; color = d3.scale.category20c(); //builtin range of colors var vis = d3.select(\"#graphic\") .append(\"svg:svg\") //create the SVG element inside the <body> .data([data]) //associate our data with the document .attr(\"width\", w) //set the width and height of our visualization (these will be attributes of the <svg> tag .attr(\"height\", h) .append(\"svg:g\") //make a group to hold our pie chart .attr(\"transform\", \"translate(\" + center + \",\" + center + \")\") //move the center of the pie chart from 0, 0 to radius, radius var arc = d3.svg.arc() //this will create <path> elements for us using arc data .outerRadius(r); var pie = d3.layout.pie() //this will create arc data for us given a list of values .value(function(d) { return d.pct; }); //we must tell it out to access the value of each element in our data array var arcs = vis.selectAll(\"g.slice\") //this selects all <g> elements with class slice (there aren't any yet) .data(pie) //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties) .enter() //this will create <g> elements for every \"extra\" data element that should be associated with a selection. The result is creating a <g> for every object in the data array .append(\"svg:g\") //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice) .attr(\"class\", \"slice\"); //allow us to style things in the slices (like text) arcs.append(\"svg:path\") .attr('id', function(d, i) { return 'party-'+d.data.id; } ) .attr(\"fill\", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above .attr(\"d\", arc) //this creates the actual SVG path using the associated data (pie) with the arc drawing function .on(\"mouseover\", function() { $('.party').removeClass('active'); $('.'+this.id).addClass('active'); d3.select(this).transition() .attr(\"transform\", function(d) { angle = d.startAngle + (d.endAngle - d.startAngle)/2 distance = 20 return \"translate(\" + distance*Math.sin(angle) + \", \" + -1*distance*Math.cos(angle) + \")\"; }) .delay(0) .duration(1000); }) .on(\"mouseout\", function() { d3.select(this).transition() .attr(\"transform\", function(d) { angle = d.startAngle + (d.endAngle - d.startAngle)/2 distance = 20 return \"translate(0,0)\"; }) .delay(1000) .duration(1000) });; arcs.append(\"svg:text\") //add a label to each slice .attr(\"transform\", function(d) { //set the label's origin to the center of the arc //we have to make sure to set these before calling arc.centroid d.innerRadius = 0; d.outerRadius = r; return \"translate(\" + arc.centroid(d) + \")\"; //this gives us a pair of coordinates like [50, 50] }) .attr(\"text-anchor\", \"middle\") //center the text on it's origin .text(function(d, i) { return data[i].name; }); //get the label from our original data array " end def historico_partidos @decorated.escrutinios.map do |escrutinio| "var data = #{escrutinio.resultados.map{|r| {:name => r.partido.nombre, :pct => r.pct_votos}}.to_json}; var c = d3.scale.linear().domain([0,100]).range([\"rgb(50%, 0, 0)\", \"rgb(100%, 0, 0)\"]).interpolate(d3.interpolateRgb) var pct_acumulado = 100 var vis = d3.select(\"#graphic\") .append(\"div\") .attr(\"width\", \"100%\") vis.append(\"span\") .text(\"#{escrutinio.hora}: #{escrutinio.pct_escrutado}%\") vis.selectAll(\"div\") .data(data) .enter().append(\"div\") .style(\"width\", function(d) { return d.pct+'%' }) .style(\"clear\", function(d, i) { return (i == 0) ? \"left\" : \"none\" }) .style(\"background-color\", function(d) { pct_acumulado -= d.pct; return c(pct_acumulado + d.pct) }) .text(function(d) { return d.name + '(' + d.pct+'%)'});" end.join("\n") end end end<file_sep>/app/models/territorio.rb class Territorio < ActiveRecord::Base has_many :escrutinios belongs_to :padre, :class_name => "Territorio", :foreign_key => "territorio_padre_id" has_many :hijos, :class_name => "Territorio", :foreign_key => "territorio_padre_id" @@TIPOS_API = {:pais => 1, :comunidad => 2, :provincia => 3, :municipio => 5} cattr_reader :TIPOS_API @@TIPOS_API.each do |name, id| scope name.to_sym, where(:tipo_api => id) end scope :interesantes, where("tipo_api = #{@@TIPOS_API[:pais]} OR tipo_api = #{@@TIPOS_API[:comunidad]} OR tipo_api = #{@@TIPOS_API[:provincia]}") def self.create_from_api id, padre, xml num_a_elegir = xml.xpath("/escrutinio_sitio/num_a_elegir").first tipo = xml.xpath("/escrutinio_sitio/tipo_sitio").first.content territorio = Territorio.find_by_id_api_and_tipo_api_and_territorio_padre_id(id, tipo, padre.id) || Territorio.create!(:nombre => xml.xpath("/escrutinio_sitio/nombre_sitio").first.content, :tipo_api => tipo, :id_api => id, :escanos => (num_a_elegir.nil? ? nil : num_a_elegir.content), :padre => padre) end def descripcion_tipo @@TIPOS_API.invert[tipo_api] end def api_url send :"api_url_#{descripcion_tipo}" end def pais_url send :"pais_url_#{descripcion_tipo}" end def consultar_escrutinio escrutinio_xml = Nokogiri::XML(Net::HTTP.get(URI.parse(api_url))) escrutinios << Escrutinio.create_from_api(self, escrutinio_xml) end def ultimo_escrutinio escrutinios.final.first || escrutinios.first(:order => "hora DESC") end protected def api_url_pais "http://rsl00.epimg.net/elecciones/#{Settings["year"]}/generales/congreso/index.xml2" end def pais_url_pais "http://resultados.elpais.com/elecciones/#{Settings["year"]}/generales/congreso/" end def api_url_comunidad "http://rsl00.epimg.net/elecciones/#{Settings["year"]}/generales/congreso/#{id_api}/index.xml2" end def pais_url_comunidad "http://resultados.elpais.com/elecciones/#{Settings["year"]}/generales/congreso/#{id_api}/" end def api_url_provincia "http://rsl00.epimg.net/elecciones/#{Settings["year"]}/generales/congreso/#{padre.id_api}/#{id_api}.xml2" end def pais_url_provincia "http://resultados.elpais.com/elecciones/#{Settings["year"]}/generales/congreso/#{padre.id_api}/#{id_api}.html" end def api_url_municipio "http://rsl00.epimg.net/elecciones/#{Settings["year"]}/generales/congreso/#{padre.padre.id_api}/#{padre.id_api}/#{id_api}.xml2" end def pais_url_municipio "http://resultados.elpais.com/elecciones/#{Settings["year"]}/generales/congreso/#{padre.padre.id_api}/#{padre.id_api}/#{id_api}.html" end end <file_sep>/db/migrate/20111120122429_add_fields_to_territorio.rb class AddFieldsToTerritorio < ActiveRecord::Migration def change add_column :territorios, :tipo_api, :integer add_column :territorios, :id_api, :string add_column :territorios, :escanos, :integer end end <file_sep>/db/migrate/20111120122618_add_fields_to_escrutinio.rb class AddFieldsToEscrutinio < ActiveRecord::Migration def change add_column :escrutinios, :total_contabilizados, :integer add_column :escrutinios, :total_abstenciones, :integer add_column :escrutinios, :total_nulos, :integer add_column :escrutinios, :total_blanco, :integer add_column :escrutinios, :pct_contabilizados, :double add_column :escrutinios, :pct_abstenciones, :double add_column :escrutinios, :pct_nulos, :double add_column :escrutinios, :pct_blanco, :double end end <file_sep>/config/initializers/vcr.rb VCR.config do |c| c.allow_http_connections_when_no_cassette = true c.cassette_library_dir = 'db/vcr' c.stub_with :webmock # or :fakeweb end<file_sep>/db/migrate/20111120122757_add_fields_to_partido.rb class AddFieldsToPartido < ActiveRecord::Migration def change add_column :partidos, :id_api, :integer end end
3dd72b83640c81c2fa39d50df7b873228257e741
[ "Ruby" ]
20
Ruby
brenes/lodel20n
b2c08e2418915f7a262647232dd31fc37839feb8
245252b90254250dc2ec629e3049da226f148158
refs/heads/master
<repo_name>akihira0907/Balls<file_sep>/Downloads/Jissekai/hello.py import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as ani import math class Ball(): max_x = 7 min_x = -7 max_y = 7 min_y = -7 def __init__(self): self.x = 0.1 * np.random.randint(-50, 50) self.y = 0.1 * np.random.randint(-50, 50) self.vx = 0.03 * np.random.randint(-50, 50) self.vy = 0.03 * np.random.randint(-50, 50) self.cnt_of_escape = 0 def update(self, dt): self.x += self.vx * dt self.y += self.vy * dt if self.x > self.max_x: self.x = self.max_x self.velocity_x_update() elif self.x < self.min_x: self.x = self.min_x self.velocity_x_update() if self.y > self.max_y: self.y = self.max_y self.velocity_y_update() elif self.y < self.min_y: self.y = self.min_y self.velocity_y_update() def velocity_x_update(self): self.vx *= -0.01 * np.random.randint(90, 111) def velocity_y_update(self): self.vy *= -0.01 * np.random.randint(90, 111) def avoidance(b1, b2): b1.cnt_of_escape -= 1 distance = math.sqrt((b1.x-b2.x)**2 + (b1.y-b2.y)**2) if distance < 2.5 and b1.cnt_of_escape <= 0: b1.velocity_x_update() b1.velocity_y_update() b1.cnt_of_escape = 5 def update_ani(i): ax.cla() ax.set_xlim(-7, 7) ax.set_ylim(-7, 7) dt = 0.5 ball1.update(dt) for i in range(1, 5): ball[i].update(dt) for i in range(1, 5): avoidance(ball[i], ball1) ax.scatter(ball1.x, ball1.y, color="r", s=100) for i in range(1, 5): ax.scatter(ball[i].x, ball[i].y, color="b", s=100) ############################################################ ############################################################ ## plot 初期化 # グラフ仕様設定 fig = plt.figure() # Axes インスタンスを作成 ax = fig.add_subplot(111) # 軸 # 最大値と最小値⇒軸の範囲設定 # max_x = 5 # min_x = -5 # max_y = 5 # min_y = -5 # # ax.set_xlim(min_x, max_x) # ax.set_ylim(min_y, max_y) # 軸の縦横比, 正方形,単位あたりの長さが等しくなります ax.set_aspect('equal') # 軸の名前設定 ax.set_xlabel('X [m]') ax.set_ylabel('Y [m]') # その他グラフ仕様 ax.grid(True) # グリッド # 凡例 # ax.legend() # ステップ数表示 step_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) ball1 = Ball() # IT ball = [Ball()] * 5 for i in range(1, 5): ball[i] = Ball() animation = ani.FuncAnimation(fig, update_ani, interval=50, frames=1500) animation.save("output.mp4", writer="ffmpeg") plt.show() <file_sep>/Downloads/Jissekai/funcanimation.py import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure() def plot(data): plt.cla() plt.tick_params(labelbottom=False, labelleft=False, labelright=False, labeltop=False) plt.tick_params(bottom=False, left=False, right=False, top=False) x = np.random.randn(20) y = np.random.randn(20) # im = plt.plot(x) im = plt.scatter(x, y) ani = animation.FuncAnimation(fig, plot, interval=50) plt.show()
bfefa8867ea29323d4021d76eb90475d59781382
[ "Python" ]
2
Python
akihira0907/Balls
0dd3c806ab4b26a3a4461aeb1938a4bf20cbac54
471e4efcde4c0ffea85c6e3a6f22e273597bc2dc
refs/heads/master
<repo_name>math4j/mathology<file_sep>/src/Vectors/src/vectors/resources/Keyboard.properties input.text= comma.text=, add.text=Add subtract.text=Subtract multiply.text=Multiply sc_tr_product.text=Scalar Triple Product vc_tr_product.text=Vector Triple Product dot_pr.text=Dot Product cr_pr.text=Cross Product vec_a.text=A vec_b.text=B vec_c.text=C open_brace.text=( close_brace.text=) ok_button.text=OK reset_button.text=Reset <file_sep>/src/Calculus/build/classes/differentiation/resources/DifferentiationAboutBox.properties title = About: ${Application.title} ${Application.version} closeAboutBox.Action.text = &Close appDescLabel.text=<html>Calculus is a software toolkit used to perform all the desired calculus operations like: Differentiation & Integration.. versionLabel.text=Product Version\: vendorLabel.text=Vendor\: imageLabel.icon=c04.jpeg <file_sep>/executor/nbproject/private/private.properties compile.on.save=false do.depend=false do.jar=true javac.debug=true javadoc.preview=true jaxws.endorsed.dir=G:\\Java\\NetBeans 6.5.1\\java2\\modules\\ext\\jaxws21\\api:G:\\Java\\NetBeans 6.5.1\\ide10\\modules\\ext\\jaxb\\api user.properties.file=C:\\Documents and Settings\\Dinesh\\.netbeans\\6.5\\build.properties <file_sep>/executor/src/mathworld/resources/Set_path.properties path.text= ok.text=OK jLabel1.text=Enter the path of your jdk till bin folder: Form.title=Set path <file_sep>/src/Expression_Evaluator/src/calci_pg/Calci_pgView.java /* * Calci_pgView.java */ package calci_pg; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; /** * The application's main frame. */ public class Calci_pgView extends FrameView { public Calci_pgView(SingleFrameApplication app) { super(app); initComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = Calci_pgApp.getApplication().getMainFrame(); aboutBox = new Calci_pgAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } Calci_pgApp.getApplication().show(aboutBox); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); input = new javax.swing.JTextField(); plus_but = new javax.swing.JButton(); nine_but = new javax.swing.JButton(); one_but = new javax.swing.JButton(); four_but = new javax.swing.JButton(); seven_but = new javax.swing.JButton(); decimal_but = new javax.swing.JButton(); two_but = new javax.swing.JButton(); five_but = new javax.swing.JButton(); eight_but = new javax.swing.JButton(); comma_but = new javax.swing.JButton(); three_but = new javax.swing.JButton(); divide_but = new javax.swing.JButton(); mul_but = new javax.swing.JButton(); six_but = new javax.swing.JButton(); minus_but = new javax.swing.JButton(); power_but = new javax.swing.JButton(); ln_but = new javax.swing.JButton(); log_but = new javax.swing.JButton(); jButton19 = new javax.swing.JButton(); atan_but = new javax.swing.JButton(); acos_but = new javax.swing.JButton(); asin_but = new javax.swing.JButton(); jButton23 = new javax.swing.JButton(); tan_but = new javax.swing.JButton(); cos_but = new javax.swing.JButton(); sine_but = new javax.swing.JButton(); zero_but = new javax.swing.JButton(); jButton28 = new javax.swing.JButton(); jButton20 = new javax.swing.JButton(); jButton21 = new javax.swing.JButton(); clear_button = new javax.swing.JButton(); backspace_button = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); output = new javax.swing.JLabel(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); statusPanel = new javax.swing.JPanel(); javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator(); statusMessageLabel = new javax.swing.JLabel(); statusAnimationLabel = new javax.swing.JLabel(); progressBar = new javax.swing.JProgressBar(); mainPanel.setName("mainPanel"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(calci_pg.Calci_pgApp.class).getContext().getResourceMap(Calci_pgView.class); input.setText(resourceMap.getString("input.text")); // NOI18N input.setName("input"); // NOI18N plus_but.setText(resourceMap.getString("plus_but.text")); // NOI18N plus_but.setName("plus_but"); // NOI18N plus_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { plus_butMouseClicked(evt); } }); nine_but.setText(resourceMap.getString("nine_but.text")); // NOI18N nine_but.setName("nine_but"); // NOI18N nine_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { nine_butMouseClicked(evt); } }); one_but.setText(resourceMap.getString("one_but.text")); // NOI18N one_but.setName("one_but"); // NOI18N one_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { one_butMouseClicked(evt); } }); four_but.setText(resourceMap.getString("four_but.text")); // NOI18N four_but.setName("four_but"); // NOI18N four_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { four_butMouseClicked(evt); } }); seven_but.setText(resourceMap.getString("seven_but.text")); // NOI18N seven_but.setName("seven_but"); // NOI18N seven_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { seven_butMouseClicked(evt); } }); decimal_but.setText(resourceMap.getString("decimal_but.text")); // NOI18N decimal_but.setName("decimal_but"); // NOI18N decimal_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { decimal_butMouseClicked(evt); } }); two_but.setText(resourceMap.getString("two_but.text")); // NOI18N two_but.setName("two_but"); // NOI18N two_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { two_butMouseClicked(evt); } }); five_but.setText(resourceMap.getString("five_but.text")); // NOI18N five_but.setName("five_but"); // NOI18N five_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { five_butMouseClicked(evt); } }); eight_but.setText(resourceMap.getString("eight_but.text")); // NOI18N eight_but.setName("eight_but"); // NOI18N eight_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { eight_butMouseClicked(evt); } }); comma_but.setText(resourceMap.getString("comma_but.text")); // NOI18N comma_but.setName("comma_but"); // NOI18N comma_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { comma_butMouseClicked(evt); } }); three_but.setText(resourceMap.getString("three_but.text")); // NOI18N three_but.setName("three_but"); // NOI18N three_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { three_butMouseClicked(evt); } }); divide_but.setText(resourceMap.getString("divide_but.text")); // NOI18N divide_but.setName("divide_but"); // NOI18N divide_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { divide_butMouseClicked(evt); } }); mul_but.setText(resourceMap.getString("mul_but.text")); // NOI18N mul_but.setName("mul_but"); // NOI18N mul_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { mul_butMouseClicked(evt); } }); six_but.setText(resourceMap.getString("six_but.text")); // NOI18N six_but.setName("six_but"); // NOI18N six_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { six_butMouseClicked(evt); } }); minus_but.setText(resourceMap.getString("minus_but.text")); // NOI18N minus_but.setName("minus_but"); // NOI18N minus_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { minus_butMouseClicked(evt); } }); power_but.setText(resourceMap.getString("power_but.text")); // NOI18N power_but.setName("power_but"); // NOI18N power_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { power_butMouseClicked(evt); } }); ln_but.setText(resourceMap.getString("ln_but.text")); // NOI18N ln_but.setName("ln_but"); // NOI18N ln_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ln_butMouseClicked(evt); } }); log_but.setText(resourceMap.getString("log_but.text")); // NOI18N log_but.setName("log_but"); // NOI18N log_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { log_butMouseClicked(evt); } }); jButton19.setText(resourceMap.getString("jButton19.text")); // NOI18N jButton19.setName("jButton19"); // NOI18N jButton19.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton19MouseClicked(evt); } }); atan_but.setText(resourceMap.getString("atan_but.text")); // NOI18N atan_but.setName("atan_but"); // NOI18N atan_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { atan_butMouseClicked(evt); } }); acos_but.setText(resourceMap.getString("acos_but.text")); // NOI18N acos_but.setName("acos_but"); // NOI18N acos_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { acos_butMouseClicked(evt); } }); asin_but.setText(resourceMap.getString("asin_but.text")); // NOI18N asin_but.setName("asin_but"); // NOI18N asin_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { asin_butMouseClicked(evt); } }); jButton23.setText(resourceMap.getString("jButton23.text")); // NOI18N jButton23.setName("jButton23"); // NOI18N jButton23.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton23MouseClicked(evt); } }); tan_but.setText(resourceMap.getString("tan_but.text")); // NOI18N tan_but.setName("tan_but"); // NOI18N tan_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tan_butMouseClicked(evt); } }); cos_but.setText(resourceMap.getString("cos_but.text")); // NOI18N cos_but.setName("cos_but"); // NOI18N cos_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cos_butMouseClicked(evt); } }); sine_but.setText(resourceMap.getString("sine_but.text")); // NOI18N sine_but.setName("sine_but"); // NOI18N sine_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { sine_butMouseClicked(evt); } }); zero_but.setText(resourceMap.getString("zero_but.text")); // NOI18N zero_but.setName("zero_but"); // NOI18N zero_but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { zero_butMouseClicked(evt); } }); jButton28.setText(resourceMap.getString("jButton28.text")); // NOI18N jButton28.setName("jButton28"); // NOI18N jButton28.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton28MouseClicked(evt); } }); jButton20.setText(resourceMap.getString("jButton20.text")); // NOI18N jButton20.setName("jButton20"); // NOI18N jButton20.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton20MouseClicked(evt); } }); jButton21.setText(resourceMap.getString("jButton21.text")); // NOI18N jButton21.setName("jButton21"); // NOI18N jButton21.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton21MouseClicked(evt); } }); clear_button.setText(resourceMap.getString("clear_button.text")); // NOI18N clear_button.setName("clear_button"); // NOI18N clear_button.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { clear_buttonMouseClicked(evt); } }); backspace_button.setText(resourceMap.getString("backspace_button.text")); // NOI18N backspace_button.setName("backspace_button"); // NOI18N backspace_button.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { backspace_buttonMouseClicked(evt); } }); jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N jButton1.setName("jButton1"); // NOI18N jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); output.setText(resourceMap.getString("output.text")); // NOI18N output.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); output.setName("output"); // NOI18N javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addGap(103, 103, 103) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(mainPanelLayout.createSequentialGroup() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(clear_button, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(backspace_button, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton21, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton19, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton23, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(ln_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(log_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(power_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton28, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(45, 45, 45) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(seven_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(four_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(one_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(zero_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(five_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(two_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eight_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(nine_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(six_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(three_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(mainPanelLayout.createSequentialGroup() .addComponent(decimal_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(comma_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(60, 60, 60) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(sine_but, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cos_but, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tan_but, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(asin_but, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE) .addComponent(acos_but, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(atan_but, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(40, 40, 40) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(plus_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(minus_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(mul_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(divide_but, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, 884, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(99, 99, 99)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup() .addContainerGap(533, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(496, 496, 496)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup() .addContainerGap(220, Short.MAX_VALUE) .addComponent(output, javax.swing.GroupLayout.PREFERRED_SIZE, 735, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(131, 131, 131)) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(asin_but) .addGap(18, 18, 18) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cos_but) .addComponent(acos_but)) .addGap(18, 18, 18) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tan_but) .addComponent(atan_but))) .addGroup(mainPanelLayout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(backspace_button, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(clear_button, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(mainPanelLayout.createSequentialGroup() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(seven_but) .addComponent(nine_but) .addComponent(eight_but) .addComponent(log_but) .addComponent(jButton21) .addComponent(sine_but) .addComponent(plus_but)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(four_but) .addComponent(five_but) .addComponent(six_but) .addComponent(ln_but) .addComponent(jButton20)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(one_but) .addComponent(two_but) .addComponent(three_but) .addComponent(power_but) .addComponent(jButton19)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(zero_but) .addComponent(decimal_but) .addComponent(comma_but) .addComponent(jButton28) .addComponent(jButton23))) .addGroup(mainPanelLayout.createSequentialGroup() .addComponent(minus_but) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(mul_but) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(divide_but))))))) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(33, 33, 33) .addComponent(output, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(42, Short.MAX_VALUE)) ); menuBar.setName("menuBar"); // NOI18N fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(calci_pg.Calci_pgApp.class).getContext().getActionMap(Calci_pgView.class, this); exitMenuItem.setAction(actionMap.get("quit")); // NOI18N exitMenuItem.setName("exitMenuItem"); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); statusPanel.setName("statusPanel"); // NOI18N statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N statusMessageLabel.setName("statusMessageLabel"); // NOI18N statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N progressBar.setName("progressBar"); // NOI18N javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 1077, Short.MAX_VALUE) .addGroup(statusPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(statusMessageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 907, Short.MAX_VALUE) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusAnimationLabel) .addContainerGap()) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(statusMessageLabel) .addComponent(statusAnimationLabel) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(3, 3, 3)) ); setComponent(mainPanel); setMenuBar(menuBar); setStatusBar(statusPanel); }// </editor-fold>//GEN-END:initComponents private void plus_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_plus_butMouseClicked String temp = input.getText(); temp = temp + "+"; input.setText(temp); }//GEN-LAST:event_plus_butMouseClicked private void minus_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_minus_butMouseClicked String temp = input.getText(); temp = temp + "-"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_minus_butMouseClicked private void mul_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mul_butMouseClicked String temp = input.getText(); temp = temp + "*"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_mul_butMouseClicked private void divide_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_divide_butMouseClicked String temp = input.getText(); temp = temp + "/"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_divide_butMouseClicked private void nine_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_nine_butMouseClicked String temp = input.getText(); temp = temp + "9"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_nine_butMouseClicked private void six_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_six_butMouseClicked String temp = input.getText(); temp = temp + "6"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_six_butMouseClicked private void three_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_three_butMouseClicked String temp = input.getText(); temp = temp + "3"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_three_butMouseClicked private void eight_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_eight_butMouseClicked String temp = input.getText(); temp = temp + "8"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_eight_butMouseClicked private void five_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_five_butMouseClicked String temp = input.getText(); temp = temp + "5"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_five_butMouseClicked private void two_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_two_butMouseClicked String temp = input.getText(); temp = temp + "2"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_two_butMouseClicked private void decimal_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_decimal_butMouseClicked String temp = input.getText(); temp = temp + "."; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_decimal_butMouseClicked private void seven_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_seven_butMouseClicked String temp = input.getText(); temp = temp + "7"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_seven_butMouseClicked private void four_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_four_butMouseClicked String temp = input.getText(); temp = temp + "4"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_four_butMouseClicked private void one_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_one_butMouseClicked String temp = input.getText(); temp = temp + "1"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_one_butMouseClicked private void zero_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_zero_butMouseClicked String temp = input.getText(); temp = temp + "0"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_zero_butMouseClicked private void sine_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sine_butMouseClicked String temp = input.getText(); temp = temp + "Sin("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_sine_butMouseClicked private void cos_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cos_butMouseClicked String temp = input.getText(); temp = temp + "cos("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_cos_butMouseClicked private void tan_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tan_butMouseClicked String temp = input.getText(); temp = temp + "tan("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_tan_butMouseClicked private void jButton23MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton23MouseClicked String temp = input.getText(); temp = temp + ")"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_jButton23MouseClicked private void asin_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_asin_butMouseClicked String temp = input.getText(); temp = temp + "asin("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_asin_butMouseClicked private void acos_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_acos_butMouseClicked String temp = input.getText(); temp = temp + "acos("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_acos_butMouseClicked private void atan_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_atan_butMouseClicked String temp = input.getText(); temp = temp + "atan("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_atan_butMouseClicked private void jButton19MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton19MouseClicked String temp = input.getText(); temp = temp + "("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_jButton19MouseClicked private void log_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_log_butMouseClicked String temp = input.getText(); temp = temp + "log("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_log_butMouseClicked private void ln_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ln_butMouseClicked String temp = input.getText(); temp = temp + "ln("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_ln_butMouseClicked private void power_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_power_butMouseClicked String temp = input.getText(); temp = temp + "^"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_power_butMouseClicked private void jButton28MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton28MouseClicked String temp = input.getText(); temp = temp + "exp("; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_jButton28MouseClicked private void jButton21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton21MouseClicked String temp = input.getText(); temp = temp + "]"; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_jButton21MouseClicked private void jButton20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton20MouseClicked String temp = input.getText(); temp = temp + "["; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_jButton20MouseClicked private void clear_buttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clear_buttonMouseClicked input.setText(" "); // TODO add your handling code here: }//GEN-LAST:event_clear_buttonMouseClicked private void backspace_buttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backspace_buttonMouseClicked String s = input.getText(); if(s.length() == 0 || s == null){ return; //... what to do for null text or no text } s = new StringBuffer(s).substring(0, s.length()-1).toString(); input.setText(s); }//GEN-LAST:event_backspace_buttonMouseClicked private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked String msg = "[" + input.getText() + "]"; Expression exp = new Expression(msg); if(exp.compile().equals(Expression.NO_ERROR_MSG)){ output.setText(Double.toString(exp.getValue(msg, 0))); } else{ output.setText("Incorrect input"); } }//GEN-LAST:event_jButton1MouseClicked private void comma_butMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_comma_butMouseClicked String temp = input.getText(); temp = temp + ","; input.setText(temp); // TODO add your handling code here: }//GEN-LAST:event_comma_butMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton acos_but; private javax.swing.JButton asin_but; private javax.swing.JButton atan_but; private javax.swing.JButton backspace_button; private javax.swing.JButton clear_button; private javax.swing.JButton comma_but; private javax.swing.JButton cos_but; private javax.swing.JButton decimal_but; private javax.swing.JButton divide_but; private javax.swing.JButton eight_but; private javax.swing.JButton five_but; private javax.swing.JButton four_but; private javax.swing.JTextField input; private javax.swing.JButton jButton1; private javax.swing.JButton jButton19; private javax.swing.JButton jButton20; private javax.swing.JButton jButton21; private javax.swing.JButton jButton23; private javax.swing.JButton jButton28; private javax.swing.JButton ln_but; private javax.swing.JButton log_but; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; private javax.swing.JButton minus_but; private javax.swing.JButton mul_but; private javax.swing.JButton nine_but; private javax.swing.JButton one_but; private javax.swing.JLabel output; private javax.swing.JButton plus_but; private javax.swing.JButton power_but; private javax.swing.JProgressBar progressBar; private javax.swing.JButton seven_but; private javax.swing.JButton sine_but; private javax.swing.JButton six_but; private javax.swing.JLabel statusAnimationLabel; private javax.swing.JLabel statusMessageLabel; private javax.swing.JPanel statusPanel; private javax.swing.JButton tan_but; private javax.swing.JButton three_but; private javax.swing.JButton two_but; private javax.swing.JButton zero_but; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; } <file_sep>/src/Vectors/src/vectors/resources/Select_a_Vector.properties jLabel1.text=Select a Vector jLabel2.text=Vector is display_field.text= select_ok_button.text=OK display_ok_button.text=OK <file_sep>/src/Non_Linear_Equation_Solver/src/polynomial_solver/Keyboard.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Keyboard.java * * Created on Aug 3, 2009, 9:50:55 PM */ package polynomial_solver; import java.awt.event.KeyEvent; /** * * @author Dinesh */ public class Keyboard extends javax.swing.JFrame { int key_position = 0; //....... DEFAULT POSITION OF THE KEY String expression;//........ EXPRESSION. /** Creates new form Keyboard */ public Keyboard() { initComponents(); otherInitilization(); } private void otherInitilization(){ key_position = 0; expression = ""; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { backspace = new javax.swing.JButton(); clear = new javax.swing.JButton(); input_field = new javax.swing.JTextField(); cosec = new javax.swing.JButton(); asin = new javax.swing.JButton(); acosec = new javax.swing.JButton(); asec = new javax.swing.JButton(); acos = new javax.swing.JButton(); sec = new javax.swing.JButton(); open_brace3 = new javax.swing.JButton(); sin = new javax.swing.JButton(); close_brace3 = new javax.swing.JButton(); cos = new javax.swing.JButton(); acot = new javax.swing.JButton(); atan = new javax.swing.JButton(); cot = new javax.swing.JButton(); tan = new javax.swing.JButton(); open_brace2 = new javax.swing.JButton(); exp = new javax.swing.JButton(); log = new javax.swing.JButton(); close_brace2 = new javax.swing.JButton(); multiply = new javax.swing.JButton(); open_brace1 = new javax.swing.JButton(); plus = new javax.swing.JButton(); power = new javax.swing.JButton(); divide = new javax.swing.JButton(); minus = new javax.swing.JButton(); close_brace1 = new javax.swing.JButton(); space = new javax.swing.JButton(); zero = new javax.swing.JButton(); one = new javax.swing.JButton(); four = new javax.swing.JButton(); seven = new javax.swing.JButton(); const_pi = new javax.swing.JButton(); dot = new javax.swing.JButton(); two = new javax.swing.JButton(); five = new javax.swing.JButton(); eight = new javax.swing.JButton(); var_x = new javax.swing.JButton(); const_e = new javax.swing.JButton(); comma = new javax.swing.JButton(); three = new javax.swing.JButton(); six = new javax.swing.JButton(); nine = new javax.swing.JButton(); ok = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setName("Form"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(polynomial_solver.Polynomial_SolverApp.class).getContext().getResourceMap(Keyboard.class); backspace.setText(resourceMap.getString("backspace.text")); // NOI18N backspace.setName("backspace"); // NOI18N backspace.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { backspaceMouseClicked(evt); } }); clear.setText(resourceMap.getString("clear.text")); // NOI18N clear.setName("clear"); // NOI18N clear.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { clearMouseClicked(evt); } }); input_field.setFont(resourceMap.getFont("input_field.font")); // NOI18N input_field.setName("input_field"); // NOI18N input_field.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { input_fieldMouseClicked(evt); } }); input_field.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { input_fieldKeyPressed(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { input_fieldKeyTyped(evt); } }); cosec.setText(resourceMap.getString("cosec.text")); // NOI18N cosec.setName("cosec"); // NOI18N cosec.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cosecMouseClicked(evt); } }); asin.setText(resourceMap.getString("asin.text")); // NOI18N asin.setName("asin"); // NOI18N asin.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { asinMouseClicked(evt); } }); acosec.setText(resourceMap.getString("acosec.text")); // NOI18N acosec.setName("acosec"); // NOI18N acosec.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { acosecMouseClicked(evt); } }); asec.setText(resourceMap.getString("asec.text")); // NOI18N asec.setName("asec"); // NOI18N asec.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { asecMouseClicked(evt); } }); acos.setText(resourceMap.getString("acos.text")); // NOI18N acos.setName("acos"); // NOI18N acos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { acosMouseClicked(evt); } }); sec.setText(resourceMap.getString("sec.text")); // NOI18N sec.setName("sec"); // NOI18N sec.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { secMouseClicked(evt); } }); open_brace3.setText(resourceMap.getString("open_brace3.text")); // NOI18N open_brace3.setName("open_brace3"); // NOI18N open_brace3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { open_brace3MouseClicked(evt); } }); sin.setText(resourceMap.getString("sin.text")); // NOI18N sin.setName("sin"); // NOI18N sin.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { sinMouseClicked(evt); } }); close_brace3.setText(resourceMap.getString("close_brace3.text")); // NOI18N close_brace3.setName("close_brace3"); // NOI18N close_brace3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { close_brace3MouseClicked(evt); } }); cos.setText(resourceMap.getString("cos.text")); // NOI18N cos.setName("cos"); // NOI18N cos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cosMouseClicked(evt); } }); acot.setText(resourceMap.getString("acot.text")); // NOI18N acot.setName("acot"); // NOI18N acot.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { acotMouseClicked(evt); } }); atan.setText(resourceMap.getString("atan.text")); // NOI18N atan.setName("atan"); // NOI18N atan.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { atanMouseClicked(evt); } }); cot.setText(resourceMap.getString("cot.text")); // NOI18N cot.setName("cot"); // NOI18N cot.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cotMouseClicked(evt); } }); tan.setText(resourceMap.getString("tan.text")); // NOI18N tan.setName("tan"); // NOI18N tan.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tanMouseClicked(evt); } }); open_brace2.setText(resourceMap.getString("open_brace2.text")); // NOI18N open_brace2.setName("open_brace2"); // NOI18N open_brace2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { open_brace2MouseClicked(evt); } }); exp.setText(resourceMap.getString("exp.text")); // NOI18N exp.setName("exp"); // NOI18N exp.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { expMouseClicked(evt); } }); log.setText(resourceMap.getString("log.text")); // NOI18N log.setName("log"); // NOI18N log.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { logMouseClicked(evt); } }); close_brace2.setText(resourceMap.getString("close_brace2.text")); // NOI18N close_brace2.setName("close_brace2"); // NOI18N close_brace2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { close_brace2MouseClicked(evt); } }); multiply.setText(resourceMap.getString("multiply.text")); // NOI18N multiply.setName("multiply"); // NOI18N multiply.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { multiplyMouseClicked(evt); } }); open_brace1.setText(resourceMap.getString("open_brace1.text")); // NOI18N open_brace1.setName("open_brace1"); // NOI18N open_brace1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { open_brace1MouseClicked(evt); } }); plus.setText(resourceMap.getString("plus.text")); // NOI18N plus.setName("plus"); // NOI18N plus.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { plusMouseClicked(evt); } }); power.setText(resourceMap.getString("power.text")); // NOI18N power.setName("power"); // NOI18N power.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { powerMouseClicked(evt); } }); divide.setText(resourceMap.getString("divide.text")); // NOI18N divide.setName("divide"); // NOI18N divide.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { divideMouseClicked(evt); } }); minus.setText(resourceMap.getString("minus.text")); // NOI18N minus.setName("minus"); // NOI18N minus.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { minusMouseClicked(evt); } }); close_brace1.setText(resourceMap.getString("close_brace1.text")); // NOI18N close_brace1.setName("close_brace1"); // NOI18N close_brace1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { close_brace1MouseClicked(evt); } }); space.setText(resourceMap.getString("space.text")); // NOI18N space.setName("space"); // NOI18N space.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { spaceMouseClicked(evt); } }); zero.setText(resourceMap.getString("zero.text")); // NOI18N zero.setName("zero"); // NOI18N zero.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { zeroMouseClicked(evt); } }); one.setText(resourceMap.getString("one.text")); // NOI18N one.setName("one"); // NOI18N one.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { oneMouseClicked(evt); } }); four.setText(resourceMap.getString("four.text")); // NOI18N four.setName("four"); // NOI18N four.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { fourMouseClicked(evt); } }); seven.setText(resourceMap.getString("seven.text")); // NOI18N seven.setName("seven"); // NOI18N seven.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { sevenMouseClicked(evt); } }); const_pi.setText(resourceMap.getString("const_pi.text")); // NOI18N const_pi.setName("const_pi"); // NOI18N const_pi.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { const_piMouseClicked(evt); } }); dot.setText(resourceMap.getString("dot.text")); // NOI18N dot.setName("dot"); // NOI18N dot.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { dotMouseClicked(evt); } }); two.setText(resourceMap.getString("two.text")); // NOI18N two.setName("two"); // NOI18N two.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { twoMouseClicked(evt); } }); five.setText(resourceMap.getString("five.text")); // NOI18N five.setName("five"); // NOI18N five.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { fiveMouseClicked(evt); } }); eight.setText(resourceMap.getString("eight.text")); // NOI18N eight.setName("eight"); // NOI18N eight.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { eightMouseClicked(evt); } }); var_x.setText(resourceMap.getString("var_x.text")); // NOI18N var_x.setName("var_x"); // NOI18N var_x.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { var_xMouseClicked(evt); } }); const_e.setText(resourceMap.getString("const_e.text")); // NOI18N const_e.setName("const_e"); // NOI18N const_e.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { const_eMouseClicked(evt); } }); comma.setText(resourceMap.getString("comma.text")); // NOI18N comma.setName("comma"); // NOI18N comma.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { commaMouseClicked(evt); } }); three.setText(resourceMap.getString("three.text")); // NOI18N three.setName("three"); // NOI18N three.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { threeMouseClicked(evt); } }); six.setText(resourceMap.getString("six.text")); // NOI18N six.setName("six"); // NOI18N six.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { sixMouseClicked(evt); } }); nine.setText(resourceMap.getString("nine.text")); // NOI18N nine.setName("nine"); // NOI18N nine.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { nineMouseClicked(evt); } }); ok.setText(resourceMap.getString("ok.text")); // NOI18N ok.setName("ok"); // NOI18N ok.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { okMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 792, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(backspace) .addGap(32, 32, 32) .addComponent(clear)) .addGroup(layout.createSequentialGroup() .addGap(81, 81, 81) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(input_field, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 701, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(cosec, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(asin, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(acosec, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(asec, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(acos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(sec, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(open_brace3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(sin, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(close_brace3, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE) .addComponent(cos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(acot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(atan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(cot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(tan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(open_brace2, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(exp, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE) .addComponent(log, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE) .addComponent(close_brace2, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(multiply, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(open_brace1, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE) .addComponent(plus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(power, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(divide, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(minus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(close_brace1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2)))) .addComponent(space, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(zero, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(one, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(four, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE) .addComponent(seven, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(const_pi, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(dot, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(two, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(five, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(eight, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(var_x, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(const_e, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(comma, 0, 0, Short.MAX_VALUE) .addComponent(three, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(six, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nine, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)) .addGap(48, 48, 48))))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(358, Short.MAX_VALUE) .addComponent(ok, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(362, 362, 362)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 413, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(77, 77, 77) .addComponent(input_field, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(clear) .addComponent(backspace)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(open_brace3) .addComponent(const_e) .addComponent(var_x) .addComponent(const_pi) .addComponent(close_brace3) .addComponent(open_brace2) .addComponent(close_brace2) .addComponent(open_brace1) .addComponent(close_brace1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(sin) .addComponent(cos) .addComponent(tan) .addComponent(plus) .addComponent(seven) .addComponent(eight) .addComponent(nine) .addComponent(minus) .addComponent(log)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cosec) .addComponent(sec) .addComponent(cot) .addComponent(divide) .addComponent(four) .addComponent(five) .addComponent(six) .addComponent(multiply) .addComponent(exp)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(asin) .addComponent(acos) .addComponent(atan) .addComponent(power) .addComponent(one) .addComponent(two) .addComponent(three)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(acosec) .addComponent(asec) .addComponent(acot) .addComponent(zero) .addComponent(dot) .addComponent(comma) .addComponent(space)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addComponent(ok) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void displayMe(String str, int offset){ expression = input_field.getText(); if(key_position == 0){ expression = str + expression; } else if(key_position == expression.length()){ expression = expression + str; } else{ String temp = new String(expression); String temp_1 = temp.substring(key_position); temp = new String(temp.substring(0, key_position)); temp += str; temp += temp_1; expression = temp; } key_position += offset; input_field.setText(expression+""); } private void backspaceMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backspaceMouseClicked if(key_position > 0){ StringBuffer temp = new StringBuffer(expression); temp.deleteCharAt(key_position-1); expression = temp.toString(); input_field.setText(expression); --key_position; } }//GEN-LAST:event_backspaceMouseClicked private void clearMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearMouseClicked input_field.setText(""); key_position = 0; }//GEN-LAST:event_clearMouseClicked private void input_fieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_input_fieldMouseClicked key_position = expression.length(); }//GEN-LAST:event_input_fieldMouseClicked private void input_fieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_input_fieldKeyPressed int key = evt.getKeyCode(); switch(key){ case KeyEvent.VK_LEFT: if(key_position >0){ --key_position; } break; case KeyEvent.VK_RIGHT: if(key_position < input_field.getText().length()){ ++key_position; } break; } }//GEN-LAST:event_input_fieldKeyPressed private void input_fieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_input_fieldKeyTyped ++key_position; }//GEN-LAST:event_input_fieldKeyTyped private void cosecMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cosecMouseClicked displayMe("Cosec(", 6); }//GEN-LAST:event_cosecMouseClicked private void asinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_asinMouseClicked displayMe("ASin(", 5); }//GEN-LAST:event_asinMouseClicked private void acosecMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_acosecMouseClicked displayMe("ACosec(", 7); }//GEN-LAST:event_acosecMouseClicked private void asecMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_asecMouseClicked displayMe("ASec(", 5); }//GEN-LAST:event_asecMouseClicked private void acosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_acosMouseClicked displayMe("ACos(", 5); }//GEN-LAST:event_acosMouseClicked private void secMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_secMouseClicked displayMe("Sec(", 4); }//GEN-LAST:event_secMouseClicked private void open_brace3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_open_brace3MouseClicked displayMe("{", 1); }//GEN-LAST:event_open_brace3MouseClicked private void sinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sinMouseClicked displayMe("Sin(", 4); }//GEN-LAST:event_sinMouseClicked private void close_brace3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_close_brace3MouseClicked displayMe("}", 1); }//GEN-LAST:event_close_brace3MouseClicked private void cosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cosMouseClicked displayMe("Cos(", 4); }//GEN-LAST:event_cosMouseClicked private void acotMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_acotMouseClicked displayMe("ACot(", 5); }//GEN-LAST:event_acotMouseClicked private void atanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_atanMouseClicked displayMe("ATan(", 5); }//GEN-LAST:event_atanMouseClicked private void cotMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cotMouseClicked displayMe("Cot(", 4); }//GEN-LAST:event_cotMouseClicked private void tanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tanMouseClicked displayMe("Tan(", 4); }//GEN-LAST:event_tanMouseClicked private void open_brace2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_open_brace2MouseClicked displayMe("[", 1); }//GEN-LAST:event_open_brace2MouseClicked private void expMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_expMouseClicked displayMe("Exp(", 4); }//GEN-LAST:event_expMouseClicked private void logMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logMouseClicked displayMe("Log(", 4); }//GEN-LAST:event_logMouseClicked private void close_brace2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_close_brace2MouseClicked displayMe("]", 1); }//GEN-LAST:event_close_brace2MouseClicked private void multiplyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_multiplyMouseClicked displayMe("*", 1); }//GEN-LAST:event_multiplyMouseClicked private void open_brace1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_open_brace1MouseClicked displayMe("(", 1); }//GEN-LAST:event_open_brace1MouseClicked private void plusMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_plusMouseClicked displayMe("+", 1); }//GEN-LAST:event_plusMouseClicked private void powerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_powerMouseClicked displayMe("^", 1); }//GEN-LAST:event_powerMouseClicked private void divideMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_divideMouseClicked displayMe("/", 1); }//GEN-LAST:event_divideMouseClicked private void minusMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_minusMouseClicked displayMe("-", 1); }//GEN-LAST:event_minusMouseClicked private void close_brace1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_close_brace1MouseClicked displayMe(")", 1); }//GEN-LAST:event_close_brace1MouseClicked private void spaceMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_spaceMouseClicked displayMe(" ", 1); }//GEN-LAST:event_spaceMouseClicked private void zeroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_zeroMouseClicked displayMe("0", 1); }//GEN-LAST:event_zeroMouseClicked private void oneMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_oneMouseClicked displayMe("1", 1); }//GEN-LAST:event_oneMouseClicked private void fourMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fourMouseClicked displayMe("4", 1); }//GEN-LAST:event_fourMouseClicked private void sevenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sevenMouseClicked displayMe("7", 1); }//GEN-LAST:event_sevenMouseClicked private void const_piMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_const_piMouseClicked displayMe("PI", 2); }//GEN-LAST:event_const_piMouseClicked private void dotMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dotMouseClicked displayMe(".", 1); }//GEN-LAST:event_dotMouseClicked private void twoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_twoMouseClicked displayMe("2", 1); }//GEN-LAST:event_twoMouseClicked private void fiveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fiveMouseClicked displayMe("5", 1); }//GEN-LAST:event_fiveMouseClicked private void eightMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_eightMouseClicked displayMe("8", 1); }//GEN-LAST:event_eightMouseClicked private void var_xMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_var_xMouseClicked displayMe("x", 1); }//GEN-LAST:event_var_xMouseClicked private void const_eMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_const_eMouseClicked displayMe("E", 1); }//GEN-LAST:event_const_eMouseClicked private void commaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_commaMouseClicked displayMe(",", 1); }//GEN-LAST:event_commaMouseClicked private void threeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_threeMouseClicked displayMe("3", 1); }//GEN-LAST:event_threeMouseClicked private void sixMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sixMouseClicked displayMe("6", 1); }//GEN-LAST:event_sixMouseClicked private void nineMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_nineMouseClicked displayMe("9", 1); }//GEN-LAST:event_nineMouseClicked private void okMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okMouseClicked this.setVisible(false); Polynomial_SolverView.valueEntry(input_field.getText()); }//GEN-LAST:event_okMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Keyboard().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton acos; private javax.swing.JButton acosec; private javax.swing.JButton acot; private javax.swing.JButton asec; private javax.swing.JButton asin; private javax.swing.JButton atan; private javax.swing.JButton backspace; private javax.swing.JButton clear; private javax.swing.JButton close_brace1; private javax.swing.JButton close_brace2; private javax.swing.JButton close_brace3; private javax.swing.JButton comma; private javax.swing.JButton const_e; private javax.swing.JButton const_pi; private javax.swing.JButton cos; private javax.swing.JButton cosec; private javax.swing.JButton cot; private javax.swing.JButton divide; private javax.swing.JButton dot; private javax.swing.JButton eight; private javax.swing.JButton exp; private javax.swing.JButton five; private javax.swing.JButton four; private javax.swing.JTextField input_field; private javax.swing.JButton log; private javax.swing.JButton minus; private javax.swing.JButton multiply; private javax.swing.JButton nine; private javax.swing.JButton ok; private javax.swing.JButton one; private javax.swing.JButton open_brace1; private javax.swing.JButton open_brace2; private javax.swing.JButton open_brace3; private javax.swing.JButton plus; private javax.swing.JButton power; private javax.swing.JButton sec; private javax.swing.JButton seven; private javax.swing.JButton sin; private javax.swing.JButton six; private javax.swing.JButton space; private javax.swing.JButton tan; private javax.swing.JButton three; private javax.swing.JButton two; private javax.swing.JButton var_x; private javax.swing.JButton zero; // End of variables declaration//GEN-END:variables } <file_sep>/src/Matrix_Solver/src/priya1/Incompatibility_Exception.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package priya1; /** * * @author Mahesh * @since June 29, 2009 */ public class Incompatibility_Exception extends java.lang.Exception { public Incompatibility_Exception(){ } public void display(){ System.err.println("The operation to be performed is incompatible"); } }<file_sep>/src/Vectors/src/vectors/Vector_Storage.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vectors; //import java.util.ArrayList; /** * * @author Dinesh */ public class Vector_Storage { private static Vector vectorA = new Vector("A"); private static Vector vectorB = new Vector("B"); private static Vector vectorC = new Vector("C"); public static void setVector(Vector v, String name){ if(name.equalsIgnoreCase("A")){ vectorA = new Vector(v, name); } else if(name.equalsIgnoreCase("B")){ vectorB = new Vector(v, name); } else if(name.equalsIgnoreCase("C")){ vectorC = new Vector(v, name); } } public static void removeVector(String name){ Vector temp = new Vector(name); setVector(temp, name); } public static String display(String name){ if(name.equalsIgnoreCase("A")){ return vectorA.toString(); } else if(name.equalsIgnoreCase("B")){ return vectorB.toString(); } else if(name.equalsIgnoreCase("C")){ return vectorC.toString(); } //..... DUMMY CODE... return "Billa"; } public static Vector getVector(String name){ if(name.equalsIgnoreCase("A")){ return vectorA; } else if(name.equalsIgnoreCase("B")){ return vectorB; } else if(name.equalsIgnoreCase("C")){ return vectorC; } //..... DUMMY CODE... return new Vector("A"); } }
1c7030353d5596fd720ecdb80c6defb9355ab867
[ "Java", "INI" ]
9
INI
math4j/mathology
94136d3f97c3c8c9a92d89121b743910c5584573
0d756b519168b0d029c956fa6a57b227b2a0f99b
refs/heads/master
<repo_name>dangduycuong/MasterSearch<file_sep>/TestFilter/TestFilter/BaseRouter/BaseNetwork.swift // // BaseNetwork.swift // TestFilter // // Created by <NAME> on 2/4/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import SwiftyJSON enum HTTPMethod { case get case post case put var value: String { get { switch self { case .get: return "GET" case .post: return "POST" case .put: return "PUT" } } } } enum ServerAPI: NSInteger { case Youtube_v3_API //https://rapidapi.com/ytdlfree/api/youtube-v31/endpoints case VivaCityDocumentationAPIDocumentation //https://rapidapi.com/din-dins-club-limited-din-dins-club-limited-default/api/viva-city-documentation } enum Result<Success, Error: Swift.Error> { case success(Success) case failure(Error) } // override the Result.get() method extension Result { func get() throws -> Success { switch self { case .success(let value): return value case .failure(let error): throw error } } } // use generics - this is where you can decode your data extension Result where Success == Data { func decoded<T: Decodable>(using decoder: JSONDecoder = .init()) throws -> T { let data = try get() return try decoder.decode(T.self, from: data) } } class BaseNetwork { // static let shared: BaseNetwork = BaseNetwork() static var SERVER: ServerAPI = ServerAPI.Youtube_v3_API var fullURL: URL { switch (BaseNetwork.SERVER) { case .Youtube_v3_API: return URL.init(string: "\(baseURLString)\(contextPathString)\(path)")! case .VivaCityDocumentationAPIDocumentation: return URL.init(string: "\(baseURLString)\(contextPathString)\(path)")! } } var fullStringURL: String { switch (BaseNetwork.SERVER) { case .Youtube_v3_API: return "\(baseURLString)\(contextPathString)\(path)" case .VivaCityDocumentationAPIDocumentation: return "\(baseURLString)\(contextPathString)\(path)" } } var serverURL: URL { switch (BaseNetwork.SERVER) { case .Youtube_v3_API: return URL.init(string: "\(baseURLString)\(contextPathString)")! case .VivaCityDocumentationAPIDocumentation: return URL.init(string: "\(baseURLString)\(contextPathString)")! } } var baseURLString: String { switch (BaseNetwork.SERVER) { case .Youtube_v3_API: return "https://youtube-v31.p.rapidapi.com" //https://viva-city-documentation.p.rapidapi.com case .VivaCityDocumentationAPIDocumentation: return "https://viva-city-documentation.p.rapidapi.com" } } var contextPathString: String { switch (BaseNetwork.SERVER) { case .Youtube_v3_API: return "" case .VivaCityDocumentationAPIDocumentation: return "/venue-i18n/" } } var basePORTString: UInt16 { switch (BaseNetwork.SERVER) { case .Youtube_v3_API: return 8761 case .VivaCityDocumentationAPIDocumentation: return 9898 } } var path: String { fatalError("[\(#function))] Must be overridden in subclass") } var method: HTTPMethod { fatalError("[\(#function))] Must be overridden in subclass") } var parameters: [URLQueryItem]? { fatalError("[\(#function))] Must be overridden in subclass") } var headerFields: [String: String]? { fatalError("[\(#function))] Must be overridden in subclass") } func getData(completion: @escaping(Result<Data, Error>) -> Void) { var builder = URLComponents(string: fullStringURL) builder?.queryItems = parameters guard let url = builder?.url else { return } var request = URLRequest(url: url) request.httpMethod = method.value // let boundary = "Boundary-\(UUID().uuidString)" // request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.cachePolicy = .useProtocolCachePolicy request.timeoutInterval = 30 request.allHTTPHeaderFields = headerFields let dataTask = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in print("fullURL: ", self.fullStringURL) print("params: ", url.queryDictionary as Any) print("header: ", self.headerFields as Any) print("json: ") if let error = error { completion(.failure(error)) return } if let response = response { let httpResponse = response as! HTTPURLResponse let status = httpResponse.statusCode switch status { case 200: break //print("Thanh cong") default: break } if !(200...299).contains(httpResponse.statusCode) && !(httpResponse.statusCode == 304) { if let httpError = error {// ... convert httpResponse.statusCode into a more readable error // completion(.failure(httpError as! Error)) completion(.failure(httpError)) } } if let data = data { completion(.success(data)) if let json = try? JSON(data: data) { print(json as Any) } } } }) dataTask.resume() } } //class BaseNetwork { // static let shared: BaseNetwork = BaseNetwork() // // func getDataFromAPI<T: Codable>(url: URL, completion: @escaping(T)->()) { // URLSession.shared.dataTask(with: url) { (data, response, error) in // if error != nil { // print(error as Any) // return // } // // guard let data = data else { return } // // do { // let data = try JSONDecoder().decode(T.self, from: data) // // DispatchQueue.main.async { // completion(data) // print("urlRequest: ", url) // // if let data = data, let dataString = String(data: data, encoding: .utf8) { // // print("Response json:\n", dataString) // // } // } // } catch let error { // print("decode error: ", error) // } // }.resume() // } //} // ////// ////// BaseURL.swift ////// GenericsAPI ////// ////// Created by <NAME> on 1/3/20. ////// Copyright © 2020 <NAME>. All rights reserved. ////// //// // //enum URLFactory: String { // case login // case chi_tiet // case thiet_bi // case diem_xung_yeu // case search // // var URL: URL { // func generalUrlComponent(host: String, port: Int?, path: String, queryItems: [URLQueryItem]) -> URL { // var urlComponents = URLComponents() // urlComponents.scheme = "http" // urlComponents.host = host // urlComponents.port = port // urlComponents.path = path // urlComponents.queryItems = queryItems // // return urlComponents.url! // } // // //path of url // switch self { // case .chi_tiet: // return generalUrlComponent(host: "10.240.232.79", // port: 145, // path: "", // queryItems: [URLQueryItem(name: "", value: "")]) // case .thiet_bi: // return generalUrlComponent(host: "", port: 8060, path: "", queryItems: [URLQueryItem(name: "", value: "")]) // case .diem_xung_yeu: // return generalUrlComponent(host: "10.240.232.79", port: 8060, path: "/QLCTKT/rest/bts360Controller/getListCriticalPoint", queryItems: [ // URLQueryItem(name: "fromDate", value: "04/10/2019"), // URLQueryItem(name: "toDate", value: "04/10/2019"), // URLQueryItem(name: "pageIndex", value: "0"), // URLQueryItem(name: "rowPage", value: "10") // ]) // case .login: // return generalUrlComponent(host: "10.240.232.68", port: 8060, path: "/QLCTKT/rest/authen/login", queryItems: [ // URLQueryItem(name: "username", value: "UserDefaults.standard.string(forKey: UserDefaultKeys.userName)"), // URLQueryItem(name: "password", value: "UserDefaults.standard.string(forKey: UserDefaultKeys.password)"), // URLQueryItem(name: "imeiMoblie", value: "IOS") // ]) // case .search: // return generalUrlComponent(host: "www.thecocktaildb.com", port: nil, path: "/api/json/v1/1/search.php", queryItems: [ // URLQueryItem(name: "rowPage", value: "10") // ]) // } // } //} <file_sep>/TestFilter/TestFilter/Controller/YoutubeSuggestViewController.swift // // YoutubeSuggestViewController.swift // TestFilter // // Created by <NAME> on 3/11/21. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit import SwiftyJSON class YoutubeSuggestViewController: BaseViewController { @IBOutlet weak var tableView: UITableView! var listSuggestVideo = [SuggestedVideosModel]() var params = [URLQueryItem]() var data = SuggestedVideosModel() override func viewDidLoad() { super.viewDidLoad() tableView.register(SuggestedVideosCell.nib(), forCellReuseIdentifier: SuggestedVideosCell.identifier()) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) callAPI(apiType: .suggestedVideos) } func validateParams(apiType: Youtubev3APIType) { params.removeAll() switch apiType { case .suggestedVideos: let relatedToVideoId = data.id?.videoId params = [ //Required Parameters URLQueryItem(name: "relatedToVideoId", value: relatedToVideoId), URLQueryItem(name: "part", value: "id,snippet"), URLQueryItem(name: "type", value: "video"), //Optional Parameters URLQueryItem(name: "maxResults", value: "50"), ] default: break } } func callAPI(apiType: Youtubev3APIType) { validateParams(apiType: apiType) switch apiType { case .suggestedVideos: suggestedVideos() case .search: break } } func suggestedVideos() { showLoading() // all properties params is OPTIONAL let params: [URLQueryItem] = [ //Required Parameters URLQueryItem(name: "relatedToVideoId", value: "7ghhRHRP6t4"), URLQueryItem(name: "part", value: "id,snippet"), URLQueryItem(name: "type", value: "video"), //Optional Parameters URLQueryItem(name: "maxResults", value: "50"), ] Youtubev3Router.init(endpoint: .suggestedVideos(params: params)).getData(completion: { [weak self] result in self?.hideLoading() switch result { case .success(let data): if let json = try? JSON(data: data) { let array = [SuggestedVideosModel](byJSON: json["items"]) self?.listSuggestVideo = array DispatchQueue.main.async { self?.tableView.reloadData() } } default: print("tram cam") } }) } } extension YoutubeSuggestViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listSuggestVideo.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SuggestedVideosCell.identifier(), for: indexPath) as! SuggestedVideosCell cell.data = listSuggestVideo[indexPath.row] cell.fillData() return cell } } extension YoutubeSuggestViewController: UITableViewDelegate { } <file_sep>/TestFilter/TestFilter/Controller/Youtubev3VC.swift // // Youtubev3VC.swift // TestFilter // // Created by <NAME> on 2/4/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import SwiftyJSON import AVKit import AVFoundation enum Youtubev3APIType { case suggestedVideos case search } class Youtubev3VC: BaseViewController { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! var listSuggestVideo = [SuggestedVideosModel]() var listVideo = [SuggestedVideosModel]() var params = [URLQueryItem]() override func viewDidLoad() { super.viewDidLoad() tableView.register(SearchYoutubeCell.nib(), forCellReuseIdentifier: SearchYoutubeCell.identifier()) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // callAPI(apiType: .suggestedVideos) } func validateParams(apiType: Youtubev3APIType) { params.removeAll() switch apiType { case .suggestedVideos: params = [ //Required Parameters URLQueryItem(name: "relatedToVideoId", value: "7ghhRHRP6t4"), URLQueryItem(name: "part", value: "id,snippet"), URLQueryItem(name: "type", value: "video"), //Optional Parameters URLQueryItem(name: "maxResults", value: "50"), ] case .search: let q = searchBar.text params = [ //Required Parameters URLQueryItem(name: "q", value: q), URLQueryItem(name: "part", value: "snippet,id"), //Optional Parameters URLQueryItem(name: "regionCode", value: "US"), URLQueryItem(name: "maxResults", value: "50"), URLQueryItem(name: "order", value: "date") ] } } func callAPI(apiType: Youtubev3APIType) { validateParams(apiType: apiType) switch apiType { case .suggestedVideos: suggestedVideos() case .search: search() } } func suggestedVideos() { showLoading() // all properties params is OPTIONAL let params: [URLQueryItem] = [ //Required Parameters URLQueryItem(name: "relatedToVideoId", value: "7ghhRHRP6t4"), URLQueryItem(name: "part", value: "id,snippet"), URLQueryItem(name: "type", value: "video"), //Optional Parameters URLQueryItem(name: "maxResults", value: "50"), ] Youtubev3Router.init(endpoint: .suggestedVideos(params: params)).getData(completion: { [weak self] result in self?.hideLoading() switch result { case .success(let data): if let json = try? JSON(data: data) { let array = [SuggestedVideosModel](byJSON: json["items"]) self?.listSuggestVideo = array DispatchQueue.main.async { self?.tableView.reloadData() } } default: print("tram cam") } }) } func search() { showLoading() Youtubev3Router.init(endpoint: .search(params: params)).getData(completion: { [weak self] result in self?.hideLoading() switch result { case .success(let data): if let json = try? JSON(data: data) { let items = [SuggestedVideosModel](byJSON: json["items"]) self?.listVideo = items DispatchQueue.main.async { self?.tableView.reloadData() } } default: break } }) } func generalUrlComponent(host: String, path: String, queryItems: [URLQueryItem]) -> URL { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = host urlComponents.path = path urlComponents.queryItems = queryItems return urlComponents.url! } @IBAction func dismissButton(_ sender: UIButton) { // dismiss(animated: true, completion: nil) } } extension Youtubev3VC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listVideo.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SearchYoutubeCell.identifier(), for: indexPath) as! SearchYoutubeCell let data = listVideo[indexPath.row] cell.titleTextView.text = data.snippet?.title cell.descriptionTextView.text = data.snippet?.descriptionVideo if let link = data.snippet?.thumbnails?.medium?.url { cell.thumbnailsImageView.dowloadFromServer(link: link) } return cell } } extension Youtubev3VC: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { title = "" let vc = Storyboard.Main.youtubeSuggestViewController() vc.data = listVideo[indexPath.row] navigationController?.pushViewController(vc, animated: true) } } extension Youtubev3VC: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { callAPI(apiType: .search) } } <file_sep>/TestFilter/TestFilter/View/CocktailCell.swift // // CocktailCell.swift // TestFilter // // Created by <NAME> on 2/7/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CocktailCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>/README.md # MasterSearch Hiển thị kết quả: Vừa nhập, lọc vừa hiển thị. Lọc xong rồi hiển thị. thêm phần base network url, sử dụng kết hợp với swiftyjson <file_sep>/TestFilter/TestFilter/Extension/View.swift // // View.swift // TestFilter // // Created by <NAME> on 3/11/21. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation import UIKit extension UIView { func roundCorners(corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath layer.mask = mask } static func nibName() -> String { let nameSpaceClassName = NSStringFromClass(self) let className = nameSpaceClassName.components(separatedBy: ".").last! as String return className } static func nib() -> UINib { return UINib(nibName: self.nibName(), bundle: nil) } static func loadFromNib<T: UIView>() -> T { let nameStr = "\(self)" let arrName = nameStr.split { $0 == "." } let nibName = arrName.map(String.init).last! let nib = UINib(nibName: nibName, bundle: nil) return nib.instantiate(withOwner: self, options: nil).first as! T } func fill(left: CGFloat? = 0, top: CGFloat? = 0, right: CGFloat? = 0, bottom: CGFloat? = 0) { guard let superview = superview else { print("\(self.description): there is no superView") return } self.translatesAutoresizingMaskIntoConstraints = false if let left = left { self.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: left).isActive = true } if let top = top { self.topAnchor.constraint(equalTo: superview.topAnchor, constant: top).isActive = true } if let right = right { self.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: -right).isActive = true } if let bottom = bottom { self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -bottom).isActive = true } } @objc func setDefaultCorner() { self.layer.cornerRadius = 4.0 } @objc func setCornerRadius(radius: CGFloat) { self.layer.cornerRadius = radius } @objc func setDefaultButton() { self.backgroundColor = #colorLiteral(red: 0.01568627451, green: 0.5333333333, blue: 0.8196078431, alpha: 1) self.setDefaultCorner() self.setShadow() } @objc func setBackgroundColor(color: UIColor) { self.backgroundColor = color } @objc func setDefaultButtonWithoutCorner(){ // self.backgroundColor = Constant.color.blueVSmart self.backgroundColor = #colorLiteral(red: 0.01568627451, green: 0.5333333333, blue: 0.8196078431, alpha: 1) self.setShadow() } @objc func setShadow(size: CGFloat = 2.0) { self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor self.layer.shadowOffset = CGSize(width: 0, height: size) self.layer.shadowOpacity = 1.0 self.layer.masksToBounds = false } } <file_sep>/TestFilter/TestFilter/Application/Storyboard.swift // // Storyboard.swift // TestFilter // // Created by <NAME> on 3/11/21. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit struct Storyboard { } extension Storyboard { struct Main { static let manager = UIStoryboard(name: "Main", bundle: nil) static func youtubeSuggestViewController() -> YoutubeSuggestViewController { return manager.instantiateViewController(withIdentifier: "YoutubeSuggestViewController") as! YoutubeSuggestViewController } } } <file_sep>/TestFilter/TestFilter/Model/SuggestedVideosModel.swift // // SuggestedVideosModel.swift // TestFilter // // Created by <NAME> on 3/11/21. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation import SwiftyJSON class SuggestedVideosModel: BaseDataModel { var kind: String? var id: SuggestedVideosModelID? var snippet: SnippetModel? override func mapping(json: JSON) { kind = json["kind"].stringValue id = SuggestedVideosModelID(byJSON: json["id"]) snippet = SnippetModel(byJSON: json["snippet"]) } } class SuggestedVideosModelID: BaseDataModel { var kind: String? var videoId: String? override func mapping(json: JSON) { kind = json["kind"].stringValue videoId = json["videoId"].stringValue } } class SnippetModel: BaseDataModel { var publishedAt: String? var channelId: String? var title: String? var descriptionVideo: String? var thumbnails: ThumbnailsModel? override func mapping(json: JSON) { publishedAt = json["publishedAt"].stringValue channelId = json["channelId"].stringValue title = json["title"].stringValue descriptionVideo = json["description"].stringValue thumbnails = ThumbnailsModel(byJSON: json["thumbnails"]) } } class ThumbnailsModel: BaseDataModel { var medium: MediumModel? var maxres: MaxresModel? override func mapping(json: JSON) { medium = MediumModel(byJSON: json["medium"]) maxres = MaxresModel(byJSON: json["maxres"]) } } class MediumModel: BaseDataModel { var url: String? var width: Int? var height: Int? override func mapping(json: JSON) { url = json["url"].stringValue width = json["width"].intValue height = json["height"].intValue } } class MaxresModel: BaseDataModel { var url: String? var width: Int? var height: Int? override func mapping(json: JSON) { url = json["url"].stringValue width = json["width"].intValue height = json["height"].intValue } } <file_sep>/TestFilter/TestFilter/View/SuggestedVideosCell/SuggestedVideosCell.swift // // SuggestedVideosCell.swift // TestFilter // // Created by <NAME> on 3/11/21. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit class SuggestedVideosCell: BaseTableViewCell { @IBOutlet weak var kindTextView: UITextView! @IBOutlet weak var videoIdTextView: UITextView! @IBOutlet weak var thumbnailsImageView: UIImageView! var data = SuggestedVideosModel() override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func fillData() { kindTextView.text = data.snippet?.title videoIdTextView.text = data.snippet?.descriptionVideo if let url = data.snippet?.thumbnails?.maxres?.url { thumbnailsImageView.dowloadFromServer(link: url) } } } <file_sep>/TestFilter/TestFilter/View/SearchYoutubeCell/SearchYoutubeCell.swift // // SearchYoutubeCell.swift // TestFilter // // Created by <NAME> on 3/11/21. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit class SearchYoutubeCell: BaseTableViewCell { @IBOutlet weak var thumbnailsImageView: UIImageView! @IBOutlet weak var titleTextView: UITextView! @IBOutlet weak var descriptionTextView: UITextView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>/TestFilter/TestFilter/BaseRouter/Youtubev3Router.swift // // Youtubev3.swift // TestFilter // // Created by <NAME> on 3/11/21. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftyJSON import Foundation enum Youtubev3APIEndpoint { case suggestedVideos(params: [URLQueryItem]) case search(params: [URLQueryItem]) } class Youtubev3Router: BaseNetwork { var endpoint: Youtubev3APIEndpoint init(endpoint: Youtubev3APIEndpoint) { self.endpoint = endpoint } override var path: String { switch endpoint { case .suggestedVideos(_): return "/search" case .search(_): return "/search" } } override var method: HTTPMethod { switch endpoint { default: return .get } } override var parameters: [URLQueryItem]? { var params: [URLQueryItem]? switch endpoint { case .suggestedVideos(let addParams): params = addParams case .search(let addParams): params = addParams } return params } override var headerFields: [String : String]? { var headers: [String: String]? switch endpoint { case .suggestedVideos(_): headers = [ "x-rapidapi-key": "<KEY>", "x-rapidapi-host": "youtube-v31.p.rapidapi.com" ] default: headers = [ "x-rapidapi-key": "<KEY>", "x-rapidapi-host": "youtube-v31.p.rapidapi.com" ] } return headers } } <file_sep>/TestFilter/TestFilter/Controller/ViewController.swift // // ViewController.swift // TestFilter // // Created by <NAME> on 2/4/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var sourceArrayLabel: UILabel! @IBOutlet weak var resultArrayLabel: UILabel! @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var noteLabel: UILabel! @IBOutlet weak var searchBar: UISearchBar! var sourceArray = ["Khanh Linh", "Huyen Linh", "Hien Linh", "Dieu Linh", "Ngoc Tram"] var resultArray = [String]() var searchActive: Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. searchTextField.delegate = self setDisplay() // SearchBar searchBar.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) noteLabel.text = note // Ẩn bàn phím khi ấn ra bên ngoài let tapGestureReconizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tapGestureReconizer.cancelsTouchesInView = false view.addGestureRecognizer(tapGestureReconizer) } @objc func dismissKeyboard() { view.endEditing(true) } let note = """ Lưu ý khi thực hiện xong bài này. Nhập xong với lọc và vừa nhập vừa lọc ra kết quả. Action trong keyboard, textField... Ẩn bàn phím khi thực hiện action. Ẩn khi ấn ra ngoài. """ func setDisplay() { var source: String = """ \(sourceArray) """ let vowels: Set<Character> = ["\\", "[", "]"] source.removeAll(where: { vowels.contains($0) }) sourceArrayLabel.text = source var result: String = """ \(resultArray) """ result.removeAll(where: { vowels.contains($0) }) resultArrayLabel.text = result } func filtering(keyWord: String) { resultArray = sourceArray.filter({ (laptop: String) in laptop.lowercased().contains(keyWord.lowercased()) }) } @IBAction func onClickedFilter(_ sender: UIButton) { filtering(keyWord: searchTextField.text!) setDisplay() view.endEditing(true) } // func textFieldDidBeginEditing(_ textField: UITextField) { // if textField == searchTextField { // filtering(keyWord: searchTextField.text!) // setDisplay() // } // } // Action cho textField // Dùng func func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() filtering(keyWord: searchTextField.text!) setDisplay() return true } // Kéo Action @IBAction func onClickToFiltering(_ sender: UITextField) { // filtering(keyWord: searchTextField.text!) // setDisplay() // view.endEditing(true) // } @IBAction func nextCooktail(_ sender: UIButton) { // let vc = storyboard?.instantiateViewController(identifier: "CocktaildbVC") as! Youtube v3VC // present(vc, animated: true, completion: nil) } } extension ViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { resultArray = sourceArray.filter({ (laptop: String) in laptop.lowercased().contains(searchBar.text!.lowercased()) }) setDisplay() } } extension ViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { // filterContentForSearch(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope]) filtering(keyWord: searchBar.text!) } // khi bắt dầu chạm vào search func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchActive = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchActive = false } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchActive = false } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchActive = false filtering(keyWord: searchBar.text!) setDisplay() view.endEditing(true) } // Nhập đến đâu lọc đến đó func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { let searchText = searchBar.text ?? "" resultArray = sourceArray.filter { word in word.lowercased().contains(searchText.lowercased()) } if (resultArray.count == 0) { searchActive = false } else { searchActive = true } setDisplay() } } <file_sep>/TestFilter/TestFilter/Model/BaseCocktaildbModel.swift // // BaseCocktaildbModel.swift // TestFilter // // Created by <NAME> on 2/4/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit struct BaseCocktaildbModel: Codable { var drinks: [Drinks] } struct Drinks: Codable { var strDrink: String? }
5415650d76809f1f1e2b534cb1f6da453d0d27b8
[ "Swift", "Markdown" ]
13
Swift
dangduycuong/MasterSearch
acd21d58568150b8185a2a9df6aa7593b8717528
ac026a2347b320576178c08e381b864b85ef6870
refs/heads/master
<repo_name>DeathArmy/AutoStonks.API<file_sep>/AutoStonks.API/Services/ModelService/IModelService.cs using AutoStonks.API.Dtos.Model; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.ModelService { public interface IModelService { public Task<ServiceResponse<Model>> AddModel(AddModelDto newModel); public Task<ServiceResponse<List<GetModelDto>>> GetAll(); public Task<ServiceResponse<GetModelDto>> GetSpecific(int idModel); public Task<ServiceResponse<Model>> Update(UpdateModelDto updateModel); public Task<ServiceResponse<List<Model>>> Delete(int idModel); } } <file_sep>/AutoStonks.API/Dtos/Generation/PlainGenerationDto.cs using AutoStonks.API.Dtos.Model; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.Generation { public class PlainGenerationDto { public int Id { get; set; } public string Name { get; set; } public PlainModelDto Model { get; set; } } } <file_sep>/AutoStonks.API/Controllers/PhotoController.cs using AutoStonks.API.Dtos.Photo; using AutoStonks.API.Models; using AutoStonks.API.Services.PhotoService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class PhotoController : Controller { private readonly IPhotoService _photoService; public PhotoController(IPhotoService photoService) { _photoService = photoService; } [HttpGet("{AdvertId}")] public async Task<IActionResult> GetPhotos(int AdvertId) { ServiceResponse<List<GetPhotosDto>> response = await _photoService.GetPhotos(AdvertId); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Controllers/GenerationController.cs using AutoStonks.API.Dtos.Generation; using AutoStonks.API.Models; using AutoStonks.API.Services.GenerationService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class GenerationController : Controller { private readonly IGenerationService _generationService; public GenerationController(IGenerationService generationService) { _generationService = generationService; } [HttpGet] public async Task<IActionResult> Get() { ServiceResponse<List<GetGenerationDto>> response = await _generationService.GetAll(); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("{idGeneration}")] public async Task<IActionResult> GetSpecific(int idGeneration) { ServiceResponse<GetGenerationDto> response = await _generationService.GetSpecific(idGeneration); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost] public async Task<IActionResult> AddModel(AddGenerationDto newGeneration) { ServiceResponse<Generation> response = await _generationService.AddGeneration(newGeneration); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpDelete("{idGeneration}")] public async Task<IActionResult> DeleteModel(int idGeneration) { ServiceResponse<List<Generation>> response = await _generationService.Delete(idGeneration); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPut] public async Task<IActionResult> UpdateModel(UpdateGenerationDto updateGeneration) { ServiceResponse<Generation> response = await _generationService.Update(updateGeneration); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Services/PaymentService/IPaymentService.cs using AutoStonks.API.Dtos.Payment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.PaymentService { public interface IPaymentService { public Task<ServiceResponse<Payment>> UpdatePayment(UpdatePaymentDto updatePayment); public Task<ServiceResponse<Payment>> AddPayment(AddPaymentDto newPayment); public Task<ServiceResponse<List<GetPaymentDto>>> GetAllPaymentsForAdvert(int idAvert); public Task<ServiceResponse<GetPaymentDto>> GetSpecific(int idPayment); } } <file_sep>/AutoStonks.API/Dtos/Payment/AddPaymentDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoStonks.API.Dtos.Advert; namespace AutoStonks.API.Dtos.Payment { public class AddPaymentDto { public AddAdvertDto Advert { get; set; } public int DurationInDays { get; set; } } } <file_sep>/AutoStonks.API/Services/AdvertService/AdvertService.cs using AutoMapper; using AutoStonks.API.Dtos.Advert; using AutoStonks.API.Dtos.AdvertEquipment; using AutoStonks.API.Dtos.Payment; using AutoStonks.API.Dtos.Photo; using AutoStonks.API.Models; using AutoStonks.API.Services.AdvertEquipmentService; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.AdvertService { public class AdvertService : IAdvertService { DataContext _context; private readonly IMapper _mapper; public AdvertService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<GetPaymentDto>> AddAdvert(AddPaymentDto newAdvert) { ServiceResponse<GetPaymentDto> serviceResponse = new ServiceResponse<GetPaymentDto>(); try { var advert = new Advert(); advert = _mapper.Map<Advert>(newAdvert.Advert); foreach (var ae in newAdvert.Advert.AdvertEquipments) { var entity = new AddAdvertEquipmentDto(); entity.AdvertId = ae.AdvertId; entity.EquipmentId = ae.EquipmentId; advert.AdvertEquipments.Add(_mapper.Map<AdvertEquipment>(entity)); } _context.Adverts.Add(advert); _context.SaveChanges(); var payment = new Payment(); payment.DurationInDays = newAdvert.DurationInDays; payment.AdvertId = advert.Id; payment.PaymentInitiation = DateTime.Now; _context.Payments.Add(payment); _context.SaveChanges(); _context.Database.ExecuteSqlRaw($"exec payment_procedure {advert.UserId}, {newAdvert.DurationInDays}, {(advert.IsPromoted ? 1 : 0)}, {payment.Id}"); _context.Entry(payment).Reload(); serviceResponse.Data = _mapper.Map<GetPaymentDto>(payment); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<Advert>>> DeleteAdvert(int idAdvert) { ServiceResponse<List<Advert>> serviceResponse = new ServiceResponse<List<Advert>>(); try { var entity = _context.Adverts.FirstOrDefault(a => a.Id == idAdvert); entity.State = States.Terminated; _context.SaveChanges(); serviceResponse.Data = _context.Adverts.ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAllActiveBasicInfo() { ServiceResponse<List<GetAdvertBasicInfoDto>> serviceResponse = new ServiceResponse<List<GetAdvertBasicInfoDto>>(); try { List<Advert> entity = _context.Adverts.Include(a => a.Generation).ThenInclude(g => g.Model).ThenInclude(m => m.Brand).Where(a => a.IsPromoted == false && a.State != States.Terminated).Include(p => p.Photos).ToList(); List<Advert> response = new List<Advert>(); foreach (Advert advert in entity) { if (advert.Photos != null) { var temporary = advert.Photos.FirstOrDefault(); advert.Photos.Clear(); advert.Photos.Add(temporary); } response.Add(advert); } serviceResponse.Data = _mapper.Map<List<GetAdvertBasicInfoDto>>(response); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAllActivePremiumInfo() { ServiceResponse<List<GetAdvertBasicInfoDto>> serviceResponse = new ServiceResponse<List<GetAdvertBasicInfoDto>>(); try { List<Advert> entity = _context.Adverts.Include(a => a.Generation).ThenInclude(g => g.Model).ThenInclude(m => m.Brand).Where(a => a.IsPromoted == true && a.State != States.Terminated).Include(p => p.Photos).ToList(); List<Advert> response = new List<Advert>(); foreach (Advert advert in entity) { if (advert.Photos != null) { var temporary = advert.Photos.FirstOrDefault(); advert.Photos.Clear(); advert.Photos.Add(temporary); } response.Add(advert); } serviceResponse.Data = _mapper.Map<List<GetAdvertBasicInfoDto>>(response); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAllInactive() { ServiceResponse<List<GetAdvertBasicInfoDto>> serviceResponse = new ServiceResponse<List<GetAdvertBasicInfoDto>>(); try { serviceResponse.Data = _context.Adverts.Where(a => a.State == States.Terminated).Select(a => _mapper.Map<GetAdvertBasicInfoDto>(a)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetAdvertBasicInfoDto>> GetSpecificBasicInfo(int idAdvert) { ServiceResponse<GetAdvertBasicInfoDto> serviceResponse = new ServiceResponse<GetAdvertBasicInfoDto>(); try { serviceResponse.Data = _mapper.Map<GetAdvertBasicInfoDto>(_context.Adverts.Include(a => a.Generation).ThenInclude(g => g.Model).ThenInclude(m => m.Brand).Include(p => p.Photos).FirstOrDefault(a => a.Id == idAdvert)); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetAdvertFullInfoDto>> GetSpecificFullInfo(int idAdvert) { ServiceResponse<GetAdvertFullInfoDto> serviceResponse = new ServiceResponse<GetAdvertFullInfoDto>(); try { var entity = _mapper.Map<GetAdvertFullInfoDto>(_context.Adverts.Include(a => a.Generation).ThenInclude(g => g.Model).ThenInclude(m => m.Brand).Include(e => e.AdvertEquipments).ThenInclude(ae => ae.Equipment).Include(p => p.Photos).FirstOrDefault(a => a.Id == idAdvert)); entity.VisitCount++; _context.SaveChanges(); serviceResponse.Data = entity; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<string>> UpdateAdvert(UpdateAdvertDto advert) { ServiceResponse<string> serviceResponse = new ServiceResponse<string>(); try { Advert entity = _context.Adverts.Include(ae => ae.AdvertEquipments).FirstOrDefault(a => a.Id == advert.Id); entity.CarProductionDate = advert.CarProductionDate; entity.Condition = (Models.ConditionState)advert.Condition; entity.Title = advert.Title; entity.Description = advert.Description; entity.Displacement = advert.Displacement; entity.DriveType = (Models.DriveTypes)advert.DriveType; entity.FirstRegistrationDate = advert.FirstRegistrationDate; entity.Fuel = (Models.FuelType)advert.Fuel; entity.GenerationId = advert.GenerationId; entity.HasBeenCrashed = advert.HasBeenCrashed; entity.Horsepower = advert.Horsepower; entity.Location = advert.Location; entity.Mileage = advert.Mileage; entity.PlateNumber = advert.PlateNumber; entity.Price = advert.Price; entity.State = (Models.States)advert.State; entity.TransmissionType = (Models.TransmissionTypes)advert.TransmissionType; entity.VIN = advert.VIN; entity.PhoneNumber = advert.PhoneNumber; var aeEntity = _context.AdvertEquipment.Where(a => a.AdvertId == entity.Id).ToList(); _context.AdvertEquipment.RemoveRange(aeEntity); if (entity.AdvertEquipments == null) entity.AdvertEquipments = new List<AdvertEquipment>(); foreach (var ae in advert.AdvertEquipments) { entity.AdvertEquipments.Add(_mapper.Map<AdvertEquipment>(ae)); } var photoEntity = _context.Photos.Where(a => a.AdvertId == entity.Id).ToList(); _context.AdvertEquipment.RemoveRange(aeEntity); if (entity.Photos == null) entity.Photos = new List<Photo>(); foreach (var photo in advert.Photos) { entity.Photos.Add(_mapper.Map<Photo>(photo)); } _context.SaveChanges(); serviceResponse.Data = "wykonano"; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAdvertsMatchingToQuery(QueryAdvertDto query) { ServiceResponse<List<GetAdvertBasicInfoDto>> serviceResponse = new ServiceResponse<List<GetAdvertBasicInfoDto>>(); try { List<Advert> adverts = _context.Adverts.Include(g => g.Generation) .ThenInclude(m => m.Model) .ThenInclude(b => b.Brand) .Include(p => p.Photos) .ToList(); if (query.VIN != null) adverts = adverts.Where(a => a.VIN == query.VIN).ToList();//co gdy wpiszemy część VINu? if (query.MinPrice > 0) { if (query.MaxPrice == 0) adverts = adverts.Where(a => a.Price >= query.MinPrice).ToList(); else if (query.MaxPrice > 0 && query.MaxPrice > query.MinPrice) adverts = adverts.Where(a => a.Price >= query.MinPrice && a.Price <= query.MaxPrice).ToList(); } else if (query.MaxPrice > 0) adverts = adverts.Where(a => a.Price <= query.MaxPrice).ToList(); if (query.MinMileage > 0) { if (query.MaxMileage == 0) adverts = adverts.Where(a => a.Mileage >= query.MinMileage).ToList(); else if (query.MaxMileage > 0 && query.MaxMileage > query.MinMileage) adverts = adverts.Where(a => a.Mileage >= query.MinMileage && a.Mileage <= query.MaxMileage).ToList(); } else if (query.MaxMileage > 0) adverts = adverts.Where(a => a.Mileage <= query.MaxMileage).ToList(); if (query.MinHorsepower > 0) { if (query.MaxHorsepower == 0) adverts = adverts.Where(a => a.Horsepower >= query.MinHorsepower).ToList(); else if (query.MaxHorsepower > 0 && query.MaxHorsepower > query.MinHorsepower) adverts = adverts.Where(a => a.Horsepower >= query.MinHorsepower && a.Horsepower <= query.MaxHorsepower).ToList(); } else if (query.MaxHorsepower > 0) adverts = adverts.Where(a => a.Horsepower <= query.MaxHorsepower).ToList(); if (query.MinDisplacement > 0) { if (query.MaxDisplacement == 0) adverts = adverts.Where(a => a.Displacement >= query.MinDisplacement).ToList(); else if (query.MaxDisplacement > 0 && query.MaxDisplacement > query.MinDisplacement) adverts = adverts.Where(a => a.Displacement >= query.MinDisplacement && a.Displacement <= query.MaxDisplacement).ToList(); } else if (query.MaxDisplacement > 0) adverts = adverts.Where(a => a.Displacement <= query.MaxDisplacement).ToList(); if (query.BrandName != null) adverts = adverts.Where(a => a.Generation.Model.Brand.Name == query.BrandName).ToList(); if (query.ModelName != null) adverts = adverts.Where(a => a.Generation.Model.Name == query.ModelName).ToList(); if (query.GenerationName != null) adverts = adverts.Where(a => a.Generation.Name == query.GenerationName).ToList(); if (query.TransmissionType != null) adverts = adverts.Where(a => a.TransmissionType.ToString() == query.TransmissionType.ToString()).ToList(); if (query.DriveType != null) adverts = adverts.Where(a => a.DriveType.ToString() == query.DriveType.ToString()).ToList(); if (query.Condition != null) adverts = adverts.Where(a => a.Condition.ToString() == query.Condition.ToString()).ToList(); if (query.Fuel != null) adverts = adverts.Where(a => a.Fuel.ToString() == query.Fuel.ToString()).ToList(); if (query.FromCarProductionDate != null) { if (query.ToCarProductionDate != null) adverts = adverts.Where(a => a.CarProductionDate.Year >= query.FromCarProductionDate.Value.Year && a.CarProductionDate.Year <= query.ToCarProductionDate.Value.Year).ToList(); else adverts = adverts.Where(a => a.CarProductionDate.Year >= query.FromCarProductionDate.Value.Year).ToList(); } else if (query.ToCarProductionDate != null) adverts = adverts.Where(a => a.CarProductionDate.Year <= query.ToCarProductionDate.Value.Year).ToList(); serviceResponse.Data = adverts.Select(a => _mapper.Map<GetAdvertBasicInfoDto>(a)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Services/PaymentService/PaymentService.cs using AutoMapper; using AutoStonks.API.Dtos.Payment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.PaymentService { public class PaymentService : IPaymentService { DataContext _context; private readonly IMapper _mapper; public PaymentService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<Payment>> AddPayment(AddPaymentDto newPayment) { ServiceResponse<Payment> serviceResponse = new ServiceResponse<Payment>(); try { var entity = _mapper.Map<Payment>(newPayment); _context.Payments.Add(entity); _context.SaveChanges(); serviceResponse.Data = entity; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetPaymentDto>>> GetAllPaymentsForAdvert(int idAvert) { ServiceResponse<List<GetPaymentDto>> serviceResponse = new ServiceResponse<List<GetPaymentDto>>(); try { serviceResponse.Data = _context.Payments.Where(p => p.AdvertId == idAvert).Select(p => _mapper.Map<GetPaymentDto>(p)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetPaymentDto>> GetSpecific(int idPayment) { ServiceResponse<GetPaymentDto> serviceResponse = new ServiceResponse<GetPaymentDto>(); try { serviceResponse.Data = _mapper.Map<GetPaymentDto>(_context.Payments.FirstOrDefault(p => p.Id == idPayment)); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<Payment>> UpdatePayment(UpdatePaymentDto updatePayment) { ServiceResponse<Payment> serviceResponse = new ServiceResponse<Payment>(); try { var updatedPayment = _context.Payments.First(p => p.Id == updatePayment.Id); if (updatePayment.isTerminated) { updatedPayment.PaymentTermination = DateTime.Now; updatedPayment.StartDate = DateTime.Now; _context.SaveChanges(); serviceResponse.Data = updatedPayment; } else { serviceResponse.Data = null; } } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Controllers/BrandController.cs using AutoStonks.API.Dtos.Brand; using AutoStonks.API.Models; using AutoStonks.API.Services.BrandService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class BrandController : ControllerBase { private readonly IBrandService _brandService; public BrandController(IBrandService brandService) { _brandService = brandService; } [HttpGet] public async Task<IActionResult> Get() { ServiceResponse<List<GetBrandDto>> response = await _brandService.GetAll(); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("{idBrand}")] public async Task<IActionResult> GetSpecific(int idBrand) { ServiceResponse<GetBrandDto> response = await _brandService.GetSpecific(idBrand); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost] public async Task<IActionResult> AddBrand(AddBrandDto newBrand) { ServiceResponse<Brand> response = await _brandService.AddBrand(newBrand); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpDelete("{idBrand}")] public async Task<IActionResult> DeleteBrand(int idBrand) { ServiceResponse<List<Brand>> response = await _brandService.DeleteBrand(idBrand); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPut] public async Task<IActionResult> UpdateBrand(UpdateBrandDto brand) { ServiceResponse<Brand> response = await _brandService.UpdateBrand(brand); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Controllers/PaymentController.cs using AutoStonks.API.Dtos.Payment; using AutoStonks.API.Models; using AutoStonks.API.Services.PaymentService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class PaymentController : Controller { private readonly IPaymentService _paymentService; public PaymentController(IPaymentService paymentService) { _paymentService = paymentService; } [HttpGet("allfor={idAdvert}")] public async Task<IActionResult> GetAllPaymentsForAdvert(int idAdvert) { ServiceResponse<List<GetPaymentDto>> response = await _paymentService.GetAllPaymentsForAdvert(idAdvert); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("{idPayment}")] public async Task<IActionResult> GetSpecific(int idPayment) { ServiceResponse<GetPaymentDto> response = await _paymentService.GetSpecific(idPayment); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost] public async Task<IActionResult> AddPayment(AddPaymentDto addPayment) { ServiceResponse<Payment> response = await _paymentService.AddPayment(addPayment); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPut] public async Task<IActionResult> UpdatePayment(UpdatePaymentDto updatePayment) { ServiceResponse<Payment> response = await _paymentService.UpdatePayment(updatePayment); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Services/GenerationService/IGenerationService.cs using AutoStonks.API.Dtos.Generation; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.GenerationService { public interface IGenerationService { public Task<ServiceResponse<Generation>> AddGeneration(AddGenerationDto newGeneration); public Task<ServiceResponse<List<GetGenerationDto>>> GetAll(); public Task<ServiceResponse<GetGenerationDto>> GetSpecific(int idGeneration); public Task<ServiceResponse<Generation>> Update(UpdateGenerationDto updateGeneration); public Task<ServiceResponse<List<Generation>>> Delete(int idGeneration); } } <file_sep>/AutoStonks.API/Services/BrandService/BrandService.cs using AutoMapper; using AutoStonks.API.Dtos.Brand; using AutoStonks.API.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.BrandService { public class BrandService : IBrandService { DataContext _context; private readonly IMapper _mapper; public BrandService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<Brand>> AddBrand(AddBrandDto brand) { ServiceResponse<Brand> serviceResponse = new ServiceResponse<Brand>(); try { var entity = _mapper.Map<Brand>(brand); _context.Brands.Add(entity); _context.SaveChanges(); serviceResponse.Data = entity; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<Brand>>> DeleteBrand(int idBrand) { ServiceResponse<List<Brand>> serviceResponse = new ServiceResponse<List<Brand>>(); try { var entity = _context.Brands.FirstOrDefault(b => b.Id == idBrand); _context.Brands.Remove(entity); serviceResponse.Data = _context.Brands.ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetBrandDto>>> GetAll() { ServiceResponse<List<GetBrandDto>> serviceResponse = new ServiceResponse<List<GetBrandDto>>(); try { serviceResponse.Data = _context.Brands.Include(b => b.Models).ThenInclude(m => m.Generations).Select(b => _mapper.Map<GetBrandDto>(b)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<Brand>> UpdateBrand(UpdateBrandDto brand) { ServiceResponse<Brand> serviceResponse = new ServiceResponse<Brand>(); try { var entity = _context.Brands.FirstOrDefault(b => b.Id == brand.Id); entity.Name = brand.Name; _context.SaveChanges(); serviceResponse.Data = entity; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetBrandDto>> GetSpecific(int idBrand) { ServiceResponse<GetBrandDto> serviceResponse = new ServiceResponse<GetBrandDto>(); try { var temp = _context.Brands.Include(b => b.Models).ThenInclude(m => m.Generations).FirstOrDefault(b => b.Id == idBrand); serviceResponse.Data = _mapper.Map<GetBrandDto>(temp); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Services/UserService/IUserService.cs using AutoStonks.API.Dtos.User; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.UserService { public interface IUserService { public Task<ServiceResponse<GetUserDto>> GetUserById(int id); public Task<ServiceResponse<UserDto>> AddUser(AddUserDto newUser); public Task<ServiceResponse<List<GetUsersDto>>> GetAllUsers(); public Task<ServiceResponse<GetUserDto>> UpdateUser(UpdateUserDto updateCharacter); public Task<ServiceResponse<DeleteUserDto>> DeleteUser(int id); public Task<ServiceResponse<UserDto>> Login(LoginDto login); public Task<ServiceResponse<UserDto>> PasswordChange(PasswordChangeDto pwdChange); } } <file_sep>/AutoStonks.API/Migrations/20210201191203_seed.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace AutoStonks.API.Migrations { public partial class seed : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.InsertData( table: "Brands", columns: new[] { "Id", "Name" }, values: new object[,] { { 1, "Renault" }, { 2, "BMW" }, { 3, "Mercedes-Benz" }, { 4, "Audi" }, { 5, "<NAME>" }, { 6, "Opel" }, { 7, "Volkswagen" }, { 8, "Toyota" }, { 9, "Ford" }, { 10, "Polonez" } }); migrationBuilder.InsertData( table: "Equipment", columns: new[] { "Id", "Name" }, values: new object[,] { { 40, "MP3" }, { 39, "Kurtyny powietrzne" }, { 38, "Komputer pokładowy" }, { 37, "Klimatyzacja manualna" }, { 36, "Klimtayzacja dwustrefowa" }, { 31, "Hak" }, { 34, "Klimatyzacja automatyczna" }, { 33, "Kamera cofania" }, { 32, "Isofix" }, { 41, "Nawigacja GPS" }, { 35, "Klimatyzacja czterostrefowa" }, { 42, "Ogranicznik prędkości" }, { 47, "Podgrzewane tylne siedzenia" }, { 44, "Podgrzewana przednia szyba" }, { 45, "Podgrzewane lusterka boczne" }, { 46, "Podgrzewane przednie siedzenia" }, { 30, "Gniazdo USB" }, { 48, "Szyberdach" }, { 49, "Światła do jazdy dziennej" }, { 50, "Światła LED" }, { 51, "Światła przecwmgielne" }, { 52, "Światła Xenonowe" }, { 53, "Tapicerka skórzana" }, { 54, "Tapicerka welurowa" }, { 55, "Tempomat" }, { 43, "Ogrzewanie postojowe" }, { 29, "Gniazdo SD" }, { 24, "Elektrochromatyczne lusterko wsteczne" }, { 27, "ESP (stabilizacja toru jazdy)" }, { 1, "ABS" }, { 2, "CD" }, { 3, "Centralny zamek" } }); migrationBuilder.InsertData( table: "Equipment", columns: new[] { "Id", "Name" }, values: new object[,] { { 4, "Elektryczne szyby przednia" }, { 5, "Elektrycznie ustawiane lusterka" }, { 6, "Immobilizer" }, { 7, "Poduszka powietrzna kierowcy" }, { 8, "Poduszka powietrzna pasażera" }, { 9, "Radio fabryczne" }, { 10, "Wspomaganie kierownicy" }, { 11, "Alarm" }, { 12, "Alufelgi" }, { 28, "Gniazdo AUX" }, { 13, "ASR (kontrola trakcji)" }, { 15, "Asysten pasa ruchu" }, { 16, "Bluetooth" }, { 17, "<NAME>" }, { 18, "<NAME> pola" }, { 19, "<NAME>" }, { 20, "Czujniki prakowania przednie" }, { 21, "Czujniki parkowania tylne" }, { 22, "<NAME>" }, { 23, "Elektrochromatyczne lusterka boczne" }, { 56, "Wielofunkcyjna kierownica" }, { 25, "Elektryczne szyby tylne" }, { 26, "Elektrycznie ustawiane fotele" }, { 14, "Asystent parkowania" } }); migrationBuilder.InsertData( table: "Users", columns: new[] { "Id", "EmailAddress", "EnforcePasswordChange", "IsActive", "LastPasswordChange", "Password", "Role", "Salt", "Username" }, values: new object[] { 1, "<EMAIL>", false, true, new DateTime(2021, 2, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), "츊း뤮䷔뛦熜뀹獳㴗༫暸쨥櫆됈", "A", "⣶刌䅦윽璅ꚮ�闏ⵁ堣帠䳀�壨瘶晤", "admin" }); migrationBuilder.InsertData( table: "Models", columns: new[] { "Id", "BrandId", "Name" }, values: new object[,] { { 1, 1, "Clio" }, { 26, 9, "Sierra" }, { 25, 9, "Escort" }, { 24, 8, "Yaris" }, { 23, 7, "Bora" }, { 22, 7, "Golf" }, { 21, 7, "Passat" }, { 20, 6, "Insignia" }, { 19, 6, "Vectra" }, { 18, 6, "Corsa" }, { 17, 5, "Brera" }, { 16, 5, "156" }, { 15, 5, "147" }, { 14, 5, "159" }, { 13, 4, "A8" }, { 12, 4, "A6" }, { 11, 4, "A4" }, { 10, 3, "<NAME>" }, { 9, 3, "<NAME>" }, { 8, 2, "<NAME>" }, { 7, 2, "<NAME>" }, { 6, 2, "<NAME>" }, { 5, 1, "Captur" }, { 4, 1, "Scenic" }, { 3, 1, "Laguna" }, { 2, 1, "Megane" }, { 27, 9, "Focus" }, { 28, 10, "Caro" } }); migrationBuilder.InsertData( table: "Generations", columns: new[] { "Id", "ModelId", "Name" }, values: new object[,] { { 1, 1, "III (2005-2012)" }, { 20, 15, "I (2000-2010)" }, { 21, 16, "I (1999-2006)" }, { 22, 17, "I (2005-2010)" }, { 23, 18, "C (2000-2006)" }, { 24, 18, "D (2006-2014)" }, { 25, 19, "C (2002-2008)" }, { 19, 14, "I (2005-2012)" }, { 26, 20, "A (2008-2017)" }, { 28, 21, "B5 FL (2000-2005)" }, { 29, 22, "V (2003-2009)" }, { 30, 23, "V (2003-2009)" }, { 31, 24, "Jetta IV (1998-2005)" }, { 32, 25, "Mk7 (1995-1999)" }, { 33, 26, "Mk2 (1987-1993)" }, { 27, 21, "B5 (1996-2000)" }, { 34, 27, "Mk4 (2018-)" }, { 18, 13, "D3 (2002-2010)" }, { 16, 11, "B7 (2004-2007)" }, { 2, 1, "IV (2012-2018)" }, { 3, 1, "V (2019-)" }, { 4, 2, "III (2008-2016)" }, { 5, 2, "IV (2016-)" }, { 6, 3, "III (2007-2015)" }, { 7, 4, "III (2009-2013)" }, { 17, 12, "C6 (2004-2011)" }, { 8, 4, "I (2013-2019)" }, { 10, 5, "E46 (1998-2007)" }, { 11, 6, "E39 (1996-2003)" }, { 12, 8, "E38 (1994-2001)" }, { 13, 9, "W203 (2000-2007)" }, { 14, 10, "W124 (1993-1997)" }, { 15, 11, "B6 (2000-2004)" }, { 9, 5, "E36 (1990-1999)" }, { 35, 28, "I (1978-1991)" } }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 1); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 2); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 3); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 4); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 5); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 6); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 7); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 8); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 9); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 10); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 11); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 12); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 13); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 14); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 15); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 16); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 17); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 18); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 19); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 20); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 21); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 22); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 23); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 24); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 25); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 26); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 27); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 28); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 29); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 30); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 31); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 32); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 33); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 34); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 35); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 36); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 37); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 38); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 39); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 40); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 41); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 42); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 43); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 44); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 45); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 46); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 47); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 48); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 49); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 50); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 51); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 52); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 53); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 54); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 55); migrationBuilder.DeleteData( table: "Equipment", keyColumn: "Id", keyValue: 56); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 1); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 2); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 3); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 4); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 5); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 6); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 7); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 8); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 9); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 10); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 11); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 12); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 13); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 14); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 15); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 16); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 17); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 18); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 19); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 20); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 21); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 22); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 23); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 24); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 25); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 26); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 27); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 28); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 29); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 30); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 31); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 32); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 33); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 34); migrationBuilder.DeleteData( table: "Generations", keyColumn: "Id", keyValue: 35); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 7); migrationBuilder.DeleteData( table: "Users", keyColumn: "Id", keyValue: 1); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 1); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 2); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 3); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 4); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 5); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 6); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 8); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 9); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 10); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 11); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 12); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 13); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 14); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 15); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 16); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 17); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 18); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 19); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 20); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 21); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 22); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 23); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 24); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 25); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 26); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 27); migrationBuilder.DeleteData( table: "Models", keyColumn: "Id", keyValue: 28); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 1); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 2); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 3); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 4); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 5); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 6); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 7); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 8); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 9); migrationBuilder.DeleteData( table: "Brands", keyColumn: "Id", keyValue: 10); } } } <file_sep>/AutoStonks.API/PasswordHashing.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Security.Cryptography; using System.Text; namespace AutoStonks.API { public class PasswordHashing { private const int saltSize = 32; private const int hashSize = 32; private const int iterationsCount = 10000; public PasswordHashing() { } public byte[] GetSalt() { byte[] salt = new byte[saltSize]; using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider()) { rngCsp.GetBytes(salt); } return salt; } public byte[] GetKey(string password, byte[] salt) { Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, salt, iterationsCount); return rfc2898.GetBytes(hashSize); } public bool IsValid(string password, string saltValue, string keyValue) { byte[] salt = Encoding.Unicode.GetBytes(saltValue); byte[] hashedValue = GetKey(password, salt); if (Encoding.Unicode.GetString(hashedValue) == keyValue) return true; else return false; } } } <file_sep>/AutoStonks.API/Services/PhotoService/PhotoService.cs using AutoMapper; using AutoStonks.API.Dtos.Photo; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.PhotoService { public class PhotoService : IPhotoService { private readonly IMapper _mapper; DataContext _context; public PhotoService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<List<GetPhotosDto>>> GetPhotos(int advertId) { ServiceResponse<List<GetPhotosDto>> serviceResponse = new ServiceResponse<List<GetPhotosDto>>(); try { serviceResponse.Data = _context.Photos.Where(p => p.AdvertId == advertId).Select(p => _mapper.Map<GetPhotosDto>(p)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Startup.cs using AutoMapper; using AutoStonks.API.Services.AdvertEquipmentService; using AutoStonks.API.Services.AdvertService; using AutoStonks.API.Services.BrandService; using AutoStonks.API.Services.EquipmentService; using AutoStonks.API.Services.GenerationService; using AutoStonks.API.Services.ModelService; using AutoStonks.API.Services.PaymentService; using AutoStonks.API.Services.PhotoService; using AutoStonks.API.Services.UserService; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAutoMapper(typeof(Startup)); services.AddScoped<IUserService, UserService>(); services.AddScoped<IBrandService, BrandService>(); services.AddScoped<IAdvertService, AdvertService>(); services.AddScoped<IAdvertEquipmentService, AdvertEquipmentService>(); services.AddScoped<IEquipmentService, EquipmentService>(); services.AddScoped<IGenerationService, GenerationService>(); services.AddScoped<IModelService, ModelService>(); services.AddScoped<IPaymentService, PaymentService>(); services.AddScoped<IPhotoService, PhotoService>(); services.AddDbContext<DataContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("AutoStonksDb")); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseCors(o => o.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>/AutoStonks.API/Dtos/Payment/GetPaymentDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.Payment { public class GetPaymentDto { public int Id { get; set; } public int AdvertId { get; set; } public float Price { get; set; } public DateTime PaymentInitiation { get; set; } public DateTime PaymentTermination { get; set; } public DateTime StartDate { get; set; } public int DurationInDays { get; set; } } } <file_sep>/AutoStonks.API/Dtos/Model/GetModelDto.cs using AutoStonks.API.Dtos.Brand; using AutoStonks.API.Dtos.Generation; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.Model { public class GetModelDto { public int Id { get; set; } public string Name { get; set; } public List<GetGenerationDto> Generations { get; set; } } } <file_sep>/AutoStonks.API/Migrations/20210201185646_initial.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace AutoStonks.API.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Brands", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Brands", x => x.Id); }); migrationBuilder.CreateTable( name: "Equipment", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Equipment", x => x.Id); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Username = table.Column<string>(type: "nvarchar(max)", nullable: true), EmailAddress = table.Column<string>(type: "nvarchar(max)", nullable: true), Role = table.Column<string>(type: "nvarchar(1)", nullable: false), Password = table.Column<string>(type: "nvarchar(max)", nullable: true), Salt = table.Column<string>(type: "nvarchar(max)", nullable: true), LastPasswordChange = table.Column<DateTime>(type: "datetime2", nullable: false), EnforcePasswordChange = table.Column<bool>(type: "bit", nullable: false), IsActive = table.Column<bool>(type: "bit", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); migrationBuilder.CreateTable( name: "Models", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), BrandId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Models", x => x.Id); table.ForeignKey( name: "FK_Models_Brands_BrandId", column: x => x.BrandId, principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Generations", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), ModelId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Generations", x => x.Id); table.ForeignKey( name: "FK_Generations_Models_ModelId", column: x => x.ModelId, principalTable: "Models", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Adverts", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserId = table.Column<int>(type: "int", nullable: false), CreationDate = table.Column<DateTime>(type: "datetime2", nullable: false), ModificationDate = table.Column<DateTime>(type: "datetime2", nullable: false), ExpiryDate = table.Column<DateTime>(type: "datetime2", nullable: false), IsPromoted = table.Column<bool>(type: "bit", nullable: false), Title = table.Column<string>(type: "nvarchar(max)", nullable: true), Description = table.Column<string>(type: "nvarchar(max)", nullable: true), VIN = table.Column<string>(type: "nvarchar(max)", nullable: true), FirstRegistrationDate = table.Column<DateTime>(type: "datetime2", nullable: false), PlateNumber = table.Column<string>(type: "nvarchar(max)", nullable: true), State = table.Column<int>(type: "int", nullable: false), Price = table.Column<double>(type: "float", nullable: false), Mileage = table.Column<int>(type: "int", nullable: false), CarProductionDate = table.Column<DateTime>(type: "datetime2", nullable: false), Fuel = table.Column<int>(type: "int", nullable: false), Condition = table.Column<int>(type: "int", nullable: false), Horsepower = table.Column<int>(type: "int", nullable: false), Displacement = table.Column<int>(type: "int", nullable: false), Location = table.Column<string>(type: "nvarchar(max)", nullable: true), HasBeenCrashed = table.Column<bool>(type: "bit", nullable: false), TransmissionType = table.Column<int>(type: "int", nullable: false), DriveType = table.Column<int>(type: "int", nullable: false), VisitCount = table.Column<int>(type: "int", nullable: false), GenerationId = table.Column<int>(type: "int", nullable: false), PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Adverts", x => x.Id); table.ForeignKey( name: "FK_Adverts_Generations_GenerationId", column: x => x.GenerationId, principalTable: "Generations", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Adverts_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AdvertEquipment", columns: table => new { AdvertId = table.Column<int>(type: "int", nullable: false), EquipmentId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AdvertEquipment", x => new { x.AdvertId, x.EquipmentId }); table.ForeignKey( name: "FK_AdvertEquipment_Adverts_AdvertId", column: x => x.AdvertId, principalTable: "Adverts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AdvertEquipment_Equipment_EquipmentId", column: x => x.EquipmentId, principalTable: "Equipment", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Payments", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), AdvertId = table.Column<int>(type: "int", nullable: false), Price = table.Column<float>(type: "real", nullable: false), PaymentInitiation = table.Column<DateTime>(type: "datetime2", nullable: false), PaymentTermination = table.Column<DateTime>(type: "datetime2", nullable: false), StartDate = table.Column<DateTime>(type: "datetime2", nullable: false), DurationInDays = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Payments", x => x.Id); table.ForeignKey( name: "FK_Payments_Adverts_AdvertId", column: x => x.AdvertId, principalTable: "Adverts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Photos", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), Source = table.Column<string>(type: "nvarchar(max)", nullable: true), AdvertId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Photos", x => x.Id); table.ForeignKey( name: "FK_Photos_Adverts_AdvertId", column: x => x.AdvertId, principalTable: "Adverts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AdvertEquipment_EquipmentId", table: "AdvertEquipment", column: "EquipmentId"); migrationBuilder.CreateIndex( name: "IX_Adverts_GenerationId", table: "Adverts", column: "GenerationId"); migrationBuilder.CreateIndex( name: "IX_Adverts_UserId", table: "Adverts", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Generations_ModelId", table: "Generations", column: "ModelId"); migrationBuilder.CreateIndex( name: "IX_Models_BrandId", table: "Models", column: "BrandId"); migrationBuilder.CreateIndex( name: "IX_Payments_AdvertId", table: "Payments", column: "AdvertId"); migrationBuilder.CreateIndex( name: "IX_Photos_AdvertId", table: "Photos", column: "AdvertId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AdvertEquipment"); migrationBuilder.DropTable( name: "Payments"); migrationBuilder.DropTable( name: "Photos"); migrationBuilder.DropTable( name: "Equipment"); migrationBuilder.DropTable( name: "Adverts"); migrationBuilder.DropTable( name: "Generations"); migrationBuilder.DropTable( name: "Users"); migrationBuilder.DropTable( name: "Models"); migrationBuilder.DropTable( name: "Brands"); } } } <file_sep>/AutoStonks.API/Dtos/Model/AddModelDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoStonks.API.Models; namespace AutoStonks.API.Dtos.Model { public class AddModelDto { public string Name { get; set; } public int BrandId { get; set; } } } <file_sep>/AutoStonks.API/Services/UserService/UserService.cs using AutoMapper; using AutoStonks.API.Dtos.User; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text; namespace AutoStonks.API.Services.UserService { public class UserService : IUserService { DataContext _context; private readonly IMapper _mapper; public UserService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<UserDto>> AddUser(AddUserDto newUser) { ServiceResponse<UserDto> serviceResponse = new ServiceResponse<UserDto>(); User user = new User(); PasswordHashing ph = new PasswordHashing(); try { user = _mapper.Map<User>(newUser); user.Salt = Encoding.Unicode.GetString(ph.GetSalt()); user.Password = Encoding.Unicode.GetString(ph.GetKey(user.Password, Encoding.Unicode.GetBytes(user.Salt))); _context.Users.Add(user); _context.SaveChanges(); serviceResponse.Data = _mapper.Map<UserDto>(user); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<DeleteUserDto>> DeleteUser(int id) { ServiceResponse<DeleteUserDto> serviceResponse = new ServiceResponse<DeleteUserDto>(); try { User user = _context.Users.FirstOrDefault(u => u.Id == id); user.IsActive = false; _context.SaveChanges(); serviceResponse.Data = _mapper.Map<DeleteUserDto>(user); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetUsersDto>>> GetAllUsers() { ServiceResponse<List<GetUsersDto>> serviceResponse = new ServiceResponse<List<GetUsersDto>>(); try { serviceResponse.Data = _context.Users.Where(u => u.IsActive != false).Select(u => _mapper.Map<GetUsersDto>(u)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetUserDto>> GetUserById(int id) { ServiceResponse<GetUserDto> serviceResponse = new ServiceResponse<GetUserDto>(); try { serviceResponse.Data = _mapper.Map<GetUserDto>(_context.Users.FirstOrDefault(u => u.Id == id)); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetUserDto>> UpdateUser(UpdateUserDto updateCharacter) { ServiceResponse<GetUserDto> serviceResponse = new ServiceResponse<GetUserDto>(); try { User user = _context.Users.FirstOrDefault(u => u.Id == updateCharacter.Id); user.Username = updateCharacter.Username; user.EmailAddress = updateCharacter.EmailAddress; user.Role = updateCharacter.Role; if (user.Password != updateCharacter.Password) { user.Password = <PASSWORD>; user.Salt = updateCharacter.Salt; user.LastPasswordChange = updateCharacter.LastPasswordChange; user.EnforcePasswordChange = false; } serviceResponse.Data = _mapper.Map<GetUserDto>(user); _context.SaveChanges(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<UserDto>> Login(LoginDto login) { ServiceResponse<UserDto> serviceResponse = new ServiceResponse<UserDto>(); PasswordHashing ph = new PasswordHashing(); User entity = new User(); try { entity = _context.Users.First(u => u.Username == login.Username); if (ph.IsValid(login.Password, entity.Salt, entity.Password)) serviceResponse.Data = _mapper.Map<UserDto>(entity); else throw new Exception(""); if (entity.EnforcePasswordChange == true) throw new Exception("Password should be changed!"); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = "Wrong username or password.\n"; serviceResponse.Message += (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<UserDto>> PasswordChange(PasswordChangeDto pwdChange) { ServiceResponse<UserDto> serviceResponse = new ServiceResponse<UserDto>(); PasswordHashing ph = new PasswordHashing(); User entity = new User(); try { entity = _context.Users.First(u => u.Username == pwdChange.Username); if (ph.IsValid(pwdChange.CurrentPassword, entity.Salt, entity.Password)) { entity.Salt = Encoding.Unicode.GetString(ph.GetSalt()); entity.Password = Encoding.Unicode.GetString(ph.GetKey(pwdChange.NewPassword, Encoding.Unicode.GetBytes(entity.Salt))); entity.LastPasswordChange = DateTime.Now; entity.EnforcePasswordChange = false; _context.SaveChanges(); serviceResponse.Data = _mapper.Map<UserDto>(entity); } else throw new Exception("Wrong current password!"); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Services/BrandService/IBrandService.cs using AutoStonks.API.Dtos.Brand; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.BrandService { public interface IBrandService { public Task<ServiceResponse<Brand>> AddBrand(AddBrandDto brand); public Task<ServiceResponse<List<Brand>>> DeleteBrand(int idBrand); public Task<ServiceResponse<Brand>> UpdateBrand(UpdateBrandDto brand); public Task<ServiceResponse<List<GetBrandDto>>> GetAll(); public Task<ServiceResponse<GetBrandDto>> GetSpecific(int idBrand); } } <file_sep>/AutoStonks.API/Services/AdvertEquipmentService/IAdvertEquipmentService.cs using AutoStonks.API.Dtos.AdvertEquipment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.AdvertEquipmentService { public interface IAdvertEquipmentService { public Task<ServiceResponse<List<AdvertEquipment>>> AddAdvert(List<AddAdvertEquipmentDto> newConnection); } } <file_sep>/AutoStonks.API/Controllers/EquipmentController.cs using AutoStonks.API.Dtos.Equipment; using AutoStonks.API.Models; using AutoStonks.API.Services.EquipmentService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class EquipmentController : ControllerBase { private readonly IEquipmentService _equipmentService; public EquipmentController(IEquipmentService equipmentService) { _equipmentService = equipmentService; } [HttpGet] public async Task<IActionResult> GetAll() { ServiceResponse<List<GetEquipmentDto>> response = await _equipmentService.GetEquipment(); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Controllers/AdvertController.cs using AutoStonks.API.Dtos.Advert; using AutoStonks.API.Dtos.Payment; using AutoStonks.API.Models; using AutoStonks.API.Services.AdvertService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class AdvertController : Controller { private readonly IAdvertService _advertService; public AdvertController(IAdvertService advertService) { _advertService = advertService; } [HttpGet("GetActiveBasic")] public async Task<IActionResult> GetAllActiveBasicInfo() { ServiceResponse<List<GetAdvertBasicInfoDto>> response = await _advertService.GetAllActiveBasicInfo(); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("GetActivePremium")] public async Task<IActionResult> GetAllActivePremiumInfo() { ServiceResponse<List<GetAdvertBasicInfoDto>> response = await _advertService.GetAllActivePremiumInfo(); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("GetInactive")] public async Task<IActionResult> GetAllInactive() { ServiceResponse<List<GetAdvertBasicInfoDto>> response = await _advertService.GetAllInactive(); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("GetBasicInfo={idAdvert}")] public async Task<IActionResult> GetSpecificBasicInfo(int idAdvert) { ServiceResponse<GetAdvertBasicInfoDto> response = await _advertService.GetSpecificBasicInfo(idAdvert); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("GetFullInfo={idAdvert}")] public async Task<IActionResult> GetSpecificFullInfo(int idAdvert) { ServiceResponse<GetAdvertFullInfoDto> response = await _advertService.GetSpecificFullInfo(idAdvert); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("Query")] public async Task<IActionResult> Query([FromQuery] QueryAdvertDto queryAdvertDto) { ServiceResponse<List<GetAdvertBasicInfoDto>> response = await _advertService.GetAdvertsMatchingToQuery(queryAdvertDto); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost] public async Task<IActionResult> AddAdvert(AddPaymentDto newAdvert) { ServiceResponse<GetPaymentDto> response = await _advertService.AddAdvert(newAdvert); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpDelete("{idAdvert}")] public async Task<IActionResult> DeleteBrand(int idAdvert) { ServiceResponse<List<Advert>> response = await _advertService.DeleteAdvert(idAdvert); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPut] public async Task<IActionResult> UpdateAdvert(UpdateAdvertDto advert) { ServiceResponse<string> response = await _advertService.UpdateAdvert(advert); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Services/GenerationService/GenerationService.cs using AutoMapper; using AutoStonks.API.Dtos.Generation; using AutoStonks.API.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.GenerationService { public class GenerationService : IGenerationService { DataContext _context; private readonly IMapper _mapper; public GenerationService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<Generation>> AddGeneration(AddGenerationDto newGeneration) { ServiceResponse<Generation> serviceResponse = new ServiceResponse<Generation>(); try { var entity = _mapper.Map<Generation>(newGeneration); _context.Generations.Add(entity); _context.SaveChanges(); serviceResponse.Data = entity; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetGenerationDto>>> GetAll() { ServiceResponse<List<GetGenerationDto>> serviceResponse = new ServiceResponse<List<GetGenerationDto>>(); try { serviceResponse.Data = _context.Generations.Select(g => _mapper.Map<GetGenerationDto>(g)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetGenerationDto>> GetSpecific(int idGeneration) { ServiceResponse<GetGenerationDto> serviceResponse = new ServiceResponse<GetGenerationDto>(); try { var temp = _context.Generations.FirstOrDefault(g => g.Id == idGeneration); serviceResponse.Data = _mapper.Map<GetGenerationDto>(temp); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<Generation>> Update(UpdateGenerationDto updateGeneration) { ServiceResponse<Generation> serviceResponse = new ServiceResponse<Generation>(); try { var updatedGeneration = _context.Generations.FirstOrDefault(m => m.Id == updateGeneration.Id); updatedGeneration.Name = updatedGeneration.Name; _context.SaveChanges(); serviceResponse.Data = updatedGeneration; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<Generation>>> Delete(int idGeneration) { ServiceResponse<List<Generation>> serviceResponse = new ServiceResponse<List<Generation>>(); try { var toDelete = _context.Generations.FirstOrDefault(g => g.Id == idGeneration); _context.Generations.Remove(toDelete); _context.SaveChanges(); serviceResponse.Data = _context.Generations.ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Dtos/Payment/UpdatePaymentDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.Payment { public class UpdatePaymentDto { public int Id { get; set; } public bool isTerminated { get; set; } } } <file_sep>/AutoStonks.API/Services/AdvertService/IAdvertService.cs using AutoStonks.API.Dtos.Advert; using AutoStonks.API.Dtos.Payment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.AdvertService { public interface IAdvertService { public Task<ServiceResponse<GetPaymentDto>> AddAdvert(AddPaymentDto newAdvert); public Task<ServiceResponse<List<Advert>>> DeleteAdvert(int idAdvert); public Task<ServiceResponse<string>> UpdateAdvert(UpdateAdvertDto advert); public Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAllActiveBasicInfo(); public Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAllActivePremiumInfo(); public Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAllInactive(); public Task<ServiceResponse<GetAdvertFullInfoDto>> GetSpecificFullInfo(int idAdvert); public Task<ServiceResponse<GetAdvertBasicInfoDto>> GetSpecificBasicInfo(int idAdvert); public Task<ServiceResponse<List<GetAdvertBasicInfoDto>>> GetAdvertsMatchingToQuery(QueryAdvertDto queryAdvertDto); } } <file_sep>/AutoStonks.API/Services/AdvertEquipmentService/AdvertEquipmentService.cs using AutoMapper; using AutoStonks.API.Dtos.AdvertEquipment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.AdvertEquipmentService { public class AdvertEquipmentService : IAdvertEquipmentService { DataContext _context; private readonly IMapper _mapper; public AdvertEquipmentService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<List<AdvertEquipment>>> AddAdvert(List<AddAdvertEquipmentDto> newConnection) { ServiceResponse<List<AdvertEquipment>> serviceResponse = new ServiceResponse<List<AdvertEquipment>>(); try { _context.AdvertEquipment.AddRange(_mapper.Map<List<AdvertEquipment>>(newConnection)); _context.SaveChanges(); serviceResponse.Data = _context.AdvertEquipment.Where(ae => ae.AdvertId == newConnection[0].AdvertId).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Services/EquipmentService/IEquipmentService.cs using AutoStonks.API.Dtos.Equipment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.EquipmentService { public interface IEquipmentService { public Task<ServiceResponse<List<GetEquipmentDto>>> GetEquipment(); } } <file_sep>/AutoStonks.API/Services/ModelService/ModelService.cs using AutoMapper; using AutoStonks.API.Dtos.Model; using AutoStonks.API.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.ModelService { public class ModelService : IModelService { DataContext _context; private readonly IMapper _mapper; public ModelService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<Model>> AddModel(AddModelDto newModel) { ServiceResponse<Model> serviceResponse = new ServiceResponse<Model>(); try { var entity = _mapper.Map<Model>(newModel); _context.Models.Add(entity); _context.SaveChanges(); serviceResponse.Data = entity; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<Model>>> Delete(int idModel) { ServiceResponse<List<Model>> serviceResponse = new ServiceResponse<List<Model>>(); try { var toDelete = _context.Models.FirstOrDefault(m => m.Id == idModel); _context.Models.Remove(toDelete); _context.SaveChanges(); serviceResponse.Data = _context.Models.ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<List<GetModelDto>>> GetAll() { ServiceResponse<List<GetModelDto>> serviceResponse = new ServiceResponse<List<GetModelDto>>(); try { serviceResponse.Data = _context.Models.Include(m => m.Generations).Select(m => _mapper.Map<GetModelDto>(m)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<GetModelDto>> GetSpecific(int idModel) { ServiceResponse<GetModelDto> serviceResponse = new ServiceResponse<GetModelDto>(); try { var temp = _context.Models.Include(m => m.Generations).FirstOrDefault(m => m.Id == idModel); serviceResponse.Data = _mapper.Map<GetModelDto>(temp); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } public async Task<ServiceResponse<Model>> Update(UpdateModelDto updateModel) { ServiceResponse<Model> serviceResponse = new ServiceResponse<Model>(); try { var updatedModel = _context.Models.FirstOrDefault(m => m.Id == updateModel.Id); updatedModel.Name = updateModel.Name; _context.SaveChanges(); serviceResponse.Data = updatedModel; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/Controllers/UserController.cs using AutoStonks.API.Dtos.User; using AutoStonks.API.Models; using AutoStonks.API.Services.UserService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class UserController : ControllerBase { private readonly IUserService _userService; public UserController(IUserService userService) { _userService = userService; } [HttpGet("GetAll")] public async Task<IActionResult> Get() { ServiceResponse<List<GetUsersDto>> response = await _userService.GetAllUsers(); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("{id}")] public async Task<IActionResult> GetSpecific(int id) { ServiceResponse<GetUserDto> response = await _userService.GetUserById(id); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost] public async Task<IActionResult> AddUser(AddUserDto newUser) { ServiceResponse<UserDto> response = await _userService.AddUser(newUser); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPut] public async Task<IActionResult> UpdateUser(UpdateUserDto updateUser) { ServiceResponse<GetUserDto> response = await _userService.UpdateUser(updateUser); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteUser(int id) { ServiceResponse<DeleteUserDto> response = await _userService.DeleteUser(id); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost("login")] public async Task<IActionResult> Login(LoginDto login) { ServiceResponse<UserDto> response = await _userService.Login(login); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost("pwd")] public async Task<IActionResult> PasswordChange(PasswordChangeDto pwdChange) { ServiceResponse<UserDto> response = await _userService.PasswordChange(pwdChange); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Dtos/Advert/QueryAdvertDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.Advert { public class QueryAdvertDto { public enum FuelType { Diesel, Petrol, Electric, LPG } public enum ConditionState { Damaged, Undamaged } public enum DriveTypes { FWD, RWD, AWD } public enum TransmissionTypes { Sequence, Automatic, Manual } public string VIN { get; set; } public double MinPrice { get; set; } public double MaxPrice { get; set; } public int MinMileage { get; set; } public int MaxMileage { get; set; } public DateTime? FromCarProductionDate { get; set; } public DateTime? ToCarProductionDate { get; set; } public FuelType? Fuel { get; set; } public ConditionState? Condition { get; set; } public int MinHorsepower { get; set; } public int MaxHorsepower { get; set; } public int MinDisplacement { get; set; } public int MaxDisplacement { get; set; } public TransmissionTypes? TransmissionType { get; set; } public DriveTypes? DriveType { get; set; } public string BrandName { get; set; } public string ModelName { get; set; } public string GenerationName { get; set; } } } <file_sep>/AutoStonks.API/Controllers/ModelController.cs using AutoStonks.API.Dtos.Model; using AutoStonks.API.Models; using AutoStonks.API.Services.ModelService; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Controllers { [ApiController] [Route("[controller]")] public class ModelController : Controller { private readonly IModelService _modelService; public ModelController(IModelService modelService) { _modelService = modelService; } [HttpGet] public async Task<IActionResult> Get() { ServiceResponse<List<GetModelDto>> response = await _modelService.GetAll(); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpGet("{idModel}")] public async Task<IActionResult> GetSpecific(int idModel) { ServiceResponse<GetModelDto> response = await _modelService.GetSpecific(idModel); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPost] public async Task<IActionResult> AddModel(AddModelDto newModel) { ServiceResponse<Model> response = await _modelService.AddModel(newModel); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpDelete("{idModel}")] public async Task<IActionResult> DeleteModel(int idModel) { ServiceResponse<List<Model>> response = await _modelService.Delete(idModel); if (response.Data == null) { return NotFound(response); } return Ok(response); } [HttpPut] public async Task<IActionResult> UpdateModel(UpdateModelDto updateModel) { ServiceResponse<Model> response = await _modelService.Update(updateModel); if (response.Data == null) { return NotFound(response); } return Ok(response); } } } <file_sep>/AutoStonks.API/Dtos/Photo/AddPhotosDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.Photo { public class AddPhotosDto { public string Name { get; set; } public string Source { get; set; } public int AdvertId { get; set; } } } <file_sep>/AutoStonks.API/Services/PhotoService/IPhotoService.cs using AutoStonks.API.Dtos.Photo; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.PhotoService { public interface IPhotoService { public Task<ServiceResponse<List<GetPhotosDto>>> GetPhotos(int advertId); } } <file_sep>/AutoStonks.API/Dtos/AdvertEquipment/AddAdvertEquipmentDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.AdvertEquipment { public class AddAdvertEquipmentDto { public int AdvertId { get; set; } public int EquipmentId { get; set; } } } <file_sep>/AutoStonks.API/Services/EquipmentService/EquipmentService.cs using AutoMapper; using AutoStonks.API.Dtos.Equipment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Services.EquipmentService { public class EquipmentService : IEquipmentService { private readonly IMapper _mapper; DataContext _context; public EquipmentService(IMapper mapper, DataContext context) { _mapper = mapper; _context = context; } public async Task<ServiceResponse<List<GetEquipmentDto>>> GetEquipment() { ServiceResponse<List<GetEquipmentDto>> serviceResponse = new ServiceResponse<List<GetEquipmentDto>>(); try { serviceResponse.Data = _context.Equipment.ToList().Select(e => _mapper.Map<GetEquipmentDto>(e)).ToList(); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } return serviceResponse; } } } <file_sep>/AutoStonks.API/AutoMapperProfile.cs using AutoMapper; using AutoStonks.API.Dtos.Brand; using AutoStonks.API.Dtos.User; using AutoStonks.API.Dtos.Equipment; using AutoStonks.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoStonks.API.Dtos.Model; using AutoStonks.API.Dtos.Generation; using AutoStonks.API.Dtos.Advert; using AutoStonks.API.Dtos.AdvertEquipment; using AutoStonks.API.Dtos.Payment; using AutoStonks.API.Dtos.Photo; namespace AutoStonks.API { public class AutoMapperProfile : Profile { public AutoMapperProfile() { CreateMap<User, GetUserDto>(); CreateMap<User, GetUsersDto>(); CreateMap<User, DeleteUserDto>(); CreateMap<AddUserDto, User>(); CreateMap<UserDto, User>(); CreateMap<User, UserDto>(); CreateMap<GetUserDto, User>(); CreateMap<UpdateUserDto, User>(); CreateMap<Brand, GetBrandDto>(); CreateMap<AddBrandDto, Brand>(); CreateMap<UpdateBrandDto, Brand>(); CreateMap<GetEquipmentDto, Equipment>(); CreateMap<Equipment, GetEquipmentDto>(); CreateMap<Model, GetModelDto>(); CreateMap<GetModelDto, Model>(); CreateMap<Generation, GetGenerationDto>(); CreateMap<GetGenerationDto, Generation>(); CreateMap<AddGenerationDto, Generation>(); CreateMap<AddAdvertDto, Advert>(); CreateMap<UpdateAdvertDto, Advert>(); CreateMap<Advert, UpdateAdvertDto>(); CreateMap<Advert, GetAdvertBasicInfoDto>(); CreateMap<Advert, GetAdvertFullInfoDto>(); CreateMap<List<AddAdvertEquipmentDto>, List<AdvertEquipment>>(); CreateMap<AddAdvertEquipmentDto, AdvertEquipment>(); CreateMap<AdvertEquipment, AddAdvertEquipmentDto>(); CreateMap<List<AdvertEquipment>, List<AddAdvertEquipmentDto>>(); CreateMap<AdvertEquipment, PlainAdvertEquipmentDto>(); CreateMap<AddPaymentDto, Payment>(); CreateMap<UpdatePaymentDto, Payment>(); CreateMap<Payment, GetPaymentDto>(); CreateMap<GetPaymentDto, Payment>(); CreateMap<Generation, PlainGenerationDto>(); CreateMap<Brand, PlainBrandDto>(); CreateMap<Model, PlainModelDto>(); CreateMap<PlainGenerationDto, Generation>(); CreateMap<PlainBrandDto, Brand>(); CreateMap<PlainModelDto, Model>(); CreateMap<AddPhotosDto, Photo>(); CreateMap<Photo, AddPhotosDto>(); CreateMap<Photo, GetPhotosDto>(); CreateMap<GetPhotosDto, Photo>(); } } } <file_sep>/AutoStonks.API/DataContext.cs using AutoStonks.API.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API { public class DataContext : DbContext { public DbSet<Advert> Adverts { get; set; } public DbSet<Photo> Photos { get; set; } public DbSet<Equipment> Equipment { get; set; } public DbSet<AdvertEquipment> AdvertEquipment { get; set; } public DbSet<User> Users { get; set; } public DbSet<Brand> Brands { get; set; } public DbSet<Model> Models { get; set; } public DbSet<Generation> Generations { get; set; } public DbSet<Payment> Payments { get; set; } public DataContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Many-To-Many --> AdverEquipment modelBuilder.Entity<AdvertEquipment>() .HasKey(ae => new { ae.AdvertId, ae.EquipmentId }); modelBuilder.Entity<AdvertEquipment>() .HasOne(ae => ae.Advert) .WithMany(a => a.AdvertEquipments) .HasForeignKey(ae => ae.AdvertId); modelBuilder.Entity<AdvertEquipment>() .HasOne(ae => ae.Equipment) .WithMany(e => e.AdvertEquipments) .HasForeignKey(ae => ae.EquipmentId); modelBuilder.Seed(); } } } <file_sep>/AutoStonks.API/Dtos/AdvertEquipment/PlainAdvertEquipmentDto.cs using AutoStonks.API.Dtos.Equipment; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AutoStonks.API.Dtos.AdvertEquipment { public class PlainAdvertEquipmentDto { public int AdvertId { get; set; } public int EquipmentId { get; set; } public GetEquipmentDto Equipment { get; set; } } }
dba3f79d11e2da36209a878e1ff9aa73916b119d
[ "C#" ]
42
C#
DeathArmy/AutoStonks.API
4e2cf193e18cda784f0dbeacbb8f9c1e513804ce
3efe3abc12e58a1286c06ac8bdb76042d9a9783a
refs/heads/master
<repo_name>cc7gs/node-movie<file_sep>/server/tasks/qiniu.js const qiniu=require('qiniu'); const nanoid=require('nanoid'); const config=require('../config') //bucket 即七牛上的存储空间名 const bucket=config.qiniu.bucket; //生成鉴权对象 const mac=new qiniu.auth.digest.Mac(config.qiniu.AK,config.qiniu.SK); //构建配置对象 const cfg=new qiniu.conf.Config(); const client=new qiniu.rs.BucketManager(mac,cfg); const uploadToQiniu=async(url,key)=>{ return new Promise((resolve,reject)=>{ client.fetch(url,bucket,key,(err,ret,info)=>{ if(err){ reject(err); }else{ if(info.statusCode===200){ resolve({key}); }else{ reject(info); } } }) }) } ;(async ()=>{ const movies = [{ doubanId: 27110296, video: 'http://vt1.doubanio.com/201901221122/f5bffd7d2db0f38c62c3ae394584aede/view/movie/M/402390189.mp4M/402390189.mp4', cover: 'https://img3.doubanio.com/img/trailer/medium/2539667252.jpg', poster: 'https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2539661066.jpg' }] movies.map(async moive=>{ if(moive.video && !moive.key){ try { console.log('正在转换video'); let videoData=await uploadToQiniu(moive.video,nanoid()+'.mp4'); console.log('正在转换cover'); let coverData=await uploadToQiniu(moive.cover,nanoid()+'.png'); console.log('正在转换poster'); let posterData=await uploadToQiniu(moive.video,nanoid()+'.png'); if(videoData.key){ moive.videoKey=videoData.key } if(coverData.key){ moive.coverKey=coverData.key } if(posterData.key){ moive.posterKey=posterData.key } console.log(moive) } catch (error) { console.log(error,'error'); } } }) })()<file_sep>/server/crawler/trailer-list.js const puppeteer=require('puppeteer'); const URL=`https://movie.douban.com/explore#!type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start=0`; const sleep=time=>new Promise(resolve=>{ setTimeout(resolve,time); }); console.log('开始执行...'); ( async ()=>{ console.log('Start visit the target page'); const browser= await puppeteer.launch({ args:['--no-sanbox'], //启动非沙箱模式 dumpio:false }); const page=await browser.newPage(); //开启新页面 await page.goto(URL,{ waitUntil:'networkidle2' }) await sleep(3000); //点击页面加载更多 await page.waitForSelector('.more'); for(let i=0;i<1;i++){ await page.click('.more'); await sleep(3000); } const result=await page.evaluate(()=>{ var $=window.$; var items=$('.list-wp a'); var links=[]; if(items.length>=1){ items.each((index,item)=>{ let it=$(item); let doubanId=it.find('div').data('id'); let title=it.find('img').attr('alt'); let rate=Number(it.find('strong').text()) let poster=it.find('img').attr('src'); //换成大图 // let poster=it.find('img').attr('src').replace('s_ratio','l_ratio'); links.push({ doubanId, title, rate, poster }) }) } return links; }) //关闭浏览器 browser.close(); // console.log(result); // console.log(result.length,'length--------') //将结果发送出去 process.send({result}); //退出进程 process.exit(0); })()<file_sep>/server/tasks/api.js //根据电影id获取电影信息列表 api //http://api.douban.com/v2/movie/subject/电影id const rp = require('request-promise-native'); //获取电影详情信息 async function fetchMovie(item) { const url = `http://api.douban.com/v2/movie/subject/${item.doubanId}`; const res = await rp(url); return res; } (async () => { let movies = [{ doubanId: 26972258, title: '江湖儿女', rate: 7.6, poster: 'https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2533283770.jpg' }, { doubanId: 26654498, title: '爱你,西蒙', rate: 8.3, poster: 'https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2523592367.jpg' } ]; movies.map(async moive => { let moiveData = await fetchMovie(moive); try{ moiveData=JSON.parse(moiveData); console.log(moiveData,'movieData'); }catch(error){ console.log('转换异常',error); } }) })(); <file_sep>/server/test/async.js function doSync(doSth,time){ return new Promise(resolve=>{ setTimeout(()=>{ console.log(doSth+'用了'+time+'毫秒'); resolve(); },time) }) } const Scott={doSync} const Meizi={doSync} ;(async ()=>{ console.log('case 1: 起床来到门口') await Scott.doSync('刷牙',1000) console.log('啥也没干 一直等'); await Meizi.doSync('去洗澡...',2000); console.log('什么也没干...'); })();<file_sep>/README.md # node-movie 基于react koa2 node 搭建的一个电影预告片项目 #获取数据 通过 puppeteer 模拟浏览器获取数据 [github地址](https://github.com/GoogleChrome/puppeteer) 除此之外我们还可以用其它库比如:Selenium、PhantomJs **Puppeteer好处:** - 利用网页生成PDF、图片 - 爬取SPA应用,并生成预渲染内容(SSR) - 获取网页内容 **常用知识点** - puppeteer.launch 启动浏览器 - browser.newPage() 创建一个新页面 - page.goto 进入指定网页 - page.screenshot 截图 ## node父子进程通信 ## 进程问题 ### 什么是同步异步 同步和异步关注的是**消息通信机制**。 **同步:** 指的是发送者发出消息后,若消息没有返回,调用者就主动等待结果什么时也不干。 **异步:** 指的发送者发出消息后,就去做别的事,当消息回来后就通知它,它就处里该消息。 ### 什么是异步IO ### 什么是阻塞与非阻塞 阻塞与非阻塞关注的是**程序等待调用结果时的==状态==** **阻塞:** 指的是调用结果返回之前,当前线程处于被挂起。调用线程只有在得到结果后才会返回。 **非阻塞:** 指的调用结果返回之前,该调用者不会阻塞当前线程。 ### 什么是事件循环与事件驱动 ### 什么是单线程 ### 什么是进程 ### 什么是子进程 ### 怎么来启动子进程 ### 进程如何通信 ## node上传资源到七牛云 > nanoid //可以生成随机id ## MongoDB vs mysql |MongoDB|mysql|名称| |---|---|---| |document|record|记录| |collection|table|表| |database|database|数据库| ### Mongoose 是mongoDB的一个对象模型库,封装了mongoDB对文档的一些增删改查等常用方法,让nodejs操作mongoDB数据库变得更容易 **Schema** 是一种文件形式存储的数据库模型骨架,不具备数据库的操作能力,即定义数据类型 例如: ```javascript var PersonSchema=new mongoose.Schema({ name:String; }) ``` **Model** 由Schema构造生成的模型,具有抽象属性和行为的数据库操作 ```javascript var PersonModel=db.model('person',PersonSchema) ``` **entity** 由Model创造的实体,他的操作也会影响数据库,可以操作数据库CRUD ```javascript var personEntity=new PersonModel({ name:'kk' }) ``` [原文传送门](https://cnodejs.org/topic/504b4924e2b84515770103dd) **git常用操作** ``` git checkout master -b 分支名 git add . git commit -m 描述 //将分支提交到远程分支 git push origin 分支名 //回到主分支 git checkout master //合并远程分支 git merge origin/分支名 //推送 git push master ```<file_sep>/server/test/stage.js const {readFile}=require('fs') const EventEmitter=require('events'); class EE extends EventEmitter{} const yy=new EE(); yy.on('event',()=>{ console.log('event 监听'); }) setTimeout(() => { console.log("0 毫秒后执行的定时器回调 "); }, 0); setTimeout(() => { console.log("100 毫秒后执行的定时器回调 "); }, 100); setTimeout(() => { console.log("200 毫秒后执行的定时器回调 "); }, 200); readFile('./async.js',data=>{ console.log('完成文件 async读操作'); }) readFile('../index.js',data=>{ console.log('完成文件 async读操作'); }) setImmediate(()=>{ console.log('immediate 回调'); }) process.nextTick(()=>{ console.log('process.nextTick 的回调'); }) Promise.resolve() .then(()=>{ yy.emit('event'); process.nextTick(()=>{ console.log('Process.nextTick 2 回调'); }) console.log('Promise的一次回调'); }) .then(()=>{ console.log('Promise 的2 次回调'); })<file_sep>/server/config/index.js module.exports={ "qiniu":{ "bucket":"movie", "AK":"<KEY>", "SK":"<KEY>" } }<file_sep>/server/index.js const Koa=require('koa'); const mongoose=require('mongoose'); require('./database/schema/movie'); const {connect,initSchemas}=require('./database/init'); const views=require('koa-views'); const {resolve} =require('path'); const app=new Koa(); app.use(views(resolve(__dirname + '/views'), { extension: 'pug' // 以 pug 模版为例 })) ;(async ()=>{ await connect() initSchemas(); const Movie=mongoose.model('Movie'); const Movies=await Movie.find({}) console.log(Movies); })() app.use(async (ctx,next)=>{ await ctx.render('index',{ you:'Luck', me:'Scott' }) }) // //添加端口号 app.listen(3333,()=>{ console.log('监听端口 3333'); });<file_sep>/server/test/eventloop.js setImmediate(()=>{ console.log('阶段三 immediate 回调1'); }); setImmediate(()=>{ console.log('阶段三 immediate 回调2'); }); setImmediate(()=>{ console.log('阶段三 immediate 回调3'); }); setTimeout(() => { console.log('定时器零毫秒'); },0);
eb1f5be8c4c803031ac1339bd393734d1bb99e6c
[ "JavaScript", "Markdown" ]
9
JavaScript
cc7gs/node-movie
fb86269f558b9e8a5004a6fc8be7be2c40af60e2
b24e8f17fd566da86302e835648f17f4df248a4a
refs/heads/master
<repo_name>clarkema/advent-of-code<file_sep>/2018/day_01/day_01.rb #! ruby require 'set' def part_2(drifts) seen = Set.new freq = 0 drifts.cycle do |delta| freq += delta break freq unless seen.add?(freq) end end drifts = File.new("day_01.input").each_line.map(&:to_i) puts "Part 1: #{drifts.sum}" puts "Part 2: #{part_2(drifts)}" <file_sep>/2017/day_01/rust_01/Cargo.toml [package] name = "rust_01" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] [dependencies] <file_sep>/2018/day_01/day_01.lua #! lua function read_file(file) local lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end function sum(a) local acc = 0; for _, v in ipairs(a) do acc = acc + v end return acc end function part_2(drift) local seen = {} local acc = 0 while true do for _, v in ipairs(drift) do acc = acc + v; if seen[acc] then return acc else seen[acc] = true end end end end drift = read_file("day_01.input") print("Part 1: " .. sum(drift)) print("Part 2: " .. part_2(drift)) <file_sep>/2017/day_05/day_05.py #!/usr/bin/env python3 with open('day_05.input') as input_file: lines = input_file.read().split("\n") instructions = [int(x) for x in lines] index = 0 stop = len(instructions) - 1 i = 0 while index <= stop: jump = instructions[index]; if jump >= 3: instructions[index] = instructions[index] - 1 else: instructions[index] = instructions[index] + 1 index = index + jump; i = i + 1 print(i) <file_sep>/2018/day_01/rust_01/src/main.rs use std::fs::File; use std::io::{self, BufRead}; use std::collections::HashSet; fn part1(drifts: &[i32]) -> i32 { drifts.iter().sum() } fn part2(drifts: &[i32]) -> i32 { let mut seen = HashSet::new(); drifts.iter().cycle() .scan(0, |acc, x| { *acc = *acc + x; Some(*acc) }) .skip_while(|x| { seen.insert(x.clone()) }) .nth(0) .unwrap() } fn main() { let filename = "../day_01.input"; let fh = File::open(filename).expect("Failed to open file"); let drifts: Vec<i32> = io::BufReader::new(fh).lines() .map(|l| l.unwrap().parse::<i32>().unwrap()) .collect(); println!("Part 1: {}", part1(&drifts)); println!("Part 2: {}", part2(&drifts)); } <file_sep>/2018/day_01/day_01.py #! python3 from itertools import cycle, accumulate def part_2(): seen = set() for x in accumulate(cycle(drift)): if x in seen: return x else: seen.add(x) drift = [int(l) for l in open("day_01.input")] print(sum(drift)) print(part_2()) <file_sep>/2017/day_01/day_01.py #! /usr/bin/env python3 # This is a Python 3 solution to day one of 2017's Advent of Code; see # http://adventofcode.com/2017/day/1 for the full puzzle. import collections def captcha_sum(digits, rotation): d = [int(d) for d in digits] n = collections.deque(d) n.rotate(-rotation) return sum([x[0] for x in zip(d, n) if x[0] == x[1]]) with open('day_01.input') as input_file: input = input_file.read().replace('\n', '') print('Part 1:', captcha_sum(input, 1)) print('Part 2:', captcha_sum(input, len(input)//2)) <file_sep>/2018/day_01/nim_01/Makefile all: nim compile -d:release day_01.nim <file_sep>/2017/day_01/rust_01/src/main.rs use std::fs::File; use std::io::Read; fn captcha_sum(input: &str, rotation: usize) -> u32 { let mut acc = 0; let digits = input.chars() .map(|c| c.to_digit(10).unwrap()) .collect::<Vec<u32>>(); for (i, c) in digits.iter().enumerate() { if digits[(i + rotation) % digits.len()] == *c { acc += *c; } } acc } fn main() { let filename = "../day_01.input"; let mut input = String::new(); let mut fh = File::open(filename).expect("file not found"); fh.read_to_string(&mut input) .expect("something went wrong reading the file"); let input = input.trim(); println!("Part 1: {:?}", captcha_sum(&input, 1)); println!("Part 2: {:?}", captcha_sum(&input, input.len() / 2)); }
db36245263710eb1fafee717b0335a512f181895
[ "Ruby", "Lua", "TOML", "Makefile", "Rust", "Python" ]
9
Ruby
clarkema/advent-of-code
ef45d369d9fedce3678c9bc610db5170a655b518
a27f922f4a350477cb69d67c92246d25f930adf7
refs/heads/master
<repo_name>nixward/bunjil<file_sep>/test/helpers/genera_helper_test.rb require 'test_helper' class GeneraHelperTest < ActionView::TestCase end <file_sep>/app/controllers/genera_controller.rb class GeneraController < ApplicationController def create @family = Family.find(params[:family_id]) @comment = @family.genera.create(params[:genus].permit(:name, :description)) redirect_to family_path(@family) end end <file_sep>/README.md bunjil ====== Website for social gardening, wildlife, food and culture specialising in Australian native plants, animals and insects.
8f0a0100a869741217827eda46a1aa1fe07992e4
[ "Markdown", "Ruby" ]
3
Ruby
nixward/bunjil
1c9d11741698bcd3a3c502cf3047a65049479d73
e65623e4a566723992cd521ef0348a437cffeb83
refs/heads/master
<file_sep>#!/usr/bin/env python from __future__ import print_function import os import os.path import tempfile import subprocess import time import signal import re import sys import shutil create = 0 log = 0 debug = 0 file_locations = os.path.expanduser(os.getcwd()) logisim_location = os.path.join(os.getcwd(),"../../../../Utilities/logisim.jar") if log: new = open('new.out', 'w') logfile = open('TEST_LOG','w') def student_reference_match_unbounded(student_out, reference_out): while True: line1 = student_out.readline() line2 = reference_out.readline() if line2 == '': break if line1 != line2: return False return True def assure_path_exists(path): dir = os.path.dirname(path) if not os.path.exists(dir): os.makedirs(dir) class TestCase(object): def __init__(self, circfile, outfile, tracefile, points): self.circfile = circfile self.outfile = outfile self.tracefile = tracefile self.points = points class AbsoluteTestCase(TestCase): """ All-or-nothing test case. """ def __call__(self): output = tempfile.TemporaryFile(mode='r+') try: stdinf = open('/dev/null') except Exception as e: if debug: print("/dev/null not found, attempting different dir..") try: stdinf = open('nul') if debug: print("nul dir works!") except Exception as e: print("The no nul directories. Program will most likely error now.") proc = subprocess.Popen(["java","-jar",logisim_location,"-tty","table",os.path.join('.',os.path.basename(self.circfile))], stdin=stdinf, stdout=subprocess.PIPE) try: assure_path_exists(self.outfile) outfile = open(self.outfile, "wb") student_out = proc.stdout.read() outfile.write(student_out) outfile.close() assure_path_exists(self.outfile) outfile = open(self.outfile, "r") reference = open(self.tracefile) passed = student_reference_match_unbounded(outfile, reference) finally: try: os.kill(proc.pid,signal.SIGTERM) except Exception as e: if debug: print("Could not kill process! Perhaps it closed itself?") if passed: return (self.points,"Matched expected output") else: return (0,"Did not match expected output") def test_submission(name,outfile,tests): # actual submission testing code print ("Testing submission for %s..." % name) total_points = 0 total_points_received = 0 tests_passed = 0 tests_partially_passed = 0 tests_failed = 0 test_results = [] for description,test,points_received,reason in ((description,test) + test() for description,test in tests): # gross points = test.points assert points_received <= points if points_received == points: print ("\t%s PASSED test: %s" % (name, description)) if log: print ("\t%s PASSED test: %s" % (name, description), file=logfile) total_points += points total_points_received += points tests_passed += 1 test_results.append("\tPassed test \"%s\" worth %d points." % (description,points)) elif points_received > 0: print ("\t%s PARTIALLY PASSED test: %s" % (name,description)) if log: print ("\t%s PARTIALLY PASSED test: %s" % (name,description), file=logfile) total_points += points total_points_received += points_received tests_partially_passed += 1 test_results.append("\tPartially passed test \"%s\" worth %d points (received %d)" % (description, points, points_received)) else: print ("\t%s FAILED test: %s" % (name, description)) if log: print ("\t%s FAILED test: %s" % (name, description), file=logfile) total_points += points tests_failed += 1 test_results.append("\tFailed test \"%s\" worth %d points. Reason: %s" % (description, points, reason)) print ("\tScore for %s: %d/%d (%d/%d tests passed, %d partially)" %\ (name, total_points_received, total_points, tests_passed, tests_passed + tests_failed + tests_partially_passed, tests_partially_passed)) print ("%s: %d/%d (%d/%d tests passed, %d partially)" %\ (name, total_points_received, total_points, tests_passed, tests_passed + tests_failed + tests_partially_passed, tests_partially_passed), file=outfile) if log: print ("\n\n%s: %d/%d (%d/%d tests passed, %d partially)" %\ (name, total_points_received, total_points, tests_passed, tests_passed + tests_failed + tests_partially_passed, tests_partially_passed), file=logfile) for line in test_results: print (line, file=outfile) if log: print ( line, file=logfile) #return points_received return tests_failed + tests_partially_passed > 0 def main(tests): e = test_submission('correctness',sys.stdout,tests) exit(e) <file_sep># RISCPU-V [![Build Status](https://travis-ci.org/ThaumicMekanism/RISCPU-V.svg?branch=master)](https://travis-ci.org/ThaumicMekanism/RISCPU-V) This project is to create a full functioning logisim template of a RISC-V CPU. Eventually, the goal is to make all 16, 32, 64, and 128 bit full functioning cpus. This project draws inspiration from UC Berkeley's CS61C's class and may contain diagrams from lectures illustrating the circuitry. ## TODO * Work on implementing the CSR register * Add more tests to confirm that everything is working as intended<file_sep>#!/usr/bin/env python import autograder_base import os.path from autograder_base import file_locations, AbsoluteTestCase, main tests = [ ("Pipelined CPU add/lui/sll test",AbsoluteTestCase(os.path.join(file_locations,'CPU-add_lui_sll.circ'), os.path.join(file_locations,'output/CPU-add_lui_sll.out'), os.path.join(file_locations,'reference_output/CPU-add_lui_sll.out'),1)), ("Pipelined CPU memory test",AbsoluteTestCase(os.path.join(file_locations,'CPU-mem.circ'), os.path.join(file_locations,'output/CPU-mem.out'), os.path.join(file_locations,'reference_output/CPU-mem.out'),1)), ("Pipelined CPU branch test",AbsoluteTestCase(os.path.join(file_locations,'CPU-branch.circ'), os.path.join(file_locations,'output/CPU-branch.out'), os.path.join(file_locations,'reference_output/CPU-branch.out'),1)), ("Pipelined CPU jump test",AbsoluteTestCase(os.path.join(file_locations,'CPU-jump.circ'), os.path.join(file_locations,'output/CPU-jump.out'), os.path.join(file_locations,'reference_output/CPU-jump.out'),1)), ("Pipelined CPU swge test",AbsoluteTestCase(os.path.join(file_locations,'CPU-swge.circ'), os.path.join(file_locations,'output/CPU-swge.out'), os.path.join(file_locations,'reference_output/CPU-swge.out'),1)), ("Pipelined CPU br_jalr test",AbsoluteTestCase(os.path.join(file_locations,'CPU-br_jalr.circ'), os.path.join(file_locations,'output/CPU-br_jalr.out'), os.path.join(file_locations,'reference_output/CPU-br_jalr.out'),1)) ] if __name__ == '__main__': main(tests) <file_sep>#!/usr/bin/env python3 import os.path import sys # This is necessary because we use the same tester for everything. sys.path.insert(0, '../../../../Utilities') import autograder_base from autograder_base import file_locations, AbsoluteTestCase, main tests = [ ("Single-cycle CPU add/lui/sll test",AbsoluteTestCase(os.path.join(file_locations,'CPU-add_lui_sll.circ'), os.path.join(file_locations,'output/CPU-add_lui_sll.out'), os.path.join(file_locations,'reference_output/CPU-add_lui_sll.out'),1)), ("Single-cycle CPU memory test",AbsoluteTestCase(os.path.join(file_locations,'CPU-mem.circ'), os.path.join(file_locations,'output/CPU-mem.out'), os.path.join(file_locations,'reference_output/CPU-mem.out'),1)), ("Single-cycle CPU branch test",AbsoluteTestCase(os.path.join(file_locations,'CPU-branch.circ'), os.path.join(file_locations,'output/CPU-branch.out'), os.path.join(file_locations,'reference_output/CPU-branch.out'),1)), ("Single-cycle CPU jump test",AbsoluteTestCase(os.path.join(file_locations,'CPU-jump.circ'), os.path.join(file_locations,'output/CPU-jump.out'), os.path.join(file_locations,'reference_output/CPU-jump.out'),1)), ("Single-cycle CPU br_jalr test",AbsoluteTestCase(os.path.join(file_locations,'CPU-br_jalr.circ'), os.path.join(file_locations,'output/CPU-br_jalr.out'), os.path.join(file_locations,'reference_output/CPU-br_jalr.out'),1)) ] if __name__ == '__main__': main(tests)<file_sep>#!/bin/bash # Just run this file and you can test your circ files! # Make sure your files are in the directory above this one though! script_full_path=$(dirname "$0") cd "$script_full_path" testdir="../tests/cpu_single/" cp mem.circ $testdir cp alu.circ $testdir cp regfile.circ $testdir cp cpu.circ $testdir cd $testdir python3 sanity_test.py ret=$? exit $ret <file_sep>from __future__ import print_function import sys hex_size = 8 num_registers = 32 def main(args): file = open(args[1]) lines = [l for l in file.readlines()] def mapper(strr): return hex(int(strr, 2))[2:] results = [] for l in lines: hexes = list(map(mapper,l.split())) result = [] for i in range(num_registers): result.append(''.join(hexes[i * hex_size : (i + 1) * hex_size])) result.append(''.join(hexes[num_registers * hex_size:num_registers * hex_size + 4])) result.append(''.join(hexes[num_registers * hex_size + 4:(num_registers + 1) * hex_size + 4])) result.append(''.join(hexes[(num_registers + 1) * hex_size + 4:])) results.append(result) print ("zero ra sp gp tp t0 t1 t2 s0 s1 a0 a1 a2 a3 a4 a5 a6 a7 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 t3 t4 t5 t6 Line# PC Inst") for r in results: string = ' '.join(r) print (string) print ('\n') if __name__ == "__main__": main(sys.argv)
ad39d9a281ae514e8e43045c5733ca1a9d27194b
[ "Markdown", "Python", "Shell" ]
6
Python
ThaumicMekanism/RISCPU-V
081276cfb5fb9c9be05d22fec87db6baeb98bc33
cb9833e53222411edad660291db07f29f60244d0
refs/heads/master
<repo_name>iScript/spring-boot-example<file_sep>/src/main/java/com/macro/app/model/User.java package com.macro.app.model; import java.io.Serializable; import java.util.Date; import javax.validation.constraints.NotEmpty; public class User implements Serializable { private Long id; @NotEmpty(message="用户名不能为空") private String username; @NotEmpty(message="密码不能为空") private String password; private String zzz; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username){ this.username = username; } public void setPassword(String password){ this.password = password; } public String getZzz() { return zzz; } public String getPassword() { return <PASSWORD>; } public String getTest(){ return "test!!!!"; //return username; } public Integer getStatus(){ return 1; } @Override public String toString() { return ("username=" + this.username + ",password=" + this.password); } }<file_sep>/src/main/java/com/macro/app/common/HttpResult.java // package com.macro.app.common; // public class HttpResult<T> { // }<file_sep>/src/main/java/com/macro/app/mapper/UserMapper.java package com.macro.app.mapper; import com.macro.app.model.User; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface UserMapper { @Select("SELECT * FROM user ") //将数据库查询到的zza字段,映射到模型的zzz @Results({ @Result(property = "zzz", column = "zza") }) List<User> getAll(); @Select("SELECT * FROM user ") List<User> list(); // @Delete("delete from user where id=#{id}") int delete(long id); //返回记录条数 @Insert("INSERT INTO user(username,password) VALUES(#{username}, #{password})") int insert(User user); //注解+xml的方式 @Update({"<script> ", "update user " , "<set>" , " <if test='username != null'>userName=#{username},</if>" , " <if test='password != null'>nick_name=#{password},</if>" , " </set> ", "where id=#{id} " , "</script>"}) int update(User user); @Select("SELECT * FROM user where username=#{username}") List<User> selectByUsername(User user); }
235090686edf56ecf0375785b08818fc3d3653f4
[ "Java" ]
3
Java
iScript/spring-boot-example
282a63074ed4342913138ea131f175c30be7b131
6a3acfe9d1f2e2959b8d7146b17797d05485576c
refs/heads/master
<file_sep><?php // Author Name : <NAME> // Information List : 2000 list print " .n . . n. . .dP dP 9b 9b. . 4 qXb . dX Xb . dXp t dX. 9Xb .dXb __ __ dXb. dXP .Xb 9XXb._ _.dXXXXb dXXXXbo. .odXXXXb dXXXXb._ _.dXXP 9XXXXXXXXXXXXXXXXXXXVXXXXXXXXOo. .oOXXXXXXXXVXXXXXXXXXXXXXXXXXXXP `9XXXXXXXXXXXXXXXXXXXXX'~ ~`OOO8b d8OOO'~ ~`XXXXXXXXXXXXXXXXXXXXXP' `9XXXXXXXXXXXP' `9XX' DIE `98v8P' HUMAN `XXP' `9XXXXXXXXXXXP' ~~~~~~~ 9X. .db|db. .XP ~~~~~~~ )b. .dbo.dP'`v'`9b.odb. .dX( ,dXXXXXXXXXXXb dXXXXXXXXXXXb. dXXXXXXXXXXXP' . `9XXXXXXXXXXXb dXXXXXXXXXXXXb d|b dXXXXXXXXXXXXb 9XXb' `XXXXXb.dX|Xb.dXXXXX' `dXXP `' 9XXXXXX( )XXXXXXP `' XXXX X.`v'.X XXXX XP^X'`b d'`X^XX X. 9 ` ' P )X `b ` ' d' ` ' Admin Finder - coded by ./Akbar Dravinky Information list : 2000 list "; echo "masukan site : "; $target = trim(fgets(STDIN)); $list = "bar.txt"; if(!preg_match("/^http:\/\//",$target) AND !preg_match("/^https:\/\//",$target)){ $targetnya = "http://$target"; }else{ $targetnya = $target; } $buka = fopen("$list","r"); $ukuran = filesize("$list"); $baca = fread($buka,$ukuran); $lists = explode("\r\n",$baca); foreach($lists as $login){ $log = "$targetnya/$login"; $ch = curl_init("$log"); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if($httpcode == 200){ $handle = fopen("result.txt", "a+"); fwrite($handle, "$log\n"); print "\n\n [".date('H:m:s')."] Mencoba : $log => Ditemukan\n"; }else{ print "\n[".date('H:m:s')."] Mencoba : $log => tidak di temukan"; } } ?> <file_sep>admin_finder Information List : 2000 list admin contact : <EMAIL> how to install : git clone https://github.com/tikung6etar/Nyarek cd Nyarek chmod +x log.php php log.php
3c8e8008f14a6a84f9a469fec15b84d0f9610acb
[ "Markdown", "PHP" ]
2
PHP
tikung6etar/Nyarek
2a170b506dd581040bfcca0423b01df1ed807b97
3e6b70a72b8918d4af60001a5f11c229c368d9cc
refs/heads/master
<file_sep>import urllib.request from xml.etree import ElementTree as ET from textblob import TextBlob import pandas as pd import operator import json def main(): # fetch xml with urllib.request.urlopen('http://www.latimes.com/local/lanow/rss2.0.xml') as url: data = url.read() # set root element of xml file root = ET.fromstring(data) channel = root[0] # find all the news titles, date, author, links given_data = [] for item in channel.findall('item'): title = str(item.find('title').text) date = str(item.find('pubDate').text) author = str(item[1].text) link = str(item.find('link').text) textForAnalyze = (str(item.find('title').text) + str(item.find('description').text).replace('<p>', '').replace('</p>', '').replace('...', '')) polarity = TextBlob(textForAnalyze).sentiment.polarity given_data.append((title, date, author, link, polarity)) labels = ['title', 'date', 'author', 'link', 'polarity'] df = pd.DataFrame.from_records(given_data, columns=labels) json_f = df.reset_index().to_json(orient='records') print(json_f) # start process if __name__ == '__main__': main() <file_sep># # created by <NAME> 5/12/2017 # import csv import re import json from math import log class NaiveBayes: def __init__(self): self.data = {} self.data['count'] = 0; self.data['classes'] = {} def save(self): with open('naive-bayes-data.json', 'w') as outfile: json.dump(self.data, outfile) def train(self, example, classifications): self.data['count'] += 1 for classification in classifications: if not classification in self.data['classes']: self.data['classes'][classification] = {} self.data['classes'][classification]['features'] = {} self.data['classes'][classification]['count'] = 0 self.data['classes'][classification]['probability'] = 0 self.data['classes'][classification]['count'] += 1 self.data['classes'][classification]['probability'] = self.data['classes'][classification]['count'] / \ self.data['count'] for feature in example: if not feature in self.data['classes'][classification]['features']: self.data['classes'][classification]['features'][feature] = {} self.data['classes'][classification]['features'][feature]['count'] = 0 self.data['classes'][classification]['features'][feature]['probability'] = 0 self.data['classes'][classification]['features'][feature]['count'] += 1 self.data['classes'][classification]['features'][feature]['probability'] = \ self.data['classes'][classification]['features'][feature]['count'] / \ self.data['classes'][classification]['count'] def classify(self, example): results = {} for classification in self.data['classes']: probability = self.data['classes'][classification]['probability']; for feature in example: if feature in self.data['classes'][classification]['features']: probability *= self.data['classes'][classification]['features'][feature]['probability'] else: probability *= 0 results[classification] = probability return results class BayesTextClassifier(NaiveBayes): def __init__(self): super(BayesTextClassifier, self).__init__() def addStopWords(self, words): self.stopwords.extend(words) def clean_text(self, text): return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", text).split()) def create_bigrams(self, array): array1 = array[:] array2 = array[:] array1.pop() array2.pop(0) rv = list(map(lambda x: ' '.join(list(x)),zip(array1, array2))) return rv def train(self, text, classifications): text = self.clean_text(text).split(' ') #text.extend(list(self.create_bigrams(text))) return super(BayesTextClassifier, self).train(text, classifications) def classify(self, text): text = self.clean_text(text).split(' ') #text.extend(list(self.create_bigrams(text))) return super(BayesTextClassifier, self).classify(text) def get_max_value_key(d1): values = list(d1.values()) keys = list(d1.keys()) max_value_index = values.index(max(values)) max_key = keys[max_value_index] return max_key def main(): print("😀") file = open('./training_sets/Sentiment Analysis Dataset.csv', 'r') reader = csv.DictReader(file, delimiter=',') training = [] testing = [] i = 0 for line in reader: if i > 10000000000: break if i % 10 != 0: training.append(line) else: testing.append(line) i += 1 file.close() bayes = BayesTextClassifier() for line in training: bayes.train(line['text'], [line['sentiment']]) bayes.save() correct = 0 total = 0 for line in testing: total += 1 if get_max_value_key(bayes.classify(line['text'])) == line['sentiment']: correct += 1 percent = correct / float(total) print("correct: " + str(correct) + " total: " + str(total) + " percent: " + str(percent)) return 0 if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python3 import signal import sys import json import os import re directory = os.path.dirname(os.path.abspath(__file__)) import nltk # Set the nltk data path nltk.data.path.append(directory + "/nltk_data") # import vader analyzer from textblob import TextBlob # setup signal handling def signal_handler(signal, frame): print('You pressed Ctrl+C!') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) def clean_tweet(tweet): return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) def main(): # Go over each line of stdin and flush after each write data = sys.argv[len(sys.argv) - 1] sentimentScores = TextBlob(clean_tweet(data)) analysis = {} analysis["compound"] = sentimentScores.sentiment.polarity sys.stdout.write(json.dumps(analysis)) return 0 if __name__ == '__main__': main() <file_sep>#!/usr/bin/env node /** * Created by Zera on 3/16/17. */ var Rx = require('rxjs/Rx'); const cp = require('child_process'); const LRUMap = require('lru_map').LRUMap; const execFile = cp.execFile; const execFileSync = cp.execFileSync; var Twitter = require('twitter'); var client = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET //bearer_token: process.env.TWITTER_BEARER_TOKEN }); // Install NLTK data // execFileSync('python3', ['nltk_data_install.py']); const MAX_TRACKED_PHRASES = 400; var termMap = new LRUMap(MAX_TRACKED_PHRASES); var trackPhrasesSubject = (new Rx.Subject()).map(term=>{ termMap.set(term,true); return Array.from(termMap.keys()); }); //switchmap the observable which tracks the terms via the twitter api var streamObservable = trackPhrasesSubject .debounce(()=>Rx.Observable.timer(100)) .switchMap( terms => Rx.Observable.fromEvent( client.stream('statuses/filter', { track:terms.toString(), //Array tostring naturally inserts a ',' between strings language: "en", stall_warnings: true, filter_level: "none" }), 'data' ) ).publish(); //publish method is used to ensure only one stream is created var tweetStreamObservable = streamObservable.refCount().filter(data => data.hasOwnProperty('text')); var warningStreamObservable = streamObservable.filter(data => data.hasOwnProperty('warning')); var limitStreamObservable = streamObservable.filter(data => data.hasOwnProperty('limit')); //Create execFileObservable from execFile var execFileObservable = Rx.Observable.bindNodeCallback(cp.execFile); //launch a python process to analyze each tweet and flatmap the returns to the same observable var streamAnalysis = tweetStreamObservable .concatMap( data => execFileObservable( 'python3', ['-W ignore', 'analyser_vader.py', JSON.stringify(data.text) ] ), (x, y, ix, iy) => { x.sentiment = JSON.parse(y[0]); return x} ).share(); var phrase_streams = {}; function getStreamForPhrase(phrase){ if (!phrase_streams[phrase]){ phrase_streams[phrase] = Rx.Observable.defer(() => { trackPhrasesSubject.next(phrase); return streamAnalysis.filter(data => data[0].text.toLowerCase().includes(phrase.toLowerCase())) } ).share(); } return phrase_streams[phrase]; } warningStreamObservable.subscribe(data => console.error("Warning: " + data["warning"]["code"])); //limitStreamObservable.subscribe(data => console.error("Limit: " + data["limit"]["track"])); streamAnalysis.subscribe(data => { var mystring = "score:"+data.sentiment["compound"]+" Text:"+data; //console.log('\x1b[36m%s\x1b[0m', mystring); console.log(data); }); // getStreamForPhrase("trump").subscribe(data => { // var mystring = "score:"+data[1]["compound"]+" Text:"+data[0].text; // return console.log('\x1b[31m%s\x1b[0m', mystring); // }); // // getStreamForPhrase("nintendo").subscribe(data => { // var mystring = "score:"+data[1]["compound"]+" Text:"+data[0].text; // return console.log('\x1b[33m%s\x1b[0m:', mystring); // }); // // getStreamForPhrase("obama").subscribe(data => { // var mystring = "score:"+data[1]["compound"]+" Text:"+data[0].text; // return console.log('\x1b[36m%s\x1b[0m', mystring); // }); // // getStreamForPhrase("twitter").subscribe(data => { // var mystring = "score:"+data[1]["compound"]+" Text:"+data[0].text; // return console.log('%s', mystring); // }); // addPhrase("nintendo"); // // Rx.Observable.timer(20000).subscribe( // ()=>addPhrase("trump") // ); // // Rx.Observable.timer(40000).subscribe( // ()=>addPhrase("obamacare") // ); trackPhrasesSubject.next("obama"); trackPhrasesSubject.next("trump"); trackPhrasesSubject.next("nintendo"); trackPhrasesSubject.next("twitter"); trackPhrasesSubject.next("cnn"); <file_sep>import {Routes, RouterModule} from "@angular/router"; import {HomeComponent} from "./home/home.component"; import {ModuleWithProviders} from "@angular/core"; import {AnalysisComponent} from "./analysis/analysis.component"; import {LiveStreamComponent} from "./live-stream/live-stream.component"; import {LaTimesComponent} from "./la-times/la-times.component"; import {TrackedPhrasesComponent} from "./tracked-phrases/tracked-phrases.component"; const appRoutes: Routes = [ { path: '/', pathMatch: 'full', component: HomeComponent}, { path: 'tracked-phrases', component:TrackedPhrasesComponent }, { path: 'live-stream', component: LiveStreamComponent}, { path: 'la-times', component: LaTimesComponent}, { path: 'analysis/:keyword', component: AnalysisComponent}, { path: '**', redirectTo: '' } ]; export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); <file_sep># NodeSMA ### Steps to get the project running 1. install [IntelliJ IDEA Ultimate](https://www.jetbrains.com/idea/) 2. install `node.js` on your local machine 3. install [Angular-Cli](https://github.com/angular/angular-cli) with `npm install -g @angular/cli@latest` 4. run `npm install` from the command line ### Program entry points The main entry point for the web app can be found under `WebApp/src/` most of the app files are under app. Lookup [Angular-Cli](https://github.com/angular/angular-cli) for more info on generating components and modules for Angular 2 The main entry point for the node.js/express backend is `bin/www` in the project root directory. Its setup so that anything in the /api url path will be captured by express ### Configurations Ive set up development configurations and a production configuration *"Dev-Serv"* and *"Dev-App"* must be run together *"Development"* is a compound configuration and will run them together but can't be debugged with the debugger __All Configurations will launch the server on localhost:3000__ <file_sep>import {Injectable, OnDestroy} from '@angular/core'; import * as socketio from 'socket.io-client'; import {Observable, Subject} from "rxjs/Rx"; @Injectable() export class SocketService implements OnDestroy{ private connectionObservable:Observable<any>; private connections: any = {}; private sendSubject: Subject<any>; constructor() { //construct the message subject this.sendSubject = new Subject(); //create new observable on subscription this.connectionObservable = Observable.defer(()=> //create the observable Observable.create((observer) => { //connect to the socket var socket = socketio.connect(); //subscribe to messages sent var subscription = this.sendSubject.subscribe((message)=>socket.emit(message.label,message.data)); observer.next(socket); //cleanup and close the connection return function () { subscription.unsubscribe(); socket.disconnect(); } } )).publishReplay().refCount(); } ngOnDestroy():void { this.sendSubject.complete(); } public messages(label:string):Observable<any> { //returns a new observable mapped to a function if (!this.connections[label]){ this.connections[label] = this.connectionObservable .switchMap((socket) => Observable.fromEvent(socket,label)) .finally(()=>this.connections[label] = null) .share(); } return this.connections[label]; } public send(label:string, data: any = {}){ this.sendSubject.next({label:label,data:data}); } } <file_sep>#!/usr/bin/env python3 import os directory = os.path.dirname(os.path.abspath(__file__)) import nltk # Download the vader lexicon nltk.download('vader_lexicon', directory+"/nltk_data") nltk.download('all-corpora', directory+"/nltk_data") #nltk.download() <file_sep>import { Component, OnInit } from '@angular/core'; import {Router, ActivatedRoute, Params} from "@angular/router"; import {SocketService} from "../services/socket.service"; import {Observable} from "rxjs/Observable"; @Component({ selector: 'app-analysis', templateUrl: './analysis.component.html', styleUrls: ['./analysis.component.scss'] }) export class AnalysisComponent implements OnInit { constructor(private route: ActivatedRoute, private router: Router, private socket: SocketService) { } keyword: string; tweets: Observable<Array<any>>; ngOnInit() { this.route.params.subscribe( (params: Params)=> { this.keyword = params["keyword"] this.tweets = this.socket.messages('tweet') .filter(tweet=>tweet.sma_keywords.indexOf(this.keyword) != -1) // .sample(Observable.interval(2000)) .scan((array: Array<any>,tweet: string)=>{ array.unshift(tweet); if( array.length > 500) array.pop(); return array }, []); this.socket.messages('search_result').take(1).subscribe(data=> console.log(data)); this.socket.send('search', this.keyword); } ); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from "@angular/router"; import {Observable} from "rxjs/Observable"; import {SocketService} from "../services/socket.service"; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { constructor(private router: Router, private socket: SocketService) { } tweets: Observable<Array<any>>; ngOnInit() { this.tweets = this.socket.messages('tweet').take(3).toArray(); } go(keyword: string){ this.router.navigate(['/analysis', keyword]); } } <file_sep>/** * Created by Zera on 3/16/17. */ var MongoClient = require('mongodb').MongoClient; var co = require('co'); var database; var init; module.exports = function(url){ if (url && !init) { init = true; co(function*(){ database = yield MongoClient.connect(url); }).catch(function(err){ console.log('Error: Cannot connect to MongoDB. Make sure mongod is running.'); process.exit(1); }); } return database; }; <file_sep>import {Component, OnInit, OnDestroy} from '@angular/core'; import {Observable, Subscription} from "rxjs/Rx"; import {SocketService} from "../services/socket.service"; @Component({ selector: 'app-la-times', templateUrl: './la-times.component.html', styleUrls: ['./la-times.component.scss'] }) export class LaTimesComponent implements OnInit, OnDestroy { timesData: Array<any>; barChartData: Array<any>; barChartLabels: Array<any>; chartType: any; barChartOptions: any; constructor(private socket: SocketService) { } ngOnInit() { this.chartType = 'bar'; this.barChartOptions = { scaleBeginAtZero: false, responsive: false, legend: { display: false }, title: { display: true, text: 'Sentimental Polarity of News' } }; this.socket.messages('times_data').take(1).subscribe(tdata=>{ let labels: Array<any> = []; let dataSet: Array<number> = []; for (let data of tdata ){ labels.push(data.date); dataSet.push(data.polarity); } this.barChartLabels = labels; this.barChartData = [{data:dataSet, label:'Polarity'}]; this.timesData=tdata; }); this.socket.send('get_times'); } ngOnDestroy(){ } } <file_sep>import {AfterContentChecked, AfterContentInit, Component, OnInit} from '@angular/core'; import {SocketService} from "../services/socket.service"; import {Observable} from "rxjs/Observable"; @Component({ selector: 'app-tracked-phrases', templateUrl: './tracked-phrases.component.html', styleUrls: ['./tracked-phrases.component.scss'] }) export class TrackedPhrasesComponent implements OnInit, AfterContentChecked { trackedPhrases: Observable<Array<any>>; constructor(private socket: SocketService) { } ngOnInit() { this.trackedPhrases = this.socket.messages('tracked_phrases').take(1); } ngAfterContentChecked(){ this.socket.send('get_tracked_phrases'); } } <file_sep>/** * Created by Zera on 3/23/17. */ const cp = require('child_process'); const Rx = require('rxjs/Rx'); const Twitter = require('twitter'); const LRUCache = require("lru-cache"); //const db = require('./database')('mongodb://localhost:27017/SMA'); // //Twitter Api // //Twitter access credentials must be provided as runtime variables //Stream client for user streams var streamClient = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET }); //Search client for app search var searchClient = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, bearer_token: process.env.TWITTER_BEARER_TOKEN }); // //LRU Map // const MAX_TRACKED_PHRASES = 400; var lru_options = { max: MAX_TRACKED_PHRASES, //length: function (n, key) { return 1 }, //dispose: function (key, n) { n.close() }, maxAge: 1000 * 60 * 60 // 1 hour }; var termMap = new LRUCache(lru_options); // //Phrase Stream // //subject for injecting trends manually var trackPhrasesSubject = new Rx.Subject(); //the trending phrases in the US every 15 seconds var trendingPhrases = Rx.Observable.timer(0, 1000 * 15) .switchMapTo(searchClient.get('trends/place',{id:23424977})) .concatMap(data=>Rx.Observable.from(data[0].trends)) .map(trend=>trend.name); //combined stream of phrases exported to a list from the lru-cache var phrasesListStream = Rx.Observable .from([trackPhrasesSubject,trendingPhrases]) .flatMap(x=>x,(stream, term, streamNum,termNum)=>{ var maxAge = streamNum == 1 ? 1000 * 60 * 60 * 2 : undefined; termMap.set(term, true, maxAge); return termMap.keys(); }); // //Twitter stream // //start the twitter stream var streamObservable = phrasesListStream .sample(Rx.Observable.timer(1000, 1000 * 60 * 60)) //resample every hour but start right now .distinctUntilChanged() //dont reset the stream if the terms havn't changed .switchMap( terms =>{ console.log('changing stream'); return Rx.Observable.fromEvent( streamClient.stream('statuses/filter', { track:terms.toString(), //Array tostring naturally inserts a ',' between strings language: "en", stall_warnings: true, filter_level: "none" }), 'data' );} ).publish(); //publish to only allow one stream var tweetStream = streamObservable.refCount().filter(tweet=> typeof tweet.text == 'string'); //var messageStream = streamObservable.filter(tweet => tweet.text == undefined).subscribe(message=>console.error(message)); //Create execFileObservable from execFile var execFileObservable = Rx.Observable.bindNodeCallback(cp.execFile); //launch a python process to analyze each tweet and flatmap the returns to the same observable var streamAnalysis = tweetStream .map(tweet=>{ var text = tweet.truncated == true ? tweet.extended_tweet.full_text : tweet.text return { text:text, user:{ name:tweet.user.name, screen_name:tweet.user.screen_name } }; }) //Todo: figure out a way to analyse more than one at once .concatMap( data => execFileObservable( 'python3', ['-W ignore', __dirname+'/scripts/analyser_textblob.py', JSON.stringify(data.text) ] ), (x, y, ix, iy) => { x.sentiment = JSON.parse(y[0]); return x} ).map(tweet=>{ tweet.sma_keywords = []; for(var key of termMap.keys()){ if (tweet.text.toLowerCase().includes(key.toLowerCase())){ tweet.sma_keywords.push(key) } } return tweet; } ).publish(); var streamSubscription = streamAnalysis.subscribe(data=>{ process.send({message:"tweet", data:data}); }); var dbSubscription = streamAnalysis.groupBy(tweet=>tweet.sma_keywords[0]) .flatMap(obs=>{ var key = obs.key; var total = 3; return obs.windowCount(total) .flatMap( obs=> obs.map( tweet=> tweet.sentiment.compound > 0 ? 1 : 0 ).count(x=>x==1)) .map( count=> { return {phrase:key, count:count, total:total}; } ); }).subscribe(data=>console.log(data)); // //Messaages // function send(message, data, id){ process.send({message:message, data:data, id:id}); } //handle messages to and from the process var messages = Rx.Observable.fromEvent(process, 'message'); messages.subscribe(message=>{ console.log('subprocess message: ' + message.message + " from: " + (message.id ? message.id : "Server") ); switch (message.message){ case "start_stream": streamAnalysis.connect(); send('stream_started'); break; case "stop_stream": if (!streamSubscription) break; streamSubscription.unsubscribe(); break; case "get_tracked_phrases": send('tracked_phrases', termMap.keys(), message.id); break; case "get_times": execFileObservable( 'python3', ['-W ignore', __dirname+'/scripts/latimes.py'] ).subscribe(data=>send('times_data', JSON.parse(data[0]), message.id)); break; case "search": Rx.Observable.fromPromise(searchClient.get('search/tweets',{ q:message.data, result_type: 'recent', count:100, language: "en" })) .subscribe(data=>send("search_result", data, message.id)); break; default: break; } });<file_sep>#!/usr/bin/env python3 import signal import sys import json import os directory = os.path.dirname(os.path.abspath(__file__)) import nltk # Set the nltk data path nltk.data.path.append(directory+"/nltk_data") # nk.data.find('sentiment/vader_lexicon.zip'); #import vader analyzer from nltk.sentiment.vader import SentimentIntensityAnalyzer # setup signal handling def signal_handler(signal, frame): print('You pressed Ctrl+C!') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) def main(): # Go over each line of stdin and flush after each write data = sys.argv[len(sys.argv)-1] sid = SentimentIntensityAnalyzer() sentimentScores = sid.polarity_scores(data) sys.stdout.write(json.dumps(sentimentScores)) return 0 if __name__ == '__main__': main() <file_sep>/** * Created by Zera on 3/15/17. */ const socketio = require('socket.io'); const searcher = require('./searcher'); module.exports = function(server){ var io = socketio(server); searcher.messages.subscribe(message=>{ if (message.id){ io.to(message.id).emit(message.message, message.data); }else{ io.emit(message.message, message.data); } }); searcher.send('start_stream'); io.on('connection', function(client){ console.log(client.rooms); client.on('get_times', (data)=>{ searcher.send("get_times", {}, client.id) }); client.on('get_tracked_phrases', (data)=>{ searcher.send("get_tracked_phrases", {}, client.id) }); client.on('search', (data)=>{ searcher.send("search", data, client.id) }); }); io.use(function(socket, next){ next(); }); // io.on('connection', function(socket){ // // console.log("connected"); // }); return io; }; <file_sep>import {Component, OnInit, OnDestroy} from '@angular/core'; import {SocketService} from "../services/socket.service"; import {Observable, Subscription} from "rxjs/Rx"; @Component({ selector: 'app-live-stream', templateUrl: './live-stream.component.html', styleUrls: ['./live-stream.component.scss'] }) export class LiveStreamComponent implements OnInit, OnDestroy{ tweets: Observable<Array<any>>; constructor(private socket: SocketService) { } ngOnInit() { this.tweets = this.socket.messages('tweet') .sample(Observable.interval(1000)) .scan((array: Array<any>,tweet: string)=>{ array.unshift(tweet); if( array.length > 500) array.pop(); return array }, []); } ngOnDestroy(){ } } <file_sep>/** * Created by Zera on 3/23/17. */ var Rx = require('rxjs/Rx'); const cp = require('child_process'); const searcher = cp.fork(`${__dirname}/searcher_subprocess.js`); function send(message, data, id) { searcher.send({message:message,data:data, id:id}); }; var messageObservable = Rx.Observable.fromEvent(searcher, 'message'); exports.send = send; exports.startStream = ()=>send("start_stream"); exports.stopStream = ()=>send("stop_stream"); exports.search = (term)=>send("search",term); exports.getTimes = ()=>send("get_times"); exports.disconnect = function(){ searcher.disconnect(); }; exports.messages = messageObservable; <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { CollapseModule } from 'ng2-bootstrap/collapse' import { routing } from "./app.routing"; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { AnalysisComponent } from './analysis/analysis.component'; import { SocketService } from "./services/socket.service"; import { LiveStreamComponent } from './live-stream/live-stream.component'; import { LaTimesComponent } from './la-times/la-times.component'; import { ChartsModule } from "ng2-charts/index"; import { TrackedPhrasesComponent } from './tracked-phrases/tracked-phrases.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, AnalysisComponent, LiveStreamComponent, LaTimesComponent, TrackedPhrasesComponent ], imports: [ BrowserModule, FormsModule, routing, HttpModule, CollapseModule, ChartsModule ], providers: [SocketService], bootstrap: [AppComponent] }) export class AppModule { }
209886f1510f5bac32c711b766c39c5044837ca5
[ "JavaScript", "Python", "TypeScript", "Markdown" ]
19
Python
MattZera/NodeSMA
5402f5ec7c43206d074a858f89c84a33eba470f8
8c0a7db339c750f5f4d561d89b08f3f4ff770a79
refs/heads/master
<repo_name>Shivam-Shah/TeachingKidsProgramming.Java<file_sep>/TeachingKidsProgramming/src/org/teachingkidsprogramming/recipes/SimpleSquare.java package org.teachingkidsprogramming.recipes; import java.awt.Color; import org.teachingextensions.logo.Tortoise; public class SimpleSquare { public static void main(String[] args) throws Exception { Tortoise.show(); Tortoise.setSpeed(10); int side = 4; for (int i = 1; i <= side; i++) { Tortoise.setPenColor(Color.blue); Tortoise.move(50); Tortoise.turn(360.0 / side); } } } <file_sep>/README.md TeachingKidsProgramming.Java ============================ Eclipse Workspace This is my homework for Learn to Program Summer Camp JAVA program.
5793f8f9306d44e09e22e1463d41c2068e0417fe
[ "Markdown", "Java" ]
2
Java
Shivam-Shah/TeachingKidsProgramming.Java
d41b14def64bc00857493e022ea97f203b4257b0
8adbc5eef412fb6c3cbf34c35a824d5476eebf7c
refs/heads/master
<file_sep>#!/bin/bash while : do has_cluster_ip=$(ip a | grep "{{ cluster_ip }}" | wc -l) if [[ ${has_cluster_ip} > 0 ]]; then systemctl start postgresql else systemctl stop postgresql fi sleep .1 done
34391c50e034ca2c512a5c0be556f7307072ee13
[ "Shell" ]
1
Shell
andrew-klassen/postgres_cluster
00e58e85b1eb79769d1257b9e1ee951bd1582699
e61265bb7dd2bee4754031893e9ef2f2e3279db7
refs/heads/master
<file_sep> import axios from 'axios'; import AppAsyncStorage from './components/common/AppAsyncStorage'; import appConstants from './components/common/AppConstants'; import * as SecureStore from 'expo-secure-store'; setFoo=async ()=>{ await SecureStore.setItemAsync("foo", "bares") } getCategories = async () => { try { let res = await axios.get('https://tarjetaapp.herokuapp.com/categories/api'); await AppAsyncStorage.storeData(appConstants.CATEGORIES,JSON.stringify(res.data)) } catch (error) { console.log("error api categories =>"+error) } }; getShops = async () => { try { let res = await axios.get('https://tarjetaapp.herokuapp.com/shops/api'); await AppAsyncStorage.storeData(appConstants.SHOPS,JSON.stringify(res.data)) } catch (error) { console.log("error api categories =>"+error) } }; getCategories() getShops() setFoo() // console.log("categories: "+JSON.stringify(getCategoriesFromApi()))<file_sep>import { Text, StyleSheet, View, } from 'react-native'; import React, { Component } from 'react'; import { TabView, SceneMap, TabBar } from 'react-native-tab-view'; import Categories from './benefits/Categories'; import Benefits from './benefits/Benefits'; import { Header, Container, Button, Icon, Left, Body, Title } from 'native-base'; import * as SecureStore from 'expo-secure-store'; import Values from '../common/Values'; class Home extends Component { static navigationOptions = { drawerLabel: 'Tarjeta APP', }; constructor(props) { super(props); this.state = { index: 0, routes: [ { key: 'first', title: 'Categorías' }, { key: 'second', title: 'Beneficios' }, ], }; // this.getFoo(); } // async getFoo(){ // let bar=await SecureStore.getItemAsync('foo'); // alert('foo:'+bar) // } tabBar = props => <TabBar {...props} renderLabel={({ route }) => ( <Text style={{ fontFamily: 'segoeuil', fontSize: 20, color: 'red', margin: 8 }}> {route.title} </Text> )} indicatorStyle={{ backgroundColor: 'red' }} style={{ height: 55, backgroundColor: '#fefafa', }} />; render() { return ( <View style={Values.styles.container}> <Container> <Header style={{ backgroundColor: 'red' }}> <Left> <Button onPress={() => { this.props.navigation.openDrawer() }} transparent> <Icon name='menu' /> </Button> </Left> <Body> <Title style={{ fontFamily: 'segoeuil' }}>Tarjeta App</Title> </Body> </Header> <TabView renderTabBar={this.tabBar} navigationState={this.state} renderScene={SceneMap({ first: Categories, second: Benefits })} onIndexChange={index => this.setState({ index })} initialLayout={styles.tabView} /> </Container> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1 }, tabView: { flex: 1 } }) export default Home;<file_sep>import React, { Component } from 'react'; import { View, ScrollView, Text, StyleSheet, TouchableOpacity, Image } from 'react-native'; import { Card, Left, Button, Body, Icon, CardItem, Right } from 'native-base'; import { Button as Btn } from 'react-native-elements'; import Values from '../../common/Values'; class BenefitInfo extends Component { static navigationOptions = ({ navigation }) => { return { header: null//navigation.getParam('otherParam', 'Home') } }; constructor(props) { super(props); this.state = { favorite: false } } truncateString(str, len) { return str.substring(0, len) + "..." } render() { const benefit = this.props.shop.benefits[this.props.benefitId] return ( <ScrollView style={styles.containter}> <Card style={{ flex: 0 }}> <CardItem> <Left> <Button style={{ backgroundColor: "#FF9501" }}> <Icon active type={this.props.shop.category.icon_type} name={this.props.shop.category.icon_name} /> </Button> <Body> <Text style={{ fontFamily: 'segoeuisb', fontSize: 16 }}>{this.props.shop.shop_name}</Text> <Text style={{ fontFamily: 'segoeuil', fontSize: 14 }} note>{this.props.shop.subtitle}</Text> </Body> </Left> <Right> <View style={{flexDirection: 'row'}}> <TouchableOpacity style={{marginRight: 8,}} onPress={() => { this.setState({ favorite: !this.state.favorite }) } }> <Icon style={{fontSize:30}} name={this.state.favorite ? "heart" : "heart-empty"} /> </TouchableOpacity> <TouchableOpacity onPress={ () => this.props.goBack() }> <Text style={{ color: '#ccc', fontFamily: 'segoeuisb', fontSize: 30 }}> <Icon style={{fontSize:30}} name='close'/> </Text> </TouchableOpacity> </View> </Right> </CardItem> <CardItem cardBody> <View style={{ height: 150, width: null, flex: 1, padding: 10, backgroundColor: '#f4f4f4', borderRadius: 2 }}> <Image source={{ uri: this.props.shop.logo }} style={{ height: 130, width: 130, alignSelf: 'center' }} /> </View> </CardItem> <CardItem style={{ paddingBottom: 0 }}> <TouchableOpacity onPress={() => alert(benefit.details_and_terms)}> <Text style={[{ fontFamily: 'segoeuil', fontSize: 18 }]}> {this.truncateString(benefit.details_and_terms, 175)} </Text> </TouchableOpacity> </CardItem> <CardItem style={{ paddingTop: 0, paddingBottom: 0 }}> <Text style={{ fontFamily: 'segoeuisb', fontSize: 18 }}> BENEFICIO : </Text> </CardItem> <CardItem style={{ paddingTop: 0, paddingBottom: 0 }}> <Text style={{ fontFamily: 'segoeuil', fontSize: 18 }}> {benefit.description} </Text> </CardItem> <CardItem> <View style={{ width: null, flex: 1, paddingLeft: 20, paddingRight: 20 }}> {/* <Button style={{ alignItems:"center", padding:5,textAlign:'center',alignSelf: 'stretch',borderRadius:5,backgroundColor:'red' }}> <Text style={{color:'white',fontFamily:'segoeuil',fontSize:20}}> Obtener Beneficio </Text> </Button> */} <Btn containerStyle={{ alignSelf: 'stretch' }} titleStyle={[Values.styles.appText, { color: 'white' }]} buttonStyle={[styles.btn]} onPress={ () => { alert("Muestra el código 45789600 a tu tienda") } } title="Obtener beneficio" /> </View> </CardItem> </Card> <View style={{ height: 20 }}> </View> </ScrollView> ); } } const styles = StyleSheet.create({ containter: { backgroundColor: '#efeef4', padding: 10, flex: 1 }, btn: { backgroundColor: 'red', height: 33, marginTop: 2 } }); export default BenefitInfo;<file_sep>import { createStackNavigator, createAppContainer } from 'react-navigation'; import Login from './src/components/UI/Login'; import RegisterCard from './src/components/UI/QR/RegisterCard'; import RegisterUserData from './src/components/UI/register/RegisterUserData'; // import Home from './src/components/UI/Home'; import DrawerHome from './src/components/UI/DrawerHome'; import BenefitInfo from './src/components/UI/benefits/BenefitInfo'; const MainNavigator = createStackNavigator({ Login: { screen: Login }, RegisterUserData: { screen: RegisterUserData }, DrawerHome: DrawerHome, BenefitInfo: { screen: BenefitInfo }, RegisterCard: { screen: RegisterCard }, }, { headerMode:'none', /* The header config from HomeScreen is now here */ defaultNavigationOptions: { headerStyle: { backgroundColor: '#f00', alignContent: 'center', }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold', marginLeft: 0 }, }, } ); const Router = createAppContainer(MainNavigator); export default Router;<file_sep>import Home from "./Home"; import Profile from './Profile'; import { createDrawerNavigator} from 'react-navigation'; import CustomDrawerContentComponent from '../common/CustomDrawerContentComponent'; const MyDrawerNavigator = createDrawerNavigator({ Home: { screen: Home, }, Perfil: { screen: Profile, }, Favoritos: { screen: Profile, }, "Mis puntos": { screen: Profile, }, Historial: { screen: Profile, }, Mapa: { screen: Profile, }, }, { contentComponent: CustomDrawerContentComponent, }); export default MyDrawerNavigator; <file_sep>import React, { Component } from 'react'; import { View,ActivityIndicator,Text } from 'react-native'; import Values from './Values'; class Loader extends Component { state = { } render() { return ( <View style={[Values.styles.container,Values.styles.centered]}> <ActivityIndicator size='large'/> <Text style={Values.styles.appText}> {this.props.message} </Text> </View> ); } } export default Loader;<file_sep>import React, { Component } from 'react'; import { ScrollView, StyleSheet, Image, View, TouchableOpacity } from 'react-native'; import { CardItem, Card, Body, Button, Left, Text, Icon } from 'native-base'; import AppAsyncStorage from '../../common/AppAsyncStorage'; import appConstants from '../../common/AppConstants'; import Values from '../../common/Values'; import BenefitInfo from './BenefitInfo'; class Benefits extends Component { constructor(props) { super(props); this.state = { categories: [], shops: [], selectedBenefit: null, selectedShop:null } this.loadShops() } async loadShops() { let shopsArray = await AppAsyncStorage.retrieveData(appConstants.SHOPS) let categoriesArray = await AppAsyncStorage.retrieveData(appConstants.CATEGORIES) if (shopsArray != null) { shops = JSON.parse(shopsArray); categories = JSON.parse(categoriesArray) shops.forEach(shop => { let category = categories.find((c) => { return c._id == shop.category_id }) if (category != null) { shop.category = category } }); this.setState({ shops: shops }) } } goBack() { this.setState({ selectedBenefit: null }) } render() { if (this.state.selectedBenefit != null) { return ( <BenefitInfo benefitId={this.state.selectedBenefit} shop={this.state.selectedShop} goBack={() => this.goBack()} /> ) } return ( <ScrollView style={[styles.containter]} > {this.state.shops.map( (shop, i) => { return shop.benefits.map( (benefit, j) => { return ( <TouchableOpacity onPress={ () => { this.setState({ selectedBenefit: j, selectedShop: shop, }) } } key={"benefit_" + i + "_" + j}> <Card> <CardItem> <Left> <Button style={{ backgroundColor: "#FF9501" }}> <Icon active type={shop.category.icon_type} name={shop.category.icon_name} /> </Button> <Body> <Text style={{fontFamily:'segoeuisb',fontSize:16}}>{shop.shop_name}</Text> <Text style={{fontFamily:'segoeuil',fontSize:14}} note>{shop.subtitle}</Text> </Body> </Left> </CardItem> <CardItem cardBody> <View style={{ height: 200, width:null,flex:1,padding:10,backgroundColor:'#f4f4f4',borderRadius:2}}> <Image source={{ uri: shop.logo }} style={{ height: 180, width: 180, alignSelf: 'center' }} /> </View> </CardItem> <CardItem> <Text style={[{ fontFamily:'segoeuisb',fontSize:16, textAlign: 'center' }]}> {benefit.description} </Text> </CardItem> </Card> </TouchableOpacity> ) } ) } )} <View style={{ height: 20 }}> </View> </ScrollView> ); } } const styles = StyleSheet.create({ containter: { backgroundColor: '#efeef4', padding: 10, flex: 1 } }); export default Benefits;<file_sep>const appConstants={ LOGIN:"Login", REGISTER_CARD:"RegisterCard", REGISTER_USER_DATA:"RegisterUserData", DRAWER_HOME :"DrawerHome", BENEFIT_INFO:"BenefitInfo", CATEGORIES:"categories", SHOPS:"shops", UNCHECKED:'unchecked', NEEDS_UPDATE:"needs_update", UP_TO_DATE:"up_to_date", USER_INFO:"user_info", } export default appConstants; <file_sep>import React from 'react'; import { StyleSheet, View, ActivityIndicator, Text, TouchableOpacity, Linking } from 'react-native'; import { Font } from 'expo'; import Router from './Router'; import appConstants from './src/components/common/AppConstants'; import axios from 'axios'; import Constants from 'expo-constants'; import Values from './src/components/common/Values'; import AppAsyncStorage from './src/components/common/AppAsyncStorage'; import Loader from './src/components/common/Loader'; const LoadingStatus = [ "Cargando Fuentes", "Cargando Información", "Revisando Actualizaciones", "ok" ] export default class App extends React.Component { constructor(props) { super(props); this.state = { LoadingStatusIndex: 0, checkVersionStatus: appConstants.UNCHECKED } } async componentDidMount() { await Font.loadAsync({ 'segoeuil': require('./assets/fonts/segoeuil.ttf'), 'segoeuisb': require('./assets/fonts/segoeuisb.ttf'), 'Roboto': require('native-base/Fonts/Roboto.ttf'), 'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'), }); this.setState({ LoadingStatusIndex: 1 }); await this.getCategories() await this.getShops() this.setState({ LoadingStatusIndex: 2 }); } getCategories = async () => { try { let res = await axios.get('https://tarjetaapp.herokuapp.com/categories/api'); await AppAsyncStorage.storeData(appConstants.CATEGORIES, JSON.stringify(res.data)) } catch (error) { console.log("error api categories =>" + error) } }; getShops = async () => { try { let res = await axios.get('https://tarjetaapp.herokuapp.com/shops/api'); await AppAsyncStorage.storeData(appConstants.SHOPS, JSON.stringify(res.data)) } catch (error) { console.log("error api categories =>" + error) } }; async checkAppVersion() { try { let response = await axios({ method: 'get', url: "https://tarjetaapp.herokuapp.com/version", timeout: 1000 }) if (Constants.appOwnership == 'expo') { this.setState({ checkVersionStatus: appConstants.UP_TO_DATE }) } else { if (Constants.platform.android.versionCode < response.data.version) { this.setState({ checkVersionStatus: appConstants.NEEDS_UPDATE }) } else { this.setState({ checkVersionStatus: appConstants.UP_TO_DATE }) } } } catch (error) { console.log("error checking updates: " + error) } } render() { switch (this.state.LoadingStatusIndex) { case 0: return ( <View style={styles.container}> <ActivityIndicator size='large' /> <Text>{LoadingStatus[this.state.LoadingStatusIndex]}</Text> </View> ); case 1: return ( <Loader message={LoadingStatus[this.state.LoadingStatusIndex]} /> ) case 2: switch (this.state.checkVersionStatus) { case appConstants.UNCHECKED: this.checkAppVersion(); return ( <Loader message={LoadingStatus[this.state.LoadingStatusIndex]}/> ) case appConstants.NEEDS_UPDATE: return ( <View style={[Values.styles.container, Values.styles.centered]}> <Text style={Values.styles.appText}>Necesitamos una actualización :)</Text> <TouchableOpacity onPress={() => { Linking.openURL('https://play.google.com/store/apps/details?id=com.cerezabusiness.tarjetaapp') }} style={styles.btn} > <Text style={Values.styles.appText}> Ir a Google Play </Text> </TouchableOpacity> </View> ); case appConstants.UP_TO_DATE: return ( <Router /> ); } default: break; } } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, btn: { margin: 10, padding: 5, borderWidth: 1, borderColor: 'red', borderRadius: 5, } });<file_sep>import React, { Component } from 'react'; import { StyleSheet, ScrollView, Text } from 'react-native'; import { DrawerItems, SafeAreaView } from 'react-navigation'; import { Button } from 'native-base'; import * as SecureStore from 'expo-secure-store'; import appConstants from './AppConstants'; const CustomDrawerContentComponent = props => ( <ScrollView> <SafeAreaView style={styles.container} forceInset={{ top: 'always', horizontal: 'never' }}> <DrawerItems {...props} /> <Button onPress={ () => { SecureStore.deleteItemAsync(appConstants.USER_INFO) props.navigation.dangerouslyGetParent().navigate(appConstants.LOGIN); } } block> <Text>Cerrar sesión</Text> </Button> </SafeAreaView> </ScrollView> ); const styles = StyleSheet.create({ container: { flex: 1, }, }); export default CustomDrawerContentComponent;<file_sep>/** * * This file was generated with Adobe XD React Exporter * Exporter for Adobe XD is written by: <NAME> <<EMAIL>> * **/ import React, { Component } from 'react'; import { View, StyleSheet, Image, PixelRatio, Text } from 'react-native'; import Constants from 'expo-constants'; import Values from '../common/Values'; import { Item, Label, Input } from 'native-base'; import { Button } from 'react-native-elements'; import appConstants from '../common/AppConstants'; import Loader from '../common/Loader'; import * as SecureStore from 'expo-secure-store'; import Axios from 'axios'; import { NavigationEvents } from 'react-navigation'; /* Adobe XD React Exporter has dropped some elements not supported by react-native-svg: style */ const loadingStatus = ["Cargando datos del usuario", 'ok'] class Login extends Component { static navigationOptions = ({ navigation }) => { return { header: null } }; constructor(props) { super(props); this.state = { loadingStatusIndex: 0, userData: { email: '', password: '', }, } this.checkUserData(); } onChangeText(value, field) { let userDataCopy = {} Object.assign(userDataCopy, this.state.userData); userDataCopy[field] = value; this.setState({ userData: userDataCopy }) } async checkUserData() { let userInfo = JSON.parse(await SecureStore.getItemAsync(appConstants.USER_INFO)); if (userInfo != null && userInfo.user) { this.goTo(appConstants.DRAWER_HOME); } else { this.setState({ loadingStatusIndex: 1 }) } } goTo(page, params = {}) { const { navigate } = this.props.navigation; navigate(page, params) // alert("clicked") } async login() { this.setState({ isLoading: true }) try { let response = await Axios.post('https://tarjetaapp.herokuapp.com/users/api/auth/signin' , this.state.userData) if (response.data.token) { await SecureStore.setItemAsync(appConstants.USER_INFO, JSON.stringify(response.data)) alert('Bienvenido, ' + response.data.user.name) this.setState({ isLoading: false }) this.goTo(appConstants.DRAWER_HOME) } } catch (error) { console.log(error) if (error.response) { /* * The request was made and the server responded with a * status code that falls out of the range of 2xx */ // console.log(error.response.data); // console.log(error.response.status); // console.log(error.response.headers); switch (error.response.status) { case 400: alert('lo sentimos no hay coincidencias'); this.setState({ userData: { email: '', password: '', } }) break; default: alert('un error ha ocurrido'); break; } } else if (error.request) { /* * The request was made but no response was received, `error.request` * is an instance of XMLHttpRequest in the browser and an instance * of http.ClientRequest in Node.js */ //console.log(error.request.response); alert('No estás conectado a internet'); this.setState({ userData: { email: '', password: '', } }) } else { // Something happened in setting up the request and triggered an Error console.log('Error', error.message); } console.log(error.config); } } render() { if (this.state.loadingStatusIndex == 0) { return ( <View style={[Values.styles.container]}> <NavigationEvents onWillFocus={payload => console.log('will focus', payload)} onDidFocus={() => this.checkUserData()} onWillBlur={payload => console.log('will blur', payload)} onDidBlur={payload => console.log('did blur', payload)} /> <Loader message={loadingStatus[this.state.loadingStatusIndex]} /> </View>) } return ( <View style={[Values.styles.container, styles.container]} > <View style={[styles.logoContainer, Values.styles.centered]}> <Image style={styles.logo} source={require('./img/logo.png')} /> </View> <View style={styles.formContainer}> <View style={[styles.formTitle, Values.styles.centered]}> <Text style={[styles.formText, styles.marginEqual]}> BIENVENIDOS A UN MUNDO DE BENEFICIOS </Text> </View> <View style={ [styles.form, Values.styles.centered, styles.marginEqual] }> <Item style={styles.formInput} floatingLabel> <Label style={[styles.formText, styles.marginBottom]}>Correo o teléfono</Label> <Input value={this.state.userData['email']} onChangeText={ (text) => { this.onChangeText(text, 'email') } } style={[styles.formText]} form /> </Item> <Item style={styles.formInput} floatingLabel> <Label style={[styles.formText, styles.marginBottom]}>Clave</Label> <Input value={this.state.userData['password']} onChangeText={ (text) => { this.onChangeText(text, '<PASSWORD>') } } style={[styles.formText]} secureTextEntry={true} /> </Item> <Button containerStyle={{ alignSelf: 'stretch' }} titleStyle={[styles.formText, { color: 'red' }]} buttonStyle={[styles.btn]} onPress={ () => { this.login(); } } title="Ingresa" /> </View> </View> <View style={styles.socialLoginContainer}> <View style={ [styles.form, { alignItems: 'center' }, styles.marginEqual] }> <Button containerStyle={{ alignSelf: 'stretch' }} titleStyle={[styles.formText, { color: 'white' }]} buttonStyle={[styles.btn, { backgroundColor: '#3B5998' }]} title="Ingresa con Facebook" /> <Button containerStyle={{ alignSelf: 'stretch' }} titleStyle={[styles.formText, { color: 'white' }]} buttonStyle={[styles.btn, { backgroundColor: '#0F9D58' }]} title="Ingresa con Google" /> <Text style={[styles.formText, { alignSelf: 'stretch' }, { marginTop: 20 }]} onPress={() => this.goTo(appConstants.REGISTER_CARD, {})} > Registra <Text style={{ textDecorationLine: 'underline' }}>aquí</Text> tu tarjeta si aún no eres socio </Text> </View> </View> </View > ); } } const styles = StyleSheet.create({ container: { backgroundColor: '#ff0000', }, logo: { width: 224,//PixelRatio.getPixelSizeForLayoutSize(126), height: 62//PixelRatio.getPixelSizeForLayoutSize(35), }, logoContainer: { flex: 0.46 }, formContainer: { flex: 1, }, formTitle: { flex: 0.20 }, form: { flex: 1 }, formText: { fontFamily: 'segoeuil', textAlign: 'center', color: 'white', fontSize: 20// fontSize: PixelRatio.getPixelSizeForLayoutSize(10), }, formInput: { borderColor: 'white', padding: 5, color: 'white', marginBottom: 5, }, btn: { backgroundColor: 'white', height: 33, marginTop: 5//PixelRatio.getPixelSizeForLayoutSize(5) }, socialLoginContainer: { flex: 0.66, }, marginEqual: { marginLeft: 68, //cambió con respecto a XD marginRight: 68,//cambió con respecto a XD }, marginBottom: { marginBottom: 2//PixelRatio.getPixelSizeForLayoutSize(2) }, }); export default Login; <file_sep>import { StyleSheet } from 'react-native'; import Constants from 'expo-constants'; export default values = { styles: StyleSheet.create({ centered: { justifyContent: 'center', alignItems: 'center', }, container: { flex: 1, paddingTop: Constants.statusBarHeight, }, promptTitle:{ fontSize:20, fontFamily: 'segoeuil', }, appText:{ fontSize:20, fontFamily: 'segoeuil', } }), }<file_sep>import React, { Component } from 'react'; import Values from "../../common/Values"; import { ScrollView, View, Text, StyleSheet, Image, KeyboardAvoidingView } from 'react-native'; import { Item, Label, Input, Right, Icon, Button as Btn } from 'native-base'; import { Button } from 'react-native-elements'; import appConstants from '../../common/AppConstants'; import Axios from 'axios'; import { isLoading } from 'expo-font'; import Loader from '../../common/Loader'; import * as SecureStore from 'expo-secure-store'; class RegisterUserData extends Component { static navigationOptions = ({ navigation }) => { return { header: null } }; constructor(props) { super(props); this.state = { secureTextEntry: true, userData: { first_name: '', last_name: '', email: '', phone_number: '', password: '', }, isLoading: false } } onChangeText(value, field) { let userDataCopy = {} Object.assign(userDataCopy, this.state.userData); userDataCopy[field] = value; this.setState({ userData: userDataCopy }) } async doRegister() { this.setState({ isLoading: true }) try { let data = this.state.userData; data2Send = { name: data.first_name + ' ' + data.last_name, email: data.email, phone_number: data.phone_number, password: <PASSWORD> } let response = await Axios.post('https://tarjetaapp.herokuapp.com/users/api' , data2Send) if (response.data.token) { await SecureStore.setItemAsync(appConstants.USER_INFO, JSON.stringify(response.data)) alert('que bien te registraste') this.setState({ isLoading: false }) this.goTo(appConstants.DRAWER_HOME) } } catch (error) { console.log(error) } } goTo(page) { this.props.navigation.navigate(page); } render() { if (this.state.isLoading) { return (<Loader message='Registrandote...' />) } return ( <KeyboardAvoidingView style={[Values.styles.container]} behavior="padding" enabled> <ScrollView style={[{ flex: 1 }, styles.container]}> <Image style={styles.logo} source={require('../img/logo.png')} /> <Text style={[styles.formText, styles.marginEqual]}> REGÍSTRATE PARA EMPEZAR A DISFRUTAR </Text> <View style={[styles.marginEqual, { flex: 1 }]}> <Item style={styles.formInput} floatingLabel> <Label style={[styles.formText, styles.marginBottom]}>Nombre</Label> <Input value={this.state.userData['first_name']} onChangeText={ text => { this.onChangeText(text, 'first_name') } } style={[styles.formText]} form /> </Item> <Item style={styles.formInput} floatingLabel> <Label style={[styles.formText, styles.marginBottom]}>Apellido</Label> <Input value={this.state.userData['last_name']} onChangeText={ text => { this.onChangeText(text, 'last_name') } } style={[styles.formText]} form /> </Item> <Item style={styles.formInput} floatingLabel> <Label style={[styles.formText, styles.marginBottom]}>Correo electrónico</Label> <Input value={this.state.userData['email']} onChangeText={ text => { this.onChangeText(text, 'email') } } style={[styles.formText]} form /> </Item> <Item style={styles.formInput} floatingLabel> <Label style={[styles.formText, styles.marginBottom]}>Teléfono</Label> <Input value={this.state.userData['phone_number']} onChangeText={ text => { this.onChangeText(text, 'phone_number') } } style={[styles.formText]} form /> </Item> <View style={{flexDirection:'row',alignSelf: 'stretch' }}> <Item style={[styles.formInput,{flex:1}]} floatingLabel> <Label style={[styles.formText, styles.marginBottom]}>Clave</Label> <Input value={this.state.userData['password']} onChangeText={ text => { this.onChangeText(text, 'password') } } style={[styles.formText]} form secureTextEntry={this.state.secureTextEntry} /> </Item> <Btn onPress={() => { this.setState({ secureTextEntry: !this.state.secureTextEntry }) }} transparent> <Icon name={this.state.secureTextEntry ? 'eye' : 'eye-off'} /> </Btn> </View> <Button containerStyle={{ marginTop: 25, alignSelf: 'stretch' }} titleStyle={[styles.formText, { color: 'red' }]} buttonStyle={[styles.btn]} onPress={ () => { this.doRegister() } } title="Registrarse" /> </View> </ScrollView> </KeyboardAvoidingView> ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'red' }, logo: { marginTop: 58, marginBottom: 28, //cambió respecto a XD alignSelf: 'center', width: 224,//PixelRatio.getPixelSizeForLayoutSize(126), height: 62//PixelRatio.getPixelSizeForLayoutSize(35), }, formText: { fontFamily: 'segoeuil', textAlign: 'center', color: 'white', fontSize: 20// fontSize: PixelRatio.getPixelSizeForLayoutSize(10), }, marginEqual: { marginLeft: 68, marginRight: 68, }, formInput: { borderColor: 'white', padding: 2, color: 'white', marginBottom: 5, }, marginBottom: { marginBottom: 2//PixelRatio.getPixelSizeForLayoutSize(2) }, btn: { backgroundColor: 'white', height: 33, marginTop: 5//PixelRatio.getPixelSizeForLayoutSize(5) }, }) export default RegisterUserData;<file_sep>import React, { Component } from 'react'; import { Text, View, StyleSheet, Image } from 'react-native'; import { Permissions, BarCodeScanner } from 'expo'; import Values from '../../common/Values'; import appConstants from '../../common/AppConstants'; import Constants from 'expo-constants'; import privateKeyJson from "../../../../keys/dev_private_key.json" class RegisterCard extends Component { constructor(props) { super(props); this.state = { hasCameraPermission: null, scanned: false, } } async componentDidMount() { const { status } = await Permissions.askAsync(Permissions.CAMERA); this.setState({ hasCameraPermission: status === 'granted' }); } static navigationOptions = ({ navigation }) => { return { header: null } }; goTo(page, params = {}) { const { navigate } = this.props.navigation; navigate(page, params) } handleBarCodeScanned = ({ type, data }) => { this.setState({ scanned:true }) alert('Tarjeta Escaneada, Completa tus datos'); this.goTo(appConstants.REGISTER_USER_DATA) }; render() { const { hasCameraPermission, scanned } = this.state; if (hasCameraPermission === null) { return ( <View style={[Values.styles.container, Values.styles.centered]}> <Text style={Values.styles.promptTitle}>Esperando los permisos de cámara</Text> </View> ) } if (hasCameraPermission === false) { return ( <View style={[Values.styles.container, Values.styles.centered]}> <Text style={Values.styles.promptTitle}>Sin Acceso a la cámara</Text> </View> ) } return (<View style={[Values.styles.container]}> <BarCodeScanner onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned} style={StyleSheet.absoluteFill} /> <View style={styles.qrReaderContainer}> <Image style={styles.qrFrame} source={require('../img/qrFrame.png')} /> </View> <View style={styles.imageContainer}> <Text style={[styles.title, styles.marginEqual]}>Apunta con tu cámara al código que figura en tu tarjeta</Text> <Image style={[styles.image]} source={require('../img/image1.png')} /> </View> </View>); } } const styles = StyleSheet.create({ qrReaderContainer: { paddingTop: Constants.statusBarHeight, flex:1, height: 320, //cambió con respecto a XD //justifyContent: 'center', alignItems: 'center', }, qrFrame:{ alignSelf:'center', height:254,//cambió con respecto a XD width:250.98,//cambió con respecto a XD }, imageContainer: { flex: 1, backgroundColor:'white' }, title: { paddingTop: 18, fontFamily: 'segoeuil', fontSize: 20, color: 'red', textAlign: 'center', }, image: { height: 200, width: 313, alignSelf: 'center', marginTop: 11, }, marginEqual: { marginLeft: 43, marginRight: 43, }, }) export default RegisterCard;
686e25afeedf9192123fe53c9a9cb56e8b1b4104
[ "JavaScript" ]
14
JavaScript
lrlineroa/tarjeta_app
43121daaa88a77e3d49c6ad31c9b26ebf64581e1
d9a69e421f68c6631b67d328b92ed7204a16070c
refs/heads/master
<file_sep>using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ToDoList.Models; namespace ToDoList.Services { public class MongoDBTrainingRepository : IRepository { MongoClient _client; private readonly IMongoCollection<ToDoItem> _collection; public MongoDBTrainingRepository() { _client = new MongoClient("mongodb://localhost:27017"); _collection = _client.GetDatabase("test").GetCollection<ToDoItem>("ItemList"); } public async Task DeleteAsync(string id) { await _collection.DeleteOneAsync(itemlist => itemlist.Id == id); } public async Task<ToDoItem> GetAsync(string id) { return await _collection.FindSync(itemlist => itemlist.Id == id).FirstAsync(); } public async Task<List<ToDoItem>> QueryAsync(string description, bool? done) { IEnumerable<ToDoItem> models = await _collection.Find(itemlist => true).ToListAsync(); if (!string.IsNullOrEmpty(description)) models = models.Where(v => v.Description?.IndexOf(description, StringComparison.OrdinalIgnoreCase) >= 0); if (done != null) models = models.Where(v => v.Done == done.Value); return models.ToList(); // return null; // return await _collection.Find(i => true).ToListAsync(); // throw new NotImplementedException(); } public async Task<ToDoItem> UpdateAsync(string id, ToDoItemUpdateModel updateModel) { //IEnumerable<ToDoItem> models = await _collection.Find(itemlist => true).ToListAsync(); //models = await _collection.Find(itemlist => true).ToList(); //if (_dic.TryGetValue(id, out var item)) //{ // if (!string.IsNullOrEmpty(updateModel.Description)) // item.Description = updateModel.Description; // if (updateModel.Favorite != null) // item.Favorite = updateModel.Favorite.Value; // if (updateModel.Done != null) // item.Done = updateModel.Done.Value; // return item; //} // return null; return null; // throw new NotImplementedException(); } public async Task UpsertAsync(ToDoItem model) { await _collection.ReplaceOneAsync(itemlist => itemlist.Id == model.Id, model); } } } <file_sep>import { UserService } from './../services/user.service'; import { ToDoItem } from './../app.todoitem '; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Observable } from 'rxjs'; import { identifierModuleUrl } from '@angular/compiler'; @Component({ selector: 'app-todo-detail', templateUrl: './todo-detail.component.html', styleUrls: ['./todo-detail.component.css'] }) export class TodoDetailComponent implements OnInit { items$: ToDoItem[]; id: string; constructor(private usersService: UserService, private router: Router, private route: ActivatedRoute) { } ngOnInit() { this.getService(); } getService(): void { this.usersService.getUsers().subscribe((items) => {this.items$ = items}); } switch(): void { if(confirm("Sure to discard changes")) { this.router.navigate(['/todo']); } } } <file_sep>using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using ToDoList.Models; using ToDoList.Services; namespace ToDoList.Controllers { [ApiController] [Route("api/[controller]")] public class ToDoItemController : ControllerBase { // private MemoryRepository _repository = MemoryRepository.Instance; private IRepository _repository; // public ToDoItemController(IRepository repository) public ToDoItemController() { _repository = new MongoDBTrainingRepository(); } /// <summary> /// Query ToDoItem by specific description and done /// </summary> /// <remarks> /// In remarks, we can document some detail information /// </remarks> /// <param name="description">ToDoItem description</param> /// <param name="done">ToDoItem status</param> /// <returns></returns> [HttpGet] public async Task<ActionResult<List<ToDoItem>>> QueryAsync( string description, bool? done) { var list = await _repository.QueryAsync(description, done); return Ok(list); } [HttpPatch("{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult<ToDoItem>> UpdateAsync( [Required] string id, [Required] ToDoItemUpdateModel updateModel) { var modelInDb = await _repository.GetAsync(id); if (modelInDb == null) return NotFound(new Dictionary<string, string>() { { "message", $"Can't find {id}" } }); //update var updated = await _repository.UpdateAsync(id, updateModel); return Ok(updated); } [HttpPut] public async Task<ActionResult<ToDoItem>> UpsertAsync(ToDoItem item) { //check id if (string.IsNullOrEmpty(item.Id)) return BadRequest(new Dictionary<string, string>() { { "message", "Id is required" } }); await _repository.UpsertAsync(item); var model = await _repository.GetAsync(item.Id); if (model == null) return new ObjectResult(500) { }; return Ok(model); } [HttpDelete("{id}")] public async Task<ActionResult> DeleteAsync( [Required] string id) { var modelInDb = await _repository.GetAsync(id); if (modelInDb == null) return NotFound(new Dictionary<string, string>() { { "message", $"Can't find {id}" } }); await _repository.DeleteAsync(id); return NoContent(); } } } <file_sep>import { ToDoItem } from './../app.todoitem '; import { Component, OnInit } from '@angular/core'; import { UserService } from '../services/user.service'; import { ActivatedRoute, Router} from '@angular/router'; import { ObjectUnsubscribedError } from 'rxjs'; @Component({ selector: 'app-todo', templateUrl: './todo.component.html', styleUrls: ['./todo.component.css'] }) export class TodoComponent implements OnInit { // item: ToDoItem; constructor(private usersService: UserService, private router: Router, private route: ActivatedRoute) { } title = 'TO-DO List'; items$: ToDoItem[]; item: ToDoItem; selectAll: boolean = true; getService(): void { this.usersService.getUsers().subscribe((items) => {this.items$ = items}); } getMongoId(): string{ return String(Math.random()); } add(): void { let item = {id: this.getMongoId(), description: '', createdTime: new Date(), done: false, favorite: false, children: []}; // this.usersService.addUser(item).subscribe(); this.items$.push(item); } // getServiceId(): void { // this.usersService.getUser(this.item.id).subscribe(i => this.item = i); // } ngOnInit() { // const id = this.route.snapshot.params['id']; this.getService(); //this.getServiceId(); } delete(ids) { if(confirm("Sure to delete?")) { this.items$ = this.items$.filter(item => ids.indexOf(item.id) === -1); } } search() { this.items$[0]; //return this.items$[0]; //return this.items$.find(item => item.id = ids); } switch(id: string): void { this.router.navigate(['todo/detail/' + id]); } } <file_sep>using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MongoDB.Bson; namespace ToDoList.Models { public class ToDoItem { // 存放数据类型 [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("description")] public string Description { get; set; } [BsonElement("createdTime")] public DateTime CreatedTime { get; set; } [BsonElement("done")] public bool Done { get; set; } [BsonElement("favorite")] public bool Favorite { get; set; } [BsonElement("children")] public ToDoItem[] Children { get; set; } } } <file_sep>import { ToDoItem } from './../app.todoitem '; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: `root`, }) export class UserService { constructor(private httpClient: HttpClient) { } getUsers(): Observable<ToDoItem[]> { return this.httpClient.get<ToDoItem[]>(`https://localhost:5001/api/ToDoItem`); } getUser(id: string): Observable<ToDoItem> { return this.httpClient.get<ToDoItem>(`https://localhost:5001/api/ToDoItem/${id}`) .pipe(catchError(this.handleError<ToDoItem>('getUsers id=${id}'))); } addUser(item: ToDoItem): Observable<ToDoItem> { return this.httpClient.post<ToDoItem>(`https://localhost:5001/api/ToDoItem`, item) .pipe(catchError(this.handleError<ToDoItem>('add item'))); } private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); // log to console instead console.log(`${operation} failed: ${error.message}`); return of(result as T); }; } } <file_sep>export interface ToDoItem { id: string; description: string; createdTime: Date; favorite: boolean; done: boolean; children: ToDoItem[]; }
ccf625a8a1339fafa4d00a625862af4bc58bca40
[ "C#", "TypeScript" ]
7
C#
fuywingfuy/TestAngular
193678b3f145bcf21f7ce57ed5c4501c2f058504
8581e7bf1f112bb573e010710856633f68bc1b38
refs/heads/master
<file_sep>#!/bin/bash source /boot/config/plugins/openvpnclient/openvpnclient.cfg if [[ $START_ON_MOUNT == "yes" ]]; then /etc/rc.d/rc.openvpnclient start fi <file_sep>**OpenVPN Client** A client for OpenVPN
eb9c0dba279c34bd781849e73d1857fbf6bff182
[ "Markdown", "Shell" ]
2
Shell
dmacias72/openvpn_client_x64
f131c6a212a3e2f8332a6edb8252685a8c3ace44
be33919406a9af73ea6063a4e42e69cebc292e33
refs/heads/master
<file_sep>const express = require('express'); const router = express.Router(); const passport = require('passport'); const User = require('../models/user'); const initializePassport = require('../passport-config'); initializePassport( passport, async uName => await User.findOne({ uName: uName}).exec(), async id => await User.findById(id) ); router.get('/', checkNotAuthenticated, (req, res) => { res.render('login/index'); }); router.post('/', checkNotAuthenticated, passport.authenticate('local', { successRedirect: '../', failureRedirect: '../login', failureFlash: true //so a message can be displayed to the user })); function checkAuthenticated(req, res, next) { if(req.isAuthenticated()) { return next(); } res.redirect('/login'); } function checkNotAuthenticated(req, res, next) { if(req.isAuthenticated()) { return res.redirect('/'); } next(); } module.exports = router;<file_sep>if(process.env.NODE_ENV !== 'production') { require('dotenv').config(); } const express = require('express'); const app = express(); const expressLayouts = require('express-ejs-layouts'); const methodOverride = require('method-override'); const passport = require('passport'); const flash = require('express-flash'); const session = require('express-session'); // const initializePassport = require('./passport-config'); // initializePassport( // passport, // uName => users.find(user => user.uName === uName) // ); const indexRouter = require('./routes/index'); const authorRouter = require('./routes/authors'); const bookRouter = require('./routes/books'); const loginRouter = require('./routes/login'); const logoutRouter = require('./routes/logout'); const registerRouter = require('./routes/register'); const error404Router = require('./routes/error404'); app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); app.set('layout', 'layouts/layout'); app.use(expressLayouts); app.use(methodOverride('_method')); app.use(express.static('public')); app.use(express.urlencoded({limit: '10mb', extended: false})); app.use(flash()); app.use(session({ secret: process.env.SESSION_SECRET, resave: false, //dont save variables if nothing has changed saveUninitialized: false //dont save empty value in session if there is no value //, cookie: {secure: true} //for https sites })) app.use(passport.initialize()); app.use(passport.session()); const mongoose = require('mongoose'); mongoose.connect(process.env.DATABASE_URL, {useNewUrlParser: true }) const db = mongoose.connection; db.on('error', error => console.error(error)); db.once('open', error => console.log('Connected to Mongoose')); app.use('/', indexRouter); app.use('/authors', authorRouter); app.use('/books', bookRouter); app.use('/login', loginRouter); app.use('/logout', logoutRouter); app.use('/register', registerRouter); app.use(error404Router); //make sure to put this after all routes app.listen(process.env.PORT || 3000);
9a296efe8d9ddb25851f65d33a77253725534adb
[ "JavaScript" ]
2
JavaScript
danidre14/Mybrary
9fb37f9436da3dca4e4b86e69700dfb7c651e7cb
726daf0ba98df32f5ae635c44db73156fc9b42c1
refs/heads/main
<repo_name>Karthik-Prabhu-kp/Emoji-interpretor-React<file_sep>/src/App.js import React, { useState } from "react"; import "./styles.css"; var emojiDictionary = { "🙂": "Happy", "😂": "Laughing", "😒": "unamused", "😴": "sleeping", "😭": "crying", "😋": "Face Savouring Delicious Food", "🤧": "Sneezing Face " }; var emojisWeKnow = Object.keys(emojiDictionary); export default function App() { var [meaning, setMeaning] = useState(""); function emojiInputHandler(event) { var userInput = event.target.value; var meaning = emojiDictionary[userInput]; if (meaning === undefined) { meaning = "we dont have this in our database"; } setMeaning(meaning); } function emojiClickHandler(emoji) { var meaning = emojiDictionary[emoji]; setMeaning(meaning); } return ( <div className="App"> <h1>Emoji Interpretor</h1> <input placeholder="Input emoji here or select from list below" onChange={() => emojiInputHandler(event)} /> <div class="meaning"> Meaning of emoji : {meaning} </div> <div class="known"> Emoji's we know</div> <span> {emojisWeKnow.map(function (emoji) { return ( <span onClick={() => emojiClickHandler(emoji)} class="emoji" key={emoji} > {emoji} </span> ); })} </span> </div> ); } <file_sep>/README.md # Emoji-interpretor-React Created with CodeSandbox
2f7f815aae08f895c8a04d4c093f887af1185555
[ "JavaScript", "Markdown" ]
2
JavaScript
Karthik-Prabhu-kp/Emoji-interpretor-React
55e111495618926a90b2481d1806c02fde4cefc5
639ac9e46ba15f227ac8857792ee7de83e98fb63
refs/heads/master
<repo_name>Avezen/telemedi-test<file_sep>/src/Controller/MainPageController.php <?php namespace App\Controller; use App\Entity\User; use App\Form\Login; use App\Form\RegisterUser; use App\Utils\UserService; use DateTime; use Doctrine\DBAL\Types\DateType; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class MainPageController extends AbstractController { /** * @Route("/", name="main_page") */ public function mainPage(Request $request) { $em = $this->getDoctrine()->getManager(); $register = new RegisterUser(); $login = new Login(); $userService = new UserService($em); $session = new Session(); $session->clear(); $loginForm = $this->get('form.factory') ->createNamedBuilder('login_form', FormType::class, $login) ->add('login', TextType::class) ->add('password', PasswordType::class) ->add('logIn', SubmitType::class, array('label' => 'Log In')) ->getForm(); $loginForm->handleRequest($request); $registerForm = $this->get('form.factory') ->createNamedBuilder('register_form', FormType::class, $register) ->add('login', TextType::class) ->add('username', TextType::class) ->add('password', PasswordType::class) ->add('passwordRepeated', PasswordType::class) ->add('register', SubmitType::class, array('label' => 'Register!')) ->getForm(); $registerForm->handleRequest($request); if (($registerForm->isSubmitted() && $registerForm->isValid()) || ($loginForm->isSubmitted() && $loginForm->isValid())) { if ($request->request->get('register_form')) { $register = $registerForm->getData(); $isRegisteredSuccessfully = $userService->registerUser($register); if($isRegisteredSuccessfully === true){ return $this->render('base.html.twig', array( 'registerForm' => $registerForm->createView(), 'loginForm' => $loginForm->createView(), 'message'=>"Account successfully created - call admin to activate it", )); }else{ return $this->render('base.html.twig', array( 'registerForm' => $registerForm->createView(), 'loginForm' => $loginForm->createView(), 'message'=>$isRegisteredSuccessfully, )); } }else if ($request->request->get('login_form')) { $loggedUser = $userService->loginUser($login); if($loggedUser === 0){ return $this->render('base.html.twig', array( 'registerForm' => $registerForm->createView(), 'loginForm' => $loginForm->createView(), 'message'=>"Account not activated", )); }else if ($loggedUser !== false){ $session->set('loggedUser', $login->getLogin()); $session->set('userRoles', unserialize($loggedUser['0']['roles'])); return $this->redirectToRoute('user_page'); }else{ return $this->render('base.html.twig', array( 'registerForm' => $registerForm->createView(), 'loginForm' => $loginForm->createView(), 'message'=>"Wrong login or password", )); } } } return $this->render('base.html.twig', array( 'registerForm' => $registerForm->createView(), 'loginForm' => $loginForm->createView(), )); } /** * @Route("/user", name="user_page") */ public function users() { $session = new Session(); $loggedUser = $session->get("loggedUser"); if(!$loggedUser) return $this->redirectToRoute("main_page"); $userRoles = $session->get("userRoles"); return $this->render('user/index.html.twig', array("user"=>$loggedUser, "roles"=>$userRoles)); } } <file_sep>/src/Controller/UserController.php <?php namespace App\Controller; use App\Entity\User; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class UserController extends Controller { /** * @Route("/getallusers", name="get_all_users") */ public function getAllUsers() { $session = new Session(); if($session->get('userRoles')[0] === "ROLE_ADMIN") { $em = $this->getDoctrine()->getManager(); $users = $em->getRepository(User::class)->createQueryBuilder('u') ->getQuery() ->getArrayResult(); if(count($users) !== 0) { for ($i = 0; $i < count($users); $i++) { $users[$i]['registrationDate'] = $users[$i]['registrationDate']->format('Y-m-d'); } return new JsonResponse($users); } return new JsonResponse(array("response"=>"No user exists")); } return new JsonResponse(array("response"=>"Access denied")); } /** * @Route("/deleteuser", name="delete_user") */ public function deleteUser(Request $request) { $session = new Session(); $id = json_decode($request->getContent(), true); if($session->get('userRoles')[0] === "ROLE_ADMIN"){ $em = $this->getDoctrine()->getManager(); $user = $em->getRepository(User::class)->find($id); if($user !== null){ $em->remove($user); $em->flush(); return new JsonResponse(array("response"=>"User deleted successfully")); } return new JsonResponse(array("response"=>"No user with id: ".$id)); } return new JsonResponse(array("response"=>"Access denied")); } /** * @Route("/changeuserstatus", name="change_user_status") */ public function changeUserStatus(Request $request) { $session = new Session(); $id = json_decode($request->getContent(), true); if($session->get('userRoles')[0] === "ROLE_ADMIN"){ $em = $this->getDoctrine()->getManager(); $user = $em->getRepository(User::class)->find($id); if($user !== null){ if($user->getIsActive()===1){ $user->setIsActive(0); }else { $user->setIsActive(1); } $em->persist($user); $em->flush(); return new JsonResponse(array("response"=>"User status changed successfully")); } return new JsonResponse(array("response"=>"No user with id: ".$id)); } return new JsonResponse(array("response"=>"Access denied")); } } <file_sep>/src/Utils/UserService.php <?php namespace App\Utils; use App\Entity\User; use DateTime; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\ORM\ORMException; use Symfony\Component\HttpFoundation\Session\Session; class UserService{ protected $em; public function __construct(ObjectManager $em) { $this->em = $em; } public function registerUser($registerData){ $now = new \DateTime(date("Y-m-d")); $doUserExist = $this->em->getRepository(User::class)->findBy(array("login"=>$registerData->getLogin())); if($doUserExist !== []){ return "Account with this login already exists"; } if(strlen($registerData->getLogin()) > 5 || strlen($registerData->getPassword()) > 5) { if ($registerData->getPassword() === $registerData->getPasswordRepeated()) { $user = new User(); $roles = array("0"=>"ROLE_USER"); $user->setLogin($registerData->getLogin()); $user->setPassword(password_hash($registerData->getPassword(), PASSWORD_BCRYPT, array('cost' => 11))); $user->setUsername($registerData->getUsername()); $user->setRoles(serialize($roles)); $user->setRegistrationDate($now); $user->setIsActive(0); $this->em->persist($user); $this->em->flush(); return true; } return "Passwords are not the same"; } return "Password or login are too short. They need to be longer than 5"; } public function loginUser($loginData){ $loggedUser = $this->em->getRepository(User::class); $loggedUser = $loggedUser->createQueryBuilder('u') ->andWhere('u.login = :login') ->setParameter('login', $loginData->getLogin()) ->getQuery() ->getArrayResult(); if($loggedUser !== []){ if(password_verify($loginData->getPassword(), $loggedUser[0]['password'])) { if ($loggedUser[0]['isActive'] === 0) return 0; return $loggedUser; } } return false; } } <file_sep>/src/Form/RegisterUser.php <?php namespace App\Form; class RegisterUser { private $login; private $password; private $passwordRepeated; private $roles; private $username; private $date; private $isActive; public function getLogin(): ?string { return $this->login; } public function setLogin(string $login): self { $this->login = $login; return $this; } public function getPassword(): ?string { return $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } public function getPasswordRepeated(): ?string { return $this->passwordRepeated; } public function setPasswordRepeated(string $passwordRepeated): self { $this->passwordRepeated = $passwordRepeated; return $this; } public function getRoles(): ?string { return $this->roles; } public function setRoles(string $roles): self { $this->roles = $roles; return $this; } public function getUsername(): ?string { return $this->username; } public function setUsername(string $username): self { $this->username = $username; return $this; } public function getDate(): ?\DateTime { return $this->date; } public function setDate(\DateTime $date): self { $this->date = $date; return $this; } public function getIsActive(): ?int { return $this->isActive; } public function setIsActive(int $isActive): self { $this->isActive = $isActive; return $this; } }
aaa2c2cf6e07d861d13dd933b2ea2ed2072f5286
[ "PHP" ]
4
PHP
Avezen/telemedi-test
ddd047d62267aced85adf94e5544ca01af97ccdc
f5e6dbaeabc712724873ab4e22927697f2999aa4
refs/heads/master
<repo_name>tanjum88/Project1<file_sep>/src/script/ValidLogin.java package script; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.Test; import generic.BaseTest; import generic.FWUtility; import page.EnterTimeTractPage; import page.LoginPage; public class ValidLogin extends BaseTest{ @Test(priority=1) public void testValidLogin() throws InterruptedException { String un=FWUtility.getXlData(XL_PATH, "ValidLogin", 1, 0); String pw= FWUtility.getXlData(XL_PATH, "ValidLogin", 1, 1); String title=FWUtility.getXlData(XL_PATH, "ValidLogin", 1, 2); //Enter Valid Username LoginPage l= new LoginPage(driver); l.setUserName(un); //enter password l.setPassword(pw); //click on login button l.clickLogin(); //verify homepage is displayed EnterTimeTractPage e=new EnterTimeTractPage(driver); e.verifyHomePageIsDisplayed(driver, ETO, title); } } <file_sep>/src/generic/FWUtility.java package generic; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.commons.io.FileUtils; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class FWUtility { public static String getXlData(String path, String sheet, int r, int c) { String v=""; try { Workbook wb= WorkbookFactory.create(new FileInputStream(path)); v=wb.getSheet(sheet).getRow(r).getCell(c).toString(); } catch(Exception e) { //e.printStackTrace(); } return v; } public static int getXlRowCount(String path, String sheet) { int count= 0; try { Workbook wb= WorkbookFactory.create(new FileInputStream(path)); count=wb.getSheet(sheet).getLastRowNum(); }catch(Exception e) { e.printStackTrace(); } return count; } public static void writeDataToXL(String path,String sheet,int r, int c,int v) { try { Workbook wb= WorkbookFactory.create(new FileInputStream(path)); wb.getSheet(sheet).getRow(r).getCell(c).setCellValue(v); wb.write(new FileOutputStream(path) { }); }catch(Exception e) { e.printStackTrace(); } } public static void getPhoto(WebDriver driver, String path) { try { TakesScreenshot t= (TakesScreenshot)driver; File srcFile = t.getScreenshotAs(OutputType.FILE); File destFile=new File(path); FileUtils.copyFile(srcFile, destFile); }catch(Exception e) { e.printStackTrace(); } } public static void scroll(WebElement element,WebElement eleHead, WebDriver driver) { int x=element.getLocation().getX(); int y=element.getLocation().getY(); int height=eleHead.getSize().getHeight(); y=y-height; //Now Type-cast JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("window.scrollTo("+x+","+y+")"); } } <file_sep>/src/script/CheckProductEdition.java package script; import org.testng.annotations.Test; import generic.BaseTest; import generic.FWUtility; import page.EnterTimeTractPage; import page.LicensePage; import page.LoginPage; public class CheckProductEdition extends BaseTest { @Test(priority=4) public void testCheckProductEdition() throws Exception{ String un = FWUtility.getXlData(XL_PATH, "CheckProductEdition", 1, 0); String pw = FWUtility.getXlData(XL_PATH, "CheckProductEdition", 1, 1); String productEdition = FWUtility.getXlData(XL_PATH, "CheckProductEdition", 1, 2); //Enter valid UserName LoginPage l=new LoginPage(driver); l.setUserName(un); //Enter Valid Password l.setPassword(pw); //ClickLogin l.clickLogin(); Thread.sleep(2000); //clickSettings EnterTimeTractPage e= new EnterTimeTractPage(driver); e.clickSettings(); e.clickLicenses(); //verify Issue Date LicensePage c= new LicensePage(driver); c.verifyProductEdition(productEdition); //click Logout c.clickLogout(); } } <file_sep>/test-output/old/Suite/methods.html <h2>Methods run, sorted chronologically</h2><h3>&gt;&gt; means before, &lt;&lt; means after</h3><p/><br/><em>Suite</em><p/><small><i>(Hover the method name to see the test class name)</i></small><p/> <table border="1"> <tr><th>Time</th><th>Delta (ms)</th><th>Suite<br>configuration</th><th>Test<br>configuration</th><th>Class<br>configuration</th><th>Groups<br>configuration</th><th>Method<br>configuration</th><th>Test<br>method</th><th>Thread</th><th>Instances</th></tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:00:11</td> <td>0</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&gt;&gt;BaseTest.openBrowser()[pri:0, instance:script.ValidLogin@52feb982]">&gt;&gt;openBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="ba7b69"> <td>18/12/06 20:00:16</td> <td>5356</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="ValidLogin.testValidLogin()[pri:1, instance:script.ValidLogin@52feb982]">testValidLogin</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:00:18</td> <td>7174</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&lt;&lt;BaseTest.closeBrowser(org.testng.ITestResult)[pri:0, instance:script.ValidLogin@52feb982]">&lt;&lt;closeBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:00:21</td> <td>9523</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&gt;&gt;BaseTest.openBrowser()[pri:0, instance:script.TestInvalidLogin@34c4973]">&gt;&gt;openBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="81ad78"> <td>18/12/06 20:00:26</td> <td>14516</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="TestInvalidLogin.testInvalidLogin()[pri:2, instance:script.TestInvalidLogin@34c4973]">testInvalidLogin</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:00:28</td> <td>17070</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&lt;&lt;BaseTest.closeBrowser(org.testng.ITestResult)[pri:0, instance:script.TestInvalidLogin@34c4973]">&lt;&lt;closeBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:00:31</td> <td>19737</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&gt;&gt;BaseTest.openBrowser()[pri:0, instance:script.CheckIssueDate@30a3107a]">&gt;&gt;openBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="e69ade"> <td>18/12/06 20:00:36</td> <td>25076</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="CheckIssueDate.testCheckIssueDate()[pri:3, instance:script.CheckIssueDate@30a3107a]">testCheckIssueDate</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:00:49</td> <td>37508</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&lt;&lt;BaseTest.closeBrowser(org.testng.ITestResult)[pri:0, instance:script.CheckIssueDate@30a3107a]">&lt;&lt;closeBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:00:51</td> <td>39875</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&gt;&gt;BaseTest.openBrowser()[pri:0, instance:script.CheckProductEdition@33c7e1bb]">&gt;&gt;openBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="6694f1"> <td>18/12/06 20:00:56</td> <td>44802</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="CheckProductEdition.testCheckProductEdition()[pri:4, instance:script.CheckProductEdition@33c7e1bb]">testCheckProductEdition</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:01:00</td> <td>48396</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="&lt;&lt;BaseTest.closeBrowser(org.testng.ITestResult)[pri:0, instance:script.CheckProductEdition@33c7e1bb]">&lt;&lt;closeBrowser</td> <td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> <tr bgcolor="d2dae5"> <td>18/12/06 20:01:02</td> <td>50837</td> <td title="&lt;&lt;BaseTest.print()[pri:0, instance:script.CheckIssueDate@30a3107a]">&lt;&lt;print</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td> <td>main@1630521067</td> <td></td> </tr> </table>
67bca88f8e605c8d5e157ae9ae50f801215079a1
[ "Java", "HTML" ]
4
Java
tanjum88/Project1
80314d14dbb810af204efb4989c96ad402d0a0f8
a9a65b12dc96fb354e5df6615779c3fb83f07a37
refs/heads/master
<file_sep>package ui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import _jz.is_digit; import _jz.jz_util; import model.category; import model.m_budget; import model.brand; import model.m_info; import model.m_to_s; import model.s_info; import util.BaseException; public class FrmModify_m extends JDialog implements ActionListener{ // public m_info m2; private m_info m = new m_info(); private brand brd = new brand(); private category cate = new category(); private s_info s_inf = new s_info(); private int s_id=0; private JPanel toolBar = new JPanel(); private JPanel jp = new JPanel(); private JPanel jp1 = new JPanel();private JPanel jp2 = new JPanel(); private JPanel jp3 = new JPanel();private JPanel jp4 = new JPanel(); private JPanel jp5 = new JPanel();private JPanel jp6 = new JPanel(); private JPanel jp7 = new JPanel();private JPanel jp8 = new JPanel(); private JPanel jp9 = new JPanel(); private JButton btnOk = new JButton("确定"); private JButton btnCancel = new JButton("取消"); private JLabel labelName = new JLabel("材料名:"); private JLabel label_brand = new JLabel("品牌号:"); private JLabel label_category = new JLabel("类别号:"); private JLabel label_standard = new JLabel("规格 :"); private JLabel label_model_number = new JLabel("型号 :"); private JLabel label_flower_color = new JLabel("花色 :"); private JLabel label_unit_price = new JLabel("单价 :"); private JLabel label_unit_of_valuation = new JLabel("计价单位:"); private JLabel label_s_inf = new JLabel("服务 :"); private JTextField edtName = new JTextField(25); private JTextField edt_brand = new JTextField(25); private JTextField edt_category = new JTextField(25); private JTextField edt_standard = new JTextField(25); private JTextField edt_model_number = new JTextField(25); private JTextField edt_flower_color = new JTextField(25); private JTextField edt_unit_price = new JTextField(25); private JTextField edt_unit_of_valuation = new JTextField(24); private JTextField edt_s_inf = new JTextField(25); private JButton btn_brand= new JButton("查看现有品牌"); private JButton btn_category= new JButton("查看现有类别"); private JButton btn_s_inf= new JButton("查看现有服务"); public FrmModify_m(Frame f, String s, boolean b) { super(f, s, b); } public FrmModify_m(MouseAdapter mouseAdapter, String s, boolean b) { // TODO Auto-generated constructor stub super(); } //================================================================================= private int flg=0;//用于判断选项,add_s=1,modify_s=2 protected void add_m() { //添加材料 flg=1; fuyong(); } protected void modify_m(m_info super_m) { //修改材料 flg=2; this.m = super_m; fuyong(); edtName.setText(m.getM_name());//赋值当前材料名 edt_brand.setText(String.valueOf(m.getBrand().getBrand_id()));//赋值当前品牌号 edt_category.setText(String.valueOf(m.getCategory().getCategory_id()));//赋值当前类别号 edt_standard.setText(m.getStandard()); edt_model_number.setText(m.getModel_number()); edt_flower_color.setText(m.getFlower_color()); edt_unit_price.setText(String.valueOf(m.getUnit_price())); edt_unit_of_valuation.setText(m.getUnit_of_valuation()); try { s_id = jz_util.m_to_s_manager.m_get_s(m.getM_id()); } catch (BaseException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(s_id!=0) edt_s_inf.setText(String.valueOf(s_id)); } protected void del_m(m_info super_m) { //删除材料 try { m_to_s mts = new m_to_s(); mts.setM_id(super_m.getM_id()); jz_util.m_to_s_manager.del_m_to_s(mts); jz_util.m_info_manager.del_m(super_m); } catch (BaseException e) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, e.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } } //公用部分========================================================================= private void fuyong() { toolBar.setLayout(new FlowLayout(FlowLayout.RIGHT)); toolBar.add(this.btnOk); toolBar.add(btnCancel); this.getContentPane().add(toolBar, BorderLayout.SOUTH); jp.setLayout(new FlowLayout(FlowLayout.LEFT)); jp1.setLayout(new FlowLayout(FlowLayout.LEFT));jp2.setLayout(new FlowLayout(FlowLayout.LEFT)); jp3.setLayout(new FlowLayout(FlowLayout.LEFT));jp4.setLayout(new FlowLayout(FlowLayout.LEFT)); jp5.setLayout(new FlowLayout(FlowLayout.LEFT));jp6.setLayout(new FlowLayout(FlowLayout.LEFT)); jp7.setLayout(new FlowLayout(FlowLayout.LEFT));jp8.setLayout(new FlowLayout(FlowLayout.LEFT)); jp9.setLayout(new FlowLayout(FlowLayout.LEFT)); jp1.add(labelName); jp1.add(edtName); jp2.add(label_brand); jp2.add(edt_brand); jp2.add(btn_brand); jp3.add(label_category); jp3.add(edt_category); jp3.add(btn_category); jp4.add(label_standard); jp4.add(edt_standard); jp5.add(label_model_number); jp5.add(edt_model_number); jp6.add(label_flower_color); jp6.add(edt_flower_color); jp7.add(label_unit_price); jp7.add(edt_unit_price); jp8.add(label_unit_of_valuation); jp8.add(edt_unit_of_valuation); jp9.add(label_s_inf); jp9.add(edt_s_inf); jp9.add(btn_s_inf); jp.add(jp1);jp.add(jp2); jp.add(jp3);jp.add(jp4); jp.add(jp5);jp.add(jp6); jp.add(jp7);jp.add(jp8); if(flg==2) jp.add(jp9); this.getContentPane().add(jp); this.setSize(500, 430); // 屏幕居中显示 double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight(); this.setLocation((int) (width - this.getWidth()) / 2, (int) (height - this.getHeight()) / 2); this.validate(); this.btnOk.addActionListener(this); this.btnCancel.addActionListener(this); this.btn_brand.addActionListener(this); this.btn_category.addActionListener(this); this.btn_s_inf.addActionListener(this); } //响应设置========================================================================== @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==this.btn_s_inf) { Frmload_s fs = new Frmload_s(this,"现有服务信息", true); fs.setVisible(true); if(fs.s_inf.getS_id()!=0) { edt_s_inf.setText(String.valueOf(fs.s_inf.getS_id())); this.s_inf = fs.s_inf; } } else if(e.getSource()==this.btn_brand) { Frmload_brand fb = new Frmload_brand(this,"现有品牌信息", true); if(fb.brand.getBrand_id()!=0) { edt_brand.setText(String.valueOf(fb.brand.getBrand_id())); this.brd = fb.brand; } } else if(e.getSource()==this.btn_category) { Frmload_category fc = new Frmload_category(this,"现有类别信息", true); if(fc.category.getCategory_id()!=0) { edt_category.setText(String.valueOf(fc.category.getCategory_id())); this.cate = fc.category; } } else if(e.getSource()==this.btnCancel) this.setVisible(false); else if(e.getSource()==this.btnOk){ try { double unit_price; if("".equals(this.edt_brand.getText())) throw new BaseException("品牌号不能为空"); else if(!is_digit.isInteger(this.edt_brand.getText())) throw new BaseException("品牌号 请输入纯数字"); if("".equals(this.edt_category.getText())) throw new BaseException("类别号不能为空"); else if(!is_digit.isInteger(this.edt_category.getText())) throw new BaseException("类别号 请输入纯数字"); if("".equals(this.edt_s_inf.getText())) this.s_id=0; else if(!is_digit.isInteger(this.edt_s_inf.getText())) throw new BaseException("服务号 请输入纯数字"); else {this.s_id=(Integer.parseInt(this.edt_s_inf.getText()));} if("".equals(this.edt_unit_price.getText())) {unit_price = 0.0;} else if(!is_digit.isDouble(this.edt_unit_price.getText())) throw new BaseException("单价 请输入纯数字"); else if(Double.parseDouble(this.edt_unit_price.getText())<0) throw new BaseException("单价 不能小于0"); else {unit_price = Double.parseDouble(this.edt_unit_price.getText());} m.setM_name(edtName.getText()); m.setBrand(jz_util.brand_manager.load_brand(Integer.parseInt(this.edt_brand.getText()))); m.setCategory(jz_util.category_manager.load_category(Integer.parseInt(this.edt_category.getText()))); m.setStandard(this.edt_standard.getText()); m.setModel_number(this.edt_model_number.getText()); m.setFlower_color(this.edt_flower_color.getText()); m.setUnit_price(unit_price); m.setUnit_of_valuation(this.edt_unit_of_valuation.getText()); m.setS_id(s_id); m_to_s mts = new m_to_s(m.getM_id(),s_id,1); if(flg==1) { jz_util.m_info_manager.add_m(m); } else if(flg==2) { jz_util.m_info_manager.change_m(m); jz_util.m_to_s_manager.change_m_to_s(mts); } else throw new BaseException("材料信息操作错误,flg="+flg); this.setVisible(false); } catch (BaseException e1) { JOptionPane.showMessageDialog(null, e1.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } } } } <file_sep>package model; public class user { public static user currentLoginUser=null; public static final String[] tableTitles={"序号","用户名","用户密码","等级"}; /** * 请自行根据javabean的设计修改本函数代码,col表示界面表格中的列序号,0开始 */ public String getCell(int col){ if(col==0) return String.valueOf(user_id); else if(col==1) return user_name; else if(col==2) return psd; else if(col==3) return String.valueOf(level); else return ""; } private int user_id; private String user_name; private int level; private String psd; public user() { super(); } public user(String user_name, int level, String psd) { super(); this.user_name = user_name; this.level = level; this.psd = psd; } public static user getCurrentLoginUser() { return currentLoginUser; } public static void setCurrentLoginUser(user currentLoginUser) { user.currentLoginUser = currentLoginUser; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getPsd() { return psd; } public void setPsd(String psd) { this.psd = psd; } } <file_sep>package _jz; import itf.*; import java.util.regex.Pattern; import function.*; public class jz_util { public static user_itf user_manager= new user_manager(); public static brand_itf brand_manager = new brand_manager(); public static category_itf category_manager = new category_manager(); public static m_budget_itf m_budget_manager = new m_budget_manager(); public static m_info_itf m_info_manager = new m_info_manager(); public static m_to_s_itf m_to_s_manager = new m_to_s_manager(); public static s_budget_itf s_budget_manager = new s_budget_manager(); public static s_info_itf s_info_manager = new s_info_manager(); } <file_sep>package model; public class s_budget { public static final String[] tableTitles={"序号","服务内容","数量","单价","服务时间","用户名"}; /** * 请自行根据javabean的设计修改本函数代码,col表示界面表格中的列序号,0开始 */ public String getCell(int col){ if(col==0) return String.valueOf(s_budget_id); else if(col==1) return s.getService_content(); else if(col==2) return String.valueOf(quantity); else if(col==3) return String.valueOf(s.getUnit_price()); else if(col==4) return String.valueOf(s.getService_time()); else if(col==5) return user.getUser_name(); else return ""; } private int s_budget_id; private int quantity; private int required_time; private String remark; private s_info s; private user user; public s_budget() { super(); } public s_budget(s_info s, int quantity, int required_time, String remark, user user) { super(); //this.s_budget_id = s_budget_id; this.s = s; this.quantity = quantity; this.required_time = required_time; this.remark = remark; this.user = user; } public s_info getS() { return s; } public void setS(s_info s) { this.s = s; } public user getUser() { return user; } public void setUser(user user) { this.user = user; } public int getS_budget_id() { return s_budget_id; } public void setS_budget_id(int s_budget_id) { this.s_budget_id = s_budget_id; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getRequired_time() { return required_time; } public void setRequired_time(int required_time) { this.required_time = required_time; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } } <file_sep>package function; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; import itf.brand_itf; import model.brand; import util.BaseException; import util.BusinessException; import util.HBUtil; public class brand_manager implements brand_itf{ @Override//1.添加品牌 public brand add_brand(brand brd) throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); Transaction tx = s.beginTransaction(); if(brd.getBrand_name()==null || "".equals(brd.getBrand_name()) || brd.getBrand_name().length()>20) {throw new BusinessException("品牌名必须是1-20个字母");} String hql = "from brand where brand_name = '"+brd.getBrand_name()+"'"; Query query = s.createQuery(hql); if(query.list().size()==0) //品牌名不存在 {s.save(brd);tx.commit();System.out.println("输出在这12");} else {throw new BusinessException("品牌名已存在1");} s.close(); return brd; } @Override//2.删除品牌,有材料存在时,不能删除 public void del_brand(brand brand) throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); Transaction tx = s.beginTransaction(); String hql = "from brand where brand_name = '"+brand.getBrand_name()+"'"; Query query = s.createQuery(hql); if(query.list().size()==0) //品牌名不存在 {throw new BusinessException("此品牌不存在");} else { String hql2 = "from m_info where brand_id = "+brand.getBrand_id(); Query query2 = s.createQuery(hql2); if(query2.list().size()!=0) {throw new BusinessException("此品牌下存在商品,不能删除");} } hql = "delete from brand where brand_name = '"+brand.getBrand_name()+"'"; s.createQuery(hql).executeUpdate(); tx.commit(); s.close(); } @Override//3.修改品牌名,不能与已有名重复 public brand change_brand(brand brd) throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); Transaction tx = s.beginTransaction(); if(brd.getBrand_name()==null || "".equals(brd.getBrand_name()) || brd.getBrand_name().length()>20) {throw new BusinessException("品牌名必须是1-20个字母");} String hql2 = "from m_info where brand_id = "+brd.getBrand_id(); Query query2 = s.createQuery(hql2); if(query2.list().size()!=0) {throw new BusinessException("此品牌下存在商品,不能修改");} String hql = "from brand where brand_name = '"+brd.getBrand_name()+"'"; Query query = s.createQuery(hql); if(query.list().size()==0) //品牌名不存在 {s.update(brd);} else {throw new BusinessException("此品牌名已存在");} tx.commit(); s.close(); return brd; } @Override//4.提取当前所有品牌 public List<brand> load_all() throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); List<brand> all_brand = new ArrayList<brand>(); String hql = "from brand"; all_brand = s.createQuery(hql).list(); s.close(); return all_brand; } //5.提取指定品牌 public brand load_brand(int brand_id)throws BaseException{ Session s = HBUtil.getSession(); brand brand = new brand(); String hql; if(brand_id==0) {throw new BusinessException("请指定品牌号");} else if(brand_id!=0) { hql = "from brand where brand_id = "+brand_id; Query query = s.createQuery(hql); if(query.list().size()==0) {throw new BusinessException("该品牌不存在");} brand = (model.brand) query.list().get(0); } s.close(); return brand; } public List<brand> load_brand_byname(String name)throws BaseException{ Session s = HBUtil.getSession(); List<brand> all_brand = new ArrayList<brand>(); String hql; if("".equals(name)) { hql = "from brand"; } else { hql = "from brand where brand_name like '%"+name+"%'"; } all_brand = s.createQuery(hql).list(); s.close(); return all_brand; } } <file_sep>package function; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; import itf.category_itf; import model.brand; import model.category; import util.BaseException; import util.BusinessException; import util.HBUtil; public class category_manager implements category_itf{ @Override//1.添加类别 public category add_category(category cate) throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); Transaction tx = s.beginTransaction(); if(cate.getCategory_name()==null || "".equals(cate.getCategory_name()) || cate.getCategory_name().length()>20) {throw new BusinessException("类别名必须是1-20个字母");} String hql = "from category where category_name = '"+cate.getCategory_name()+"'"; Query query = s.createQuery(hql); if(query.list().size()==0) //类别名不存在 {s.save(cate);} else {throw new BusinessException("类别名已存在");} tx.commit(); s.close(); return cate; } @Override//2.删除类别,有材料存在时,不能删除 public void del_category(category category) throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); Transaction tx = s.beginTransaction(); String hql = "from category where category_name = '"+category.getCategory_name()+"'"; Query query = s.createQuery(hql); if(query.list().size()==0) //类别名不存在 {throw new BusinessException("此类别不存在");} else { String hql2 = "from m_info where category_id = "+category.getCategory_id(); Query query2 = s.createQuery(hql2); if(query2.list().size()!=0) {throw new BusinessException("此类别下存在商品,不能删除");} } hql = "delete from category where category_name = '"+category.getCategory_name()+"'"; s.createQuery(hql).executeUpdate(); tx.commit(); s.close(); } @Override//3.修改类别名,不能与已有名重复 public category change_category(category cate) throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); Transaction tx = s.beginTransaction(); if(cate.getCategory_name()==null || "".equals(cate.getCategory_name()) || cate.getCategory_name().length()>20) {throw new BusinessException("类别名必须是1-20个字母");} else { String hql2 = "from m_info where category_id = "+cate.getCategory_id(); Query query2 = s.createQuery(hql2); if(query2.list().size()!=0) {throw new BusinessException("此类别下存在商品,不能修改");} String hql = "from category where category_name = '"+cate.getCategory_name()+"'"; Query query = s.createQuery(hql); if(query.list().size()==0) //品牌名不存在 {s.update(cate);} else {throw new BusinessException("此类别名已存在");} } tx.commit(); s.close(); return cate; } @Override//4.提取当前所有类别 public List<category> load_all() throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); List<category> all_category = new ArrayList<category>(); String hql = "from category"; all_category = s.createQuery(hql).list(); s.close(); return all_category; } //5.提取指定品牌 public category load_category(int category_id)throws BaseException{ Session s = HBUtil.getSession(); category category = new category(); String hql; if(category_id==0) {throw new BusinessException("请指定类别号");} else if(category_id!=0) { hql = "from category where category_id = "+category_id; Query query = s.createQuery(hql); if(query.list().size()==0) {throw new BusinessException("该类别不存在");} category = (model.category) query.list().get(0); } s.close(); return category; } public List<category> load_category_byname(String name) throws BaseException { // TODO Auto-generated method stub Session s = HBUtil.getSession(); String hql; List<category> all_category = new ArrayList<category>(); if("".equals(name)) hql = "from category"; else hql = "from category where category_name like '%"+name+"%'"; all_category = s.createQuery(hql).list(); s.close(); return all_category; } } <file_sep>package ui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import _jz.jz_util; import model.m_budget; import model.s_budget; import model.user; import util.BaseException; public class Frmload_bgt extends JDialog implements ActionListener{ private List<m_budget> all_m_budget = null; private List<s_budget> all_s_budget = null; private user usr = new user(); private Object tbl_m_budget_title[] = m_budget.tableTitles; private Object tbl_m_budget_data[][]; private DefaultTableModel tab_m_budget_model = new DefaultTableModel(); private JTable data_table_m_budget = new JTable(tab_m_budget_model); private TableRowSorter<DefaultTableModel> sort_m_budget = new TableRowSorter<DefaultTableModel>(tab_m_budget_model); //服务预算 private Object tbl_s_budget_title[] = s_budget.tableTitles; private Object tbl_s_budget_data[][]; private DefaultTableModel tab_s_budget_model = new DefaultTableModel(); private JTable data_table_s_budget = new JTable(tab_s_budget_model); private TableRowSorter<DefaultTableModel> sort_s_budget = new TableRowSorter<DefaultTableModel>(tab_s_budget_model); private JPanel jp = new JPanel(new BorderLayout()); private JPanel jp_left = new JPanel(new BorderLayout()); private JPanel jp_right = new JPanel(new BorderLayout()); private JScrollPane jp1 = new JScrollPane();private JScrollPane jp2 = new JScrollPane(); private JLabel label_m_bgt = new JLabel("材料预算表"); private JLabel label_s_bgt = new JLabel("服务预算表"); private JPanel jp_left_n = new JPanel(new FlowLayout(FlowLayout.CENTER)); private JPanel jp_right_n = new JPanel(new FlowLayout(FlowLayout.CENTER)); private JPanel jp_s_c = new JPanel(new FlowLayout(FlowLayout.CENTER)); private JButton btn_total = new JButton("合计"); public Frmload_bgt(Frmload_user f, String s, boolean b, user super_usr) { // TODO Auto-generated constructor stub super(f,s,b); this.usr = super_usr; fuyong(); } //============================================================================================= private void fuyong() { jp1 = new JScrollPane(this.data_table_m_budget); jp2 = new JScrollPane(this.data_table_s_budget); jp_left_n.add(label_m_bgt);jp_right_n.add(label_s_bgt); jp_left.add(jp_left_n, BorderLayout.NORTH); jp_left.add(jp1,BorderLayout.CENTER); jp_right.add(jp_right_n, BorderLayout.NORTH); jp_right.add(jp2, BorderLayout.CENTER); jp.add(jp_left, BorderLayout.WEST); jp.add(jp_right, BorderLayout.CENTER); jp.add(btn_total, BorderLayout.SOUTH); this.getContentPane().add(jp); this.reload_m_budget_table(); this.reload_s_budget_table(); this.setSize(1000, 600); double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight(); this.setLocation((int) (width - this.getWidth()) / 2, (int) (height - this.getHeight()) / 2); this.validate(); this.btn_total.addActionListener(this); } //============================================================================================= @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==this.btn_total) { Frmtotal dlg = new Frmtotal(this,"合计", true, usr); dlg.setVisible(true); } } //============================================================================================= private void reload_m_budget_table() {//当前用户材料预算 try { all_m_budget = jz_util.m_budget_manager.load_m_budget(usr); }catch (BaseException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } tbl_m_budget_data = new Object[all_m_budget.size()][m_budget.tableTitles.length]; for(int i=0; i<all_m_budget.size(); i++) for(int j=0; j<m_budget.tableTitles.length; j++) { if(j==0) {tbl_m_budget_data[i][j]=i+1;continue;}//序号 tbl_m_budget_data[i][j] = all_m_budget.get(i).getCell(j); } tab_m_budget_model.setDataVector(tbl_m_budget_data, tbl_m_budget_title); this.data_table_m_budget.validate(); this.data_table_m_budget.repaint(); } protected void reload_s_budget_table() {//当前用户服务预算 try { all_s_budget = jz_util.s_budget_manager.load_s_budget(usr); }catch (BaseException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } tbl_s_budget_data = new Object[all_s_budget.size()][s_budget.tableTitles.length]; for(int i=0; i<all_s_budget.size(); i++) for(int j=0; j<s_budget.tableTitles.length; j++) { if(j==0) {tbl_s_budget_data[i][j]=i+1;continue;}//序号 tbl_s_budget_data[i][j] = all_s_budget.get(i).getCell(j); } tab_s_budget_model.setDataVector(tbl_s_budget_data, tbl_s_budget_title); this.data_table_s_budget.validate(); this.data_table_s_budget.repaint(); } } <file_sep>package model; public class brand { public static final String[] tableTitles={"序号","品牌名","描述"}; /** * 请自行根据javabean的设计修改本函数代码,col表示界面表格中的列序号,0开始 */ public String getCell(int col){ if(col==0) return String.valueOf(brand_id); else if(col==1) return brand_name; else if(col==2) return brand_describe; else return ""; } private int brand_id; private String brand_name; private String brand_describe; public brand() { super(); } public brand(String brand_name, String brand_describe) { super(); //this.brand_id = brand_id; this.brand_name = brand_name; this.brand_describe = brand_describe; } public int getBrand_id() { return brand_id; } public void setBrand_id(int brand_id) { this.brand_id = brand_id; } public String getBrand_name() { return brand_name; } public void setBrand_name(String brand_name) { this.brand_name = brand_name; } public String getBrand_describe() { return brand_describe; } public void setBrand_describe(String brand_describe) { this.brand_describe = brand_describe; } } <file_sep>package model; public class s_info { public static final String[] tableTitles={"序号","服务内容","服务等级","单价","计价单位","服务时间"}; /** * 请自行根据javabean的设计修改本函数代码,col表示界面表格中的列序号,0开始 */ public static final String[] tableTitles2={"序号","服务内容","服务等级","单价","计价单位","服务时间","数量"}; public String getCell(int col){ if(col==0) return String.valueOf(s_id); else if(col==1) return service_content; else if(col==2) return String.valueOf(service_level); else if(col==3) return String.valueOf(unit_price); else if(col==4) return unit_of_valuation; else if(col==5) return String.valueOf(service_time); else return ""; } private int s_id; private String service_content; //服务内容 private int service_level; //服务等级 private double unit_price; //单价 private String unit_of_valuation;//计价单位 private int service_time; //服务时间 public s_info() { super(); } public s_info(String service_content, int service_level, double unit_price, String unit_of_valuation, int service_time) { super(); this.service_content = service_content; this.service_level = service_level; this.unit_price = unit_price; this.unit_of_valuation = unit_of_valuation; this.service_time = service_time; } public int getS_id() { return s_id; } public void setS_id(int s_id) { this.s_id = s_id; } public String getService_content() { return service_content; } public void setService_content(String service_content) { this.service_content = service_content; } public int getService_level() { return service_level; } public void setService_level(int service_level) { this.service_level = service_level; } public double getUnit_price() { return unit_price; } public void setUnit_price(double unit_price) { this.unit_price = unit_price; } public String getUnit_of_valuation() { return unit_of_valuation; } public void setUnit_of_valuation(String unit_of_valuation) { this.unit_of_valuation = unit_of_valuation; } public int getService_time() { return service_time; } public void setService_time(int service_time) { this.service_time = service_time; } } <file_sep>package ui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import _jz.jz_util; import model.m_budget; import model.s_budget; import model.user; import util.BaseException; public class Frmtotal extends JDialog implements ActionListener{ private double cnt_m = 0; private double cnt_s = 0; private double total = 0; private user usr = new user(); private List<m_budget> list_m = new ArrayList<m_budget>(); private List<s_budget> list_s = new ArrayList<s_budget>(); private JPanel jp = new JPanel(); private JPanel jp1 = new JPanel();private JPanel jp2 = new JPanel(); private JPanel jp3 = new JPanel();private JPanel jp4 = new JPanel(); private JButton btnOk = new JButton("确定"); private JLabel label_cnt_m = new JLabel("材料合计:"); private JLabel label_cnt_s = new JLabel("服务合计:"); private JLabel label_total = new JLabel("合计:"); public Frmtotal(FrmMain f, String s, boolean b) { // TODO Auto-generated constructor stub super(f,s,b); try { list_m = jz_util.m_budget_manager.load_m_budget(user.currentLoginUser); list_s = jz_util.s_budget_manager.load_s_budget(user.currentLoginUser); } catch (BaseException e) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, e.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } fuyong(); } public Frmtotal(Frmload_bgt f, String s, boolean b, user super_usr) { // TODO Auto-generated constructor stub super(f,s,b); this.usr = super_usr; try { list_m = jz_util.m_budget_manager.load_m_budget(this.usr); list_s = jz_util.s_budget_manager.load_s_budget(this.usr); } catch (BaseException e) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, e.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } fuyong(); } private void fuyong() { for(int i=0; i<list_m.size(); i++) { cnt_m+=list_m.get(i).getUnit_price()*list_m.get(i).getQuantity(); } for(int i=0; i<list_s.size(); i++) { double unit_price = list_s.get(i).getS().getUnit_price(); cnt_s+=list_s.get(i).getQuantity()*unit_price; } total = cnt_m+cnt_s; label_cnt_m.setText("材料合计:"+cnt_m); label_cnt_s.setText("服务合计:"+cnt_s); label_total.setText("合计 :"+total); jp.setLayout(new FlowLayout(FlowLayout.LEFT)); jp1.setLayout(new FlowLayout(FlowLayout.LEFT));jp2.setLayout(new FlowLayout(FlowLayout.LEFT)); jp3.setLayout(new FlowLayout(FlowLayout.LEFT));jp4.setLayout(new FlowLayout(FlowLayout.RIGHT)); jp4.add(this.btnOk); this.getContentPane().add(jp4, BorderLayout.SOUTH); jp1.setPreferredSize(new Dimension(350, 30));jp2.setPreferredSize(new Dimension(350, 30)); jp3.setPreferredSize(new Dimension(350, 30)); jp1.add(label_cnt_m); jp2.add(label_cnt_s); jp3.add(label_total); jp.add(jp1);jp.add(jp2); jp.add(jp3); this.getContentPane().add(jp); this.setSize(300, 200); // 屏幕居中显示 double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight(); this.setLocation((int) (width - this.getWidth()) / 2, (int) (height - this.getHeight()) / 2); this.validate(); this.btnOk.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==this.btnOk) this.setVisible(false); } }
f904d4c8de45784226eb6b05f3bc87e0d061d905
[ "Java" ]
10
Java
jiu-yuan/java
505391f724415f3dece3d0b9976facaf6c5b5832
ba11e0db202d837e4d6268c2cc9df0bebc77d7e6
refs/heads/master
<repo_name>skalmannen/Crawler<file_sep>/crawler.py import requests import bs4 import urllib import random def initCrawl(url, step, steps): print('Crawling ...') crawler(url, step, steps) def crawler(url, step, steps): if step < steps: try: print('** Site ', step, ' : ', url, ' **') res = requests.get(url) soup = bs4.BeautifulSoup(res.text, 'lxml') badLinks = [] for link in soup.find_all('a'): badLinks.append(link.get('href')) print('CONTROL : badLinks=',len(badLinks)) links = [] for i in badLinks: # if you wan't to view all websites, remove comment below # print(i) if i != None and "http" in i: links.append(i) if not links: print('*** Results: ', step, ' websites were crawled. ***') return print('CONTROL : links=', len(links)) nextUrl = links[random.randint(0,(len(links)))] step = step + 1 crawler(nextUrl, step, steps) except IndexError as ie: print('Error : ', ie) print('*** Results: ', step, ' websites were crawled. ***') except Exception as e: print('Error : ', e) print('*** Results: ', step, ' websites were crawled. ***') else: print('*** Results: ', step, ' websites were crawled. ***') initCrawl('https://whynohttps.com/', 1, 20)
84eaad1b5e86f1da11e941db50041074f6201d41
[ "Python" ]
1
Python
skalmannen/Crawler
1df13bed7e6abef79af08029d3aaa4d5f9697ed6
040f1e186c07dcf9d3a64a451fda82a39c345223
refs/heads/main
<repo_name>MedhaChirumarri/Deep-learning_pattern-recognition<file_sep>/Method1.py import pandas as pd import numpy as np import math import glob import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') import torch import torch.nn.functional as F import torch.nn as nn from sklearn.model_selection import train_test_split def f(path,x): all_files = glob.glob(path + "/*.csv") li = [] for filename in all_files: df = pd.read_csv(filename, index_col=None, header=0,encoding='utf-16') li.append(df) frame = pd.concat(li, axis=0, ignore_index=True) frame["class"]=[x for i in range(len(frame))] return (frame) data1=f("/content/kan.zip",0) data2=f("/content/hin.zip",1) data3=f("/content/asm.zip",2) data4=f("/content/ben.zip",0) data5=f("/content/guj",2) data1=data1.append(data2) data=data3.append(data1) data6=data4.append(data5) Y=np.asarray(data["class"]) X=np.asarray(data.drop("class",axis=1)) Y1=np.asarray(data6["class"]) X1=np.asarray(data6.drop("class",axis=1)) #print(type(X)) #X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.3,random_state=0) #X_train, Y_train, X_test, Y_test = map(torch.tensor, (X_train, Y_train, X_test, Y_test)) X,Y=map(torch.tensor,(X,Y)) X1,Y1=map(torch.tensor,(X1,Y1)) def accuracy(y_hat, y): pred = torch.argmax(y_hat, dim=1) return (pred == y).float().mean() def fit(epochs = 1000, learning_rate = 1): loss_arr = [] acc_arr = [] for epoch in range(epochs): # y_hat = fn(X_train) # loss = F.cross_entropy(y_hat, Y_train) #loss_arr.append(loss.item()) #acc_arr.append(accuracy(y_hat, Y_train)) #y_hat = fn(X_train) y_hat = fn(X) loss = F.cross_entropy(y_hat, Y) loss_arr.append(loss.item()) acc_arr.append(accuracy(y_hat, Y)) loss.backward() with torch.no_grad(): for param in fn.parameters(): param -= learning_rate * param.grad fn.zero_grad() plt.plot(loss_arr, 'r-') plt.plot(acc_arr, 'b-') plt.show() print('acurracy', acc_arr[-1]) print('Loss after training', loss_arr[-1]) class FirstNetwork(nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.weights1 = nn.Parameter(torch.randn(80,700) / math.sqrt(2)) self.bias1 = nn.Parameter(torch.zeros(700)) self.weights2 = nn.Parameter(torch.randn(700, 500) / math.sqrt(2)) self.bias2 = nn.Parameter(torch.zeros(500)) self.weights3 = nn.Parameter(torch.randn(500, 5) / math.sqrt(2)) self.bias3 = nn.Parameter(torch.zeros(5)) def forward(self, X): a1 = torch.matmul(X, self.weights1.double()) + self.bias1 h1 = a1.sigmoid() a2 = torch.matmul(h1, self.weights2.double()) + self.bias2 h2 = a2.sigmoid() a3=torch.matmul(h2, self.weights3.double()) + self.bias3 h3 = a3.exp()/a3.exp().sum(-1).unsqueeze(-1) return h3 fn = FirstNetwork() fit() y1=fn(X1) acc=accuracy(y1,Y1) print(acc) <file_sep>/README.md # FFN DL code <file_sep>/SRP2.PY import pandas as pd import numpy as np import glob import torch import torch.nn as nn import torch.optim as optim import time folders = glob.glob("/home/system/Desktop/SRP/train/*") Xtrain=[] Ytrain=[] k=0 for folder in folders: for filename in glob.glob(folder+"/*.csv"): df = pd.read_csv(filename, index_col=None, header=0,encoding='utf-16') Ytrain.append(np.array(k)) Xtrain.append(np.array(df)) k=k+1 print(len(Xtrain)) folders = glob.glob("/home/system/Desktop/SRP/test/*") Xtest=[] Ytest=[] k=0 check_p=0 m=0 for folder in folders: for filename in glob.glob(folder+"/*.csv"): df = pd.read_csv(filename, index_col=None, header=0,encoding='utf-16') Ytest.append(np.array(k)) Xtest.append(np.array(df)) k=k+1 print(len(Xtest)) def eval(net,criterion,batch_size,topk, X, Y): correct = 0 files,langs = batched_dataloader(batch_size, X, Y,False) hidden = net.init_hidden(batch_size) output, hidden = net(files, hidden) val, indices = output.topk(topk) for i,j in zip(indices,langs): if j in i: correct += 1 accuracy = correct/batch_size loss=criterion(output, langs) return accuracy,loss def batched_dataloader(batch_size, X, Y,train=True): files = [] langs = [] file_len=[] if train==True: for i in range(batch_size): index = np.random.randint(len(X)) file, lang = X[index], Y[index] file_len.append(len(file)) files.append(torch.tensor(file)) langs.append(lang) else: langs=Y file_len=[len(i) for i in X] files=[torch.tensor(i) for i in X] langs=np.array(langs) files=nn.utils.rnn.pad_sequence(files, batch_first=True) files=np.array(files) k=np.empty([max(file_len),batch_size,80]) for i in range(max(file_len)): for j in range(batch_size): k[i][j]=np.array(files[j][i]) files=torch.from_numpy(k).float() langs=torch.from_numpy(langs).long() files = nn.utils.rnn.pack_padded_sequence(files,file_len, enforce_sorted = False) return files, langs def train_batch(net, opt, criterion, batch_size): opt.zero_grad() files, langs = batched_dataloader(batch_size, Xtrain, Ytrain) hidden = net.init_hidden(batch_size) output, hidden = net(files,hidden) loss = criterion(output, langs) loss.backward() opt.step() print("loss:",loss) print(" ") return loss def train_setup(net, lr = 0.01, n_batches = 100, batch_size = 10, momentum = 0.9): criterion = nn.NLLLoss() opt = optim.SGD(net.parameters(), lr=lr, momentum=momentum) loss_arr = np.zeros(n_batches + 1) for i in range(n_batches): print("batch:",i+1) loss_arr[i+1] = (loss_arr[i]*i + train_batch(net, opt, criterion, batch_size))/(i + 1) print("avg_loss_array:",loss_arr) print(" ") print('Top-3:', eval(net, criterion,len(Xtest), 3, Xtest, Ytest), 'Top-2:', eval(net, criterion,len(Xtest), 2, Xtest, Ytest)) class LSTM_net(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(LSTM_net, self).__init__() self.hidden_size = hidden_size self.lstm_cell = nn.LSTM(input_size, hidden_size) self.h2o = nn.Linear(hidden_size, output_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, input, hidden): out, hidden = self.lstm_cell(input, hidden) output = self.h2o(hidden[0].view(-1, self.hidden_size)) output = self.softmax(output) return output, hidden def init_hidden(self, batch_size = 1): return (torch.zeros(1, batch_size, self.hidden_size), torch.zeros(1, batch_size, self.hidden_size)) n_hidden = 128 tic = time.time() net = LSTM_net(80, n_hidden, 9) train_setup(net, lr=1, n_batches=20, batch_size = 128) toc = time.time() print(" ") print('Time taken', toc - tic)<file_sep>/SRP3.py import pandas as pd import numpy as np import glob import torch import torch.nn as nn import torch.optim as optim import time folders = glob.glob("/home/system/Desktop/SRP/train/*") Xtrain=[] Ytrain=[] k=0 for folder in folders: for filename in glob.glob(folder+"/*.csv"): df = pd.read_csv(filename, index_col=None, header=0,encoding='utf-16') Ytrain.append(np.array([k])) Xtrain.append(np.array(df)) k=k+1 print(len(Xtrain)) folders = glob.glob("/home/system/Desktop/SRP/test/*") Xtest=[] Ytest=[] k=0 for folder in folders: for filename in glob.glob(folder+"/*.csv"): df = pd.read_csv(filename, index_col=None, header=0,encoding='utf-16') Ytest.append(np.array([k])) Xtest.append(np.array(df)) k=k+1 print(len(Xtest)) def eval(net,criterion,batch_size,topk, X, Y): files=np.array(X) langs=np.array(Y) correct = 0 total_loss=0 for file,lang in zip(files,langs): hidden = net.init_hidden() file=torch.from_numpy(file).float() file=file.view(file.size()[0],1,80) lang=torch.from_numpy(lang).long() output, hidden = net(file, hidden) loss = criterion(output, lang) total_loss+=loss val, indices = output.topk(topk) if lang in indices: correct += 1 accuracy = correct/batch_size return accuracy,total_loss/batch_size def batched_dataloader(batch_size, X, Y): files = [] langs = [] for i in range(batch_size): index = np.random.randint(len(X)) file, lang = X[index], Y[index] files.append(file) langs.append(lang) files=np.array(files) langs=np.array(langs) return files, langs def train(net, opt, criterion, batch_size): opt.zero_grad() total_loss = 0 files,langs = batched_dataloader(batch_size, Xtrain, Ytrain) total_loss = 0 for file,lang in zip(files,langs): hidden = net.init_hidden() file=torch.from_numpy(file).float() file=file.view(file.size()[0],1,80) lang=torch.from_numpy(lang).long() output, hidden = net(file, hidden) loss = criterion(output, lang) loss.backward(retain_graph=True) total_loss += loss print("loss :",total_loss/batch_size) print(" ") opt.step() return total_loss/batch_size def train_setup(net, lr = 0.01, n_batches = 100, batch_size = 10, momentum = 0.9): criterion = nn.NLLLoss() opt = optim.SGD(net.parameters(), lr=lr, momentum=momentum) loss_arr = np.zeros(n_batches + 1) for i in range(n_batches): print("batch:",i+1) loss_arr[i+1] = (loss_arr[i]*i + train(net, opt, criterion, batch_size))/(i + 1) print("avg_loss_arr:",loss_arr) print(" ") print('Top-3:', eval(net,criterion ,len(Xtest), 3, Xtest, Ytest), 'Top-2:', eval(net,criterion, len(Xtest), 2, Xtest, Ytest)) class LSTM_net(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(LSTM_net, self).__init__() self.hidden_size = hidden_size self.lstm_cell = nn.LSTM(input_size, hidden_size) self.h2o = nn.Linear(hidden_size, output_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, input, hidden): out, hidden = self.lstm_cell(input, hidden) output = self.h2o(hidden[0].view(-1, self.hidden_size)) output = self.softmax(output) return output, hidden def init_hidden(self, batch_size = 1): return (torch.zeros(1, batch_size, self.hidden_size), torch.zeros(1, batch_size, self.hidden_size)) n_hidden = 128 tic = time.time() net = LSTM_net(80, n_hidden, 9) train_setup(net, lr=1, n_batches=20, batch_size = 128) toc = time.time() print(" ") print('Time taken', toc - tic)<file_sep>/method3.py import warnings import pandas as pd warnings.filterwarnings('ignore') import torch import torch.nn.functional as F from sklearn.model_selection import train_test_split import torch.nn as nn from torch import optim import numpy as np data1=pd.read_csv("/content/hin13.csv",encoding="utf-16") data2=pd.read_csv("/content/kan12.csv",encoding="utf-16") data1["class"]=[1 for i in range(len(data1))] data2["class"]=[2 for i in range(len(data2))] data=data1.append(data2) Y=np.asarray(data["class"]) X=np.asarray(data.drop("class",axis=1)) X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.3,random_state=0) X_train, Y_train, X_test, Y_test = map(torch.tensor, (X_train, Y_train, X_test, Y_test)) X_train=X_train.float() def fit_v2(x, y, model, opt, loss_fn, epochs = 1000): for epoch in range(epochs): loss = loss_fn(model(x), y) loss.backward() opt.step() opt.zero_grad() return loss.item() class FirstNetwork_v2(nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.net = nn.Sequential( nn.Linear(80, 700).float(), nn.Sigmoid(), nn.Linear(700, 500).float(), nn.Sigmoid(), nn.Linear(500,5).float(), nn.Softmax() ) def forward(self, X): return self.net((X)) fn = FirstNetwork_v2() loss_fn = F.cross_entropy opt = optim.SGD(fn.parameters(), lr=1) print(fit_v2(X_train, Y_train, fn, opt, loss_fn)) fn = FirstNetwork_v2() fit_v1() <file_sep>/SRP1.PY import pandas as pd import numpy as np import glob import torch import torch.nn as nn import torch.optim as optim folders = glob.glob("/home/system/Desktop/SRP/test/*") X=[] Y=[] k=0 for folder in folders: for filename in glob.glob(folder+"/*.csv"): df = pd.read_csv(filename, index_col=None, header=0,encoding='utf-16') Y.append(np.array(k)) X.append(np.array(df)) k=k+1 def batched_dataloader(batch_size, X, Y): files = [] langs = [] file_len=[] for i in range(batch_size): index = np.random.randint(len(X)) file, lang = X[index], Y[index] file_len.append(len(file)) files.append(torch.tensor(file)) langs.append(lang) langs=np.array(langs) files=nn.utils.rnn.pad_sequence(files, batch_first=True) files=np.array(files) files=torch.from_numpy(files).float() langs=torch.from_numpy(langs).long() return files, langs def train(net, opt, criterion, batch_size): opt.zero_grad() files, langs = batched_dataloader(batch_size, X, Y) hidden = net.init_hidden(batch_size) output, hidden = net(files,hidden) loss = criterion(output, langs) loss.backward() opt.step() print("loss:",loss) return loss def train_setup(net, lr = 0.01, n_batches = 100, batch_size = 10, momentum = 0.9): criterion = nn.NLLLoss() opt = optim.SGD(net.parameters(), lr=lr, momentum=momentum) loss_arr = np.zeros(n_batches + 1) for i in range(n_batches): print(i) loss_arr[i+1] = (loss_arr[i]*i + train(net, opt, criterion, batch_size))/(i + 1) print(loss_arr) #print('Top-1:', eval(net, len(X), 1, X, Y), 'Top-2:', eval(net, len(X), 2, X, Y)) class LSTM_net(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(LSTM_net, self).__init__() self.hidden_size = hidden_size self.lstm_cell = nn.LSTM(input_size, hidden_size) self.h2o = nn.Linear(hidden_size, output_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, input, hidden): out, hidden = self.lstm_cell(input.view(input.size()[1],64,80), hidden) output = self.h2o(hidden[0].view(-1, self.hidden_size)) output = self.softmax(output) return output.view(64,9), hidden def init_hidden(self, batch_size = 1): return (torch.zeros(1, batch_size, self.hidden_size), torch.zeros(1, batch_size, self.hidden_size)) n_hidden = 128 net = LSTM_net(80, n_hidden, 9) train_setup(net, lr=0.15, n_batches=50, batch_size = 64) <file_sep>/Method2.py #method 2 import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') import torch import torch.nn.functional as F import torch.nn as nn from torch import optim import pandas as pd import numpy as np from sklearn.model_selection import train_test_split def accuracy(y_hat, y): pred = torch.argmax(y_hat, dim=1) return (pred == y).float().mean() data1=pd.read_csv("/hin13.csv",encoding="utf-16") data2=pd.read_csv("/kan12.csv",encoding="utf-16") data1["class"]=[1 for i in range(len(data1))] data2["class"]=[2 for i in range(len(data2))] data=data1.append(data2) Y=np.asarray(data["class"]) X=np.asarray(data.drop("class",axis=1)) X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.3,random_state=0) X_train, Y_train, X_test, Y_test = map(torch.tensor, (X_train, Y_train, X_test, Y_test)) X_train=X_train.float() def fit_v1(epochs = 1000, learning_rate = 1): loss_arr = [] acc_arr = [] opt = optim.SGD(fn.parameters(), lr=learning_rate) for epoch in range(epochs): y_hat = fn(X_train) loss = F.cross_entropy(y_hat, Y_train) loss_arr.append(loss.item()) acc_arr.append(accuracy(y_hat, Y_train)) loss.backward() opt.step() opt.zero_grad() plt.plot(loss_arr, 'r-') plt.plot(acc_arr, 'b-') plt.show() print('Loss before training', loss_arr[0]) print('Loss after training', loss_arr[-1]) class FirstNetwork_v1(nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.lin1 = nn.Linear(80, 700) self.lin2 = nn.Linear(700, 500) self.lin3 = nn.Linear(500,5) def forward(self, X): a1 = self.lin1(X) h1 = a1.sigmoid() a2 = self.lin2(h1) h2= a2.sigmoid() a3 = self.lin3(h2) h3 = a3.exp()/a3.exp().sum(-1).unsqueeze(-1) return h3 fn = FirstNetwork_v1() fit_v1() fn = FirstNetwork_v1() fit()
89ddc6baf4edde8485c4566a506a134b2dc94df6
[ "Markdown", "Python" ]
7
Python
MedhaChirumarri/Deep-learning_pattern-recognition
e0a189cf013c11ea3b54e0bada29abcc68db8637
108b9902007eacff900f8e6632e02941713e50d5
refs/heads/master
<repo_name>rahul28malviya/TutorWebApp<file_sep>/README.md # TutorWebApp I have created a sample web application named as TutorWebApp in C# along with AngularJS, using .NET framework 4.7.2 and Angular1.7. This application has the following features. Bind the data and showing in table list (UI). Create, Edit and Update tutors. In Memory Data storage. <file_sep>/TutorWebApp/Controllers/HomeController.cs using System.Collections.Generic; using System.Web.Mvc; using TutorWebApp.InMemoryData; using TutorWebApp.Models; namespace TutorWebApp.Controllers { public class HomeController : Controller { private static int Id; static HomeController() { Id = 1; //Adding Intial Record CacheStore.Add(Id.ToString(), new Tutor { Id = 1, Name = "<NAME>", Email = "<EMAIL>", Topics = "AngularJS Assignment", Price = 1000 }); } public ActionResult Index() { return View(); } //public ActionResult About() //{ // ViewBag.Message = "Your application description page."; // return View(); //} //public ActionResult Contact() //{ // ViewBag.Message = "Your contact page."; // return View(); //} [HttpPost] public JsonResult AddEditDetails(Tutor model) { string status = string.Empty; if (ModelState.IsValid) { if (model.Id > 0) { CacheStore.Remove<Tutor>(model.Id.ToString()); CacheStore.Add<Tutor>(model.Id.ToString(), model); status = "updated"; } else { model.Id = ++Id; CacheStore.Add(Id.ToString(), model); status = "saved"; } } string message = $"Tutor has been { status } successfully!"; return Json(message, JsonRequestBehavior.AllowGet); } [HttpGet] public JsonResult Delete(int id) { CacheStore.Remove<Tutor>(id.ToString()); string message = $"User has been removed successfully!"; return Json(message, JsonRequestBehavior.AllowGet); } [HttpGet] public JsonResult GetAll() { List<Tutor> tutors = CacheStore.GetAll<Tutor>(); return Json(tutors, JsonRequestBehavior.AllowGet); } [HttpGet] public JsonResult Get(int id) { Tutor result = CacheStore.Get<Tutor>(id.ToString()); return Json(result, JsonRequestBehavior.AllowGet); } } }<file_sep>/TutorWebApp/DataContext/InMemoryData.cs namespace TutorWebApp.InMemoryData { using System; using System.Collections.Generic; public static class CacheStore { private static Dictionary<string, object> _cache; private static object _sync; static CacheStore() { _cache = new Dictionary<string, object>(); _sync = new object(); } public static bool Exists<T>(string key) where T : class { Type type = typeof(T); lock (_sync) { return _cache.ContainsKey(key); } } public static T Get<T>(string key) where T : class { Type type = typeof(T); lock (_sync) { if (_cache.ContainsKey(key) == false) throw new ApplicationException(String.Format("An object with key '{0}' does not exists", key)); lock (_sync) { return (T)_cache[key]; } } } public static List<T> GetAll<T>() where T : class { Type type = typeof(T); List<T> list = new List<T>(); lock (_sync) { lock (_sync) { foreach (KeyValuePair<string, object> temp in _cache) { list.Add((T)temp.Value); } } } return list; } public static void Add<T>(string key, T value) { Type type = typeof(T); if (value.GetType() != type) throw new ApplicationException(String.Format("The type of value passed to cache {0} does not match the cache type {1} for key {2}", value.GetType().FullName, type.FullName, key)); lock (_sync) { if (_cache.ContainsKey(key)) throw new ApplicationException(String.Format("An object with key '{0}' already exists", key)); lock (_sync) { _cache.Add(key, value); }; } } public static void Remove<T>(string key) { Type type = typeof(T); lock (_sync) { if (_cache.ContainsKey(key) == false) throw new ApplicationException(String.Format("An object with key '{0}' does not exists in cache", key)); lock (_sync) { _cache.Remove(key); } } } } }
757bb721976b4ee87adb7129fa98a5b4f7770e8b
[ "Markdown", "C#" ]
3
Markdown
rahul28malviya/TutorWebApp
5cd886a37dd821f5432c5fe1a8c72fc61ec2aac8
d8c9c0e6364e613134f665c38929bd040bc14baf
refs/heads/master
<repo_name>Kostyk163/Home-Project<file_sep>/token.php <?php $access = ['friends', 'messages', 'ads' , 'groups']; $request_params = [ 'client_id' => '6833752', 'display' => 'page', 'redirect_url' => 'https://oauth.vk.com/blank.html', 'scope' => implode( ',' , $access), 'response_type' => 'token', 'v' => '5.92' ]; $url = "https://oath.vk.com/authorize?" . http_build_query($request_params); echo $url; <file_sep>/messages_send.php <?php $message = $_POST['message']; $token = $_POST['token']; //121090975 $request_params = [ 'user_id' => '121090975', 'random_id' => mt_rand(20, 99999999), 'peer_id' => '88422285', 'domains' => 'kostyk163rus', 'message' => implode( "", $message), 'access_token' => implode( "", $token), 'v' => '5.92', ]; $url = "https://api.vk.com/method/messages.send?" . http_build_query($request_params); print_r(file_get_contents($url)); //'chat_id' => '121090975', //100000000 //121090975<file_sep>/test.php <?php include 'menu.php'; ?> <ul> <li><a href='<?php include 'menu.php'; echo $menu[0]['href']?>'><?php include 'menu.php'; echo $menu[0]['link']?></a></li> <li><a href='<?php include 'menu.php'; echo $menu[1]['href']?>'><?php include 'menu.php'; echo $menu[1]['link']?></a></li> <li><a href='<?php include 'menu.php'; echo $menu[2]['href']?>'><?php include 'menu.php'; echo $menu[2]['link']?></a></li> <li><a href='<?php include 'menu.php'; echo $menu[3]['href']?>'><?php include 'menu.php'; echo $menu[3]['link']?></a></li> </ul>
1347fad84d7ea4798bc62b2b6cb795142b569499
[ "PHP" ]
3
PHP
Kostyk163/Home-Project
2142391f03c8820cfde67804292ec8ebbd7e7360
2b22154562e098448d63ae1f6638147364bb3aae
refs/heads/main
<file_sep>import Vue from 'vue' import VueRouter from 'vue-router' import postiApp from '../views/posti-app.vue' import userProfile from '../views/user-profile.vue' // import postiNew from '../views/posti-new.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'postiApp', component: postiApp }, { path: '/user/:userId', name: 'userProfile', component: userProfile }, // { // path: '/posti/new', // component: postiNew // }, ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router <file_sep>import { storageService } from './async-storage.service' const USER_DB = 'user'; const loggedinUser = { _id: "EEE22", fullname: "<NAME>", imgUrl: "https://res.cloudinary.com/carmitvk/image/upload/v1615984358/instagram/users-pic/user1_yqme7r.jpg", }; _saveLocalUser(loggedinUser) _createUsers() export const userService = { getUsers, getById, getLoggedinUser, } function getUsers() { return storageService.query(USER_DB) } function getById(userId) { return storageService.get(USER_DB, userId) } function _saveLocalUser(user) { sessionStorage.setItem('loggedinUser', JSON.stringify(user)) return user } function getLoggedinUser() { return JSON.parse(sessionStorage.getItem('loggedinUser')) } function _createUsers() { var users = JSON.parse(localStorage.getItem(USER_DB)) if (!users || !users.length) { users = [ { "_id": "eeAA22", "username": "yossi.tik", "password": "123", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984344/instagram/users-pic/user3.jpg_clzrsm.jpg", "createdAt": 12122134434, "following": [ { "_id": "aar4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984349/instagram/users-pic/user2.jpg_muesqu.jpg" }, { "_id": "ccr4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615985058/instagram/users-pic/user5_vtz4w4.jpg" } ], "followers": [ { "_id": "EEE22", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984358/instagram/users-pic/user1_yqme7r.jpg" }, { "_id": "aar4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984349/instagram/users-pic/user2.jpg_muesqu.jpg" } ], "savedPosts": ["FFF234", "ad24si9eu", "ewwoei2e29e"] }, { "_id": "OOO987", "username": "Yoni.Doy", "password": "123", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615984338/instagram/users-pic/user4_p6n68b.jpg", "createdAt": 12122134434, "following": [ { "_id": "eeAA22", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984344/instagram/users-pic/user3.jpg_clzrsm.jpg" }, { "_id": "ccr4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615985058/instagram/users-pic/user5_vtz4w4.jpg" } ], "followers": [ { "_id": "EEE22", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984358/instagram/users-pic/user1_yqme7r.jpg" }, { "_id": "aar4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984349/instagram/users-pic/user2.jpg_muesqu.jpg" } ], "savedPosts": ["FFF234", "ad24si9eu", "ewwoei2e29e"] }, { "_id": "ccr4577", "username": "Roni.Mizrahi", "password": "123", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615985058/instagram/users-pic/user5_vtz4w4.jpg", "createdAt": 12122134434, "following": [ { "_id": "EEE22", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615984358/instagram/users-pic/user1_yqme7r.jpg" } ], "followers": [ { "_id": "EEE22", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984358/instagram/users-pic/user1_yqme7r.jpg" }, { "_id": "aar4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984349/instagram/users-pic/user2.jpg_muesqu.jpg" } ], "savedPosts": ["FFF234", "ad24si9eu", "ewwoei2e29e"] }, { "_id": "EEE22", "username": "Benny.Orenshtein", "password": "123", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984358/instagram/users-pic/user1_yqme7r.jpg", "createdAt": 12122134434, "following": [ { "_id": "ccr4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615985058/instagram/users-pic/user5_vtz4w4.jpg" } ], "followers": [ { "_id": "ccr4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615985058/instagram/users-pic/user5_vtz4w4.jpg" }, { "_id": "aar4577", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1615984349/instagram/users-pic/user2.jpg_muesqu.jpg" } ], "savedPosts": ["FFF234", "ad24si9eu", "ewwoei2e29e"] }, { "_id": "aar4577", "username": "Gal.Dvori", "password": "123", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984349/instagram/users-pic/user2.jpg_muesqu.jpg", "createdAt": 12122134434, "following": [ { "_id": "EEE22", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984358/instagram/users-pic/user1_yqme7r.jpg" }, { "_id": "eeAA22", "fullname": "yossi tik", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984344/instagram/users-pic/user3.jpg_clzrsm.jpg" } ], "followers": [ { "_id": "EEE22", "fullname": "<NAME>", "imgUrl": "https://res.cloudinary.com/carmitvk/image/upload/v1615984358/instagram/users-pic/user1_yqme7r.jpg" } ], "savedPosts": ["FFF234", "ad24si9eu", "ewwoei2e29e"] } ] localStorage.setItem(USER_DB, JSON.stringify(users)) } return users; }
9b411f420b06e853394bf38879cdb8cde153b6d0
[ "JavaScript" ]
2
JavaScript
carmitvk/instush
6ef949efa294c393440f3d80b810faf788c5e035
2052a732872c461bcc74c1fb9f32db611d37bd33
refs/heads/main
<repo_name>johny1122/Java-OOP<file_sep>/Ex6/src/CheckScope.java import java.util.HashMap; import java.util.InvalidPropertiesFormatException; import java.util.Stack; /** * Checking the global scope and the methods scopes thoroughly */ public class CheckScope { private static final String ERROR_MESSAGE_GLOBAL = "ERROR: Global scope must contain methods and variable " + "declarations\\assignments only"; private static final String ERROR_MESSAGE_NESTED_METHOD = "ERROR: Methods may only be declared at the global scope"; private static final String OPEN_CURLY_BRACKET = "{"; private static final String CLOSE_CURLY_BRACKET = "}"; private static final String NEW_LINE = "\n"; private static final String REGEX_EMPTY_LINE = "^\\s*$"; private static final String REGEX_BRACKETS_DELIMITER = "(?<=[{}])|(?=[{}])"; private static String[] methodParameterLines = null; private static HashMap<String, Method> methods; /** * Checking the scopes starting with the global scope and than the methods * @param code * @throws InvalidPropertiesFormatException */ public static void checkScopes(String code) throws InvalidPropertiesFormatException { methods = CheckMethod.findMethods(code); String globalScopeCode = getGlobalScopeCode(code); Scope globalScope = checkGlobalScopeLines(globalScopeCode); checkMethods(globalScope); } /** * Getting the global scope code by deleting the methods from it * @param code * @return */ private static String getGlobalScopeCode(String code){ for(Method method: methods.values()){ code = code.replace(method.getCode(), ""); } return code; } /** * Checking the methods scope (and any scope beneath them) * @param globalScope * @throws InvalidPropertiesFormatException */ private static void checkMethods(Scope globalScope) throws InvalidPropertiesFormatException { methodParameterLines = null; for(Method method: methods.values()){ String[] splitCode = method.getCode().split(REGEX_BRACKETS_DELIMITER); scopify(splitCode, globalScope); setUninitializedGlobal(globalScope); } } /** * After checking each method we need to set the globally uninitialized global variables for the next method * @param globalScope */ private static void setUninitializedGlobal(Scope globalScope){ for(Variable variable: globalScope.getScopeVariables().values()){ if(!variable.isGlobalInitialized()){ variable.setUnInitialized(); } } } /** * Going over the scopes inside the method and checking all lines validity and updating variables * @param splitCode * @param globalScope * @throws InvalidPropertiesFormatException */ private static void scopify(String[] splitCode, Scope globalScope) throws InvalidPropertiesFormatException { Stack<Scope> scopeStack = new Stack<>(); scopeStack.push(globalScope); String prevBracket = OPEN_CURLY_BRACKET; int currIndex = 0; Scope newScope; while(currIndex < splitCode.length){ String currCode = splitCode[currIndex]; if(isBracket(currCode)){ prevBracket = currCode; } else{ if(prevBracket.equals(OPEN_CURLY_BRACKET)){ newScope = new Scope(scopeStack.peek()); checkMethodLines(currCode + splitCode[currIndex + 1], newScope, globalScope); scopeStack.push(newScope); } else{ scopeStack.pop(); Scope currScope = scopeStack.peek(); if(currScope != globalScope && currIndex + 1 < splitCode.length) { checkMethodLines(currCode + splitCode[currIndex + 1], currScope, globalScope); } } } currIndex++; } } /** * Is bracket "}" or "{" * @param str * @return */ private static boolean isBracket(String str){ return str.equals(OPEN_CURLY_BRACKET) || str.equals(CLOSE_CURLY_BRACKET); } /** * Checking the global scope - must have variable related code only (after removing the methods code) * and updating the global variables * @param code * @return * @throws InvalidPropertiesFormatException */ private static Scope checkGlobalScopeLines(String code) throws InvalidPropertiesFormatException { String[] lines = code.split("\n"); Scope globalScope = new Scope(null); for(String line: lines) { if(line.matches(REGEX_EMPTY_LINE)){ continue; } else if(CheckVariable.checkJustFormat(line)){ CheckVariable.checkVariableLine(line, globalScope, true); } else{ throw new InvalidPropertiesFormatException(ERROR_MESSAGE_GLOBAL); } } return globalScope; } /** * Given a scope's portion of a code, we check each line for more advanced errors (not syntax) * @param code * @param scope * @param globalScope * @throws InvalidPropertiesFormatException */ private static void checkMethodLines(String code, Scope scope, Scope globalScope) throws InvalidPropertiesFormatException { String[] lines = code.split(NEW_LINE); if(methodParameterLines != null){ for(String line: methodParameterLines) { CheckVariable.checkVariableLine(line, scope, true); } for(Variable variable: scope.getScopeVariables().values()){ variable.setInitialized(); } methodParameterLines = null; } for(String line: lines) { if(line.matches(CheckMethod.REGEX_RETURN) || line.matches(CheckMethod.REGEX_CLOSE_CURLY_BRACKET) || line.matches(REGEX_EMPTY_LINE)){ continue; } else if(CheckIfWhile.checkJustFormat(line)){ CheckIfWhile.checkIfWhileLine(line, scope); } else if(CheckMethod.isMethodSignatureLayout(line)){ if(scope.getParentScope() == globalScope) // Methods only on global scope { methodParameterLines = CheckMethod.getParameterVariablesLines(line); } else{ throw new InvalidPropertiesFormatException(ERROR_MESSAGE_NESTED_METHOD); } } else if(CheckMethodCall.isValidMethodCallLayout(line)){ CheckMethodCall.checkMethodCall(CheckMethodCall.getMethodCall(line), methods, scope); } else { CheckVariable.checkVariableLine(line, scope, true); } } } } <file_sep>/Ex3/src/BoopingSite.java import oop.ex3.searchengine.Hotel; import oop.ex3.searchengine.HotelDataset; import java.util.*; public class BoopingSite { /** representing double max latitude valid value of 90 */ private static final double MAX_LATITUDE_VALID = 90.0; /** representing double max longitude valid value of 180 */ private static final double MAX_LONGITUDE_VALID = 180.0; private final ArrayList<Hotel> hotels = new ArrayList<Hotel>(); /** * constructor of BoopingSite * @param name: string of the name of the dataset */ public BoopingSite(String name) { Hotel[] array_hotels = HotelDataset.getHotels(name); hotels.addAll(Arrays.asList(array_hotels)); } /** * return an ArrayList of all the hotels in the database which located in the given valid city * @param city: String of valid city name in the database * @return ArrayList of all hotels in the given city */ private ArrayList<Hotel> allHotelsInCity(String city) { ArrayList<Hotel> hotelsInCity = new ArrayList<Hotel>(); // filter for all the hotels in the given city for (Hotel hotel : hotels) { if (hotel.getCity().equals(city)) { hotelsInCity.add(hotel); } } return hotelsInCity; } /** * returns an Hotel array located in the given city sorted from the highest star rating to the lowest. if * two hotels have the same rating it will sort the two hotels according to the alphabet order of the * property name. * @param city: String of the city * @return: sorted hotel array by rating in the given city */ public Hotel[] getHotelsInCityByRating(String city) { ArrayList<Hotel> hotelsInCity = new ArrayList<Hotel>(); // city name is null if (city == null) { return hotelsInCity.toArray(new Hotel[0]); } hotelsInCity = allHotelsInCity(city); RatingCompare ratingCompare = new RatingCompare(); Collections.sort(hotelsInCity, ratingCompare); Collections.reverse(hotelsInCity); return hotelsInCity.toArray(new Hotel[0]); } /** * returns an Hotel array sorted by proximity from the given location in ascending order. if two hotels * have the same proximity it will sort the two hotels according to the number of points-of-interest they * are close to. * @param latitude: given latitude * @param longitude: given longitude * @return: sorted hotel array by proximity */ public Hotel[] getHotelsByProximity(double latitude, double longitude) { ArrayList<Hotel> hotelsProximity = new ArrayList<Hotel>(); // latitude or longitude are not valid if ((Math.abs(latitude) > MAX_LATITUDE_VALID) || (Math.abs(longitude) > MAX_LONGITUDE_VALID)) { return hotelsProximity.toArray(new Hotel[0]); } hotelsProximity = hotels; ProximityCompare proximityCompare = new ProximityCompare(latitude, longitude); Collections.sort(hotelsProximity, proximityCompare); return hotelsProximity.toArray(new Hotel[0]); } /** * returns an Hotel array sorted by proximity from the given location in ascending order in the given * city. if two hotels have the same proximity it will sort the two hotels according to the number of * points-of-interest they are close to. * @param city: String of city name * @param latitude: given latitude * @param longitude: given longitude * @return: sorted hotel array by proximity in the given city */ public Hotel[] getHotelsInCityByProximity(String city, double latitude, double longitude) { ArrayList<Hotel> hotelsInCity = new ArrayList<Hotel>(); // city name is null or latitude/longitude are not valid if ((city == null) || (Math.abs(latitude) > MAX_LATITUDE_VALID) || (Math.abs(longitude) > MAX_LONGITUDE_VALID)) { return hotelsInCity.toArray(new Hotel[0]); } hotelsInCity = allHotelsInCity(city); ProximityCompare proximityCompare = new ProximityCompare(latitude, longitude); Collections.sort(hotelsInCity, proximityCompare); return hotelsInCity.toArray(new Hotel[0]); } } <file_sep>/Ex2/src/SpaceShip.java import java.awt.Image; import oop.ex2.*; import javax.swing.*; /** * The API spaceships need to implement for the SpaceWars game. It is your decision whether SpaceShip.java * will be an interface, an abstract class, a base class for the other spaceships or any other option you will * choose. * @author <NAME> */ public abstract class SpaceShip { private SpaceShipPhysics shipPhysics; protected int max_energy; protected int current_energy; protected int health; protected boolean shield_is_on; protected int rounds_left_after_fire; /** The start level of maximal energy */ private static final int START_MAX_ENERGY = 210; /** The start level of current energy */ private static final int START_CURRENT_ENERGY = 190; /** The start level of health */ private static final int START_HEALTH = 22; /** when there is no health */ private static final int NO_HEALTH = 0; /** The reduce from the maximal energy level when shot without shield */ private static final int REDUCE_MAX_ENERGY_WITHOUT_SHIELD = 10; /** Teleport energy cost */ private static final int TELEPORT_ENERGY_COST = 140; /** Shield energy cost */ private static final int SHIELD_ENERGY_COST = 3; /** Fire energy cost */ private static final int FIRE_ENERGY_COST = 19; /** Rounds left after fire at the beginning */ protected static final int NO_ROUNDS_LEFT_AFTER_FIRE = 0; /** Rounds left after fire */ private static final int ROUNDS_LEFT_AFTER_FIRE = 7; /** No energy */ private static final int NO_ENERGY = 0; /** Energy added because of bashing */ private static final int BASH_ENERGY_ADD = 18; /** Symbols the ship turns left */ protected static final int TURN_LEFT = 1; /** Symbols the ship turns right */ protected static final int TURN_RIGHT = (-1); /** Symbols the ship doesnt turn */ protected static final int NO_TURN = 0; /** Zero angle degree */ protected static final double ZERO_ANGLE = 0; /** used to symbol accelerate as argument to the move method */ protected static final boolean ACCELERATE = true; /** * SpaceShip constructor sets all the data members to the default and create a new SpaceShipPhysics */ public SpaceShip() { shipPhysics = new SpaceShipPhysics(); max_energy = START_MAX_ENERGY; current_energy = START_CURRENT_ENERGY; health = START_HEALTH; shield_is_on = false; rounds_left_after_fire = NO_ROUNDS_LEFT_AFTER_FIRE; } /** * Does the actions of this ship for this round. This is called once per round by the SpaceWars game * driver. * @param game the game object to which this ship belongs. */ abstract void doAction(SpaceWars game); /** * This method is called every time a collision with this ship occurs */ public void collidedWithAnotherShip() { if (shield_is_on) { max_energy += BASH_ENERGY_ADD; current_energy += BASH_ENERGY_ADD; } else { health--; max_energy -= REDUCE_MAX_ENERGY_WITHOUT_SHIELD; if (max_energy < NO_ENERGY) { max_energy = NO_ENERGY; } if (current_energy > max_energy) { current_energy = max_energy; } } } /** * This method is called whenever a ship has died. It resets the ship's attributes, and starts it at a * new * random position. */ public void reset() { shipPhysics = new SpaceShipPhysics(); max_energy = START_MAX_ENERGY; current_energy = START_CURRENT_ENERGY; health = START_HEALTH; shield_is_on = false; rounds_left_after_fire = NO_ROUNDS_LEFT_AFTER_FIRE; } /** * Checks if this ship is dead. * @return true if the ship is dead. false otherwise. */ public boolean isDead() { return health <= NO_HEALTH; } /** * Gets the physics object that controls this ship. * @return the physics object that controls the ship. */ public SpaceShipPhysics getPhysics() { return shipPhysics; } /** * This method is called by the SpaceWars game object when ever this ship gets hit by a shot. */ public void gotHit() { if (!shield_is_on) { health--; max_energy -= REDUCE_MAX_ENERGY_WITHOUT_SHIELD; if (max_energy < NO_ENERGY) { max_energy = NO_ENERGY; } if (current_energy > max_energy) { current_energy = max_energy; } } } /** * Gets the image of this ship. This method should return the image of the ship with or without the * shield. This will be displayed on the GUI at the end of the round. * @return the image of this ship. */ abstract Image getImage(); /** * Attempts to fire a shot. * @param game the game object. */ public void fire(SpaceWars game) { if (current_energy < FIRE_ENERGY_COST) { // has enough energy return; } if (rounds_left_after_fire == NO_ROUNDS_LEFT_AFTER_FIRE) { // possible to fire game.addShot(getPhysics()); current_energy -= FIRE_ENERGY_COST; rounds_left_after_fire = ROUNDS_LEFT_AFTER_FIRE; } } /** * Attempts to turn on the shield. */ public void shieldOn() { if (current_energy < SHIELD_ENERGY_COST) { // has enough energy return; } current_energy -= SHIELD_ENERGY_COST; shield_is_on = true; } /** * Attempts to teleport. */ public void teleport() { if (current_energy < TELEPORT_ENERGY_COST) { // has enough energy return; } current_energy -= TELEPORT_ENERGY_COST; shipPhysics = new SpaceShipPhysics(); } } <file_sep>/Ex5/src/filesprocessing/Order.java package filesprocessing; import java.io.File; import java.util.ArrayList; import java.util.Collections; import static filesprocessing.DirectoryProcessor.*; import static filesprocessing.Errors.*; import static filesprocessing.OrderFactory.*; public class Order { /** abs order */ protected static final String ABS = "abs"; /** type order */ protected static final String TYPE = "type"; /** size order */ protected static final String SIZE = "size"; /** REVERSE suffix */ protected static final String REVERSE = "REVERSE"; /** start index of array */ protected static final int START_OF_ARRAY = 0; /** * check if the order line has a REVERSE suffix * @param parsedLine: given parsed order line * @return true if has and false if not */ private static boolean HasReverseSuffix(String[] parsedLine) { return parsedLine[parsedLine.length - 1].equals(REVERSE); } protected static void orderFiles(String orderLine, ArrayList<File> filteredFiles, int line_counter) { String[] parsedLine = orderLine.split(SEPARATOR_IN_LINE); boolean foundError = false; try { switch (parsedLine[0]) { case ABS: hasErrorInAbsOrder(parsedLine); // check for error Sort.sort(filteredFiles, START_OF_ARRAY, filteredFiles.size() - 1, absOrder()); break; case TYPE: hasErrorInTypeOrder(parsedLine); // check for error Sort.sort(filteredFiles, START_OF_ARRAY, filteredFiles.size() - 1, typeOrder()); break; case SIZE: hasErrorInSizeOrder(parsedLine); // check for error Sort.sort(filteredFiles, START_OF_ARRAY, filteredFiles.size() - 1, sizeOrder()); break; default: // name is not valid foundError = true; break; } } catch (IllegalArgumentException exception) { foundError = true; } // found Type-1 error so order by abs if (foundError) { Sort.sort(filteredFiles, START_OF_ARRAY, filteredFiles.size() - 1, absOrder()); System.err.println(WARNING_MESSAGE + line_counter); } if (!foundError && HasReverseSuffix(parsedLine)) { Collections.reverse(filteredFiles); } } } <file_sep>/Ex6/src/CheckIfWhile.java import java.util.InvalidPropertiesFormatException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * class to check a line of if\while */ public class CheckIfWhile { private static final String EMPTY_STRING = ""; private static final String TRUE = "true"; private static final String FALSE = "false"; private static final String BOOLEAN = "boolean"; private static final String INT = "int"; private static final String DOUBLE = "double"; private static final String OPEN_ROUND_BRACKET = "("; private static final String ERROR_MESSAGE_CONDITION_INPUT_INVALID = "ERROR: condition input is invalid"; private static final String ERROR_MESSAGE_INVALID_IF_WHILE_FORMAT = "ERROR: if\\while line format is invalid"; /* regex of whitespace one or more times */ private static final String REGEX_WHITESPACE = "\\s+"; /* regex of || or && */ private static final String REGEX_AND_OR_OR = "\\|\\||&&"; /* regex of if\while format */ private static final String REGEX_IF_WHILE_FORMAT = "\\s*(if|while)\\s*\\(\\s*([\\w.-]+)\\s*(\\s*(\\|\\||&&)" + "\\s*[\\w.-]+\\s*)*\\s*\\)\\s*\\{\\s*"; private static final Pattern patternIfWhile = Pattern.compile(REGEX_IF_WHILE_FORMAT); /** * check a single part of the condition is valid * @param input: a single part of the condition * @param thisScope: the current scope of the if\while * @throws InvalidPropertiesFormatException: throws if the pars is invalid */ private static void checkConditionInput(String input, Scope thisScope) throws InvalidPropertiesFormatException { if ((input.equals(TRUE)) || (input.equals(FALSE))) { return; } try { Double.parseDouble(input); } catch (NumberFormatException e) { // if it isn't a number - maybe it is a variable name Variable variable = thisScope.findVariableInScopes(input); // if variable doesnt exist OR not initialized OR not in the correct Type (boolean\double\int) if ((variable == null) || (!variable.isInitialized()) || ((!variable.getType().equals(BOOLEAN)) && (!variable.getType().equals(INT)) && (!variable.getType().equals(DOUBLE)))) { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_CONDITION_INPUT_INVALID); } } } /** * check just if the format of the line is a match to a valid if\while line * @param line: given string of a line * @return: true if the line match the format and false otherwise */ public static boolean checkJustFormat(String line) { Matcher matcher = patternIfWhile.matcher(line); return matcher.matches(); } /** * check a line of if\while - format and logic * @param line: string of a possible if\while line * @param thisScope: the current scope the if\while is in * @throws InvalidPropertiesFormatException: throws if the logic or the format is wrong */ public static void checkIfWhileLine(String line, Scope thisScope) throws InvalidPropertiesFormatException { Matcher matcher = patternIfWhile.matcher(line); if (matcher.matches()) { int indexOfOpenBracket = line.indexOf(OPEN_ROUND_BRACKET); // take only the part after "(" String subLine = line.substring(indexOfOpenBracket + 1); // remove all whitespaces subLine = subLine.replaceAll(REGEX_WHITESPACE, EMPTY_STRING); // take only the part before ")" subLine = subLine.substring(0, subLine.length() - 2); // split by || or && String[] splitInputs = subLine.split(REGEX_AND_OR_OR); for (String input : splitInputs) { checkConditionInput(input, thisScope); } } else { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_INVALID_IF_WHILE_FORMAT); } } }<file_sep>/Ex1/src/TestOrel.java /** * Created by: Evyatar * version 5.0 * Changes history: * 23:07 ‎08/‎08/‎2020 - Orel - willEnjoyBook can be >= and not >. * Test flow was adjusted accordingly in "test Library methods". * <p> * 01:37 ‎24/‎03/‎2018 - Kali - When adding a patron that was already registered to the library, the * return value should by a !negative number! (as far as I understand the API), * unlike a book that was added twice - in that case should return existing book * id. Changed tests: 8.1, 14, 28. * 01:47 24/‎03/‎2018 - Kali - Reverted changes (8.1, 14) due to forum answer. * <p> * 21:49 25/‎03/‎2018 - Evyatar - Now support any non-negative int's as ID's for books and patrons. Added two * libraries tests. willEnjoyBook has to be > and not >=. */ class TestOrel { TestOrel() { } public static void main(String[] args){ // set up Book book1 = new Book("book1", "author1", 2001, 2, 3, 1); Book book2 = new Book("book2", "author2", 2002, 8, 3, 6); Book book3 = new Book("book2", "author2", 2002, 8, 3, 6); Book book4 = new Book("book4", "author4", 2004, 10, 10, 10); int book1ID, book2ID, book3ID, book4ID; Patron patron1 = new Patron("patron1", "last1", 3, 5, 1, 21); Patron patron2 = new Patron("patron1", "last1", 2, 1, 1, 0); Patron patron3 = new Patron("patron3", "last3", 2, 1, 1, 0); int patron1ID1, patron2ID1, patron1ID2, patron2ID2; Library lib = new Library(3, 2, 2); // test book System.out.println("test Book methods"); System.out.println(); System.out.println(book1.stringRepresentation().equals("[book1,author1,2001,6]")); System.out.println(book1.getLiteraryValue() == 2 + 3 + 1); System.out.println(book1.getCurrentBorrowerId() < 0); book1.setBorrowerId(5); System.out.println(book1.getCurrentBorrowerId() == 5); book1.returnBook(); // test patron System.out.println(); System.out.println("test Patron methods"); System.out.println(); System.out.println("0.1:" + patron1.stringRepresentation().equals("patron1 last1")); System.out.println("0.2:" + (patron1.getBookScore(book1) == 3 * 2 + 5 * 3 + 1 * 1)); System.out.println("0.3:" + patron1.willEnjoyBook(book1)); // 22>=22 [Summer 2020] System.out.println("0.4:" + patron1.willEnjoyBook(book2)); // test library System.out.println(); System.out.println("test Library methods"); System.out.println(); System.out.println("1: " + (!lib.isBookIdValid(1))); System.out.println("1.1: " + (!lib.isBookIdValid(88))); System.out.println("1.2: " + (!lib.isBookAvailable(1))); book1ID = lib.addBookToLibrary(book1); System.out.println("2: " + (book1ID >= 0)); System.out.println("3: " + lib.isBookIdValid(book1ID)); book2ID = lib.addBookToLibrary(book2); System.out.println("4: " + (book2ID >= 0)); System.out.println("4.1: " + (book2ID != book1ID)); System.out.println("4.2: " + (lib.isBookIdValid(book2ID))); System.out.println("4.3: " + (lib.addBookToLibrary(book2) == book2ID)); // add the same book, should // return the index of original and shouldn't save another copy. book3ID = lib.addBookToLibrary(book3); // book with same arguments System.out.println("5: " + (book3ID >= 0 && book3ID != book1ID && book3ID != book2ID)); System.out.println("6: " + (lib.addBookToLibrary(book4) < 0)); // no room System.out.println("6.1: " + (lib.addBookToLibrary(book2) == book2ID)); // add the same book when // there is no room. System.out.println("7: " + (!lib.isPatronIdValid(1))); System.out.println("7.1: " + (!lib.isPatronIdValid(8))); patron1ID1 = lib.registerPatronToLibrary(patron1); System.out.println("8:" + (patron1ID1 >= 0)); System.out.println("9:" + (lib.registerPatronToLibrary(patron1) == patron1ID1)); System.out.println("10: " + (lib.isPatronIdValid(patron1ID1))); patron2ID1 = lib.registerPatronToLibrary(patron2); System.out.println("11: " + (lib.registerPatronToLibrary(patron2) == patron2ID1)); System.out.println("12: " + (lib.isPatronIdValid(patron2ID1))); System.out.println("13: " + (lib.registerPatronToLibrary(patron3) < 0)); System.out.println("14: " + (lib.registerPatronToLibrary(patron1) == patron1ID1)); System.out.println("15: " + (lib.getPatronId(patron2) == patron2ID1)); // tests for 'borrowBook' System.out.println("16: " + (lib.isBookAvailable(book1ID))); // actually will enjoy (22>=22) System.out.println("17: " + (lib.borrowBook(book1ID, patron1ID1))); System.out.println("18: " + (!lib.borrowBook(book1ID, patron2ID1))); // the book is taken System.out.println("19: " + (!lib.isBookAvailable(book1ID))); System.out.println("20: " + (lib.borrowBook(book2ID, patron1ID1))); System.out.println("21: " + (!lib.borrowBook(80, patron2ID1))); // book id is not valid System.out.println("22: " + (!lib.borrowBook(book3ID, 80))); // patron id is not // valid System.out.println("23: " + (!lib.borrowBook(book2ID, patron1ID1))); System.out.println("24: " + (!lib.borrowBook(book3ID, patron1ID1))); // too many books for one patron lib.returnBook(book1ID); System.out.println("25: " + (lib.borrowBook(book3ID, patron2ID1))); System.out.println("26: " + (book1.getCurrentBorrowerId() < 0)); System.out.println("27: " + (lib.getBookId(lib.suggestBookToPatron(patron2ID1)) == book1ID)); System.out.println("28: " + (lib.suggestBookToPatron(patron1ID1) == book1)); book1.comicValue -= 1; // null because book2 and book3 are taken and he will not enjoy book1 System.out.println("29: " + (lib.suggestBookToPatron(patron1ID1) == null)); // two libraries tests Library lib2 = new Library(1, 1, 2); System.out.println(); System.out.println("two libraries tests"); System.out.println(); System.out.println("30: " + (!lib2.isBookIdValid(0))); book4ID = lib2.addBookToLibrary(book4); System.out.println("31: " + (book4ID >= 0)); patron1ID2 = lib2.registerPatronToLibrary(patron1); patron2ID2 = lib2.registerPatronToLibrary(patron2); System.out.println("32: " + (patron1ID2 >= 0)); System.out.println("33: " + (patron2ID2 >= 0)); System.out.println("34: " + (patron1ID2 != patron2ID2)); System.out.println("35: " + (lib2.borrowBook(book4ID, patron1ID2))); // patron1 has the max number // of books in library1, should be able to borrow in another library. } } <file_sep>/Ex6/src/Test.java /** * הוראות שימוש (בעברית, כי נמאס כבר מתיעודים באנגלית) * שימו את הקובץ הנוכחי בתיקיית * src * שלכם בסמוך לחבילה * oop.ex6 * כדי שיהיה אפשר להריץ ושהוא יכיר את התכנית שלכם * * יש שני שדות סטטים, אחד צריך להכיל את הנתיב לתיקייה עם כל הטסטים שהם נתנו (הקבצי * javac) * השדה נקרא * testDirPath * השדה השני צריך להכיל את הנתיב לקובץ סיכום שהם נתנו * sjavac_tests.txt * זהו השדה * exceptedFilePath * * מה שהטסט עושה זה מריץ את התכנית שלכם על כל הקבצים (היא אמורה להדפיס 0 או 1 בכל פעם) * ובסמוך לכל טסט להדפיס את השורה הרלוונטית בקובץ שלהם, כך תוכלו להשוות את הערך שמתקבל * ולבדוק שהתכנית שלכם נופלת באמת בגלל הסיבה הזאת * * שימו לב שיש קבצים שאין להם שורה מתאימה בקובץ ולידם לא יודפס כלום. * * המלצה שלי- בכל פעם שהתכנית מדפיסה 1 תדפיסו את הסיבה לכך אצלכם וכך יהיה נוח להשוות * */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.Objects; public class Test { // enter here the path to tests directory public static final String testDirPath = "G:\\My Drive\\year2-semesterA\\OOP\\Exercises\\Ex6\\tests"; // enter here the path to sjavac_tests.txt public static final String exceptedFilePath = "G:\\My Drive\\year2-semesterA\\OOP\\Exercises\\Ex6\\sjavac_tests.txt"; public static void main(String[] args) { File tesDir = new File(testDirPath); try { FileReader reader = new FileReader(exceptedFilePath); BufferedReader bReader = new BufferedReader(reader); HashMap<String, String> filesLines = new HashMap<>(); String line = ""; while (line != null) { line = bReader.readLine(); while (line.equals("")) { line = bReader.readLine(); if(line == null) { break; } } if(line == null) { break; } String fileName = line.substring(0, 13); filesLines.put(fileName, line); } for (File file : Objects.requireNonNull(tesDir.listFiles())) { String[] arguments = {file.getAbsolutePath()}; System.out.println("_________\n" + file.getName()); Sjavac.main(arguments); if (filesLines.containsKey(file.getName())) { System.out.println(filesLines.get(file.getName())); } System.out.println("_________"); } } catch (Exception ignored) { } } } <file_sep>/Ex2/src/Aggressive.java import oop.ex2.GameGUI; import java.awt.*; /** * A class that represents an Aggressive SpaceShip */ public class Aggressive extends SpaceShip { /** The angle the aggressive need to be from another spaceship to try firing */ private static final double MAX_ANGLE_TO_FIRE = 0.21; /** * Does the actions of this ship for this round. This is called once per round by the SpaceWars game * driver. This ship pursues other ships and tries to fire at them. It will always accelerate, and turn * towards the nearest ship. When its angle to the nearest ship is less than 0.21 radians, it will try to * fire. * @param game the game object to which this ship belongs. */ public void doAction(SpaceWars game) { //------------- Accelerate and Turn ------------- SpaceShip closest = game.getClosestShipTo(this); double angle_to_closest = this.getPhysics().angleTo(closest.getPhysics()); double distance_from_closest = this.getPhysics().distanceFrom(closest.getPhysics()); int turn; if (angle_to_closest < ZERO_ANGLE) { turn = TURN_RIGHT; } else if (angle_to_closest > ZERO_ANGLE) { turn = TURN_LEFT; } else { turn = NO_TURN; } getPhysics().move(ACCELERATE, turn); //------------- Firing a shot ------------- if (rounds_left_after_fire != NO_ROUNDS_LEFT_AFTER_FIRE) { rounds_left_after_fire--; } else if (Math.abs(angle_to_closest) < MAX_ANGLE_TO_FIRE) { fire(game); } //------------- Add 1 Energy unit ------------- if (current_energy < max_energy) { current_energy++; } } /** * Gets the image of this ship. This method should return the image of the ship with or without the * shield. This will be displayed on the GUI at the end of the round. * @return the image of this ship. */ public Image getImage() { if (shield_is_on) { return GameGUI.ENEMY_SPACESHIP_IMAGE_SHIELD; } return GameGUI.ENEMY_SPACESHIP_IMAGE; } } <file_sep>/Ex5/src/filesprocessing/OrderFactory.java package filesprocessing; import java.io.File; import java.util.Comparator; public class OrderFactory { /** equal in comparator */ protected static final int EQUAL = 0; /** period doesnt exist in the file name */ protected static final int PERIOD_DOES_NOT_EXIST = (-1); /** the index at the beginning of a string */ protected static final int FIRST_STRING_INDEX = 0; /** * compare between files name (in lexicographically order) * @return 0 iff their size is equal, number bigger than 0 if file1 > file2 and number smaller than 0 if * file1 < file2 */ protected static Comparator<File> absOrder() { return (file1, file2) -> (file1.getAbsolutePath().compareTo(file2.getAbsolutePath())); } /** * find the file's type * @param file: file to find the type of * @return the extension after the last point in the name string */ private static String findFileType(File file) { String fileName = file.getName(); String fileType; int fileLastPointIndex = fileName.lastIndexOf("."); if (file.isHidden()) { // if hidden if ((fileLastPointIndex == FIRST_STRING_INDEX) || (fileLastPointIndex == fileName.length() - 1)) { fileType = ""; } else { fileType = fileName.substring(fileLastPointIndex + 1); } } else { // not hidden if ((fileLastPointIndex == PERIOD_DOES_NOT_EXIST) || (fileLastPointIndex == fileName.length() - 1)) { fileType = ""; } else { fileType = fileName.substring(fileLastPointIndex + 1); } } return fileType; } /** * compare between files type (in lexicographically order) * @return 0 iff their size is equal, number bigger than 0 if file1 > file2 and number smaller than 0 if * file1 < file2 */ protected static Comparator<File> typeOrder() { return (file1, file2) -> { int compare_value = findFileType(file1).compareTo(findFileType(file2)); return (compare_value == EQUAL) ? file1.getAbsolutePath().compareTo(file2.getAbsolutePath()) : compare_value; }; } /** * compare between files size * @return 0 iff their size is equal, number bigger than 0 if file1 > file2 and number smaller than 0 if * file1 < file2 */ protected static Comparator<File> sizeOrder() { return (file1, file2) -> { int compare_value = Long.compare(file1.length(), file2.length()); return (compare_value == EQUAL) ? file1.getAbsolutePath().compareTo(file2.getAbsolutePath()) : compare_value; }; } } <file_sep>/Ex1/src/TesterAdir.java //written by Adir import java.lang.reflect.Method; public class TesterAdir { public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_CYAN = "\u001B[36m"; public static final String ANSI_BG = "\u001B[46m"; public static void main(String[] args) { //general API structure check System.out.println("Checking if API methods exists in Book class..."); checkingMethodExistsBook(); System.out.println("Checking if API methods exists in Patron class..."); checkingMethodExistsPatron(); System.out.println("Checking if API methods exists in Library class..."); checkingMethodExistsLibrary(); System.out.println("Running Book basic tests..."); BookSanityTests(); System.out.println("Running Patron basic tests..."); PatronBasicTests(); System.out.println("Running Library basic tests..."); LibraryBasicTests(); LibraryBasicTests2(); semiMsg("ALL TESTS PASSED!"); } public static void LibraryBasicTests2() { int n = 5; Patron[] patrons = new Patron[n]; Book[] books = new Book[n]; int[] patronsID = new int[n]; int[] booksID = new int[n]; Library lib = new Library(n,n,n); for (int i = 0; i < n; i++) { patrons[i] = new Patron("a", "b", 1, 1, 1, 1); books[i] = new Book("a","b",2001,1,1,1); patronsID[i] = lib.registerPatronToLibrary(patrons[i]); booksID[i] = lib.addBookToLibrary(books[i]); } for(int i = 0; i < n; i++){ if(patronsID[i] != lib.getPatronId(patrons[i])){ writeError("ERROR: getPatronID: Incorrect patron's ID."); } if(booksID[i] != lib.getBookId(books[i])){ writeError("ERROR: getPatronID: Incorrect patron's ID."); } if(!lib.isBookIdValid(booksID[i])){ writeError("ERROR: isBookIdValid returned false, but ID is valid."); } if(!lib.isPatronIdValid(patronsID[i])){ writeError("ERROR: isPatronIdValid returned false, but ID is valid."); } } if(lib.isBookIdValid(23123)) { //random id writeError("ERROR: isBookIdValid returned true for random id."); } if(lib.isPatronIdValid(23123)) { //random id writeError("ERROR: isPatronIdValid returned true for random id."); } writeSuccess("getBookId and getPatronId - VALID"); writeSuccess("isBookIdValid and isPatronIdValid - VALID"); for(int i = 0; i < n;i++){ if(!lib.isBookAvailable(booksID[i])){ writeError("ERROR: Available book labeled as borrowed."); } lib.borrowBook(booksID[i],patronsID[i]); if(lib.isBookAvailable(booksID[i])){ writeError("ERROR: Borrowed book labeled as available."); } } boolean c = lib.isBookAvailable(-1); if(c){ writeError("ERROR: isBookAvailable returned True for boolId=-1."); } //c = false c = true; c = lib.isBookAvailable(23123);//random id if(c){ writeError("ERROR: isBookAvailable return True for random id."); } lib.returnBook(booksID[0]); lib.returnBook(booksID[1]); if(!lib.borrowBook(booksID[0],patronsID[1]) || !lib.borrowBook(booksID[1],patronsID[0])) { writeError("ERROR: Trying to borrow returned book failed."); } lib.returnBook(booksID[0]); lib.returnBook(booksID[0]); //double return, check if program collapse. lib.returnBook(-1); //check invalid id lib.returnBook(202020); //check valid id but not in the library. writeSuccess("returnBook - VALID"); Library lib2 = new Library(4,2,2); Patron patron1 = new Patron("a","b",2,2,2,6); Patron patron2 = new Patron("a","b",3,4,3,1); Book b1 = new Book("t","a",2001,1,1,1); Book b2 = new Book("t","a",2003,1,2,1); Book b3 = new Book("t","a",2004,2,2,2); Book b4 = new Book("t","a",2004,2,2,2); lib2.addBookToLibrary(b1); lib2.addBookToLibrary(b2); lib2.addBookToLibrary(b3); lib2.addBookToLibrary(b4); lib2.registerPatronToLibrary(patron1); lib2.registerPatronToLibrary(patron2); lib2.borrowBook(lib2.getBookId(b2),lib2.getPatronId(patron1)); if(lib2.suggestBookToPatron(lib2.getPatronId(patron1)) != b3){ writeError("ERROR: Incorrect book returned from suggestBookToPatron.(1)"); } lib2.borrowBook(lib2.getBookId(b3), lib2.getPatronId(patron2)); if(lib2.suggestBookToPatron(lib2.getPatronId(patron1)) != b4){ writeError("ERROR: Incorrect book returned from suggestBookToPatron.(2)"); } lib2.borrowBook(lib2.getBookId(b4), lib2.getPatronId(patron1)); //patron 1 with 2 books (b2,b4) //patron 2 with 1 book b3 //patron 1 won't enjoy any other book, so should get null if(lib2.suggestBookToPatron(lib2.getPatronId(patron1)) != null){ writeError("ERROR: Incorrect book returned from suggestBookToPatron.(3)"); } //patron 2 will enjoy b1. if(lib2.suggestBookToPatron(lib2.getPatronId(patron2)) != b1){ writeError("ERROR: Incorrect book returned from suggestBookToPatron.(4)"); } writeSuccess("suggestBookToPatron - VALID"); } public static void LibraryBasicTests() { Library lib = new Library(1, 1, 1); Patron p = new Patron("d", "d", 1, 1, 1, 20); Patron p2 = new Patron("dd", "dd", 2, 2, 2, 20); Book b = new Book("A", "A", 2000, 1, 1, 1); Book b2 = new Book("B", "B", 2000, 2, 2, 2); int bookId = lib.addBookToLibrary(b); if (bookId < 0) { writeError("ERROR: Adding a book to the library returned negative id."); } int bookId2 = lib.addBookToLibrary(b); if (bookId != bookId2) { writeError("ERROR: Adding the same book object succeeded."); } int shouldNotBeIn = lib.addBookToLibrary(b2); if (shouldNotBeIn >= 0) { writeError("ERROR: Capacity is full, but adding book succeeded."); } writeSuccess("Book addition, copies handling, capacity - VALID"); int patronId = lib.registerPatronToLibrary(p); if (patronId < 0) { writeError("ERROR: Registering patron to the library returned negative id."); } int patronId2 = lib.registerPatronToLibrary(p); if (patronId != patronId2) { writeError("ERROR: Adding the same patron object succeeded."); } int shouldNotBeIn2 = lib.registerPatronToLibrary(p2); if (shouldNotBeIn2 >= 0) { writeError("ERROR: Capacity is full, but adding patron succeeded."); } writeSuccess("Patron registration, double registration handling, capacity - VALID"); Library lib2 = new Library(3, 1, 1); Patron patron1 = new Patron("patron1", "patron1", 2, 2, 2, 10); Book book11 = new Book("book1", "a1", 2001, 4, 4, 4); Book book12 = new Book("book2", "a1", 2001, 3, 1, 1); Book book13 = new Book("book2", "a1", 2001, 5, 5, 5); int patron1ID = lib2.registerPatronToLibrary(patron1); int book11ID = lib2.addBookToLibrary(book11); int book12ID = lib2.addBookToLibrary(book12); //פטרון משאיל ספר שהוא לא יהנה ממנו boolean x = lib2.borrowBook(book12ID, patron1ID); if (x) { writeError("ERROR: Patron succeeded to borrow he won't enjoy."); } //פטרון מנסה להשאיל ספר שלא קיים boolean xx = lib2.borrowBook(book12ID + 20, patron1ID); //פטרון מנסה להשאיל ספר שכבר מושאל if (xx) { writeError("ERROR: Patron succeeded to borrow that doesn't exist."); } boolean xxx = lib2.borrowBook(book12ID, patron1ID + 20); if (xxx) { writeError("ERROR: Incorrect patron's ID succeeded to borrow."); } boolean xxxx = lib2.borrowBook(book11ID, patron1ID); if (!xxxx) { writeError("ERROR: Patron failed to borrow valid book."); } //פטרון מנסה להשאיל ספר למרות שהוא כבר משאיל הכל boolean y = lib2.borrowBook(book11ID, patron1ID); if (y) { writeError("ERROR: Patron succeeded to borrow unavailable book."); } int book3ID = lib2.addBookToLibrary(book13); boolean z = lib2.borrowBook(book3ID, patron1ID); if (z) { writeError("ERROR: Patron succeeded to borrow 2 books, but max borrow is 1."); } writeSuccess("Borrowing tests - VALID"); } public static void PatronBasicTests() { Patron p = new Patron("Some", "Name", 4, 3, 11, 33); Book b1 = new Book("A", "B", 2001, 1, 1, 1); Book b2 = new Book("A", "B", 2001, 2, 1, 2); Book b3 = new Book("A", "B", 2001, 3, 1, 2); if (p.getBookScore(b1) != (4 + 3 + 11)) { writeError("Patron's getBookScore FAILED, should be " + (4 + 3 + 11) + "."); } if (p.getBookScore(b2) != (4 * 2 + 3 + 11 * 2)) { writeError("Patron's getBookScore FAILED, should be " + (4 * 2 + 3 + 11 * 2) + "."); } writeSuccess("Patron's getBookScore PASSED"); if (!p.stringRepresentation().equals("Some Name")) { writeError("Patron's stringRepresentation FAILED, expected:Some Name got: " + p.stringRepresentation()); } writeSuccess("Patron's stringRepresentation PASSED"); if (p.willEnjoyBook(b1)) { //enjoyment of b1 is 18 < 33 - should be false. writeError("Patron's willEnjoyBook FAILED, should be false."); } if (p.willEnjoyBook(b2)) { //enjoyment of b2 is 33 - should be false. writeError("Patron's willEnjoyBook FAILED, should be false."); } if (!p.willEnjoyBook(b3)) { //enjoyment of b3 is 37 > 33 - should be true. writeError("Patron's willEnjoyBook FAILED, should be true."); } writeSuccess("Patron's willEnjoyBook PASSED"); semiMsg("Basic tests of Patron PASSED"); } public static void BookSanityTests() { Book test = new Book("A", "B", 2009, 4, 12, 5); if (test.getLiteraryValue() != (4 + 12 + 5)) { writeError("Book's getLiteraryValue FAILED"); } writeSuccess("Book's getLiteraryValue PASSED"); if (!test.stringRepresentation().equals("[A,B,2009," + (4 + 12 + 5) + "]")) { writeError("Book's stringRepresentation FAILED"); } writeSuccess("Book's stringRepresentation PASSED"); if (test.getCurrentBorrowerId() != -1) { writeError("Book's getCurrentBorrowerId FAILED, should be -1."); } int borrowerID = 15; test.setBorrowerId(borrowerID); if (test.getCurrentBorrowerId() != borrowerID) { writeError("Book's getCurrentBorrowerId FAILED, should be " + borrowerID + "."); } writeSuccess("Book's getCurrentBorrowerId and setBorrowerId PASSED"); test.returnBook(); test.returnBook(); if (test.getCurrentBorrowerId() != -1) { writeError("Book's returnBook FAILED, getCurrentBorrowerId() should return -1."); } writeSuccess("Book's returnBook PASSED"); semiMsg("Basic tests of Book PASSED"); } public static void checkingMethodExistsBook() { //checking Constructor Book b = new Book("Title", "Author", 2000, 1, 1, 1); writeSuccess("Book Constructor EXISTS"); int checkIntReturn = b.getCurrentBorrowerId(); //won't compile unless getCurrentBorrowerId exists and returns int. writeSuccess("Book getCurrentBorrowerId EXISTS and return type's VALID"); checkIntReturn = b.getLiteraryValue(); //won't compile unless getCurrentBorrowerId exists and returns int. writeSuccess("Book getLiteraryValue EXISTS and return type's VALID"); b.returnBook(); try { Method m = Book.class.getDeclaredMethod("returnBook"); if (m.getReturnType().equals(Void.TYPE)) { writeSuccess("Book returnBook EXISTS and return type's VALID"); } else { writeError("ERROR: Book returnBook's return type is not void."); } } catch (Exception e) { e.printStackTrace(); } b.setBorrowerId(10); try { Method m = Book.class.getDeclaredMethod("setBorrowerId", int.class); if (m.getReturnType().equals(Void.TYPE)) { writeSuccess("Book setBorrowerId EXISTS and return type's VALID"); } else { writeError("ERROR: Book setBorrowerId's return type is not void."); } } catch (Exception e) { e.printStackTrace(); } String t = b.stringRepresentation(); writeSuccess("Book stringRepresentation EXISTS and return type's VALID"); semiMsg("Book class includes all API methods - VALID"); } public static void checkingMethodExistsPatron() { Patron p = new Patron("First", "Name", 1, 1, 1, 10); writeSuccess("Patron Constructor EXISTS"); Book b = new Book("Title", "Author", 2001, 1, 1, 1); int d = p.getBookScore(b); writeSuccess("Patron getBookScore EXISTS and return type's VALID"); boolean s = p.willEnjoyBook(b); writeSuccess("Patron willEnjoyBook EXISTS and return type's VALID"); String s1 = p.stringRepresentation(); writeSuccess("Patron stringRepresentation EXISTS and return type's VALID"); semiMsg("Patron class includes all API methods - VALID"); } public static void checkingMethodExistsLibrary() { Library lib = new Library(1, 1, 1); Patron p = new Patron("A", "B", 1, 1, 1, 1); Book b = new Book("a", "b", 2009, 1, 1, 2); writeSuccess("Library Constructor EXISTS"); int d = lib.addBookToLibrary(b); boolean s = lib.borrowBook(0, 2); //invalid id's!! writeSuccess("Library addBookToLibrary EXISTS and return type's VALID"); d = lib.getBookId(b); writeSuccess("Library getBookId EXISTS and return type's VALID"); d = lib.getPatronId(p); writeSuccess("Library getPatronId EXISTS and return type's VALID"); s = lib.isBookAvailable(0); writeSuccess("Library isBookAvailable EXISTS and return type's VALID"); s = lib.isBookIdValid(0); writeSuccess("Library isBookIdValid EXISTS and return type's VALID"); s = lib.isPatronIdValid(0); writeSuccess("Library isPatronIdValid EXISTS and return type's VALID"); d = lib.registerPatronToLibrary(p); writeSuccess("Library registerPatronToLibrary EXISTS and return type's VALID"); try { Method m = Library.class.getDeclaredMethod("returnBook", int.class); if (m.getReturnType().equals(Void.TYPE)) { writeSuccess("Library returnBook EXISTS and return type's VALID"); } else { writeError("ERROR: Library returnBook's return type is not void."); } } catch (Exception e) { e.printStackTrace(); } Book t = lib.suggestBookToPatron(0); writeSuccess("Library suggestBookToPatron EXISTS and return type's VALID"); semiMsg("Library class includes all API methods - VALID"); } public static void writeError(String msg) { System.out.println(ANSI_RED + msg + ANSI_RESET); System.exit(0); } public static void writeSuccess(String msg) { System.out.println(ANSI_CYAN + msg + ANSI_RESET); } public static void semiMsg(String msg) { System.out.println("========================================="); System.out.println(ANSI_BG + msg + ANSI_RESET); System.out.println("========================================="); } } <file_sep>/Ex6/src/MethodCall.java /** * MethodCall class saving the name and values given as parameters */ public class MethodCall { private String name; private String[] values; /** * Basic constructor * @param name * @param values */ public MethodCall(String name, String[] values){ this.name = name; this.values = values; } /** * Getting the name of the method we are calling to * @return */ public String getName(){ return name; } /** * Getting the values to send as parameters * @return */ public String[] getValues(){ return values; } } <file_sep>/Ex1/src/TestAdi.java import org.junit.Assert; public class TestAdi { TestAdi() { test3(); } public void test3() { // make libraries and patrons: Library library1 = new Library(3, 2, 3); Library library2 = new Library(1, 1, 1); Book book1 = new Book("<NAME> 1", "<NAME>", 1996, 3, 1, 3); Book book2 = new Book("<NAME>", "<NAME>.", 1996, 3, 2, 1); Book book3 = new Book("Hello", "<NAME>", 1996, 2, 3, 1); Book book4 = new Book("Hello 2", "<NAME>", 1996, 1, 1, 1); Patron patron1 = new Patron("Adi", "Shimoni", 3, 1, 1, 7); Patron patron2 = new Patron("Adi2", "Shimoni", 1313, 5, 2, 7); Patron patron3 = new Patron("Adi3", "Shimoni", 2, 100, 1, 2); Patron patron4 = new Patron("Adi4", "Shimoni", 0, 0, 0, 0); // register patrons: int b = library1.registerPatronToLibrary(patron1); boolean s = library1.isPatronIdValid(1); Assert.assertFalse(s); int k = library1.registerPatronToLibrary(patron2); int l = library1.registerPatronToLibrary(patron3); int ll = library1.registerPatronToLibrary(patron3); Assert.assertEquals(2, ll); boolean m = library1.isPatronIdValid(0); Assert.assertTrue(m); library1.getPatronId(patron1); int jjj = library1.registerPatronToLibrary(patron3); int kkk = library1.registerPatronToLibrary(patron2); int mmm = library1.registerPatronToLibrary(patron1); Assert.assertEquals(3, jjj + kkk + mmm); // add books library 1: int a = library1.addBookToLibrary(book1); Assert.assertEquals(0, a); library1.addBookToLibrary(book2); library1.addBookToLibrary(book3); int mm = library1.addBookToLibrary(book3); Assert.assertEquals(2, mm); boolean c = library1.borrowBook(2, 0); Assert.assertTrue(c); library1.returnBook(2); boolean d = library1.borrowBook(2, 0); Assert.assertTrue(d); library1.returnBook(2); boolean r = library1.borrowBook(2, 0); Assert.assertTrue(r); Book whichBook = library1.suggestBookToPatron(0); Book whichBook2 = library1.suggestBookToPatron(1); Book whichBook3 = library1.suggestBookToPatron(2); Assert.assertEquals("[<NAME> 1,<NAME>,1996,7]", whichBook.stringRepresentation()); Assert.assertEquals("[<NAME>,<NAME>.,1996,6]", whichBook2.stringRepresentation()); Assert.assertEquals("[<NAME>,<NAME>.,1996,6]", whichBook3.stringRepresentation()); int aaaa = library2.addBookToLibrary(book1); Assert.assertEquals(0, aaaa); library2.addBookToLibrary(book2); library2.addBookToLibrary(book3); int mmmm = library2.addBookToLibrary(book3); Assert.assertEquals(-1, mmmm); boolean cc = library2.borrowBook(2, 0); Assert.assertFalse(cc); library2.returnBook(2); boolean dd = library2.borrowBook(2, 0); Assert.assertFalse(dd); library2.returnBook(2); boolean rr = library2.borrowBook(2, 0); Assert.assertFalse(rr); Book whichBook111 = library2.suggestBookToPatron(0); Book whichBook222 = library2.suggestBookToPatron(1); Book whichBook333 = library2.suggestBookToPatron(2); Assert.assertNull(whichBook111); Assert.assertNull(whichBook222); Assert.assertNull(whichBook333); } } <file_sep>/Ex5/src/filesprocessing/Filter.java package filesprocessing; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Arrays; import static filesprocessing.DirectoryProcessor.*; import static filesprocessing.Errors.*; import static filesprocessing.FilterFactory.*; public class Filter { /** greater_than filter */ protected static final String GREATER_THAN = "greater_than"; /** between filter */ protected static final String BETWEEN = "between"; /** smaller_than filter */ protected static final String SMALLER_THAN = "smaller_than"; /** file filter */ protected static final String FILE = "file"; /** contains filter */ protected static final String CONTAINS = "contains"; /** prefix filter */ protected static final String PREFIX = "prefix"; /** suffix filter */ protected static final String SUFFIX = "suffix"; /** writable filter */ protected static final String WRITABLE = "writable"; /** executable filter */ protected static final String EXECUTABLE = "executable"; /** hidden filter */ protected static final String HIDDEN = "hidden"; /** all filter */ protected static final String ALL = "all"; /** NOT suffix */ protected static final String NOT = "NOT"; /** empty string */ protected static final String EMPTY_STRING = ""; /** length of array of size 1 */ protected static final int LENGTH_OF_ONE = 1; static boolean foundError = false; /** * check if the filter line has a NOT suffix * @param parsedLine: given parsed filter line * @return true if has and false if not */ private static boolean HasNotSuffix(String[] parsedLine) { return parsedLine[parsedLine.length - 1].equals(NOT); } /** * returns a filter by greater_than * @param parsedLine: given parsed filter line * @return FileFilter filtering files by greater_than */ private static FileFilter filterGreaterThan(String[] parsedLine) { try { hasErrorInGreaterThanFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return greaterThanCheck(Double.parseDouble(parsedLine[1]), true); } return greaterThanCheck(Double.parseDouble(parsedLine[1]), false); } catch (IllegalArgumentException e) { foundError = true; return null; } } /** * returns a filter by between * @param parsedLine: given parsed filter line * @return FileFilter filtering files by between */ private static FileFilter filterBetween(String[] parsedLine) { try { hasErrorInBetweenFilter(parsedLine);// check for errors if (HasNotSuffix(parsedLine)) { return betweenCheck(Double.parseDouble(parsedLine[1]), Double.parseDouble(parsedLine[2]), true); } return betweenCheck(Double.parseDouble(parsedLine[1]), Double.parseDouble(parsedLine[2]), false); } catch (IllegalArgumentException | ArithmeticException exception) { foundError = true; return null; } } /** * returns a filter by smaller_than * @param parsedLine: given parsed filter line * @return FileFilter filtering files by smaller_than */ private static FileFilter filterSmallerThan(String[] parsedLine) { try { hasErrorInSmallerThanFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return smallerThanCheck(Double.parseDouble(parsedLine[1]), true); } return smallerThanCheck(Double.parseDouble(parsedLine[1]), false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by file * @param parsedLine: given parsed filter line * @return FileFilter filtering files by file */ private static FileFilter filterFile(String[] parsedLine) { try { hasErrorInFileFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return fileCheck(parsedLine[1], true); } return fileCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by contains * @param parsedLine: given parsed filter line * @return FileFilter filtering files by contains */ private static FileFilter filterContains(String[] parsedLine) { try { hasErrorInContainsFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return containsCheck(parsedLine[1], true); } if (parsedLine.length == LENGTH_OF_ONE) { // in case for "contains#" (empty string after #) return containsCheck(EMPTY_STRING, false); } return containsCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by prefix * @param parsedLine: given parsed filter line * @return FileFilter filtering files by prefix */ private static FileFilter filterPrefix(String[] parsedLine) { try { hasErrorInPrefixFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return prefixCheck(parsedLine[1], true); } if (parsedLine.length == LENGTH_OF_ONE) { // in case for "prefix#" (empty string after #) return prefixCheck(EMPTY_STRING, false); } return prefixCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by suffix * @param parsedLine: given parsed filter line * @return FileFilter filtering files by suffix */ private static FileFilter filterSuffix(String[] parsedLine) { try { hasErrorInSuffixFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return suffixCheck(parsedLine[1], true); } if (parsedLine.length == LENGTH_OF_ONE) { // in case for "suffix#" (empty string after #) return suffixCheck(EMPTY_STRING, false); } return suffixCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by writable * @param parsedLine: given parsed filter line * @return FileFilter filtering files by writable */ private static FileFilter filterWritable(String[] parsedLine) { try { hasErrorInWritableFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return writableCheck(parsedLine[1], true); } return writableCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by executable * @param parsedLine: given parsed filter line * @return FileFilter filtering files by executable */ private static FileFilter filterExecutable(String[] parsedLine) { try { hasErrorInExecutableFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return executableCheck(parsedLine[1], true); } return executableCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by hidden * @param parsedLine: given parsed filter line * @return FileFilter filtering files by hidden */ private static FileFilter filterHidden(String[] parsedLine) { try { hasErrorInHiddenFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return hiddenCheck(parsedLine[1], true); } return hiddenCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by all * @param parsedLine: given parsed filter line * @return FileFilter filtering files by all */ private static FileFilter filterAll(String[] parsedLine) { try { hasErrorInAllFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return allCheck(true); } return allCheck(false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * filter the files in the sourceDir directory according to the filter in the given filter line * @param filterLine: String of the filter line * @param sourceDir: Directory to filter files from * @param line_counter: counter the current line in the Commands file * @return ArrayList<File> of the filtered files in the sourceDir directory */ protected static ArrayList<File> filterFiles(String filterLine, File sourceDir, int line_counter) { String[] parsedLine = filterLine.split(SEPARATOR_IN_LINE); File[] files; FileFilter filter = null; switch (parsedLine[0]) { case GREATER_THAN: filter = filterGreaterThan(parsedLine); break; case BETWEEN: filter = filterBetween(parsedLine); break; case SMALLER_THAN: filter = filterSmallerThan(parsedLine); break; case FILE: filter = filterFile(parsedLine); break; case CONTAINS: filter = filterContains(parsedLine); break; case PREFIX: filter = filterPrefix(parsedLine); break; case SUFFIX: filter = filterSuffix(parsedLine); break; case WRITABLE: filter = filterWritable(parsedLine); break; case EXECUTABLE: filter = filterExecutable(parsedLine); break; case HIDDEN: filter = filterHidden(parsedLine); break; case ALL: filter = filterAll(parsedLine); break; default: // name is not valid foundError = true; break; } if (foundError) { filter = allCheck(false); System.err.println(WARNING_MESSAGE + line_counter); foundError = false; } // filter the files files = sourceDir.listFiles(filter); // move filtered files to ArrayList (easier to sort with) ArrayList<File> filesArrayList = null; if (files != null) { filesArrayList = new ArrayList<File>(Arrays.asList(files)); } return filesArrayList; } } <file_sep>/Ex3/src/LongTermStorage.java import oop.ex3.spaceship.Item; import java.util.TreeMap; /** * Implementation of a Long-Term storage class */ public class LongTermStorage extends Storage { /** total storage unit capacity of long-term storage */ private static final int TOTAL_LTS_CAPACITY = 1000; /** * constructor of LongTermStorage */ public LongTermStorage() { this.capacity = TOTAL_LTS_CAPACITY; this.available_capacity = TOTAL_LTS_CAPACITY; } /** * try to add n items of the given item to the storage * @param item: type of item to add * @param n: number of items to add * @return: 0 if addition was successful (-1) if there is not enough space in storage */ public int addItem(Item item, int n) { if ((n < 0) || (item == null)) { // invalid input System.out.println(MESSAGE_GENERAL_ERROR); return VALUE_MINUS_ONE; } if (available_capacity < (item.getVolume() * n)) { System.out.println(MESSAGE_NO_ROOM_BEGIN + n + MESSAGE_ITEMS_OF_TYPE + item.getType()); return VALUE_MINUS_ONE; } if (n > 0) { // add just if amount is positive if (itemsCount.containsKey(item.getType())) { // item exist in itemsCount itemsCount.put(item.getType(), itemsCount.get(item.getType()) + n); } else { // item does not exist in itemsCount itemsCount.put(item.getType(), n); } available_capacity -= (n * item.getVolume()); } return VALUE_ZERO; } /** * reset and delete all the items in the LTS */ public void resetInventory() { available_capacity = TOTAL_LTS_CAPACITY; itemsCount = new TreeMap<String, Integer>(); } } <file_sep>/Ex5/src/test/python_tests/tester_python.py """ SecondaryTester for OOP, exercise 5. """ import textwrap from os import listdir # from os import startfile from os.path import isfile, join, isdir, exists from os import path import subprocess tester_ver = 1.3 ASCII_ERROR = """ ______ _______ _______ _______ _______ ( ____ \( ____ )( ____ )( ___ )( ____ ) | ( \/| ( )|| ( )|| ( ) || ( )| | (__ | (____)|| (____)|| | | || (____)| | __) | __)| __)| | | || __) | ( | (\ ( | (\ ( | | | || (\ ( | (____/\| ) \ \__| ) \ \__| (___) || ) \ \__ (_______/|/ \__/|/ \__/(_______)|/ \__/ """ ASCII_PASSES = """ , ; , .-'^^^'-. , ; , \\|/ .' '. \|// \-;-/ () () \-;-/ // ; ; \\ //__; :. .; ;__\\ `-----\'.'-.....-'.'/-----' '.'.-.-,_.'.' '( (..-' '-' """ # paths to files and folder path_to_test_files = path.join("tester_files") path_to_tests = path.join(path_to_test_files, "tests") path_to_type_2_tests = path.join(path_to_test_files, "tests_error_type_2") path_to_files_to_filter = path.join(path_to_test_files, "files_to_filter") folders_of_files_to_filter = ['simple', 'complex'] path_to_java_files = path.join("src") path_to_compiled_files = path.join(path_to_test_files, "compiled_files") path_to_DirectoryProcessor_compiled = path.join("filesprocessing.DirectoryProcessor") path_to_filesprocessing = path.join(path_to_java_files, "filesprocessing") path_to_DirectoryProcessor_not_compiled = path.join(path_to_filesprocessing, "DirectoryProcessor.java") # name of files name_of_user_output_file_no_folder = "_user" + "_output" + ".txt" name_of_user_errors_file_no_folder = "_user" + "_errors" + ".txt" name_of_commands_file = "commands.txt" name_of_school_solution_output_no_folder = "_school_solution" + "_output" + ".txt" name_of_school_solution_errors_no_folder = "_school_solution" + "_errors" + ".txt" name_of_p_file = path.join(path_to_files_to_filter, folders_of_files_to_filter[1], "99..size-8780.NHDR.png") def can_not_test(msg): print("Error:", msg) input("press Enter to exit") exit(1) def run_with_cmd(command_list): """ Execute the given command list with the command line Return a tuple containing the return code, output and errors. """ process = subprocess.Popen(command_list, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) output, errors = process.communicate() return process.returncode, output, errors def print_with_indentation(title, to_print): """print text in a nice way""" prefix = title + ": " wrapper = textwrap.TextWrapper(initial_indent=prefix, break_long_words=False, subsequent_indent=' ' * len(prefix)) print(wrapper.fill(to_print)) def compile_file(): """ compile the java files. the compiled files are located in \test_files\compiled_files. terminate the tester if there was an error. :return: true if was successful. """ if not exists(path_to_java_files) or not isdir(path_to_java_files): can_not_test("You don't have the folder: " + path_to_java_files) if not exists(path_to_DirectoryProcessor_not_compiled): can_not_test("You don't have the file: " + path_to_DirectoryProcessor_not_compiled) if not exists(path_to_filesprocessing) or not isdir(path_to_filesprocessing): can_not_test("You don't have the folder: " + path_to_filesprocessing) if not exists(path_to_DirectoryProcessor_not_compiled): can_not_test("You don't have the file: " + path_to_DirectoryProcessor_not_compiled) command_list = ['javac', '-d', path_to_compiled_files, '-cp', path_to_java_files, path_to_DirectoryProcessor_not_compiled] code, output, errors = run_with_cmd(command_list) if code != 0: can_not_test("problem with compiling\n"+"error message\n"+errors) print("compile OK\n\n") def run_one_test(test_folder_name, files_to_filter_folder): """ run one test. run your code with command file given and with the data given. sva the rusolts in a txt file. then compare it to the school solution txt file. :param test_folder_name: the name of the folder of the test (tests/test#) :param files_to_filter_folder: the data folder (simple of complex) :return: true if was successful. """ path_to_test_folder = path.join(path_to_tests, test_folder_name) path_to_command_file = path.join(path_to_test_folder, name_of_commands_file) name_of_school_solution_output = files_to_filter_folder + name_of_school_solution_output_no_folder name_of_school_solution_errors = files_to_filter_folder + name_of_school_solution_errors_no_folder path_to_school_solution_output = path.join(path_to_test_folder, name_of_school_solution_output) path_to_school_solution_errors = path.join(path_to_test_folder, name_of_school_solution_errors) name_of_user_output = files_to_filter_folder + name_of_user_output_file_no_folder name_of_user_errors = files_to_filter_folder + name_of_user_errors_file_no_folder path_to_user_output = path.join(path_to_test_folder, name_of_user_output) path_to_user_errors = path.join(path_to_test_folder, name_of_user_errors) path_to_files_to_filter_folder = path.join(path_to_files_to_filter, files_to_filter_folder) print("starting", test_folder_name, "with data folder", files_to_filter_folder+"..") command_list = ["java", '-cp', path_to_compiled_files, path_to_DirectoryProcessor_compiled, path_to_files_to_filter_folder, path_to_command_file] code, user_output, user_errors = run_with_cmd(command_list) # run your code # save the files output and errors with open(path_to_user_output, 'w') as output_file: output_file.write(user_output) with open(path_to_user_errors, 'w') as errors_file: errors_file.write(user_errors) # compare to school solution compare_outputs = compare_files(path_to_school_solution_output, path_to_user_output) compare_errors = compare_files(path_to_school_solution_errors, path_to_user_errors) # print helpful information if there was mistakes. if compare_outputs is not None or compare_errors is not None: # compare failed if compare_outputs is not None: print("Output file compare failed: here are the details:") print_with_indentation("output compare", compare_outputs) if compare_errors is not None: print("Errors file compare failed: here are the details:") print_with_indentation("errors compare", compare_errors) return False print("passed :)") return True def compare_files(file1, file2): """ compare to files with FC (windows file comparer) :param file1: :param file2: :return: the compaction text if there was errors """ command_to_compare = ['fc', '/W', '/N', '/A', file1, file2] code, output, errors = run_with_cmd(command_to_compare) if code != 0: # if code != 0 return output return None def run_tests(): """ run all the test in the folder test_files\tests with both data folders (simple, complex) :return: true iff all passed """ all_passed = True tests_names = [t for t in listdir(path_to_tests) if isdir(join(path_to_tests, t))] # list of test names number_of_tests = len(tests_names) * len(folders_of_files_to_filter) passed_tests = 0 for folder_to_filter in folders_of_files_to_filter: # the two data folders print("########## testing with data -", folder_to_filter, " ##########\n") for test_name in tests_names: # each test if run_one_test(test_name, folder_to_filter): passed_tests += 1 else: all_passed = False print() print() if all_passed: print("All tests passed!!") return True else: print("passes", passed_tests, "out of", number_of_tests, "tests") return False def run_type_2_tests(): """ run all type-2 tests :return: true iff all passed """ print("\n########## type-2 error tests: ##########\n") folder_to_filter = path.join(path_to_files_to_filter, folders_of_files_to_filter[0]) path_to_test = path.join(path_to_type_2_tests, "no_file_with_that_name.txt") passed1 = run_one_type_2_test(folder_to_filter, path_to_test, "no_command_file") folder_to_filter = path.join(path_to_files_to_filter, folders_of_files_to_filter[0]) path_to_test = path.join(path_to_type_2_tests, "no_file_with_that _name.txt") passed2 = run_one_type_2_test(folder_to_filter, path_to_test, "too many parameters") folder_to_filter = path.join(path_to_files_to_filter, folders_of_files_to_filter[0]) path_to_test = "" passed3 = run_one_type_2_test(folder_to_filter, path_to_test, "only 1 parameter") return type_2_tests() and passed1 and passed2 and passed3 def type_2_tests(): """ run all the test in the folder test_files\tests_error_type_2 :return: true iff all passed """ all_passed = True tests_names = [f for f in listdir(path_to_type_2_tests) if isfile(join(path_to_type_2_tests, f))] number_of_tests = len(tests_names) passed_tests = 0 for test in tests_names: folder_to_filter = path.join(path_to_files_to_filter, folders_of_files_to_filter[0]) path_to_test = path.join(path_to_type_2_tests, test) passed = run_one_type_2_test(folder_to_filter, path_to_test, test) if passed: passed_tests += 1 else: all_passed = False if all_passed: print("All type-2 error tests passed!!") return True else: print("passes", passed_tests, "out of", number_of_tests, "type-2 error tests") return False def passed_all(): print(ASCII_PASSES) print("you passed everything!!! \ngo get some sleep") # startfile(name_of_p_file) def run_one_type_2_test(folder_to_filter, path_to_test, test): """run one type-2 test""" command = ["java", '-cp', path_to_compiled_files, path_to_DirectoryProcessor_compiled, folder_to_filter, path_to_test] code, output, errors = run_with_cmd(command) if output or not errors: print("test-type-2", test, "failed. nothing should be printed as filtered. and an error should " "be printed. the print was:\n") print_with_indentation("output", output) print_with_indentation("errors", errors) print("\ncontinue...\n") passed = False else: print("test-type-2", test, "passed") passed = True return passed if __name__ == "__main__": while True: print("starting tester for ex5 version", tester_ver, '\n') compile_file() tests_passed = run_tests() type_2_passed = run_type_2_tests() if tests_passed and type_2_passed: passed_all() else: print(ASCII_ERROR) input("press enter to restart the tester") print('\n\n\nRestarting...') <file_sep>/Ex3/src/Locker.java import oop.ex3.spaceship.Item; /** * Locker implementation class */ public class Locker extends Storage { /** items moved to LTS message */ private static final String MESSAGE_ITEMS_MOVED_TO_LTS = "Warning: Action successful, but has caused " + "items to be moved to storage"; /** tried to remove a negative number of items message */ private static final String MESSAGE_REMOVE_NEGATIVE_NUMBER = "Error: Your request cannot be completed " + "at this time. Problem: cannot remove a " + "negative number of items of type "; /** error message of not containing enough items to remove - beginning */ private static final String MESSAGE_REMOVE_LESS_THAN_CONTAIN_BEGIN = "Error: Your request cannot be " + "completed at this time. Problem:" + " the locker does not contain "; /** error message of found constraint - begin */ private static final String MESSAGE_FOUND_CONSTRAINT_BEGIN = "Error: Your request cannot be completed " + "at this time. Problem: the locker cannot" + " contain items of type "; /** error message of found constraint - end */ private static final String MESSAGE_FOUND_CONSTRAINT_END = ", as it contains a contradiction item"; /** symbols a return function value of minus two */ private static final int VALUE_MINUS_TWO = (-2); /** symbols a no amount of item in locker */ private static final int ZERO_AMOUNT = 0; private LongTermStorage lts = null; private Item[][] constraints = null; /** * constructor of Locker * @param lts: LongTermStorage of the spaceship * @param capacity: total capacity of this locker * @param constraints: array of size-2 arrays of all the constraints between the items */ public Locker(LongTermStorage lts, int capacity, Item[][] constraints) { this.lts = lts; this.constraints = constraints; this.capacity = capacity; this.available_capacity = capacity; } /** * trying to remove items from the locker. * @param item: type of item to remove * @param n: number of the given item to remove * @return: (- 1) if n is negative or n is bigger the actual amount 0 if remove succeeded */ public int removeItem(Item item, int n) { if (item == null){ System.out.println(MESSAGE_GENERAL_ERROR); return VALUE_MINUS_ONE; } // n is negative else if (n < 0) { System.out.println(MESSAGE_REMOVE_NEGATIVE_NUMBER + item.getType()); return VALUE_MINUS_ONE; } // n is bigger the amount of item in the locker else if (getItemCount(item.getType()) < n) { System.out.println( MESSAGE_REMOVE_LESS_THAN_CONTAIN_BEGIN + n + MESSAGE_ITEMS_OF_TYPE + item.getType()); return VALUE_MINUS_ONE; } // locker doesnt contain the item if (!itemsCount.containsKey(item.getType())){ return VALUE_ZERO; } // n is equal to amount of item in the locker if (n == itemsCount.get(item.getType())) { itemsCount.remove(item.getType()); } else { // n is less than the amount of item in the locker itemsCount.put(item.getType(), itemsCount.get(item.getType()) - n); } available_capacity += (n * item.getVolume()); return VALUE_ZERO; } /** * check if the given item take more the 50% of locker's space * @param item: given item * @param amountToAdd: number of items trying to add * @return true if more the 50% and false otherwise */ private boolean moreThan50(Item item, int amountToAdd) { int total_volume_of_type; total_volume_of_type = (getItemCount(item.getType()) + amountToAdd) * item.getVolume(); return total_volume_of_type > (FIFTY_PERCENT * capacity); } /** * check if locker can keep all 20% of the item or not. if the locker can the method calls the * addItemsToLockerAndLTS to check if there is enough space in LTS. If the LTS does have, the method * will add the correct amount to the locker and the LTS. * @param item: given item * @param amountToAdd: given amount to move to add to locker * @return true if there is enough space: and do the addition false if there isn't enough space */ private boolean tryToAddToLTS(Item item, int amountToAdd) { // current amount + amount to add int total_item_amount = amountToAdd + getItemCount(item.getType()); // (20% of total locker capacity) / (item's volume) int max_items_number_can_keep_in_locker = (int) (TWENTY_PERCENT * capacity) / item.getVolume(); int min_number_of_items_to_move_to_LTS = total_item_amount - max_items_number_can_keep_in_locker; return addItemsToLockerAndLTS(item, max_items_number_can_keep_in_locker, min_number_of_items_to_move_to_LTS); } /** * check if there is enough space in LTS. If the LTS does have, the method will add the correct amount * to the locker and the LTS. * @param item: item to add * @param number_of_items_can_keep_in_locker: number of items to add to locker * @param number_of_items_must_move_to_LTS: number of items to add to LTS * @return true is enough room in LTS and false otherwise. */ private boolean addItemsToLockerAndLTS(Item item, int number_of_items_can_keep_in_locker, int number_of_items_must_move_to_LTS) { if (lts.addItem(item, number_of_items_must_move_to_LTS) == VALUE_ZERO) { if (itemsCount.containsKey(item.getType())) { // item exist in itemsCount // remove old item amount in locker available_capacity += item.getVolume() * itemsCount.get(item.getType()); } // update to the new amount in locker itemsCount.put(item.getType(), number_of_items_can_keep_in_locker); // update the available capacity available_capacity -= item.getVolume() * number_of_items_can_keep_in_locker; return true; } return false; } /** * trying to add the given amount of the given item to the locker's space * @param item: given item * @param n: amount of items to add * @return -1 if there is not enough room in the locker or LTS, or n is a negative number 1 if some * items have to move to LTS and there is place for them 0 if succeeded to add and no items have * been * moved to LTS */ public int addItem(Item item, int n) { if ((item == null) || (item.getType() == null)) { System.out.println(MESSAGE_GENERAL_ERROR); return VALUE_MINUS_ONE; } boolean foundConstraint = false; for (String storedItem : itemsCount.keySet()) { for (Item[] constraint : constraints) { if ((constraint[0].getType().equals(storedItem) && constraint[1].getType().equals(item.getType())) || (constraint[0].getType().equals(item.getType()) && constraint[1].getType().equals(storedItem))) { foundConstraint = true; } } } if (foundConstraint) { System.out .println(MESSAGE_FOUND_CONSTRAINT_BEGIN + item.getType() + MESSAGE_FOUND_CONSTRAINT_END); return VALUE_MINUS_TWO; } if (n < 0) { // n is negative System.out.println(MESSAGE_GENERAL_ERROR); return VALUE_MINUS_ONE; } //not enough space in locker for all n items else if (available_capacity < (item.getVolume() * n)) { System.out.println(MESSAGE_NO_ROOM_BEGIN + n + MESSAGE_ITEMS_OF_TYPE + item.getType()); return VALUE_MINUS_ONE; } if (moreThan50(item, n)) { // space of item will be more than 50% if (tryToAddToLTS(item, n)) { // there is enough space in LTS System.out.println(MESSAGE_ITEMS_MOVED_TO_LTS); return VALUE_ONE; } // not enough space in LTS // (The printout is already printed in the addItem of LTS) return VALUE_MINUS_ONE; } if (n > 0) { // add items just if n positive if (itemsCount.containsKey(item.getType())) { // item exist in itemsCount itemsCount.put(item.getType(), itemsCount.get(item.getType()) + n); } else { // item does not exist in itemsCount itemsCount.put(item.getType(), n); } available_capacity -= (n * item.getVolume()); } return VALUE_ZERO; } } <file_sep>/Ex3/src/BoopingSiteTest.java import oop.ex3.searchengine.Hotel; import org.junit.*; import static org.junit.Assert.*; public class BoopingSiteTest { /** name file of hotels_tst1 which has only one city */ private static final String DATASET_ONE_CITY = "hotels_tst1.txt"; /** name file of hotels_tst2 which is empty */ private static final String DATASET_EMPTY = "hotels_tst2.txt"; /** name file of hotels_dataset which is the full dataset */ private static final String DATASET_FULL = "hotels_dataset.txt"; /** city name not in database */ private static final String CITY_NOT_IN_DATABASE = "makore"; /** city name in database */ private static final String CITY_IN_DATABASE = "manali"; /** representing the maximum star rating possible */ private static final int MAXIMUM_STAR_RATING = 5; /** representing a valid double latitude degree [-90,90] */ private static final double VALID_LATITUDE = 85.2; /** representing double value over 90 degree */ private static final double OVER_90_LATITUDE = 91.1; /** representing double value below (-90) degree */ private static final double BELOW_MINUS_90_LATITUDE = (-91.3); /** representing a valid double longitude degree [-180,180] */ private static final double VALID_LONGITUDE = 150.4; /** representing double value over 180 degree */ private static final double OVER_180_LONGITUDE = 180.8; /** representing double value below (-180) degree */ private static final double BELOW_MINUS_180_LONGITUDE = (-183.6); /** representing the numbers of hotels in DATASET_ONE_CITY (all of them) */ private static final int NUMBER_OF_HOTELS_IN_DATASET_ONE_CITY = 70; /** representing the numbers of hotels in DATASET_EMPTY (no hotels because it's empty) */ private static final int NUMBER_OF_HOTELS_IN_DATASET_EMPTY = 0; /** representing the smallest string possible according to the alphabet order */ private static final String SMALLEST_STRING_POSSIBLE = "a"; /** representing the equal value is returned from comparator method */ private static final int COMPARE_EQUAL = 0; BoopingSite boopingSite_empty = new BoopingSite(DATASET_EMPTY); BoopingSite boopingSite_one_city = new BoopingSite(DATASET_ONE_CITY); BoopingSite boopingSite_full = new BoopingSite(DATASET_FULL); /** * reset the boopingSite after each test */ @Before public void reset() { boopingSite_empty = new BoopingSite(DATASET_EMPTY); boopingSite_one_city = new BoopingSite(DATASET_ONE_CITY); boopingSite_full = new BoopingSite(DATASET_FULL); } /** * test constructor function */ @Test public void constructorTest() { assertNotNull(boopingSite_empty); assertNotNull(boopingSite_one_city); assertNotNull(boopingSite_full); } /** * test getHotelsInCityByRating function */ @Test public void getHotelsInCityByRatingTest() { hotelsInCityByRatingTest(boopingSite_empty); hotelsInCityByRatingTest(boopingSite_one_city); hotelsInCityByRatingTest(boopingSite_full); } /** * test getHotelsInCityByRating function with given BoopingSite object */ private void hotelsInCityByRatingTest(BoopingSite boopingSite) { // --------------------- invalid inputs --------------------- Hotel[] empty_hotel_array = new Hotel[0]; // no hotels in the given city (==city not in database) assertArrayEquals(empty_hotel_array, boopingSite.getHotelsInCityByRating(CITY_NOT_IN_DATABASE)); // given city name is null assertArrayEquals(empty_hotel_array, boopingSite.getHotelsInCityByRating(null)); // --------------------- valid inputs --------------------- Hotel[] sorted_rating_hotels = boopingSite.getHotelsInCityByRating(CITY_IN_DATABASE); int last_star_rating = MAXIMUM_STAR_RATING; String last_hotel_name = SMALLEST_STRING_POSSIBLE; // moving across all returned hotels and check if their rating and name is in descending order for (Hotel hotel : sorted_rating_hotels) { // current rate is bigger than last assertFalse(hotel.getStarRating() > last_star_rating); // if they have the same rating => check current name is before the last name in alphabet order if (hotel.getStarRating() == last_star_rating) { assertFalse(last_hotel_name.compareTo(hotel.getPropertyName()) < COMPARE_EQUAL); } last_star_rating = hotel.getStarRating(); last_hotel_name = hotel.getPropertyName(); } } /** * calculating the distance from (x1,y1) to (x2,y2) according to the Euclidean distance * @param x1 : double of latitude * @param y1 : double of longitude * @return double of the distance */ private double calculateDistance(double x1, double y1) { return Math.sqrt(((BoopingSiteTest.VALID_LONGITUDE - y1) * (BoopingSiteTest.VALID_LONGITUDE - y1)) + ((BoopingSiteTest.VALID_LATITUDE - x1) * (BoopingSiteTest.VALID_LATITUDE - x1))); } /** * test getHotelsByProximity function */ @Test public void getHotelsByProximityTest() { hotelsByProximityTest(boopingSite_empty); hotelsByProximityTest(boopingSite_one_city); hotelsByProximityTest(boopingSite_full); } /** * test getHotelsByProximity function with given BoopingSite object */ private void hotelsByProximityTest(BoopingSite boopingSite) { // --------------------- invalid inputs --------------------- Hotel[] empty_hotel_array = new Hotel[0]; // invalid: latitude > 90 assertArrayEquals(empty_hotel_array, boopingSite.getHotelsByProximity(OVER_90_LATITUDE, VALID_LONGITUDE)); // invalid: latitude < (-90) assertArrayEquals(empty_hotel_array, boopingSite.getHotelsByProximity(BELOW_MINUS_90_LATITUDE, VALID_LONGITUDE)); // invalid: longitude > 180 assertArrayEquals(empty_hotel_array, boopingSite.getHotelsByProximity(VALID_LATITUDE, OVER_180_LONGITUDE)); // invalid: longitude < (-180) assertArrayEquals(empty_hotel_array, boopingSite.getHotelsByProximity(VALID_LATITUDE, BELOW_MINUS_180_LONGITUDE)); // --------------------- valid inputs --------------------- Hotel[] sorted_proximity_hotels = boopingSite.getHotelsByProximity(VALID_LATITUDE, VALID_LONGITUDE); // checking the number of hotels in sorted_proximity_hotels if (boopingSite == boopingSite_empty) { assertEquals(NUMBER_OF_HOTELS_IN_DATASET_EMPTY, sorted_proximity_hotels.length); } else if (boopingSite == boopingSite_one_city) { assertEquals(NUMBER_OF_HOTELS_IN_DATASET_ONE_CITY, sorted_proximity_hotels.length); } double last_distance = 0.0; // initialize to not important value int last_POIs_number = 0; boolean first_hotel = true; // moving across all hotels and check if their proximity and POIs are in the right order for (Hotel hotel : sorted_proximity_hotels) { if (first_hotel) { last_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude()); last_POIs_number = hotel.getNumPOI(); first_hotel = false; continue; } double curr_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude()); // current distance is smaller than lat distance assertFalse(curr_distance < last_distance); // if they have the same distance => check if curr number of POI is bigger than last POI number if (curr_distance == last_distance) { assertFalse(last_POIs_number < hotel.getNumPOI()); } last_distance = curr_distance; last_POIs_number = hotel.getNumPOI(); } } /** * test getHotelsByProximity function */ @Test public void getHotelsInCityByProximityTest() { hotelsInCityByProximityTest(boopingSite_empty); hotelsInCityByProximityTest(boopingSite_one_city); hotelsInCityByProximityTest(boopingSite_full); } /** * test getHotelsInCityByProximity function with given BoopingSite object */ private void hotelsInCityByProximityTest(BoopingSite boopingSite) { // --------------------- invalid inputs --------------------- Hotel[] empty_hotel_array = new Hotel[0]; // invalid: city not in database assertArrayEquals(empty_hotel_array, boopingSite .getHotelsInCityByProximity(CITY_NOT_IN_DATABASE, VALID_LATITUDE, VALID_LONGITUDE)); // invalid: city's name is null assertArrayEquals(empty_hotel_array, boopingSite .getHotelsInCityByProximity(null, VALID_LATITUDE, VALID_LONGITUDE)); // invalid: latitude > 90 assertArrayEquals(empty_hotel_array, boopingSite .getHotelsInCityByProximity(CITY_IN_DATABASE, OVER_90_LATITUDE, VALID_LONGITUDE)); // invalid: latitude < (-90) assertArrayEquals(empty_hotel_array, boopingSite .getHotelsInCityByProximity(CITY_IN_DATABASE, BELOW_MINUS_90_LATITUDE, VALID_LONGITUDE)); // invalid: longitude > 180 assertArrayEquals(empty_hotel_array, boopingSite .getHotelsInCityByProximity(CITY_IN_DATABASE, VALID_LATITUDE, OVER_180_LONGITUDE)); // invalid: longitude < (-180) assertArrayEquals(empty_hotel_array, boopingSite .getHotelsInCityByProximity(CITY_IN_DATABASE, VALID_LATITUDE, BELOW_MINUS_180_LONGITUDE)); // --------------------- valid inputs --------------------- Hotel[] sorted_proximity_hotels_by_city = boopingSite .getHotelsInCityByProximity(CITY_IN_DATABASE, VALID_LATITUDE, VALID_LONGITUDE); // checking the number of hotels in sorted_proximity_hotels if (boopingSite == boopingSite_empty) { assertEquals(NUMBER_OF_HOTELS_IN_DATASET_EMPTY, sorted_proximity_hotels_by_city.length); } else if (boopingSite == boopingSite_one_city) { assertEquals(NUMBER_OF_HOTELS_IN_DATASET_ONE_CITY, sorted_proximity_hotels_by_city.length); } double last_distance = 0.0; // initialize to not important value int last_POIs_number = 0; boolean first_hotel = true; // moving across all returned hotels and check if their proximity and POIs are in the right order for (Hotel hotel : sorted_proximity_hotels_by_city) { // hotel is not from the given city assertEquals(CITY_IN_DATABASE, hotel.getCity()); if (first_hotel) { last_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude()); last_POIs_number = hotel.getNumPOI(); first_hotel = false; continue; } double curr_distance = calculateDistance(hotel.getLatitude(), hotel.getLongitude()); // current distance is smaller than lat distance assertFalse(curr_distance < last_distance); // if they have the same distance => check if curr number of POI is bigger than last POI number if (curr_distance == last_distance) { assertFalse(last_POIs_number < hotel.getNumPOI()); } last_distance = curr_distance; last_POIs_number = hotel.getNumPOI(); } } } <file_sep>/Ex6/src/CheckVariable.java import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * class to check a line of variable (declaration\assign) */ public class CheckVariable { // constants private static final String INT = "int"; private static final String DOUBLE = "double"; private static final String STRING = "String"; private static final String BOOLEAN = "boolean"; private static final String CHAR = "char"; private static final String TRUE = "true"; private static final String FALSE = "false"; private static final String SPACE = " "; private static final String EMPTY_STRING = ""; private static final String COMMA = ","; // Error messages private static final String ERROR_MESSAGE_TYPE_INVALID = "ERROR: type is invalid"; private static final String ERROR_MESSAGE_NAME_INVALID = "ERROR: name format is invalid"; private static final String ERROR_MESSAGE_NAME_IS_NULL = "ERROR: name is null"; private static final String ERROR_MESSAGE_NOTHING_BETWEEN_COMMAS = "ERROR: nothing between commas"; private static final String ERROR_MESSAGE_FINAL_MUST_BE_ASSIGN = "ERROR: final must be assigned"; private static final String ERROR_MESSAGE_INVALID_TYPE = "ERROR: invalid type"; private static final String ERROR_MESSAGE_VALUE_DOESNT_FIT_TYPE = "ERROR: value doesn't fit the variable type"; private static final String ERROR_MESSAGE_VARIABLE_NOT_FOUND_OR_FINAL = "ERROR: variable not found or is final"; private static final String ERROR_MESSAGE_2_VARIABLES_IN_SCOPE_WITH_SAME_NAME = "ERROR: 2 variables in the scope with the same name"; private static final String ERROR_MESSAGE_VARIABLE_NOT_FOUND_OR_NOT_INITIALIZED_OR_ILLEGAL_VALUE = "ERROR: variable not found or not initialized or illegal value"; private static final String ERROR_MESSAGE_VARIABLE_LINE_DOEST_MATCH_ANY_FORMAT = "ERROR: variable line doesn't match any possible format"; /* regex of whitespace one or more times */ private static final String REGEX_WHITESPACE = "\\s+"; /* regex of whitespace one or more times in the beginning */ private static final String REGEX_START_WHITESPACE = "^\\s+"; /* regex of final in the beginning */ private static final String REGEX_START_WHITESPACE_AND_FINAL = "^\\s*final\\s*"; /* regex of name format */ private static final String REGEX_NAME_FORMAT = "([a-zA-Z][\\w]*)|(_[\\w]+)"; /* regex of string value format */ private static final String REGEX_STRING_VALUE = "\"[^\\s\"',\\\\]*\""; /* regex of char value format */ private static final String REGEX_CHAR_VALUE = "'[^\\s\"',\\\\]'"; /* regex of "name = value ;" (a = 3;) */ private static final String REGEX_VARIABLE_STARTS_WITH_NAME = "\\s*(\\w+)\\s*=\\s*([^\\s,\\\\]+)\\s*;\\s*"; /* regex of "name = value" without the ';' in the end (a = 3) */ private static final String REGEX_ASSIGN_VALUE_TO_VARIABLE = "\\s*(\\w+)\\s*=\\s*([^\\s,\\\\]+)\\s*"; /* regex of "type name ;" (int a;) or "type name = value ;" (int a = 3;) or "type name1, name2, name 3; (int a, b, c;) or "type name1, name2 = value, name 3; (int a,b = 3,c;) */ private static final String REGEX_VARIABLE_STARTS_WITH_TYPE = "\\s*([a-zA-Z]+)\\s+(\\w+(\\s*=\\s*[^\\s,\\\\]+)?)" + "\\s*(\\s*,\\s*\\w+(\\s*=\\s*[^\\s,\\\\]+)?\\s*)*;\\s*"; /* regex of "final type name = value ;" (final int a = 3;) or "final type name1 = value1, name2 = value2;" (final int a = 1, b = 2;) */ private static final String REGEX_VARIABLE_STARTS_WITH_FINAL = "\\s*final\\s+([a-zA-Z]+)\\s+(\\w+(\\s*=\\s*[^\\s,\\\\]+)?)" + "\\s*(\\s*,\\s*\\w+(\\s*=\\s*[^\\s,\\\\]+)?\\s*)*;\\s*"; private static final String[] ARRAY_TYPES = new String[]{INT, DOUBLE, BOOLEAN, STRING, CHAR}; private static final List<String> validTypesList = Arrays.asList(ARRAY_TYPES); private static final Pattern patternVariableStartsWithName = Pattern .compile(REGEX_VARIABLE_STARTS_WITH_NAME); private static final Pattern patternVariableStartsWithType = Pattern .compile(REGEX_VARIABLE_STARTS_WITH_TYPE); private static final Pattern patternVariableStartsWithFinal = Pattern .compile(REGEX_VARIABLE_STARTS_WITH_FINAL); private static final Pattern patternAssignValueToVariable = Pattern .compile(REGEX_ASSIGN_VALUE_TO_VARIABLE); /** * check the format of the Name * @param str: given string of name * @throws InvalidPropertiesFormatException throws if format is invalid */ public static void checkNameFormat(String str) throws InvalidPropertiesFormatException { if (str.matches(REGEX_NAME_FORMAT)) { return; } throw new InvalidPropertiesFormatException(ERROR_MESSAGE_NAME_INVALID); } /** * check if a given Value is in the right format for the given Type * @param type: given type * @param value: given value * @throws NumberFormatException: throws if value isn't int\double * @throws InvalidPropertiesFormatException: throws if one of the value doesn't match the other types */ public static void checkValueAndTypeFormat(String type, String value) throws NumberFormatException, InvalidPropertiesFormatException { switch (type) { case INT: Integer.parseInt(value); return; case DOUBLE: Double.parseDouble(value); return; case STRING: if (value.matches(REGEX_STRING_VALUE)) { return; } break; case BOOLEAN: if (value.equals(TRUE) || value.equals(FALSE)) { return; } Double.parseDouble(value); return; case CHAR: if (value.matches(REGEX_CHAR_VALUE)) { return; } break; } throw new InvalidPropertiesFormatException(ERROR_MESSAGE_VALUE_DOESNT_FIT_TYPE); } /** * check if the given string is a valid Type to assign into variable with assignType type * @param assignType: type of variable tried to assign with * @param varType: type of the variable to assign into * @throws InvalidPropertiesFormatException: throws if the types dont allow the given type */ private static void checkAssignType(String assignType, String varType) throws InvalidPropertiesFormatException { // check if the found assigned type is valid to assign to the given type switch (varType) { case DOUBLE: if (assignType.equals(DOUBLE) || assignType.equals(INT)) { return; } break; case BOOLEAN: if (assignType.equals(BOOLEAN) || assignType.equals(INT) || assignType.equals(DOUBLE)) { return; } break; case INT: if (assignType.equals(INT)) { return; } break; case STRING: if (assignType.equals(STRING)) { return; } break; case CHAR: if (assignType.equals(CHAR)) { return; } break; } throw new InvalidPropertiesFormatException(ERROR_MESSAGE_TYPE_INVALID); } /** * check the value - format and logical * @param type: type of the variable to assign into * @param value: value to assign with * @param thisScope: the current scope of the variable * @throws InvalidPropertiesFormatException: throws if the value assign is invalid */ private static void checkValue(String type, String value, Scope thisScope) throws InvalidPropertiesFormatException { try { checkValueAndTypeFormat(type, value); } // value is not a legal value - so check if it is another variable name catch (NumberFormatException | InvalidPropertiesFormatException e) { Variable variableWithValueName = thisScope.findVariableInScopes(value); // check if the found variable exist and is initialized if (variableWithValueName != null && variableWithValueName.isInitialized()) { // if so - check if it's type is valid to the given type checkAssignType(variableWithValueName.getType(), type); } else { // if not found OR not initialized OR illegal value - throw // exception throw new InvalidPropertiesFormatException( ERROR_MESSAGE_VARIABLE_NOT_FOUND_OR_NOT_INITIALIZED_OR_ILLEGAL_VALUE); } } } /** * check the name - format and logical * @param name: string of name to check * @param thisScope: the current scope * @throws InvalidPropertiesFormatException: throws if the name is invalid */ private static void checkName(String name, Scope thisScope) throws InvalidPropertiesFormatException { checkNameFormat(name); // 2 variables with the same name in the same scope if (thisScope.getScopeVariables().containsKey(name)) { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_2_VARIABLES_IN_SCOPE_WITH_SAME_NAME); } } /** * check the assign * @param name: name of variable * @param value: value to assign * @param type: type of the variable * @param thisScope: the current scope * @throws InvalidPropertiesFormatException: throws if the assign is invalid */ private static void checkAssign(String name, String value, String type, Scope thisScope) throws InvalidPropertiesFormatException { if (name != null) { checkName(name, thisScope); } else { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_NAME_IS_NULL); } checkValue(type, value, thisScope); } /** * check each variable in a line declaration - which starts with "final" * @param type: type declaration * @param thisScope: the current scope * @param splitByComma: string array of all the variables declarations * @param addVariableToScope: boolean if the variables need to be added to the scope or not * @throws InvalidPropertiesFormatException: throws if the declaration is invalid */ private static void checkEachVarInDeclarationFinal(String type, Scope thisScope, String[] splitByComma, boolean addVariableToScope) throws InvalidPropertiesFormatException { String name, value; Variable newVariable; Matcher matcher; for (String part : splitByComma) { if (part == null) { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_NOTHING_BETWEEN_COMMAS); } matcher = patternAssignValueToVariable.matcher(part); if (matcher.matches()) { // with assign name = matcher.group(1); value = matcher.group(2); checkAssign(name, value, type, thisScope); if (thisScope.getParentScope() == null){ // global scope newVariable = new Variable(type, name, true, true, true); } else{ // not global scope newVariable = new Variable(type, name, true, true, false); } } else { // final must be assign in declaration throw new InvalidPropertiesFormatException(ERROR_MESSAGE_FINAL_MUST_BE_ASSIGN); } // if all good and need to add - add the new variable to this scope if (addVariableToScope) { thisScope.getScopeVariables().put(name, newVariable); } } } /** * check each variable in a line declaration - which doesnt starts with "final" * @param type: type declaration * @param thisScope: the current scope * @param splitByComma: string array of all the variables declarations * @param addVariableToScope: boolean if the variables need to be added to the scope or not * @throws InvalidPropertiesFormatException: throws if the declaration is invalid */ private static void checkEachVarInDeclaration(String type, Scope thisScope, String[] splitByComma, boolean addVariableToScope) throws InvalidPropertiesFormatException { String name, value = null; Variable newVariable; Matcher matcher; for (String part : splitByComma) { if (part == null) { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_NOTHING_BETWEEN_COMMAS); } matcher = patternAssignValueToVariable.matcher(part); if (matcher.matches()) { // with assign name = matcher.group(1); value = matcher.group(2); checkAssign(name, value, type, thisScope); if (thisScope.getParentScope() == null){ // global scope newVariable = new Variable(type, name, true, false, true); } else { // not global scope newVariable = new Variable(type, name, true, false, false); } } else { // without assign name = part; checkName(name, thisScope); checkType(type); newVariable = new Variable(type, name, false, false, false); } // if all good and need to add - add the new variable to this scope if (addVariableToScope) { thisScope.getScopeVariables().put(name, newVariable); } } } /** * split by commas a given declaration line to the different variables parts assume there is nothing * before the type in the line * @param subLine: given line * @return string array of the different parts separated by commas */ private static String[] splitVariablesByComma(String subLine) { // find first space (must be after type) int indexOfFirstSpaceAfterType = subLine.indexOf(SPACE); // take only the part of: "a" \ "a - 3" \ "a, b, c" \ "a, b = 3, c" (remove type part) subLine = subLine.substring(indexOfFirstSpaceAfterType + 1, subLine.lastIndexOf(";")); // remove all spaces subLine = subLine.replaceAll(REGEX_WHITESPACE, EMPTY_STRING); // split by ',' return subLine.split(COMMA); } /** * check if the type is one of the valid types * @param type: given string to check * @throws InvalidPropertiesFormatException: throws if it's not one of the possible types */ private static void checkType(String type) throws InvalidPropertiesFormatException { if (validTypesList.contains(type)){ return; } throw new InvalidPropertiesFormatException(ERROR_MESSAGE_INVALID_TYPE); } /** * check just if the format of the line is a match to a valid variable possible line * @param line: given string of a line * @return: true if the line match one of the possible formats and false otherwise */ public static boolean checkJustFormat(String line) { Matcher matcher = patternVariableStartsWithName.matcher(line); if (matcher.matches()) { return true; } matcher = patternVariableStartsWithType.matcher(line); if (matcher.matches()) { return true; } matcher = patternVariableStartsWithFinal.matcher(line); return matcher.matches(); } /** * check a line manipulating variables (declaration/assign) * @param line: given string of a line * @param thisScope: the current scope of the line * @param addVariableToScope: boolean if the variables need to be added to the scope or not * @throws InvalidPropertiesFormatException: throws if something went wrong * @throws NumberFormatException: throws if number assign went wrong */ public static void checkVariableLine(String line, Scope thisScope, boolean addVariableToScope) throws InvalidPropertiesFormatException, NumberFormatException { // Variable starts with Name - (a = 3;) Matcher matcher = patternVariableStartsWithName.matcher(line); if (matcher.matches()) { String name = matcher.group(1); String value = matcher.group(2); checkNameFormat(name); Variable variableWithGivenName = thisScope.findVariableInScopes(name); // if a variable with such name exist and it's not final if ((variableWithGivenName != null) && (!variableWithGivenName.isFinal())) { checkValue(variableWithGivenName.getType(), value, thisScope); } else { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_VARIABLE_NOT_FOUND_OR_FINAL); } variableWithGivenName.setInitialized(); if (thisScope.getParentScope() == null){ // global scope variableWithGivenName.setIsGlobalInitialized(); } return; } // Variable starts with Type - (int a;) or (int a = 3;) or (int a, b, c;) or (int a,b = 3,c;) matcher = patternVariableStartsWithType.matcher(line); if (matcher.matches()) { String type = matcher.group(1); // remove all beginning whitespaces String subLine = line.replaceAll(REGEX_START_WHITESPACE, EMPTY_STRING); // split by comma String[] splitByComma = splitVariablesByComma(subLine); checkEachVarInDeclaration(type, thisScope, splitByComma, addVariableToScope); return; } // Variable starts with final - (final int a;) matcher = patternVariableStartsWithFinal.matcher(line); if (matcher.matches()) { String type = matcher.group(1); // remove all beginning whitespaces and final String subLine = line.replaceAll(REGEX_START_WHITESPACE_AND_FINAL, EMPTY_STRING); // split by comma String[] splitByComma = splitVariablesByComma(subLine); checkEachVarInDeclarationFinal(type, thisScope, splitByComma, addVariableToScope); return; } // line doesn't match any of the possible variable-line formats throw new InvalidPropertiesFormatException(ERROR_MESSAGE_VARIABLE_LINE_DOEST_MATCH_ANY_FORMAT); } }<file_sep>/Ex3/src/RatingCompare.java import oop.ex3.searchengine.Hotel; import java.util.Comparator; /** * implementation of hotels rating star compare class */ public class RatingCompare implements Comparator<Hotel> { /** representing bigger return value in comparator */ private static final int BIGGER = 1; /** representing smaller return value in comparator */ private static final int SMALLER = (-1); /** * @param hotel1: hotel object * @param hotel2: hotel object * @return 1 if hotel1's star rating is bigger, (-1) if hotel1's star rating is smaller. if the two * hotels have the same star rating it will compare between their names with String.compareTo() */ public int compare(Hotel hotel1, Hotel hotel2) { if (hotel1.getStarRating() < hotel2.getStarRating()) { return SMALLER; } if (hotel1.getStarRating() > hotel2.getStarRating()) { return BIGGER; } return hotel1.getPropertyName().compareTo(hotel2.getPropertyName()); } } <file_sep>/Ex5/src/filesprocessing/DirectoryProcessor.java package filesprocessing; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import static filesprocessing.Errors.*; import static filesprocessing.Filter.*; import static filesprocessing.Order.*; import static filesprocessing.Output.*; /** * class implementation of DirectoryProcessor */ public class DirectoryProcessor { /** Error message of invalid number of arguments */ protected static final String ERROR_MESSAGE_NOT_2_ARGS = "ERROR: invalid usage - didnt receive 2 arguments"; /** Error message of invalid arguments */ protected static final String ERROR_MESSAGE_INVALID_ARGS = "ERROR: invalid arguments"; /** Error message of I/O problems */ protected static final String ERROR_MESSAGE_IO_PROBLEM = "ERROR: I/O problems"; /** Error message of missing sub-section */ protected static final String ERROR_MESSAGE_MISSING_SUBSECTION_NAME = "ERROR: Missing subsection"; /** Error message of bad sub-section name or missing sub-section */ protected static final String ERROR_MESSAGE_BAD_OR_MISSING_SUBSECTION_NAME = "ERROR: Bad subsection " + "name"; /** name of filter sub-section */ protected static final String FILTER_SECTION_NAME = "FILTER"; /** name of order sub-section */ protected static final String ORDER_SECTION_NAME = "ORDER"; /** number of the max lines distance between two sub-sections */ protected static final int MAX_LINES_BETWEEN_SUBSECTIONS = 2; /** the separator between the filter line parts */ protected static final String SEPARATOR_IN_LINE = "#"; /** first line in a section */ protected static final int FIRST_LINE = 1; /** second line in a section */ protected static final int SECOND_LINE = 2; /** fourth line in a section */ protected static final int FOURTH_LINE = 4; protected static String commandsFilePath; protected static String sourceDirPath; protected static File sourceDir; protected static File commandsFile; protected static Scanner fileScanner; protected static ArrayList<File> filtered_files = null; /** * return a Scanner of the commands file * @return Scanner of the commands file * @throws IOException: if there was an error with accessing the file */ protected static Scanner getFileScanner() throws IOException { try { return new Scanner(commandsFile); } catch (IOException ioe) { // I/O problems System.err.println(ERROR_MESSAGE_IO_PROBLEM); throw new IOException(); } } /** * process the commands file to filter and order as written inside * @param fileScanner: Scanner of the Commands file */ private static void processCommandsFile(Scanner fileScanner) { int line_in_section = 1; int line_counter = 1; String curr_line; boolean finished_section = false; boolean last_was_ORDER = false; while (fileScanner.hasNext()) { // every row curr_line = fileScanner.nextLine(); switch (curr_line) { case FILTER_SECTION_NAME: if (line_in_section == SECOND_LINE) { // last ORDER didnt have an order-name line - sort by abs filtered_files = filterFiles(curr_line, sourceDir, line_counter); } // when the section has only 3 lines so the 4th line is actually a new FILTER line if (line_in_section == FOURTH_LINE) { finished_section = true; line_in_section = FIRST_LINE; } break; case ORDER_SECTION_NAME: // sort-by ABS in case that's the last row in the file and obviously has no order-name if (line_in_section == FOURTH_LINE) { orderFiles(curr_line, filtered_files, line_counter); break; } // in case ORDER was instead of a filter-name line if (line_in_section == SECOND_LINE) { filtered_files = filterFiles(curr_line, sourceDir, line_counter); break; } orderFiles(ABS, filtered_files, line_counter); last_was_ORDER = true; break; default: // if not a title line if (line_in_section == SECOND_LINE) { // filter-name line filtered_files = filterFiles(curr_line, sourceDir, line_counter); } else if (line_in_section == FOURTH_LINE) { // order-name line orderFiles(curr_line, filtered_files, line_counter); finished_section = true; last_was_ORDER = false; } break; } line_in_section++; if (finished_section) { if (!curr_line.equals(FILTER_SECTION_NAME)) { line_in_section = FIRST_LINE; } printSortedFiles(); // Print files finished_section = false; } line_counter++; } if (last_was_ORDER) { printSortedFiles(); // Print files } } /** * main method * @param args: list of Strings where args[0] is sourceDir path and args[1] is Commands File path */ public static void main(String[] args) { try { if (args.length != 2) { // Type 2 error - not 2 arguments throw new IllegalArgumentException(); } commandsFilePath = args[1]; sourceDirPath = args[0]; sourceDir = new File(args[0]); commandsFile = new File(commandsFilePath); // Type 2 Errors foundType2Error(); // Filter and Order the files fileScanner = getFileScanner(); } catch (IllegalArgumentException exception) { System.err.println(ERROR_MESSAGE_NOT_2_ARGS); return; } // Error messages already printed in the methods catch (RuntimeException exception) { return; } catch (IOException ioe) { System.err.println(ERROR_MESSAGE_IO_PROBLEM); return; } processCommandsFile(fileScanner); fileScanner.close(); } } <file_sep>/Ex6/src/CheckMethod.java import java.util.HashMap; import java.util.InvalidPropertiesFormatException; import java.util.LinkedList; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Checking the method code validity */ public class CheckMethod { private static final String ERROR_MESSAGE_METHOD_DUPLICATE = "ERROR: Methods must have different names"; private static final String ERROR_MESSAGE_METHOD_RETURN = "ERROR: Methods must end with return; line " + "followed by a closing curly bracket line"; private static final String OPEN_CURLY_BRACKET = "{"; private static final String NEW_LINE = "\n"; static final String REGEX_CLOSE_CURLY_BRACKET = "^\\s*\\}\\s*$"; static final String REGEX_OPEN_CURLY_BRACKET_END = "^[\\s\\S]*\\{\\s*$"; static final String REGEX_SIGNATURE_FORMAT = "^\\s*\\bvoid\\b\\s+[a-zA-Z][\\w]*\\s*\\(\\s*(((\\s*final\\s+)" + "?(String|boolean|char|int|double)\\s+(([a-zA-Z][\\w]*)|(_[\\w]+))\\s*(\\)|(\\s*,\\s*(\\s*final\\s+)?" + "(String|boolean|char|int|double)\\s+(([a-zA-Z][\\w]*)|(_[\\w]+))\\s*)*\\s*\\)))|(\\s*\\)\\s*))\\s*\\{\\s*$"; static final String REGEX_SIGNATURE_FIND = "\\bvoid\\b\\s+[a-zA-Z][\\w]*\\s*\\(\\s*(((\\s*final\\s+)" + "?(String|boolean|char|int|double)\\s+(([a-zA-Z][\\w]*)|(_[\\w]+))\\s*(\\)|(\\s*,\\s*(\\s*final\\s+)?" + "(String|boolean|char|int|double)\\s+(([a-zA-Z][\\w]*)|(_[\\w]+))\\s*)*\\s*\\)))|(\\s*\\)\\s*))\\s*\\{\\s*"; static final String REGEX_SIGNATURE_LAYOUT = "\\s*\\S+\\s+\\S+\\s*\\([\\s\\S]*\\)\\s*\\{\\s*"; static final String REGEX_PARAMETER = "(final\\s+)?(String|boolean|char|int|double)\\s+" + "(([a-zA-Z][\\w]*)|(_[\\w]+))"; static final String REGEX_METHOD_NAME = "void\\b\\s+([a-zA-Z][\\w]*)\\s*\\("; static final String REGEX_RETURN = "^\\s*return\\s*;\\s*$"; static final int FINAL_PARAM_FIELDS = 3; private static String lastMethodCode; /** * Checking validity of method's signature by regex * @param line * @return */ public static boolean isValidMethodSignature(String line){ return line.matches(REGEX_SIGNATURE_FORMAT); } /** * Checking for a method's signature by regex (not strict) * @param line * @return */ public static boolean isMethodSignatureLayout(String line){ return line.matches(REGEX_SIGNATURE_LAYOUT); } /** * Creating a String array out of the method's signature line to hold the parameters * @param line * @return */ public static String[] getParameterVariablesLines(String line){ Matcher m = Pattern.compile(REGEX_PARAMETER).matcher(line); String variables = ""; while (m.find()) { variables += m.group() + ";" + NEW_LINE; } if(variables.isEmpty()){ return null; } return variables.substring(0, variables.lastIndexOf(NEW_LINE)).split(NEW_LINE); } /** * Creating a Variable array out of the method's signature line to hold the parameters * @param line * @return */ public static Variable[] getParameterVariables(String line){ Matcher m = Pattern.compile(REGEX_PARAMETER).matcher(line); LinkedList<Variable> varLines = new LinkedList<>(); while (m.find()) { String parameter = m.group(); String[] parameterFields = parameter.split("\\s+"); boolean isFinal = false; String varName = parameterFields[1]; String varType = parameterFields[0]; if(parameterFields.length == FINAL_PARAM_FIELDS){ isFinal = true; varName = parameterFields[2]; varType = parameterFields[1]; } varLines.add(new Variable(varType, varName, true, isFinal, false)); } return varLines.toArray(new Variable[varLines.size()]); } /** * Finding methods in the code and checking for duplicates/no return at the end etc * @param code * @return * @throws InvalidPropertiesFormatException */ public static HashMap<String, Method> findMethods(String code) throws InvalidPropertiesFormatException { HashMap<String, Method> methods = new HashMap<>(); Matcher methodMatcher = Pattern.compile(REGEX_SIGNATURE_FIND).matcher(code); while (methodMatcher.find()) { String currMethod = methodMatcher.group(); if(isReturnEnd(code, currMethod, methodMatcher.end())) { Variable[] methodParams = getParameterVariables(currMethod); Matcher methodNameMatcher = Pattern.compile(REGEX_METHOD_NAME).matcher(currMethod); methodNameMatcher.find(); String methodName = methodNameMatcher.group(1); if (methods.containsKey(methodName)) { throw new InvalidPropertiesFormatException(ERROR_MESSAGE_METHOD_DUPLICATE); } else { methods.put(methodName, new Method(methodName, methodParams, lastMethodCode)); } } else{ throw new InvalidPropertiesFormatException(ERROR_MESSAGE_METHOD_RETURN); } } return methods; } /** * Checking that there is a return statement at the end of the method's code * (Also getting the method's code along the search) * @param code * @param signature * @param startIndex * @return */ public static boolean isReturnEnd(String code,String signature, int startIndex){ Stack<String> stack = new Stack<>(); stack.push(OPEN_CURLY_BRACKET); String[] lines = code.substring(startIndex).split(NEW_LINE); String prevCodeLine = ""; int currIndex = 0; String methodCode = signature; while(!stack.isEmpty()){ if(lines[currIndex].matches(REGEX_OPEN_CURLY_BRACKET_END)){ stack.push(OPEN_CURLY_BRACKET); } else if(lines[currIndex].matches(REGEX_CLOSE_CURLY_BRACKET)){ stack.pop(); if(!stack.isEmpty()){ prevCodeLine = lines[currIndex]; } } else{ prevCodeLine = lines[currIndex]; } methodCode += lines[currIndex] + NEW_LINE; currIndex++; } lastMethodCode = methodCode.substring(0, methodCode.lastIndexOf(NEW_LINE)); return prevCodeLine.matches(REGEX_RETURN); } } <file_sep>/Ex5/src/test/java/python_tests/readable_files.py import subprocess if __name__ == '__main__': schoolOutput = open("C:\\Users\\24565\\PycharmProjects\\javaTest" "\\tester_files\\tests\\zzz-test-by-school_filter054" ".flt\\complex_school_solution_output.txt") schoolOutputContent = {x.strip() for x in schoolOutput} schoolOutput.close() avishaiOutput = open("C:\\Users\\24565\\PycharmProjects\\javaTest" "\\tester_files\\tests\\test03\\complex_user_output" ".txt") avOutputContent = {x.strip() for x in avishaiOutput} needToBeRead = set() for item in avOutputContent: if item not in schoolOutputContent: command_list = ["attrib" ,"+R", "C:\\Users\\24565\\PycharmProjects\\javaTest" "\\tester_files\\files_to_filter\\complex" ""+"\\" + item] process = subprocess.Popen(command_list, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) process.communicate()<file_sep>/Ex4/src/SingleLinkedList.java import java.util.LinkedList; /** * Wrapper class of a LinkedList<String> */ public class SingleLinkedList extends LinkedList<String> { LinkedList<String> list; /** * constructor of the class */ SingleLinkedList(){ list = new LinkedList<String>(); } /** * Inserts the specified element at the beginning of this list. * * @param newValue the string to add */ public void addValue(String newValue){ list.addFirst(newValue); } /** * Returns true iff this list contains at least one element of the given string * * @param searchVal string whose presence in this list is to be tested * @return true if this list contains the specified element and false otherwise */ public boolean contains(String searchVal){ return list.contains(searchVal); } /** * Removes the element with the lowest index of the element if such an element exists * * @param toDelete string to be removed from this list, if present */ public void remove(String toDelete){ list.remove(toDelete); } /** * @return the linked list of this instance */ public LinkedList<String> getList(){ return list; } } <file_sep>/Ex4/src/SimpleHashSet.java /** * abstract class implementing SimpleSet Just the size method is being implemented and the other methods are * implemented in subclasses to their use */ abstract class SimpleHashSet implements SimpleSet { /** no elements in the HashSet */ protected static final int NO_ELEMENTS = 0; /** default initial capacity of the HashSet */ protected static final int DEFAULT_INIT_CAPACITY = 16; /** default initial upperLoadFactor of the HashSet */ protected static final float DEFAULT_INIT_UPPER_LOAD_FACTOR = 0.75f; /** default initial lowerLoadFactor of the HashSet */ protected static final float DEFAULT_INIT_LOWER_LOAD_FACTOR = 0.25f; /** representing an increase size */ protected static final int INCREASE_SIZE = 1; /** representing a decrease size */ protected static final int DECREASE_SIZE = (-1); protected int numOfElements; protected int capacity; protected float upperLoadFactor; protected float lowerLoadFactor; /** * constructor of SimpleHashSet */ SimpleHashSet() { numOfElements = NO_ELEMENTS; capacity = DEFAULT_INIT_CAPACITY; upperLoadFactor = DEFAULT_INIT_UPPER_LOAD_FACTOR; lowerLoadFactor = DEFAULT_INIT_LOWER_LOAD_FACTOR; } /** * @return The number of elements currently in the set */ @Override public int size() { return numOfElements; } /** * @return The current capacity (number of cells) of the table. */ public int capacity() { return capacity; } /** * @return the load factor - current number of elements in the hash divided by the capacity */ protected float loadFactor() { return ((float) numOfElements / (float) capacity);} /** * resizing the hash according to the given type type=1 : increase , type=(-1): decrease * @param type: int of which resize type to apply */ abstract void resize(int type); }
4e3ce70911472f21501c31dcaa33fc49587c47ae
[ "Java", "Python" ]
24
Java
johny1122/Java-OOP
1ab48a76fca25bf0d115040e1870bc4cbc25f017
01d9645d564ca7d0cfc8980b30fb629d2cb0a525
refs/heads/master
<repo_name>gerkirill/book-box<file_sep>/src/app.php <?php use Silex\Application; use Silex\Provider\SessionServiceProvider; use Silex\Provider\TwigServiceProvider; use Silex\Provider\UrlGeneratorServiceProvider; use Silex\Provider\ValidatorServiceProvider; use Silex\Provider\ServiceControllerServiceProvider; use Dropbox as dbx; $app = new Application(); $app->register(new UrlGeneratorServiceProvider()); $app->register(new ValidatorServiceProvider()); $app->register(new ServiceControllerServiceProvider()); $app->register(new TwigServiceProvider()); $app->register(new SessionServiceProvider()); $app['twig'] = $app->share($app->extend('twig', function($twig, $app) { // add custom globals, filters, tags, ... $twig->addGlobal('currentUser', $app['persi']->getCurrentUser()); $twig->addFilter(new Twig_SimpleFilter('md5', 'md5')); return $twig; })); $app['dbox.auth'] = $app->share(function() { $appInfo = dbx\AppInfo::loadFromJsonFile(__DIR__ . '/../config/dropbox.json'); $webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0"); return $webAuth; }); $app['persi'] = $app->share(function() use ($app) { $persi = new Personalizer(); $persi->setCurrentUserId($app['session']->get('user')); return $persi; }); $app['user.dboxClient'] = $app->share(function($app) { $user = $app['persi']->getCurrentUser(); if (!$user) { throw new \Exception('Can not create user.dboxClient service instance until user is logged in'); } if (!$user->dbAccessToken) { throw new \Exception('User has not linked dropbox account yet'); } return new dbx\Client($user->dbAccessToken, "PHP-Example/1.0"); }); $app['injectBasename'] = $app->protect(function($entries) { return array_map(function($entry) { $entry['basename'] = preg_replace('%^.*/%', '', $entry['path']); return $entry; }, $entries); }); $app['tmpFileManager'] = $app->share(function() { return new TmpFileManager(__DIR__ . '/../var/cache'); }); return $app; <file_sep>/config/dev.php <?php use Silex\Provider\MonologServiceProvider; use Silex\Provider\WebProfilerServiceProvider; // include the prod configuration require __DIR__.'/prod.php'; require_once(__DIR__ . '/../lib/redbean/rb.php'); R::setup( 'mysql:host=localhost;dbname=bookbox', 'root', 'vagrant' ); // enable the debug mode $app['debug'] = true; $app->register(new MonologServiceProvider(), array( 'monolog.logfile' => __DIR__.'/../var/logs/silex_dev.log', )); $app->register($p = new WebProfilerServiceProvider(), array( 'profiler.cache_dir' => __DIR__.'/../var/cache/profiler', )); $app->mount('/_profiler', $p);<file_sep>/Vagrantfile $script = <<SCRIPT echo Adjusting webroot symlink... rm -rf /var/www ln -s /vagrant/web /var/www service apache2 restart SCRIPT Vagrant.configure("2") do |config| config.vm.box = "ubuntu-lamp-2014-07-07" config.vm.box_url = "https://www.dropbox.com/s/r7awn51cpfef8gz/package-2014-07-07-php55.box?dl=1" config.vm.network :private_network, ip: "192.168.72.10" config.vm.hostname = "bookbox.local" config.vm.provision "shell", inline: $script config.vm.provider "virtualbox" do |v| v.name = "book-box" v.customize ["modifyvm", :id, "--memory", "650"] v.customize ["modifyvm", :id, "--cpus", "1"] v.customize ["modifyvm", :id, "--ioapic", "on"] end end<file_sep>/src/controllers.php <?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Dropbox as dbx; // link dropbox account $app->get('/', function () use ($app) { $user = $app['persi']->getCurrentUser(); if (!$user->dbAccessToken) { return new RedirectResponse('/link'); } elseif (!$user->booksFolder) { return new RedirectResponse('/choose'); } else { return new RedirectResponse('/done'); } }) ->bind('homepage'); $app->get('/link', function() use ($app) { $authorizeUrl = $app['dbox.auth']->start(); return $app['twig']->render('index.html', array('authUrl' => $authorizeUrl)); }); // select OPDS-published folder $app->get('/choose/{path}', function ($path) use ($app) { try { $folderMetadata = $app['user.dboxClient']->getMetadataWithChildren("/" . $path); } catch (\Exception $e) { return new RedirectResponse('/'); } return $app['twig']->render( 'account.html', [ 'entries' => $app['injectBasename']($folderMetadata['contents']), 'path' => $path ]); }) ->value('path', '') ->assert('path', '.*'); $app->get('/done', function() use ($app) { $user = $app['persi']->getCurrentUser(); if (!$user->booksFolder) { return new RedirectResponse('/'); } return $app['twig']->render('done.html', []); }); // finish dropbox auth process $app->post('/code', function (Request $request) use ($app) { $authCode = trim($request->get('code')); list($accessToken, $dropboxUserId) = $app['dbox.auth']->finish($authCode); $user = $app['persi']->getCurrentUser(); $user->dbAccessToken = $accessToken; $user->dbUserId = $dropboxUserId; R::store($user); return new RedirectResponse('/'); }); // list books in a subpath of OPDS-published folder $app->get('/opds/{path}', function($path, Request $request) use ($app) { $user = $app['persi']->getCurrentUser(); // connect to dropbox and list contents $folderMetadata = $app['user.dboxClient']->getMetadataWithChildren($user->booksFolder . ($path ? "/$path" : '')); return $app['twig']->render('opds-file-list.xml', ['entries' => $app['injectBasename']($folderMetadata['contents'])]); }) ->value('path', '') ->assert('path', '.*') ->bind('opds'); $app->get('/opds-download/{path}', function($path, Request $request) use ($app) { $user = $app['persi']->getCurrentUser(); $path = '/' . $path; if (0 !== strpos($path, $user->booksFolder)) { throw new \Exception('This file is out of the OPDS-shared folder'); } list($tmpDownloadUrl, $expires) = $app['user.dboxClient']->createTemporaryDirectLink($path); return new RedirectResponse($tmpDownloadUrl); // list($cachedFilePath, $cachedFileHandle) = $app['tmpFileManager']->createFile('downloads/'); // $fileMetadata = $app['user.dboxClient']->getFile($path, $cachedFileHandle); // fclose($cachedFileHandle); // return $app->sendFile($cachedFilePath); }) ->assert('path', '.+') ->bind('opds-download'); // display context menu at the folder chooser $app->get('/folder-menu/{path}', function($path) use ($app) { return $app['twig']->render( 'folder-menu.html', [ 'path' => $path, 'parentPath' => preg_replace('%/?[^/]*$%', '', $path) ] ); }) ->value('path', '') ->assert('path', '.*'); // currently selected folder to share with opds $app->get('/selected-folder', function() use ($app) { $user = $app['persi']->getCurrentUser(); return $app['twig']->render( 'selected-folder.html', [ 'folder' => $user->booksFolder ] ); }); // update OPDS-shared folder $app->get('/select-folder/{path}', function($path ) use ($app) { $user = $app['persi']->getCurrentUser(); $user->booksFolder = '/' . $path; R::store($user); return new RedirectResponse( '/' ); }) ->value('path', '') ->assert('path', '.*'); $app->match('/login', function(Request $request) use ($app) { $data = []; if ('POST' == $request->getMethod()) { $user = $app['persi']->getUserByCredentials($request->get('login'), $request->get('password')); if ($user) { $app['session']->set('user', $user->id); return new RedirectResponse('/'); } $data['login'] = $request->get('login'); $data['errors']['credentials'] = true; } return $app['twig']->render('login.html', $data); }) ->bind('login'); $app->match('/register', function(Request $request) use ($app) { $login = trim($request->get('login')); $data = ['login' => $login, 'password' => $request->get('<PASSWORD>')]; if ('POST' == $request->getMethod()) { if ('' == $login) { $data['errors']['login']['empty'] = true; } elseif (R::findOne( 'user', ' email = ? ', [$login] )) { $data['errors']['login']['unique'] = true; } if('' == $request->get('password')) { $data['errors']['password']['empty'] = true; } if (empty($data['errors'])) { $newUser = R::dispense('user'); $newUser->email = $request->get('login'); $newUser->password = $request->get('password'); $app['session']->set('user', R::store($newUser)); return new RedirectResponse('/'); } } return $app['twig']->render('register.html', $data); }) ->bind('register'); $app->get('/logout', function() use ($app) { $app['session']->set('user', null); return new RedirectResponse('/'); }) ->bind('logout'); $app->get('/navigation', function() use($app) { return $app['twig']->render('navigation.html'); }); // handling errors $app->error(function (\Exception $e, $code) use ($app) { if ($app['debug']) { return; } // 404.html, or 40x.html, or 4xx.html, or error.html $templates = array( 'errors/'.$code.'.html', 'errors/'.substr($code, 0, 2).'x.html', 'errors/'.substr($code, 0, 1).'xx.html', 'errors/default.html', ); return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code); }); $app->finish(function (Request $request, Response $response) use ($app) { $app['tmpFileManager']->cleanup(); }); $app->before(function(Request $request) use ($app) { $route = $app['request']->attributes->get('_route'); $publicRoutes = ['login', 'register', 'logout']; $basicHttpAuthRoutes = ['opds', 'opds-download']; if (in_array($route, $basicHttpAuthRoutes)) { $user = $app['persi']->authBasicHttp($request); if (!$user) { return new Response('Not Authorized', 401, ['WWW-Authenticate' => 'Basic realm="Bookbox OPDS"']); } $app['persi']->setCurrentUserId($user->id); } else { if (!in_array($route, $publicRoutes) && !$app['session']->get('user')) { return new RedirectResponse('/login'); } } });<file_sep>/src/Personalizer.php <?php use Symfony\Component\HttpFoundation\Request; class Personalizer { private $userId; public function setCurrentUserId($userId) { $this->userId = $userId; } public function getCurrentUser() { if (!$this->userId) { return null; } return R::load( 'user', $this->userId ); } public function getUserByCredentials($login, $password) { if (empty($login) || empty($password)) { return NULL; } // check against database $user = R::findOne( 'user', ' email = ? ', [$login] ); if (!$user || $user->password != $password) { return NULL; } return $user; } public function authBasicHttp(Request $request) { // get username and pass from headers $credentials = preg_replace('/^Basic /i', '', $request->headers->get('Authorization')); $credentials = base64_decode($credentials); // Notice: Undefined offset: 1 @list($userName, $pass) = explode(':', $credentials, 2); return $this->getUserByCredentials($userName, $pass); } } <file_sep>/src/TmpFileManager.php <?php class TmpFileManager { private $tmpDir; private $createdFiles = array(); public function __construct($tmpDir) { $this->tmpDir = rtrim($tmpDir, '/') . '/'; } public function createFile($subpath, $prefix='tmp_') { $path = tempnam($this->tmpDir . $subpath, $prefix); $handle = fopen($path, 'w+b'); $this->createdFiles[$path] = $handle; return [$path, $handle]; } public function cleanup() { foreach($this->createdFiles as $path => $handle) { @fclose($handle); @unlink($path); } } } <file_sep>/README.md book-box ======== Silex-powered service which allows you to access selected dropbox folder over OPDS (password-protected)
2624b56b5812d7545cfbb31be55be9a0a7ae0812
[ "Markdown", "Ruby", "PHP" ]
7
PHP
gerkirill/book-box
dad237ab2c3af0a8f33ae17d1df2afb894076b9b
8724432a713f11353d0ed9b03e3ce6a214352d8a
refs/heads/master
<repo_name>ImadBouirmane/phiber<file_sep>/library/controller.php <?php namespace Phiber; class controller extends wire { public function __construct() { $this->view; } } <file_sep>/library/ui/ui.php <?php namespace Phiber\Ui; use Phiber\phiber; class ui extends phiber { public $html; public function __construct() { $this->html = html::createElement(); } }
ee9ffd9719e40652b3234283957a3b01a9cd4652
[ "PHP" ]
2
PHP
ImadBouirmane/phiber
a43a07620eca1ccd788ac43ba73d634ca60ad7c9
b2ff52153957b92704531b9359f5d526bae46ead
refs/heads/master
<file_sep>#!/usr/bin/env python from flask import Flask, session, redirect, url_for, escape, request from flask_session import Session app = Flask(__name__) # using flask_session to replace Flask.session # will persist session dictionaries as string-valued keys # (basically python pickles) to redis at 127.0.0.1:6379 # TIP to watch the set/get action while this app is running, # enter 'redis-cli monitor' in another shell SESSION_TYPE = 'redis' app.config.from_object(__name__) Session(app) # helpful for in-browser debugging - not really necessary try: from flask_debugtoolbar import DebugToolbarExtension toolbar = DebugToolbarExtension() app.config['DEBUG_TB_ENABLED'] = True toolbar.init_app(app) print(">>>>>> Using sweet debug toolbar.") except ImportError: pass # now for the Box-y parts... from boxsdk import OAuth2 from boxsdk import Client from boxsdk.exception import BoxAPIException from boxsdk.object.collaboration import CollaborationRole import configparser config = configparser.RawConfigParser() config.read('boxapp.cfg') CLIENT_ID = config.get('boxapp', 'CLIENT_ID') CLIENT_SECRET = config.get('boxapp', 'CLIENT_SECRET') # In the box developer console, set your app's callback URL to # http://localhost:5000/callback GOHOME = 'Back to <a href="/">home page</a>.</p>' ## define various Flask routes # start oauth-ing @app.route('/auth/') def authenticate(oauth_class=OAuth2): oauth = oauth_class( client_id=CLIENT_ID, client_secret=CLIENT_SECRET ) # where should they go? auth_url, csrf_token = oauth.get_authorization_url('http://localhost:5000/callback') # save so we can verify in the callback session['csrf_token'] = csrf_token # go get authorized return redirect(url_for('auth')) # finish oauth-ing @app.route('/callback') def get_tokens(oauth_class=OAuth2): # welcome back 'friend', if that _is_ your real name # get the auth code so we can exchange it for an access token auth_code = {} auth_code['auth_code'] = request.args.get('code') auth_code['state'] = request.args.get('state') # does our nonce match up? print(auth_code['state']) print(session['csrf_token','nope']) #assert auth_code['state'] == session['csrf_token'] oauth = oauth_class( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, ) # onwards! access_token, refresh_token = oauth.authenticate(auth_code['auth_code']) store_tokens(access_token, refresh_token) #return "<p>access_token: {} <br/>refresh_token: {}</p>".format(access_token, refresh_token) return redirect(url_for('index')) # extracted to method b/c we can use it as a callback in the Oauth2() definition... def store_tokens(access_token, refresh_token): session['access_token'] = access_token session['refresh_token'] = refresh_token # Now that the access_token is in the session, we can construct a # box client to act on behalf of the user. only until the current # session expires. # TODO: But if we store a 'username' key based on Cosign or # Shibboleth in redis, we can use that key to call up the access # and refresh tokens per user each time they show up and login. # simple box api invocation @app.route('/whoami') def whoami(): # TODO extract this to a method so all routes can call it # IDEA flask has a 'run-method-pre-this-route' annotation... oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=session['access_token'], refresh_token=session['refresh_token'], ) client = Client(oauth) return whoami_guts(client) + GOHOME def whoami_guts(client): # 'me' is a handy value to get info on the current authenticated user. me = client.user(user_id='me').get(fields=['login']) return ('<p>Box says your login name is: {0}</p>'.format(me['login'])) # another simple box api invocation @app.route('/mystuff') def mystuff(): # TODO extract this to a method so all routes can call it oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=session['access_token'], refresh_token=session['refresh_token'], ) client = Client(oauth) return mystuff_guts(client) + GOHOME def mystuff_guts(client): # 'me' is a handy value to get info on the current authenticated user. root = client.folder(folder_id='0').get() items = root.get_items(limit=50, offset=0) thegoods = ("<p>Box says these are some of your folders and items:</p>" + "<p>" + '<br/>'.join([item.name for item in items]) + "</p>") return thegoods ### just exercising redis sessions here. get or set. # storing session data in redis @app.route('/set/<key>/<value>') def set(key,value): session[key] = value return '<p>OK. <a href="/get/{}">Check it?</a></p>'.format(key) # getting it back @app.route('/get/<key>') def get(key): return session.get(key, 'not set') ### playing with fake username data in redis # landing page invites you to 'login', or remembers you if your # redis session has not yet expired. @app.route('/') def index(): if 'username' in session: # logged in? login_status = ''' <p>Logged in as %s. <a href="/logout">Logout</a></p> ''' % (escape(session['username'])) # box authorized? box_auth_status = ''' <p><a href="/auth/">Authorize Box?</a></p> ''' if 'refresh_token' in session: box_auth_status = ''' <p>Box authorized! <a href="/whoami">Use it</a>, and maybe <a href="/mystuff">use it again</a.</p> ''' # tell 'em how it is return login_status + box_auth_status return '<p>You are not logged in. <a href="/login">Login</a></p>' # be who you were meant to be... @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' # go back to oblivion... # TODO would make sense to purse the session entirely here, # but we're keeping it around until it expires naturally. @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) # only invoked when running a la 'python <thisfile>.py' # if you do 'flask run' you will not be in debug mode if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=True) <file_sep># Box SDK and Oauth2 in Flask Just a quick demo of authorizing the Box SDK via OauthW in a Flask app. Fake user logins are associated with sessions, and Flask-Sessions is used to store session keys/values in local Redis at 127.0.0.1:6379. To run, clone this repo, `cd` into it, and: % virtualenv env % . env/bin/activate % pip install -r requirements.txt % cp boxapp.cfg-sample boxapp.cfg % <edit boxapp.cfg to add your client_id and client_secret> % python flessions.py The `/auth/` route kicks off the Oauth2 journey, and the `/callback` route completes the circle. Once the access_token and refresh_token are stored in the session, we can pull them out to construct an authenticated Box client on-demand. The `/whoami` and `/mystuff` routes exercise the Box API after the application has been authorized, and the tokens stored. Lots to do here to make this sane regarding users, sessions, expiry, persistence, etc. <file_sep>Flask==2.3.2 Flask-Session==0.3.1 boxsdk==2.5.0 redis==4.4.4
3bf53177c2107ff92d922c897af80fb7612cc284
[ "Markdown", "Python", "Text" ]
3
Python
knoxilla/flessions
c488b1e070404d208f544737e4e096a23f16b46c
6309b453d6bfacc00bea98415b17b9e1366dcc9f
refs/heads/master
<repo_name>patrickmlong/axondeepseg<file_sep>/AxonDeepSeg/integrity_test.py # -*- coding: utf-8 -*- # Basic integrity test to check is AxonDeepSeg is correctly installed # Launches a segmentation in the data_test folder try: import json import os from AxonDeepSeg.testing.segmentation_scoring import * from time import time from scipy.misc import imread, imsave # input parameters path_testing = "../AxonDeepSeg/data_test/" model_name = 'default_SEM_model_v1' path_model = '../AxonDeepSeg/models/' + model_name path_configfile = path_model + '/config_network.json' if not os.path.exists(path_model): os.makedirs(path_model) with open(path_configfile, 'r') as fd: config_network = json.loads(fd.read()) from AxonDeepSeg.apply_model import axon_segmentation prediction = axon_segmentation([path_testing], ["image.png"], path_model, config_network,verbosity_level=0) mask = imread(path_testing + '/mask.png', flatten=True) pred = imread(path_testing + '/AxonDeepSeg.png', flatten=True) gt_axon = mask > 200 gt_myelin = np.logical_and(mask >= 50, mask <= 200) pred_axon = pred > 200 pred_myelin = np.logical_and(pred >= 50, pred <= 200) dice_axon = pw_dice(pred_axon, gt_axon) dice_myelin = pw_dice(pred_myelin, gt_myelin) print "* * * Integrity test passed. AxonDeepSeg is correctly installed. * * * " except IOError: print "Integrity test failed... " <file_sep>/AxonDeepSeg/testing/segmentation_scoring.py from skimage import measure from skimage.measure import regionprops import numpy as np import pandas as pd def score_analysis(img, groundtruth, prediction, visualization=False, min_area=2): """ Calculates segmentation score by keeping an only true centroids as TP. Excess of centroids detected for a unique object is counted by diffusion (Excess/TP+FN) Returns sensitivity (TP/P), precision (TP/TP+FN) and diffusion :param img: image to segment :param groundtruth: groundtruth of the image :param prediction: segmentation :param visualization: if True, FP and TP are displayed on the image :param min_area: minimal area of the predicted axon to count. :return: [sensitivity, precision, diffusion] """ labels_pred = measure.label(prediction) regions_pred = regionprops(labels_pred) centroids = np.array([list(x.centroid) for x in regions_pred]) centroids = centroids.astype(int) areas = np.array([x.area for x in regions_pred]) centroids = centroids[areas > min_area] labels_true = measure.label(groundtruth) regions_true = regionprops(labels_true) centroid_candidates = set([tuple(row) for row in centroids]) centroids_T = [] notDetected = [] n_extra = 0 for axon in regions_true: axon_coords = [tuple(row) for row in axon.coords] axon_center = (np.array(axon.centroid)).astype(int) centroid_match = set(axon_coords) & centroid_candidates centroid_candidates = centroid_candidates.difference(centroid_match) centroid_match = list(centroid_match) if len(centroid_match) != 0: diff = np.sum((centroid_match - axon_center) ** 2, axis=1) ind = np.argmin(diff) center = centroid_match[ind] centroids_T.append(center) n_extra += len(centroid_match) - 1 if len(centroid_match) == 0: notDetected.append(axon_center) centroids_F = list(centroid_candidates) P = len(regions_true) TP = len(centroids_T) FP = len(centroids_F) centroids_F = np.array(centroids_F) centroids_T = np.array(centroids_T) # not_detected = len(np.array(notDetected)) sensitivity = round(float(TP) / P, 3) # errors = round(float(FP) / P, 3) diffusion = float(n_extra) / (TP + FP) precision = round(float(TP) / (TP + FP), 3) if visualization: plt.figure(1) plt.imshow(img, cmap=plt.get_cmap('gray')) plt.hold(True) plt.imshow(prediction, alpha=0.7) plt.hold(True) plt.scatter(centroids_T[:, 1], centroids_T[:, 0], color='g') plt.hold(True) plt.scatter(centroids_F[:, 1], centroids_F[:, 0], color='r') plt.hold(True) plt.scatter(notDetected[:, 1], notDetected[:, 0], color='y') plt.title('Prediction, Sensitivity : %s , Precision : %s ' % (sensitivity, precision)) plt.figure(2) plt.imshow(img, cmap=plt.get_cmap('gray')) plt.hold(True) plt.imshow(groundtruth, alpha=0.7) plt.hold(True) plt.scatter(centroids_T[:, 1], centroids_T[:, 0], color='g') plt.hold(True) plt.scatter(centroids_F[:, 1], centroids_F[:, 0], color='r') plt.title('Ground Truth, Sensitivity : %s , Precision : %s ' % (sensitivity, precision)) plt.show() return [sensitivity, precision, round(diffusion, 4)] def dice(img, groundtruth, prediction, min_area=3): """ :param img: image to segment :param groundtruth : True segmentation :param prediction : Segmentation predicted by the algorithm :param min_area: minimum area of the predicted object to measure dice :return dice_scores: pandas dataframe associating the axon predicted, its size and its dice score To get the global dice score of the prediction, """ h, w = img.shape labels_true = measure.label(groundtruth) regions_true = regionprops(labels_true) labels_pred = measure.label(prediction) regions_pred = regionprops(labels_pred) features = ['coords', 'area', 'dice'] df = pd.DataFrame(columns=features) i = 0 for axon_predicted in regions_pred: centroid = (np.array(axon_predicted.centroid)).astype(int) if groundtruth[(centroid[0], centroid[1])] == 1: for axon_true in regions_true: if [centroid[0], centroid[1]] in axon_true.coords.tolist(): surface_pred = np.zeros((h, w)) surface_true = np.zeros((h, w)) surface_pred[axon_predicted.coords[:, 0], axon_predicted.coords[:, 1]] = 1 surface_true[axon_true.coords[:, 0], axon_true.coords[:, 1]] = 1 intersect = surface_pred * surface_true Dice = 2 * float(sum(sum(intersect))) / (sum(sum(surface_pred)) + sum(sum(surface_true))) df.loc[i] = [axon_predicted.coords, axon_predicted.area, Dice] break i += 1 dice_scores = df[df['area'] > min_area] return dice_scores def pw_dice(img1, img2): """ img1 and img2 are boolean masks ndarrays This functions compute the pixel-wise dice coefficient (not axon-wise but pixel wise) """ img_sum = img1.sum() + img2.sum() if img_sum == 0: return 1 intersection = np.logical_and(img1, img2) # Return the global dice coefficient return 2. * intersection.sum() / img_sum<file_sep>/AxonDeepSeg/invert_image.py import sys def invert_image(path_image): ''' :param image: path of the image to invert :return: Nothing. ''' from PIL import Image import PIL.ImageOps image = Image.open(path_image) inverted_image = PIL.ImageOps.invert(image) inverted_image.save(path_image) if __name__ == "__main__": path_image = string(sys.argv[1]) invert_image(path_image) <file_sep>/AxonDeepSeg/segment.py # Segmentation script # ------------------- # This script lets the user segment automatically one or many images based on the default segmentation models: SEM or # TEM. # # <NAME> - 2017-08-30 # Imports from AxonDeepSeg.apply_model import axon_segmentation import os, json from tqdm import tqdm import pkg_resources import argparse # Global variables SEM_DEFAULT_MODEL_NAME = "default_SEM_model_v1" TEM_DEFAULT_MODEL_NAME = "default_TEM_model_v1" MODELS_PATH = pkg_resources.resource_filename('AxonDeepSeg', 'models') # Definition of the functions def segment_image(path_testing_image, path_model, overlap_value, config, resolution_model, segmented_image_prefix, acquired_resolution = 0.0, verbosity_level=0): ''' Segment the image located at the path_testing_image location. :param path_testing_image: the path of the image to segment. :param path_model: where to access the model :param overlap_value: the number of pixels to be used for overlap when doing prediction. Higher value means less border effects but more time to perform the segmentation. :param config: dict containing the configuration of the network :param resolution_model: the resolution the model was trained on. :param segmented_image_prefix: the prefix to add before the segmented image. :param verbosity_level: Level of verbosity. The higher, the more information is given about the segmentation process. :return: Nothing. ''' if os.path.exists(path_testing_image): # Extracting the image name and its folder path from the total path. tmp_path = path_testing_image.split('/') acquisition_name = tmp_path[-1] path_acquisition = '/'.join(tmp_path[:-1]) # Performing the segmentation segmented_image_name = segmented_image_prefix + acquisition_name axon_segmentation(path_acquisitions_folders=path_acquisition, acquisitions_filenames=[acquisition_name], path_model_folder=path_model, config_dict=config, ckpt_name='model', inference_batch_size=1, overlap_value=overlap_value, segmentations_filenames=segmented_image_name, resampled_resolutions=resolution_model, verbosity_level=verbosity_level, acquired_resolution=acquired_resolution, prediction_proba_activate=False, write_mode=True) if verbosity_level >= 1: print "Image {0} segmented.".format(path_testing_image) else: print "The path {0} does not exist.".format(path_testing_image) return None def segment_folders(path_testing_images_folder, path_model, overlap_value, config, resolution_model, segmented_image_suffix, acquired_resolution = 0.0, verbosity_level=0): ''' Segments the images contained in the image folders located in the path_testing_images_folder. :param path_testing_images_folder: the folder where all image folders are located (the images to segment are located in those image folders) :param path_model: where to access the model. :param overlap_value: the number of pixels to be used for overlap when doing prediction. Higher value means less border effects but more time to perform the segmentation. :param config: dict containing the configuration of the network :param resolution_model: the resolution the model was trained on. :param segmented_image_suffix: the prefix to add before the segmented image. :param verbosity_level: Level of verbosity. The higher, the more information is given about the segmentation process. :return: Nothing. ''' # We loop over all image folders in the specified folded and we segment them one by one. # We loop through every file in the folder as we look for an image to segment for file_ in tqdm(os.listdir(path_testing_images_folder), desc="Segmentation..."): # We segment the image only if it's not already a segmentation. len_suffix = len(segmented_image_suffix)+4 # +4 for ".png" if (file_[-4:] == ".png") and (not (file_[-len_suffix:] == (segmented_image_suffix+'.png'))): # Performing the segmentation basename = file_.split('.') basename.pop() # We remove the extension. basename = ".".join(basename) segmented_image_name = basename + segmented_image_suffix + '.png' axon_segmentation(path_acquisitions_folders=path_testing_images_folder, acquisitions_filenames=[file_], path_model_folder=path_model, config_dict=config, ckpt_name='model', inference_batch_size=1, overlap_value=overlap_value, segmentations_filenames=[segmented_image_name], acquired_resolution=acquired_resolution, verbosity_level=verbosity_level, resampled_resolutions=resolution_model, prediction_proba_activate=False, write_mode=True) if verbosity_level >= 1: print "Image {0} segmented.".format(os.path.join(path_testing_images_folder, file_)) # The segmentation has been done for this image folder, we go to the next one. return None def generate_default_parameters(type_acquisition, new_path): ''' Generates the parameters used for segmentation for the default model corresponding to the type_model acquisition. :param type_model: String, the type of model to get the parameters from. :param new_path: Path to the model to use. :return: the config dictionary. ''' # Building the path of the requested model if it exists and was supplied, else we load the default model. if type_acquisition == 'SEM': if (new_path is not None) and (os.path.exists(new_path)): path_model = new_path else: path_model = os.path.join(MODELS_PATH, SEM_DEFAULT_MODEL_NAME) elif type_acquisition == 'TEM': if (new_path is not None) and (os.path.exists(new_path)): path_model = new_path else: path_model = os.path.join(MODELS_PATH, TEM_DEFAULT_MODEL_NAME) path_config_file = os.path.join(path_model, 'config_network.json') config = generate_config_dict(path_config_file) return path_model, config def generate_config_dict(path_to_config_file): ''' Generates the dictionary version of the configuration file from the path where it is located. :param path_to_config: relative path where the file config_network.json is located. :return: dict containing the configuration of the network, or None if no configuration file was found at the mentioned path. ''' try: with open(path_to_config_file, 'r') as fd: config_network = json.loads(fd.read()) except ValueError: print "No configuration file available at this path." config_network = None return config_network def generate_resolution(type_acquisition, model_input_size): ''' Generates the resolution to use related to the trained modeL. :param type_acquisition: String, "SEM" or "TEM" :param model_input_size: String or Int, the size of the input. :return: Float, the resolution of the model. ''' dict_size = { "SEM":{ "512":0.1, "256":0.2 }, "TEM":{ "512":0.01 } } return dict_size[str(type_acquisition)][str(model_input_size)] # Main loop def main(): ''' Main loop. :return: None. ''' ap = argparse.ArgumentParser() # Setting the arguments of the segmentation ap.add_argument("-t", "--type", required=True, help="Choose the type of acquisition you want to segment.") # type ap.add_argument("-i", "--imgpath", required=True, nargs='+', help="Folder where the images folders are located.") ap.add_argument("-m", "--model", required=False, help="Folder where the model is located.", default=None) ap.add_argument("-s", "--sizepixel", required=False, help="Pixel size in micrometers to use for the segmentation.", default=0.0) ap.add_argument("-v", "--verbose", required=False, help="Verbosity level.", default=0) ap.add_argument("-o", "--overlap", required=False, help="Overlap value when doing the segmentation. The higher the" "value, the longer it will take to segment the whole image.", default=25) # Processing the arguments args = vars(ap.parse_args()) type_ = str(args["type"]) verbosity_level = int(args["verbose"]) overlap_value = int(args["overlap"]) psm = float(args["sizepixel"]) path_target_list = args["imgpath"] new_path = args["model"] # Preparing the arguments to axon_segmentation function path_model, config = generate_default_parameters(type_, new_path) resolution_model = generate_resolution(type_, config["trainingset_patchsize"]) segmented_image_suffix = "_segmented" # Going through all paths passed into arguments for current_path_target in path_target_list: if (current_path_target[-4:] == '.png') and (not os.path.isdir(current_path_target)): # Performing the segmentation over the image segment_image(current_path_target, path_model, overlap_value, config, resolution_model, segmented_image_suffix, acquired_resolution=psm, verbosity_level=verbosity_level) else: # Performing the segmentation over all folders in the specified folder containing acquisitions to segment. segment_folders(current_path_target, path_model, overlap_value, config, resolution_model, segmented_image_suffix, acquired_resolution=psm, verbosity_level=verbosity_level) print "Segmentation finished." # Calling the script if __name__ == '__main__': main()
e931d4d3039060fddf261251ae0e91c1f8c1c00e
[ "Python" ]
4
Python
patrickmlong/axondeepseg
6c7d20a2fa3a19b323b3c1e87ded2c943a7e344e
44337643b990589a4239d8cefc70080b268e410d
refs/heads/master
<file_sep>AwesomeTkinter==2020.9.16 certifi==2020.6.20 chardet==3.0.4 debtcollector==2.2.0 EasyTkinter==1.1.0 fire==0.3.1 future==0.18.2 hdpitkinter==1.0.3 idna==2.10 ModTkinter==0.0.22 mttkinter==0.6.1 mutagen==1.45.1 netaddr==0.8.0 numpy==1.19.2 OmegaMath01==1.0.8 os-android-apk-builder==1.13 os-tools==4.48 oslo.config==8.3.2 oslo.i18n==5.0.1 packaging==20.4 pbr==5.5.0 Pillow==7.2.0 pygame==1.9.6 pyparsing==2.4.7 pyquickhelper==1.9.3418 python-dateutil==2.8.1 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 rfc3986==1.4.0 six==1.15.0 stevedore==3.2.2 termcolor==1.1.0 tkinter-fonts-viewer==0.1.1 Tkinter-Managed-Frame==1.0.3 tkinter-nav==0.0.5 tkinter.help==2.0 TkinterClock01==1.0.3 tkinterhtml==0.7 tkinterquickhelper==1.5.72 tkintertable==1.3.2 tkintertoy==1.3.0 tkinterx==0.0.9 urllib3==1.25.10 wrapt==1.12.1 <file_sep># Music Player This project is about creating a music player using python language. ### Setup - create virtual environment, we are using `venv` here ```python python -m venv venv ``` - activate virtual environment **windows** ```python venv/Scripts/activate.bat ``` **bash/linux** ```python . venv/bin/activate ``` - install requirements ```python pip install -r requirements.txt ``` - finally to run the music player ```python python Canvas.py ``` ### Contrubution To contribute to this project, find an issue to work on or create an issue for something new you want to add or fix. And make a pull request. ### Hacktoberfest Contribution If you are new and want to learn, you can start by improving documentation of the project, fix typos or improving readme <file_sep># system imports import os from mutagen.id3 import ID3 import random # pygame imports import pygame from pygame import mixer # tkinter imports from tkinter import * from tkinter.ttk import from tkinter.filedialog import askdirectory # initialization root = Tk() root.geometry('400x400+200+50') root.title("Music Player") root.iconbitmap("player.ico") root.resizable(False,False) listofsongs = [] index=0 v = StringVar() songlabel = Label(root, textvariable=v, width=50) def playsong(event): """ plays song @param: event : pygame event object """ pygame.mixer.music.play() pygame.mixer.unpause() updatelabel() def nextsong(event): """ plays next song @param: event : pygame event object """ global index index += 1 pygame.mixer.music.load(listofsongs[index]) pygame.mixer.music.play() updatelabel() def prevsong(event): """ plays prev song @param: event : pygame event object """ global index index -= 1 pygame.mixer.music.load(listofsongs[index]) pygame.mixer.music.play() updatelabel() def randomsong(event): """ plays random song @param: event : pygame event object """ x = random.randint(0, len(listofsongs)) pygame.mixer.music.load(listofsongs[x]) pygame.mixer.music.play() updatelabel(x) def stopsong(event): """ stops song @param: event : pygame event object """ pygame.mixer.music.stop() v.set("") def updatelabel(loc=None): """ update's label to present songs name @param: loc : int, index location of the present song playing """ global index # if loc is passed then play song at that index # otherwise if loc is not None: v.set(listofsongs[loc]) else: v.set(listofsongs[index]) def directorychooser(): """ function to choose the directory containing the songs """ directory = askdirectory() os.chdir(directory) for files in os.listdir(directory): if files.endswith(".mp3"): listofsongs.append(files) print(files) pygame.mixer.init() pygame.mixer.music.load(listofsongs[0]) directorychooser() label = Label(root, text=f"Music List-{len(listofsongs)}Songs") label.pack() listbox = Listbox(root) listbox.pack() listofsongs.reverse() for items in listofsongs: listbox.insert(0,items) listofsongs.reverse() playbutton = Button(root, text="Play") playbutton.pack() nextbutton = Button(root,text="Next Song") nextbutton.pack() randombutton = Button(root,text="Random Song") randombutton.pack() previousbutton = Button(root,text="Previous Song") previousbutton.pack() stopbutton = Button(root,text="Stop") stopbutton.pack() playbutton.bind("<Button-1>", playsong) nextbutton.bind("<Button-1>", nextsong) randombutton.bind("<Button-1>", randomsong) previousbutton.bind("<Button-1>", prevsong) stopbutton.bind("<Button-1>", stopsong) songlabel.pack() root.mainloop()
d0f154037b62fe128470a42cd9a3c04975e599e7
[ "Markdown", "Python", "Text" ]
3
Text
RishabhP24/Music-Player
7ade756642b43b7ca70fc9b292b3befc958eb8f9
2f21368fcca58f78d9edb38b93fb913f5ebe5405
refs/heads/master
<file_sep><?php namespace Plata\Fravel; use League\Fractal\Manager; use Illuminate\Support\ServiceProvider; use Illuminate\Contracts\View\Factory as ViewFactoryContract; class FravelServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $this->bootConfigurationFiles(); $this->commands('command.make.transformer'); } /** * Register the application services. * * @return void */ public function register() { $this->registerFacade(); $this->registerFractalManager(); $this->registerFravelResponse(); $this->registerTransformerGenerator(); } private function registerFacade() { $this->app->singleton('Fractal', function () { return new FractalResourceFactory(); }); } private function registerFractalManager() { $this->app->singleton(Manager::class, function () { $manager = new Manager(); $url = \URL::to(config('fravel.base_link', '/')); $serializer = config('fravel.serializer', \League\Fractal\Serializer\DataArraySerializer::class); $manager->setSerializer(new $serializer($url)); return $manager; }); } private function registerFravelResponse() { \Response::swap(new \Plata\Fravel\Response( $this->app[ViewFactoryContract::class], $this->app['redirect'], $this->app[Manager::class] )); } private function registerTransformerGenerator() { $this->app->singleton('transformer.creator', function ($app) { return new TransformerCreator($app['files']); }); $this->app->singleton('command.make.transformer', function ($app) { // Once we have the migration creator registered, we will create the command // and inject the creator. The creator is responsible for the actual file // creation of the transformers, and may be extended by developers. $creator = $app['transformer.creator']; $composer = $app['composer']; return new TransformerMakeCommand($creator, $composer); }); } private function bootConfigurationFiles() { $this->publishes([ __DIR__.'/config/config.php' => app()->basePath() . '/config/fravel.php', ]); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ 'Fractal', 'transformer.creator', 'command.make.transformer' ]; } } <file_sep># Fravel [![License](https://img.shields.io/badge/license-MIT-orange.svg)](https://packagist.org/packages/plata/fravel) A Fractal wrapper for Laravel Fractal is designed in such a way that it could be used by any frameworks or no framework at all. But wouldn't it be cool if we can use it like it's build right on top of Laravel? ## Installation ### Composer ```shell composer require plata/fravel ``` Then in your `config/app.php`'s provider array: ```php 'providers' => [ // ... 'Plata\Fravel\FravelServiceProvider::class', // ... ] ``` and within the same file, ```php 'aliases' => [ // ... ''Fractal' => \Plata\Fravel\Facade\Fractal::class', // ... ] ``` ## Usage For a collection of resource, ```php $resource = Fractal::collection(User::all(), $transformer); return Response::fractal($resource); ``` For a single resource, ```php $resource = Fractal::item(User::find(1), $transformer); return Response::fractal($resource); ``` ## Generators Everyone knows that developers doesn't like repetitive tasks. That's why generators are really helpful for creating a base template for you! ### Transformers Existing Model and Migration ```shell php artisan make:transformer UserTransformer ``` For non existing model/migration, just append `-t` flag ```shell php artisan make:model User -m -t ``` ## Configurations Fravel ships with a configuration file where you can change any Fractal specific behaviour. Just run: ```shell php artisan vendor:publish ``` ## Support Need more control? Check this thorough documentation of Fravel. <file_sep><?php namespace Plata\Fravel; use Illuminate\Filesystem\Filesystem; class TransformerCreator { /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * Stub content. * * @var string */ protected $stub; /** * Create a new transformer creator instance. * * @param \Illuminate\Filesystem\Filesystem $files * @return void */ public function __construct(Filesystem $files) { $this->files = $files; } public function create($name, $path) { // Get the class template. $stub = $this->files->get(__DIR__.'/stubs/transformer.stub'); // Make sure the path exists. if (!$this->files->exists($path)) $this->files->makeDirectory($path); // Write the generated template. $this->files->put( $path.'/'.$name.'Transformer.php', $this->populateStub($stub, $name) ); } protected function populateStub($stub, $name) { $this->stub = $stub; $defaultNamespace = config('app.name') == 'Laravel' ? 'App' : config('app.name'); return $this->setClassName($name) ->setTransformerNamespace($defaultNamespace) ->setModelNamespace($name) ->setParameterType($name) ->setParameterName($name) ->stub; } private function setClassName($name) { $this->stub = str_replace( 'StubTransformer', $name.'Transformer', $this->stub ); return $this; } private function setTransformerNamespace($namespace) { $this->stub = str_replace( 'Namespace', $namespace.'\\Transformers', $this->stub ); return $this; } private function setModelNamespace($name) { $this->stub = str_replace( 'use Model', 'use '.config('fravel.model_namespace').'\\'.$name, $this->stub ); return $this; } private function setParameterType($name) { $this->stub = str_replace( 'ModelInstance', $name, $this->stub ); return $this; } private function setParameterName($name) { $this->stub = str_replace( '$model', '$'.strtolower($name), $this->stub ); return $this; } }<file_sep><?php namespace Plata\Fravel; use League\Fractal\Resource\Item; use League\Fractal\Resource\Collection; class FractalResourceFactory { /** * Create a new resource instance. * * @param mixed $data * @param callable|TransformerAbstract|null $transformer * @param string $resourceKey * @return Item */ public function item($data, $transformer, $resourceKey) { return new Item($data, $transformer, $resourceKey); } /** * Create a new resource instance. * * @param mixed $data * @param callable|TransformerAbstract|null $transformer * @param string $resourceKey * @return Collection */ public function collection($data, $transformer, $resourceKey) { return new Collection($data, $transformer, $resourceKey); } }<file_sep><?php namespace Plata\Fravel; use Illuminate\Console\Command; use Illuminate\Support\Composer; class TransformerMakeCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:transformer {name : The name of the transformer.}'; /** * The console command description. * * @var string */ protected $description = 'Creates a new transformer class'; /** * TransformerCreator instance. * * @var TransformerCreator */ private $transformerCreator; /** * Composer instance. * * @var Composer */ private $composer; /** * Create a new command instance. * * @param TransformerCreator $transformerCreator * @param Composer $composer * @return void */ public function __construct(TransformerCreator $transformerCreator, Composer $composer) { parent::__construct(); $this->transformerCreator = $transformerCreator; $this->composer = $composer; } /** * Execute the console command. * * @return mixed */ public function handle() { $name = trim($this->input->getArgument('name')); // Checks to see if the name already has a Transformer suffix. $name = str_contains($name, 'Transformer') ? str_replace('Transformer', '', $name) : $name; $this->transformerCreator->create($name, app_path('Transformers')); $this->line("<info>Transformer created successfully.</info>"); $this->composer->dumpAutoloads(); } } <file_sep><?php namespace Plata\Fravel; use League\Fractal\Manager; use Illuminate\Http\JsonResponse; use Illuminate\Routing\ResponseFactory; use League\Fractal\Resource\ResourceAbstract; class Response extends ResponseFactory { /** * Fractal manager instance. * * @var Manager */ protected $fractalManager; /** * Create a new response factory instance. * * @param \Illuminate\Contracts\View\Factory $view * @param \Illuminate\Routing\Redirector $redirector * @param Manager $fractalManager * @return void */ public function __construct(\Illuminate\Contracts\View\Factory $view, \Illuminate\Routing\Redirector $redirector, Manager $fractalManager) { parent::__construct($view, $redirector); $this->fractalManager = $fractalManager; } /** * Return a new JSON response from the application. * * @param ResourceAbstract $data * @param int $status * @param array $headers * @param int $options * @return \Illuminate\Http\JsonResponse */ public function fractal(ResourceAbstract $data, $status = 200, array $headers = [], $options = 0) { return new JsonResponse($this->fractalManager->createData($data)->toArray(), $status, $headers, $options); } }<file_sep><?php /** * This file is part of Fravel, * a Fractal wrapper for Laravel. * * @license MIT * @package Plata\Fravel */ return [ /* |-------------------------------------------------------------------------- | Json Serializer |-------------------------------------------------------------------------- | | This is the default json serializer that will be used throughout | the entire response. Of course you can override this if you | want to set the serializer to only a certain response. | */ 'serializer' => \League\Fractal\Serializer\DataArraySerializer::class, /* |-------------------------------------------------------------------------- | Resource base link |-------------------------------------------------------------------------- | | This will be use to generate resource links. | */ 'base_link' => '/', 'model_namespace' => 'App' ];
7e44b5f01ae028682701e4a760921e311d5520b7
[ "Markdown", "PHP" ]
7
PHP
silverxjohn/fravel
be18464c74e5a21259e048e1401e6d319e089f43
1d2db0bbdc9dbd74cc8a7db097f33efdb94b7c41
refs/heads/master
<file_sep><?php if(! function_exists("string_plural_select_pl")) { function string_plural_select_pl($n){ return ($n==1 ? 0 : ($n%10>=2 && $n%10<=4) && ($n%100<12 || $n%100>14) ? 1 : $n!=1 && ($n%10>=0 && $n%10<=1) || ($n%10>=5 && $n%10<=9) || ($n%100>=12 && $n%100<=14) ? 2 : 3);; }} ; $a->strings["bitchslap"] = ""; $a->strings["bitchslapped"] = ""; $a->strings["shag"] = "czupryna"; $a->strings["shagged"] = ""; $a->strings["do something obscenely biological to"] = "zrobić coś nieprzyzwoicie biologicznego"; $a->strings["did something obscenely biological to"] = "zrobił coś nieprzyzwoicie biologicznego"; $a->strings["point out the poke feature to"] = "zwróć uwagę na funkcję poke"; $a->strings["pointed out the poke feature to"] = "wskazał na funkcję poke do"; $a->strings["declare undying love for"] = "zadeklaruję dozgonną miłość do"; $a->strings["declared undying love for"] = "deklaruję dozgonną miłość dla"; $a->strings["patent"] = "patent"; $a->strings["patented"] = "opatentowane"; $a->strings["stroke beard"] = ""; $a->strings["stroked their beard at"] = ""; $a->strings["bemoan the declining standards of modern secondary and tertiary education to"] = "opłakują upadające standardy nowoczesnej szkoły średniej i wyższej"; $a->strings["bemoans the declining standards of modern secondary and tertiary education to"] = "żałuje upadających standardów nowoczesnej edukacji na poziomie średnim i wyższym"; $a->strings["hug"] = "objął"; $a->strings["hugged"] = "objąć"; $a->strings["kiss"] = "pocałunek"; $a->strings["kissed"] = "ucałować"; $a->strings["raise eyebrows at"] = "podnieś brwi"; $a->strings["raised their eyebrows at"] = "podnieśli brwi"; $a->strings["insult"] = "obraza"; $a->strings["insulted"] = "znieważony"; $a->strings["praise"] = "pochwała"; $a->strings["praised"] = "pochwalić"; $a->strings["be dubious of"] = "być wątpliwe"; $a->strings["was dubious of"] = "było wątpliwe"; $a->strings["eat"] = "jeść"; $a->strings["ate"] = "jadł"; $a->strings["giggle and fawn at"] = "chichotać i płakać"; $a->strings["giggled and fawned at"] = ""; $a->strings["doubt"] = "wątpić"; $a->strings["doubted"] = "powątpiewać"; $a->strings["glare"] = "blask"; $a->strings["glared at"] = "spojrzał na"; <file_sep><?php if(! function_exists("string_plural_select_pl")) { function string_plural_select_pl($n){ return ($n==1 ? 0 : ($n%10>=2 && $n%10<=4) && ($n%100<12 || $n%100>14) ? 1 : $n!=1 && ($n%10>=0 && $n%10<=1) || ($n%10>=5 && $n%10<=9) || ($n%100>=12 && $n%100<=14) ? 2 : 3);; }} ; $a->strings["Post to LiveJournal"] = "Opublikuj w LiveJournal"; $a->strings["LiveJournal Post Settings"] = "Ustawienia Postów LiveJournal"; $a->strings["Enable LiveJournal Post Addon"] = "Włącz dodatek LiveJournal"; $a->strings["LiveJournal username"] = "Nazwa użytkownika LiveJournal"; $a->strings["LiveJournal password"] = "<PASSWORD>"; $a->strings["Post to LiveJournal by default"] = "Opublikuj domyślnie w LiveJournal"; $a->strings["Submit"] = "Wyślij"; <file_sep><?php /** * Name: Forum Directory * Description: Add a directory of forums hosted on your server, with verbose descriptions. * Version: 1.0 * Author: <NAME> <https://beardyunixer.com/profile/beardyunixer> */ use Friendica\Content\Nav; use Friendica\Content\Widget; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Database\DBM; use Friendica\Model\Profile; use Friendica\Util\Temporal; require_once 'boot.php'; require_once 'include/dba.php'; require_once 'include/text.php'; function forumdirectory_install() { Addon::registerHook('app_menu', 'addon/forumdirectory/forumdirectory.php', 'forumdirectory_app_menu'); } function forumdirectory_uninstall() { Addon::unregisterHook('app_menu', 'addon/forumdirectory/forumdirectory.php', 'forumdirectory_app_menu'); } function forumdirectory_module() { return; } function forumdirectory_app_menu($a, &$b) { $b['app_menu'][] = '<div class="app-title"><a href="forumdirectory">' . L10n::t('Forum Directory') . '</a></div>'; } function forumdirectory_init(&$a) { $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/forumdirectory/forumdirectory.css" media="all" />'; $a->set_pager_itemspage(60); if (local_user()) { $a->page['aside'] .= Widget::findPeople(); } else { unset($_SESSION['theme']); } } function forumdirectory_post(&$a) { if (x($_POST, 'search')) { $a->data['search'] = $_POST['search']; } } function forumdirectory_content(&$a) { if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) { notice(L10n::t('Public access denied.') . EOL); return; } $o = ''; Nav::setSelected('directory'); if (x($a->data, 'search')) { $search = notags(trim($a->data['search'])); } else { $search = ((x($_GET, 'search')) ? notags(trim(rawurldecode($_GET['search']))) : ''); } $tpl = get_markup_template('directory_header.tpl'); $globaldir = ''; $gdirpath = Config::get('system', 'directory'); if (strlen($gdirpath)) { $globaldir = '<ul><li><div id="global-directory-link"><a href="' . Profile::zrl($gdirpath, true) . '">' . L10n::t('Global Directory') . '</a></div></li></ul>'; } $admin = ''; $o .= replace_macros($tpl, [ '$search' => $search, '$globaldir' => $globaldir, '$desc' => L10n::t('Find on this site'), '$admin' => $admin, '$finding' => (strlen($search) ? '<h4>' . L10n::t('Finding: ') . "'" . $search . "'" . '</h4>' : ""), '$sitedir' => L10n::t('Site Directory'), '$submit' => L10n::t('Find') ]); $sql_extra = ''; if (strlen($search)) { $sql_extra = " AND MATCH (`profile`.`name`, `user`.`nickname`, `pdesc`, `locality`,`region`,`country-name`," . "`gender`,`marital`,`sexual`,`about`,`romance`,`work`,`education`,`pub_keywords`,`prv_keywords` )" . " AGAINST ('" . dbesc($search) . "' IN BOOLEAN MODE) "; } $publish = Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 "; $r = q("SELECT COUNT(*) AS `total` FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`" . " WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 AND `page-flags` = 2 $sql_extra "); if (DBM::is_result($r)) { $a->set_pager_total($r[0]['total']); } $order = " ORDER BY `name` ASC "; $r = q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`" . " FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` WHERE `is-default` = 1 $publish" . " AND `user`.`blocked` = 0 AND `page-flags` = 2 $sql_extra $order LIMIT %d , %d ", intval($a->pager['start']), intval($a->pager['itemspage']) ); if (DBM::is_result($r)) { if (in_array('small', $a->argv)) { $photo = 'thumb'; } else { $photo = 'photo'; } foreach ($r as $rr) { $profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']); $pdesc = (($rr['pdesc']) ? $rr['pdesc'] . '<br />' : ''); $details = ''; if (strlen($rr['locality'])) { $details .= $rr['locality']; } if (strlen($rr['region'])) { if (strlen($rr['locality'])) { $details .= ', '; } $details .= $rr['region']; } if (strlen($rr['country-name'])) { if (strlen($details)) { $details .= ', '; } $details .= $rr['country-name']; } if (strlen($rr['dob']) && ($years = Temporal::getAgeByTimezone($rr['dob'], $rr['timezone'], '')) != 0) { $details .= '<br />' . L10n::t('Age: ') . $years; } if (strlen($rr['gender'])) { $details .= '<br />' . L10n::t('Gender: ') . $rr['gender']; } switch ($rr['page-flags']) { case PAGE_NORMAL : $page_type = "Personal Profile"; break; case PAGE_SOAPBOX : $page_type = "Fan Page" ; break; case PAGE_COMMUNITY: $page_type = "Community Forum" ; break; case PAGE_FREELOVE : $page_type = "Open Forum" ; break; case PAGE_PRVGROUP : $page_type = "Private Group" ; break; } $profile = $rr; $location = ''; if (x($profile, 'address') == 1 || x($profile, 'locality') == 1 || x($profile, 'region') == 1 || x($profile, 'postal-code') == 1 || x($profile, 'country-name') == 1 ) { $location = L10n::t('Location:'); } $gender = x($profile, 'gender') == 1 ? L10n::t('Gender:') : false; $marital = x($profile, 'marital') == 1 ? L10n::t('Status:') : false; $homepage = x($profile, 'homepage') == 1 ? L10n::t('Homepage:') : false; $about = x($profile, 'about') == 1 ? L10n::t('About:') : false; $tpl = get_markup_template('forumdirectory_item.tpl', 'addon/forumdirectory/'); $entry = replace_macros($tpl, [ '$id' => $rr['id'], '$profile_link' => $profile_link, '$photo' => $rr[$photo], '$alt_text' => $rr['name'], '$name' => $rr['name'], '$details' => $pdesc . $details, '$page_type' => $page_type, '$profile' => $profile, '$location' => $location, '$gender' => $gender, '$pdesc' => $pdesc, '$marital' => $marital, '$homepage' => $homepage, '$about' => $about, ]); $o .= $entry; } $o .= "<div class=\"directory-end\" ></div>\r\n"; $o .= paginate($a); } else { info(L10n::t("No entries \x28some entries may be hidden\x29.") . EOL); } return $o; } <file_sep>Twitter Addon ============== Main authors <NAME>, <NAME> and <NAME>. This bi-directional connector addon allows each user to crosspost their Friendica public posts to Twitter, import their Twitter timeline, interact with tweets from Friendica, and crosspost to Friendica their public tweets. ## Installation To use this addon you have to register an [application](https://apps.twitter.com/) for your Friendica instance on Twitter. Please leave the field "Callback URL" empty. After the registration please enter the values for "Consumer Key" and "Consumer Secret" in the [administration](admin/addons/twitter). ## License The _Twitter Connector_ is licensed under the [3-clause BSD license][2] see the LICENSE file in the addons directory. The _Twitter Connector_ uses the [Twitter OAuth library][2] by <NAME>, MIT licensed [1]: http://opensource.org/licenses/BSD-3-Clause [2]: https://github.com/abraham/twitteroauth <file_sep><?php if(! function_exists("string_plural_select_nl")) { function string_plural_select_nl($n){ return ($n != 1);; }} ; $a->strings["Geonames settings updated."] = "Geonames instellingen bijgewerkt."; $a->strings["Geonames Settings"] = ""; $a->strings["Enable Geonames Addon"] = ""; $a->strings["Submit"] = "";
45ea01b4dc9d51c71c7d64220d45981de16efc5c
[ "Markdown", "PHP" ]
5
PHP
JeroenED/friendica-addons
97108080c26ab7b98b30e4b6c61f057314b44577
2b55bb47621674856cb10df490ff17364212fcde
refs/heads/master
<repo_name>DreamN/Multiuserblog<file_sep>/models.py from google.appengine.ext import db class Post(db.Model): """Post Model""" subject = db.StringProperty(required=True) author = db.StringProperty(required=True) content = db.TextProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) class Comment(db.Model): """Comment Model""" post = db.StringProperty(required=True) user = db.StringProperty(required=True) content = db.TextProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) class Like(db.Model): """Like Model""" post = db.StringProperty(required=True) user = db.StringProperty(required=True) <file_sep>/README.md # Multi User Blog ## This multi user blog web app is a project submitted to Udacity's nanodegrees full stack developer course **To run website* - Clone [Multi User Blog](https://github.com/DreamN/Multiuserblog) (This Project) ``` $git clone https://github.com/DreamN/Multiuserblog.git ``` - Install Python 2 - Install [Google App Engine SDK](https://cloud.google.com/appengine/downloads#Google_App_Engine_SDK_for_Python) - run website(when developing) ``` dev_appserver.py . ``` - run website(Deploy) ``` gcloud app deploy ``` ## Features - Signup, Login and Logout (User account) - Change password and email (User account) - Add, Edit, Delete Post (Users only be able to edit/delete their own posts) - Like/Unlike and Comment Post! - Profile for user - storing passwords by hashing - edit/delete comment<file_sep>/auth.py import webapp2 import random import hashlib from string import letters from google.appengine.ext import db import blog def make_salt(length=5): """make salt for hashing""" return ''.join(random.choice(letters) for x in xrange(length)) def make_pw_hash(name, pw, salt=None): """make hashed password""" if not salt: salt = make_salt() h = hashlib.sha256(name + pw + salt).hexdigest() return '%s,%s' % (salt, h) def valid_pw(name, password, h): """password validation""" salt = h.split(',')[0] return h == make_pw_hash(name, password, salt) def users_key(group='default'): """user key""" return db.Key.from_path('users', group) class User(db.Model): """User Model""" username = db.StringProperty(required=True) password = db.StringProperty(required=True) email = db.StringProperty(required=False) @classmethod def by_id(cls, uid): """Get user by ID""" return User.get_by_id(uid, parent=users_key()) @classmethod def by_username(cls, username): """Get user by Username""" u = User.all().filter('username =', username).get() return u @classmethod def register(cls, username, password, email=None): """Register User""" pw_hash = make_pw_hash(username, password) return User(parent=users_key(), username=username, password=<PASSWORD>, email=email) @classmethod def login(cls, username, password): """Login User""" u = cls.by_username(username) if u and valid_pw(username, password, u.password): return u @classmethod def set_password(cls, username, old_password, new_password): """Set New Password for User""" u = cls.by_username(username) if u and valid_pw(username, old_password, u.password): pw_hash = make_pw_hash(username, new_password) u.password = <PASSWORD> return u else: return False <file_sep>/blog.py import auth import os import webapp2 import jinja2 import re import hmac from string import letters from pprint import pprint from google.appengine.ext import db from models import Post, Comment, Like SECRET = 'MayTheForceBeWithYou' BLOG_TITLE = 'This is my blog' POST_LIMIT = 10 # Post display in 'home' page limit template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True) 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) def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) def make_secure_val(val): return '%s|%s' % (val, hmac.new(SECRET, val).hexdigest) def check_secure_val(secure_val): val = secure_val.split('|') val2 = make_secure_val(val[0]).split('|') if val[0] == val2[0]: return val[0] class BaseHandler(webapp2.RequestHandler): def render(self, template, **kw): kw['blog_title'] = BLOG_TITLE if self.user: kw['user'] = self.user else: kw['user'] = False self.response.out.write(render_str(template, **kw)) def write(self, *a, **kw): self.response.out.write(*a, **kw) def set_secure_cookie(self, name, val): cookie_val = make_secure_val(val) self.response.headers.add_header( 'Set-Cookie', '%s=%s; Path=/' % (name, cookie_val)) def read_secure_cookie(self, name): cookie_val = self.request.cookies.get(name) return cookie_val and check_secure_val(cookie_val) def login(self, user): self.set_secure_cookie('user_id', str(user.key().id())) def logout(self): self.response.headers.add_header('Set-Cookie', 'user_id=; Path=/') def login_required(self): if not self.user: self.redirect('/login') return False return True def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) uid = self.read_secure_cookie('user_id') self.user = uid and auth.User.by_id(int(uid)) # <<<----Views---->>> class Welcome(BaseHandler): """Welcome Page of Blog""" def render_front(self): posts = db.GqlQuery("SELECT * FROM Post " "ORDER BY created DESC")[:POST_LIMIT] self.render('index.html', posts=posts) def get(self): self.render_front() class SignUp(BaseHandler): """Signup Page""" def get(self): self.render('signup.html') def post(self): self.username = self.request.get('username') self.password = self.request.get('<PASSWORD>') self.verify = self.request.get('verify') self.email = self.request.get('email') have_error = False params = {'username': self.username, 'password': <PASSWORD>} if not valid_username(self.username): params['error_username'] = "That's not a valid username." have_error = True if not valid_password(self.password): params['error_password'] = "That wasn't a valid password." have_error = True elif self.password != self.verify: params['error_verify'] = "Your passwords didn't match." have_error = True if not valid_email(self.email): params['error_email'] = "That's not a valid email." have_error = True if have_error: self.render('signup.html', **params) else: self.done() def done(self): # make sure the user doesn't already exist u = auth.User.by_username(self.username) if u: msg = 'That user already exists.' self.render('signup.html', error_username=msg) else: u = auth.User.register(self.username, self.password, self.email) u.put() self.login(u) self.redirect('/profile') class Login(BaseHandler): """Login Page""" def get(self): self.render('login.html') def post(self): username = self.request.get('username') password = self.request.get('password') u = auth.User.login(username, password) if u: self.login(u) self.redirect('/') else: msg = 'Invalid login' self.render('login.html', error_message=msg) class Logout(BaseHandler): """Logout and Redirect to Signup page""" def get(self): self.logout() self.redirect('/signup') class NewPost(BaseHandler): """New Post Page (For Create a new post)""" def get(self): if self.login_required(): self.render('newpost.html') def post(self): if self.login_required(): subject = self.request.get('subject') content = self.request.get('content') if subject and content: p = Post(subject=subject, author=self.user.username, content=content) p.put() p_id = p.key().id() self.redirect('/post/'+str(p_id)) else: error_message = 'both subject and content is required!' self.render('newpost.html', error_message=error_message, subject=subject, content=content) class PostPage(BaseHandler): """Page of each post""" def get(self, post_id=""): p = Post.get_by_id(int(post_id)) comments = Comment.all().filter('post = ', post_id) comments = sorted(comments, key=lambda x: x.created, reverse=True) like = Like.all().filter('post = ', post_id) like_amount = like.count() if self.user: like_able = not p.author == self.user.username liked = like.filter('user = ', self.user.username).get() self.render('post.html', post=p, editable=not like_able, comments=comments, liked=liked, like_able=like_able, like_amount=like_amount) else: self.render('post.html', post=p, comments=comments) def post(self, post_id=""): if self.login_required(): if 'like_post' in str(self.request): # Like or unlike like_post = self.request.get('like_post') p = Post.get_by_id(int(post_id)) if not p.author == self.user.username: if like_post == 'Like': l = Like(post=post_id, user=self.user.username) l.put() elif like_post == 'Unlike': try: l = Like.all().filter('post = ', post_id) l = l.filter('user = ', self.user.username).get() l.delete() except: print('Like isn\'t exist') else: self.write('You can\'t Like\\Unlike your own post') else: # Comment p = Post.get_by_id(int(post_id)) content = self.request.get('comment') comment = Comment(post=post_id, user=self.user.username, content=content) comment.put() self.redirect('/post/'+post_id) class Profile(BaseHandler): """User's Profile Page (Detail, user's post)""" def get(self): if self.login_required(): p = Post.all().filter('author = ', self.user.username) self.render('profile.html', profile_user=self.user, posts=p) class EditPage(BaseHandler): """Page that display when edit post""" def get(self, post_id=""): if self.login_required(): p = Post.get_by_id(int(post_id)) if p.author == self.user.username: self.render('newpost.html', subject=p.subject, content=p.content, edit=True, post_id=post_id) else: self.render('permissionerror.html', item=p.subject) def post(self, post_id=""): if self.login_required(): p = Post.get_by_id(int(post_id)) subject = self.request.get('subject') content = self.request.get('content') if p.author == self.user.username: if subject and content: p.subject = subject p.content = content p.put() self.redirect('/post/'+post_id) else: error_message = 'both subject and content is required!' self.render('newpost.html', error_message=error_message, subject=subject, content=content) else: self.render('permissionerror.html', item=p.subject) class DeletePage(BaseHandler): """Delete Post Comfirmation Page""" def get(self, post_id=""): if self.login_required(): p = Post.get_by_id(int(post_id)) if p.author == self.user.username: self.render('deletepage.html', item=p.subject, post_id=post_id) else: self.render('permissionerror.html', item=p.subject) def post(self, post_id=""): if self.login_required(): confirm = self.request.get('confirm') if confirm == 'Delete': p = Post.get_by_id(int(post_id)) p.delete() self.redirect('/') class EditComment(BaseHandler): """Page that display when edit comment""" def get(self, comment_id=""): if self.login_required(): c = Comment.get_by_id(int(comment_id)) if c.user == self.user.username: self.render('editcomment.html', content=c.content, post_id=c.post) else: self.render('permissionerror.html', item='this comment') def post(self, comment_id=""): if self.login_required(): c = Comment.get_by_id(int(comment_id)) content = self.request.get('content') if c.user == self.user.username: if content: c.content = content c.put() self.redirect('/post/'+c.post) else: er_msg = 'Comment\'s content is required' self.render('editcomment.html', error_message=er_msg, content=content) else: self.render('permissionerror.html', item='this comment') class DeleteComment(BaseHandler): """Delete Comment Confirmation Page""" def get(self, comment_id=""): if self.login_required(): c = Comment.get_by_id(int(comment_id)) if c.user == self.user.username: self.render('deletepage.html', item='this comment', post_id=c.post) else: self.redirect('/post/'+c.post) def post(self, comment_id=""): if self.login_required(): confirm = self.request.get('confirm') if confirm == 'Delete': c = Comment.get_by_id(int(comment_id)) p = c.post c.delete() self.redirect('/post/'+p) class Setting(BaseHandler): """User's Setting Page (able to change email and password)""" def get(self): if self.login_required(): self.render('setting.html', email=self.user.email) def post(self): if self.login_required(): email = self.request.get('email') old_password = self.request.get('old_password') password = self.request.get('password') verify = self.request.get('verify') u = self.user have_error = False params = {'email': email} if not valid_email(email): params['error_email'] = "That's not a valid email." have_error = True if not valid_password(password): params['error_password'] = "That wasn't a valid password." have_error = True if password != verify: params['error_verify'] = "Your passwords didn't match." have_error = True u_new = auth.User.set_password(u.username, old_password, password) if not u_new: params['error_old_password'] = "Your old password is invalid" have_error = True if not have_error: u_new.email = email u_new.put() self.redirect('/profile') else: self.render('setting.html', **params) app = webapp2.WSGIApplication([(r'/', Welcome), (r'/newpost', NewPost), (r'/post/(\d+)', PostPage), (r'/edit/(\d+)', EditPage), (r'/delete/(\d+)', DeletePage), (r'/edit-comment/(\d+)', EditComment), (r'/delete-comment/(\d+)', DeleteComment), (r'/profile', Profile), (r'/setting', Setting), (r'/signup', SignUp), (r'/login', Login), (r'/logout', Logout)], debug=True)
486f874b4ba3125e3956e6d09bdc2297de186cc0
[ "Markdown", "Python" ]
4
Python
DreamN/Multiuserblog
873739ea01d19d4a37616360704d1ee9fbb69fae
b86fd47925218b007ee0066c78253237f74ff9e9
refs/heads/main
<repo_name>SamuelMontague/codeQuiz<file_sep>/README.md # hw4-quiz [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)] # Description This front-end application creates a quiz about coding language that we have learned in the bootcamp so far! ![screenshot](./images/pwss.PNG) # Table of Contents * [Usage](#usage) * [License](#license) * [Contributing](#contributing) * [Questions](#questions) # Usage The user can take the quiz to achieve a high score. # License This application is covered by the MIT license. # Contributing Contributors: <NAME> # Questions If you have any questions about the repo, open an issue or contact me directly at <EMAIL>. You can find more of my work at (https://github.com/SamuelMontague/). <file_sep>/script.js const startButton = document.getElementById("start"); const question = document.getElementById("question"); const scoreContainer = document.getElementById("scoreContainer"); const choices = Array.from(document.querySelectorAll('.selection')) var secondsLeft = 100; let currentQuestion = {} let acceptingAnswers = true let score = 0 let questionCounter = 0 let availableQuestions = [] let questions = [ { question: "What color is the sky?", A : "blue", B : "red", C : "green", D : "yellow", correct : [1], },{ question: "What color is grass?", A : "purple", B : "green", C : "yellow", D : "black", correct : [2], },{ question: "Which one of these is not a primary color", A : "yellow", B : "blue", C : "green", D : "red", correct : [3], } ]; const Score_Points = 100 const max_Questions = 3 startGame = function() { currentQuestion = 0 score = 0 availableQuestions = [...questions] getNewQuestion() } function startTimer() { setInterval(function(){ secondsLeft--; if (secondsLeft > 0) { time = document.getElementById("timer"); time.innerHTML = secondsLeft; } if (secondsLeft === 0) { alert("sorry, out of time"); clearInterval(secondsLeft); } },1000); console.log("timer has started") } function revealQuiz(){ document.getElementById('quiz').style.display = "block"; } function displayQuestion(currentQuestion){ question.innerText = currentQuestion.question; A.innerText = currentQuestion.A; B.innerText = currentQuestion.B; C.innerText = currentQuestion.C; D.innerText = currentQuestion.D; } displayQuestion(questions[0]); function getNewQuestion() { if (questionCounter < questions.length){ question.innerText = questions[questionCounter].title; choices.textContent = ""; } for(let i = 0; i< questions[questionCounter]; i++) { let el = document.createElement("button"); el.innerText = questions[questionCounter].multichoice[i]; el.setAttribute("data-id", i); el.addEventListener("click", function (event){ event.stopPropagation(); if (el.innerText === questions[questionCounter].answer){ score += secondsLeft; } else { score -= 10; secondsLeft = secondsLeft -15 } question.innerHTML = ""; if (questionCounter === questions.length){ return; } else { questionCounter++; getNewQuestion(); } }); choices.append(el); } } choices.forEach( function(choice) { choice.addEventListener('click',function(event) { if(!acceptingAnswers) return acceptingAnswers = false const selectedChoice = event.target const selectedAnswer = selectedChoice.dataset['number'] let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect' if(classToApply === 'correct') { incrementScore(Score_Points) } selectedChoice.parentElement.classList.add(classToApply) // setTimeout( function() { // selectedChoice.parentElement.classList.remove(classToApply) // getNewQuestion() // },1000) }) }) incrementScore = function(num){ score +=num //setCounterText.innerText = score } // function displayQuestion(currentQuestion){ // question.innerText = currentQuestion.question; // A.innerText = currentQuestion.A; // B.innerText = currentQuestion.B; // C.innerText = currentQuestion.C; // D.innerText = currentQuestion.D; // } // displayQuestion(questions[0]); // function getAnswer(currentQuestion, userSelection){ // currentQuestion.correct == userSelection // } startButton.addEventListener("click", function(){ console.log("button is clicked") })
b5a39204f750478dfc1f04b9698ed72e9b45b537
[ "Markdown", "JavaScript" ]
2
Markdown
SamuelMontague/codeQuiz
8a9de22ca6c9c03a971f1ff3a9f8f70456e0f253
c36acca0737723469c2d603c9dd0b1f5535af3fe
refs/heads/master
<file_sep># choujiang choujiangdemo <file_sep> $(function(){ // $(".ji").click(function(){ // $(".alert").hide(); // return false; // }); var timeOut = function(){ //超时函数 $("#lotteryBtn").rotate({ angle:0, duration: 10000, animateTo: 2160, callback:function(){ alert('网络超时') } }); }; var rotateFunc = function(awards,angle,text){ //awards:奖项,angle:奖项对应的角度 $('#lotteryBtn').stopRotate(); $("#lotteryBtn").rotate({ angle:0, duration: 5000, animateTo: angle+3600, //angle是图片上各奖项对应的角度,1440是我要让指针旋转4圈。所以最后的结束的角度就是这样子^^ }); }; $(".one").click(function(){ $("#lotteryBtn").rotate(); $(".yi .gif").show(); rotateFunc(1,180,'恭喜您抽中的一等奖'); setTimeout("go(1,1)",5000) ; $(this).attr("disabled","disabled"); $(this).css("background","#af1439"); }); $(".two").click(function(){ $(".er .gif").show(); $("#lotteryBtn").rotate(); rotateFunc(2,300,'恭喜您抽中的二等奖'); setTimeout("go(2,2)",5000) ; $(this).attr("disabled","disabled"); $(this).css("background","#af1439"); }); $(".three").click(function(){ $(".san .gif").show(); $("#lotteryBtn").rotate(); rotateFunc(3,70,'恭喜您抽中的三等奖'); setTimeout("go(3,3)",5000); $(this).attr("disabled","disabled"); $(this).css("background","#af1439"); }); $(".four").click(function(){ $(".si .gif").show(); $("#lotteryBtn").rotate(); $(".alert").show(); rotateFunc(4,230,'恭喜您抽中的四等奖'); setTimeout("go(10,4)",5000); $(this).attr("disabled","disabled"); $(this).css("background","#af1439"); }); $(".five").click(function(){ $(".wu .gif").show(); $("#lotteryBtn").rotate(); $(".alert").show(); rotateFunc(5,0,'恭喜您抽中的五等奖'); setTimeout("go(10,5)",5000); $(this).attr("disabled","disabled"); $(this).css("background","#af1439"); }); $(".six").click(function(){ $(".liu .gif").show(); $("#lotteryBtn").rotate(); $(".alert").show(); rotateFunc(6,130,'恭喜您抽中的六等奖'); setTimeout("go(10,6)",5000); $(this).attr("disabled","disabled"); $(this).css("background","#af1439"); }); }); var canvas = document.getElementById("cas"); var ocas = document.createElement("canvas"); var octx = ocas.getContext("2d"); var ctx = canvas.getContext("2d"); ocas.width = canvas.width = window.innerWidth; ocas.height = canvas.height = window.innerHeight; var bigbooms = []; window.onload = function(){ initAnimate() } function initAnimate(){ lastTime = new Date(); animate(); } var lastTime; function animate(){ ctx.save(); img = new Image(); img.src = "bj.jpg"; ctx.drawImage(img, 0, 0,ocas.width,ocas.height); ctx.restore(); ctx.save(); img1 = new Image(); var newTime = new Date(); if(newTime-lastTime>500+(window.innerHeight-767)/2){ var random = Math.random()*100>2?true:false; var x = getRandom(canvas.width/5 , canvas.width*4/5); var y = getRandom(50 , 200); if(random){ var bigboom = new Boom(getRandom(canvas.width/3,canvas.width*2/3) ,2,"#FFF" , {x:x , y:y}); bigbooms.push(bigboom) } else { var bigboom = new Boom(getRandom(canvas.width/3,canvas.width*2/3) ,2,"#FFF" , {x:canvas.width/2 , y:200} , document.querySelectorAll(".shape")[parseInt(getRandom(0, document.querySelectorAll(".shape").length))]); bigbooms.push(bigboom) } lastTime = newTime; console.log(bigbooms) } stars.foreach(function(){ this.paint(); }) drawMoon(); bigbooms.foreach(function(index){ var that = this; if(!this.dead){ this._move(); this._drawLight(); } else{ this.booms.foreach(function(index){ if(!this.dead) { this.moveTo(index); } else if(index === that.booms.length-1){ bigbooms[bigbooms.indexOf(that)] = null; } }) } }); raf(animate); } function drawMoon(){ var moon = document.getElementById("moon"); var centerX = canvas.width-200 , centerY = 100 , width = 80; if(moon.complete){ ctx.drawImage(moon , centerX , centerY , width , width ) } else { moon.onload = function(){ ctx.drawImage(moon ,centerX , centerY , width , width) } } var index = 0; for(var i=0;i<10;i++){ ctx.save(); ctx.beginPath(); ctx.arc(centerX+width/2 , centerY+width/2 , width/2+index , 0 , 2*Math.PI); ctx.fillStyle="rgba(240,219,120,0.005)"; index+=2; ctx.fill(); ctx.restore(); } } Array.prototype.foreach = function(callback){ for(var i=0;i<this.length;i++){ if(this[i]!==null) callback.apply(this[i] , [i]) } } var raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; canvas.onclick = function(){ var x = event.clientX; var y = event.clientY; var bigboom = new Boom(getRandom(canvas.width/3,canvas.width*2/3) ,2,"#FFF" , {x:x , y:y}); bigbooms.push(bigboom) } var Boom = function(x,r,c,boomArea,shape){ this.booms = []; this.x = x; this.y = (canvas.height+r); this.r = r; this.c = c; this.shape = shape || false; this.boomArea = boomArea; this.theta = 0; this.dead = false; this.ba = parseInt(getRandom(80 , 200)); } Boom.prototype = { _paint:function(){ ctx.save(); ctx.beginPath(); ctx.arc(this.x,this.y,this.r,0,2*Math.PI); ctx.fillStyle = this.c; ctx.fill(); ctx.restore(); }, _move:function(){ var dx = this.boomArea.x - this.x , dy = this.boomArea.y - this.y; this.x = this.x+dx*0.01; this.y = this.y+dy*0.01; if(Math.abs(dx)<=this.ba && Math.abs(dy)<=this.ba){ if(this.shape){ this._shapBoom(); } else this._boom(); this.dead = true; } else { this._paint(); } }, _drawLight:function(){ ctx.save(); ctx.fillStyle = "rgba(255,228,150,0.3)"; ctx.beginPath(); ctx.arc(this.x , this.y , this.r+3*Math.random()+1 , 0 , 2*Math.PI); ctx.fill(); ctx.restore(); }, _boom:function(){ var fragNum = getRandom(30 , 200); var style = getRandom(0,10)>=5? 1 : 2; var color; if(style===1){ color = { a:parseInt(getRandom(128,255)), b:parseInt(getRandom(128,255)), c:parseInt(getRandom(128,255)) } } var fanwei = parseInt(getRandom(300, 400)); for(var i=0;i<fragNum;i++){ if(style===2){ color = { a:parseInt(getRandom(128,255)), b:parseInt(getRandom(128,255)), c:parseInt(getRandom(128,255)) } } var a = getRandom(-Math.PI, Math.PI); var x = getRandom(0, fanwei) * Math.cos(a) + this.x; var y = getRandom(0, fanwei) * Math.sin(a) + this.y; var radius = getRandom(0 , 2) var frag = new Frag(this.x , this.y , radius , color , x , y ); this.booms.push(frag); } }, _shapBoom:function(){ var that = this; putValue(ocas , octx , this.shape , 5, function(dots){ var dx = canvas.width/2-that.x; var dy = canvas.height/2-that.y; for(var i=0;i<dots.length;i++){ color = {a:dots[i].a,b:dots[i].b,c:dots[i].c} var x = dots[i].x; var y = dots[i].y; var radius = 1; var frag = new Frag(that.x , that.y , radius , color , x-dx , y-dy); that.booms.push(frag); } }) } } function putValue(canvas , context , ele , dr , callback){ context.clearRect(0,0,canvas.width,canvas.height); var img = new Image(); if(ele.innerHTML.indexOf("img")>=0){ img.src = ele.getElementsByTagName("img")[0].src; imgload(img , function(){ context.drawImage(img , canvas.width/2 - img.width/2 , canvas.height/2 - img.width/2); dots = getimgData(canvas , context , dr); callback(dots); }) } else { var text = ele.innerHTML; context.save(); var fontSize =200; context.font = fontSize+"px 宋体 bold"; context.textAlign = "center"; context.textBaseline = "middle"; context.fillStyle = "rgba("+parseInt(getRandom(128,255))+","+parseInt(getRandom(128,255))+","+parseInt(getRandom(128,255))+" , 1)"; context.fillText(text , canvas.width/2 , canvas.height/2); context.restore(); dots = getimgData(canvas , context , dr); callback(dots); } } function imgload(img , callback){ if(img.complete){ callback.call(img); } else { img.onload = function(){ callback.call(this); } } } function getimgData(canvas , context , dr){ var imgData = context.getImageData(0,0,canvas.width , canvas.height); context.clearRect(0,0,canvas.width , canvas.height); var dots = []; for(var x=0;x<imgData.width;x+=dr){ for(var y=0;y<imgData.height;y+=dr){ var i = (y*imgData.width + x)*4; if(imgData.data[i+3] > 128){ var dot = {x:x , y:y , a:imgData.data[i] , b:imgData.data[i+1] , c:imgData.data[i+2]}; dots.push(dot); } } } return dots; } function getRandom(a , b){ return Math.random()*(b-a)+a; } var maxRadius = 1 , stars=[]; var Star = function(x,y,r){ this.x = x;this.y=y;this.r=r; } Star.prototype = { paint:function(){ ctx.save(); ctx.beginPath(); ctx.arc(this.x , this.y , this.r , 0 , 2*Math.PI); ctx.fillStyle = "rgba(255,255,255,"+this.r+")"; ctx.fill(); ctx.restore(); } } var focallength = 250; var Frag = function(centerX , centerY , radius , color ,tx , ty){ this.tx = tx; this.ty = ty; this.x = centerX; this.y = centerY; this.dead = false; this.centerX = centerX; this.centerY = centerY; this.radius = radius; this.color = color; } Frag.prototype = { paint:function(){ ctx.save(); ctx.beginPath(); ctx.arc(this.x , this.y , this.radius , 0 , 2*Math.PI); ctx.fillStyle = "rgba("+this.color.a+","+this.color.b+","+this.color.c+",1)"; ctx.fill() ctx.restore(); }, moveTo:function(index){ this.ty = this.ty+0.3; var dx = this.tx - this.x , dy = this.ty - this.y; this.x = Math.abs(dx)<0.1 ? this.tx : (this.x+dx*0.1); this.y = Math.abs(dy)<0.1 ? this.ty : (this.y+dy*0.1); if(dx===0 && Math.abs(dy)<=80){ this.dead = true; } this.paint(); } } function random(min,max){ return Math.floor(min+Math.random()*(max-min)); } var awardListDom=document.getElementById("awardListDom"), firstPrize=document.getElementById("firstPrize"), submit=document.getElementById("submit"); var awardList=["吕玉力","<NAME>","李沐然","张文枢","曾琪祥","王洁琼","侯文雪","何 笑","闫玉珍","张宝柱","朱森瑞","刘宝莲","张丰良","龚建兵","田志辉","杨 涛","尹时光","杨一帆","武云利","秦国华","赵勃航","秦昌柱","刘宏超","东晓峰","崔方娜","薛光辉","<NAME>","孙常成","张 博","王月英","李 炎","闫 俊","<NAME>","刘 潮","仇长生","李皖都","李 野","<NAME>","王东林","<NAME>","董有红","郜路阳","孙文慧","唐永强","孟豪帅","宋亚正","孔祥磊","李亚振","鲁丽微","陈雨顺","高海宾","张云逸","房秋宇","施志聪","同小杰","李素伟"]; var firstList=[]; var scondList=[]; var thirdList=[]; var fourList=[]; var fiveList=[]; var sixList=[]; function go(firstPrizeber,prize){ for(var i=0;i<firstPrizeber;i++){ var oldArray=awardList; var rfirstPrize=random(0,oldArray.length); if(oldArray.length<1){ awardListDom.value="活动结束"; firstPrize.value="活动结束"; } else{ if (firstPrizeber==1 && prize==1) { firstPrize.value=oldArray[rfirstPrize]; firstList.push(firstPrize.value+" "); var index = 0; $(".yi .gif").hide(); var _setInterval1 = setInterval(function () { $(".yi li").html(awardList[index]); ++index; if (index >= awardList.length) { clearInterval(_setInterval1); } }, 50); $(".yi li").html(firstList[0]); var showLable = $(".yi li").html(); $(".yi li").lbyl({ content: showLable, speed: 300, type: 'show' }); clearInterval(_setInterval1); } if (firstPrizeber==2 && prize==2) { var secondPrize =oldArray[rfirstPrize]; scondList.push(secondPrize+" "); var index = 0; $(".er .gif").hide(); var _setInterval2 = setInterval(function () { $(".er li").html(awardList[index]); ++index; if (index >= awardList.length) { clearInterval(_setInterval2); } }, 50); $(".er li").html(scondList[0]+scondList[1]); var showLable = $(".er li").html(); $(".er li").lbyl({ content: showLable, speed: 300, type: 'show' }); clearInterval(_setInterval2); } if (firstPrizeber==3 && prize==3) { var thirdPrize=oldArray[rfirstPrize]; thirdList.push(thirdPrize+" "); var index = 0; $(".san .gif").hide(); var _setInterval3 = setInterval(function () { $(".san li").html(awardList[index]); ++index; if (index >= awardList.length) { clearInterval(_setInterval3); } }, 50); $(".san li").html(thirdList[0]+thirdList[1]+thirdList[2]); var showLable = $(".san li").html(); $(".san li").lbyl({ content: showLable, speed:300, type: 'show' }); clearInterval(_setInterval3); } if (firstPrizeber==10 && prize==4) { var fourPrize=oldArray[rfirstPrize]; fourList.push(fourPrize+" "); var index = 0; $(".si .gif").hide(); var _setInterval4 = setInterval(function () { $(".si li").html(awardList[index]); ++index; if (index >= awardList.length) { clearInterval(_setInterval4); } }, 50); $(".si li").html(fourList[0]+fourList[1]+fourList[2]+fourList[3]+fourList[4]+fourList[5]+fourList[6]+fourList[7]+fourList[8]+fourList[9]); var showLable = $(".si li").html(); $(".si li").lbyl({ content: showLable, speed: 300, type: 'show' }); clearInterval(_setInterval4); } if (firstPrizeber==10 && prize==5) { var fivePrize=oldArray[rfirstPrize]; fiveList.push(fivePrize+" "); var index = 0; $(".wu .gif").hide(); var _setInterval5 = setInterval(function () { $(".wu li").html(awardList[index]); ++index; if (index >= awardList.length) { clearInterval(_setInterval5); } }, 50); $(".wu li").html(fiveList[0]+fiveList[1]+fiveList[2]+fiveList[3]+fiveList[4]+fiveList[5]+fiveList[6]+fiveList[7]+fiveList[8]+fiveList[9]); var showLable = $(".wu li").html(); $(".wu li").lbyl({ content: showLable, speed: 300, type: 'show' }); clearInterval(_setInterval5); } if (firstPrizeber==10 && prize==6) { var sixPrize=oldArray[rfirstPrize]; sixList.push(sixPrize+" "); var index = 0; $(".liu .gif").hide(); var _setInterval6 = setInterval(function () { $(".liu li").html(awardList[index]); ++index; if (index >= awardList.length) { clearInterval(_setInterval6); } }, 50); $(".liu li").html(sixList[0]+sixList[1]+sixList[2]+sixList[3]+sixList[4]+sixList[5]+sixList[6]+sixList[7]+sixList[8]+sixList[9]); var showLable = $(".liu li").html(); $(".liu li").lbyl({ content: showLable, speed: 300, type: 'show' }); clearInterval(_setInterval6); } oldArray.splice(rfirstPrize,1); awardListDom.value=oldArray; } } } <file_sep>/* Copyright © 2015 <EMAIL> Licensed Under MIT */ !function(e){e.fn.lbyl=function(n){{var t=e.extend({content:"",speed:10,type:"show",fadeSpeed:500,finished:function(){}},n),d=e(this),s=[],i=t.content;e(this).length}d.empty(),d.attr("data-time",i.length*t.speed);for(var p=0;p<i.length;p++)s.push(i[p]);e.each(s,function(e,n){d.append('<span style="display: none;">'+n+"</span>"),setTimeout(function(){"show"==t.type?d.find("span:eq("+e+")").show():"show"==t.type&&d.find("span:eq("+e+")").show()},e*t.speed)}),setTimeout(function(){t.finished()},i.length*t.speed)}}(jQuery);
92b2d5643d2c0603001d0c21c57c533e3ab71909
[ "Markdown", "JavaScript" ]
3
Markdown
manong555/choujiang
ba1c88f01f31f8a2ea27cdb308aacc62ae86a3be
13c21916325b68cb5c1c15224bf192b2f3c1d6a0
refs/heads/master
<file_sep>// // KeyChainHelper.swift // // Created by <NAME> on 23/09/2015. // Copyright © 2015 Weihong. All rights reserved. // import Foundation import Security let SecMatchLimit: String! = kSecMatchLimit as String let SecReturnData: String! = kSecReturnData as String let SecValueData: String! = kSecValueData as String let SecAttrAccessible: String! = kSecAttrAccessible as String let SecClass: String! = kSecClass as String let SecAttrService: String! = kSecAttrService as String let SecAttrGeneric: String! = kSecAttrGeneric as String let SecAttrAccount: String! = kSecAttrAccount as String let SecReturnPersistentRef: String! = kSecReturnPersistentRef as String class KeyChainHelper{ private class func service() -> String{ return NSBundle.mainBundle().bundleIdentifier! } class func storeData(key: String, value: String){ let query = KeyChainHelper.getQueryDataStructureForKeyChain(key) var result: AnyObject? = nil query[SecValueData] = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) let status = SecItemAdd(query, &result) switch status{ case errSecSuccess: print("data stored successfully") case errSecDuplicateItem: print("data already exists") default: print("data stored fails") } } class func deleteData(key: String){ let query = KeyChainHelper.getQueryDataStructureForKeyChain(key) query[SecReturnData] = kCFBooleanTrue let status = SecItemCopyMatching(query, nil) if status == errSecSuccess{ let deleted = SecItemDelete(query) if deleted == errSecSuccess{ print("data exists, delete sucessfully") }else{ print("data exists, but deleting data fail") } }else{ print("data doese not exist, deleting data fail") } } class func retrieveData(key: String) -> NSData?{ let query = KeyChainHelper.getQueryDataStructureForKeyChain(key) var result: AnyObject? let value: String? query[SecReturnData] = kCFBooleanTrue let status = SecItemCopyMatching(query, &result) if status == errSecSuccess{ value = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding) as? String print(value) return value?.dataUsingEncoding(NSUTF8StringEncoding) } print("nothing to be retrieved") return NSData() } class func updateData(key: String, newData: String){ let query = KeyChainHelper.getQueryDataStructureForKeyChain(key) let EncodedNewData = newData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) let status = SecItemCopyMatching(query, nil) if status == errSecSuccess{ let update = [ SecValueData:EncodedNewData! ] let success = SecItemUpdate(query, update) if success == errSecSuccess{ print("suceesfully update value") }else{ print("failt to update value") } }else{ print("cannot update the data, because there is no existing data") } } private class func getQueryDataStructureForKeyChain(key: String) -> NSMutableDictionary{ let queryDictionary: NSMutableDictionary = [SecClass: kSecClassGenericPassword] queryDictionary[SecAttrService] = KeyChainHelper.service() queryDictionary[SecAttrAccount] = key.dataUsingEncoding(NSUTF8StringEncoding) return queryDictionary } }<file_sep># KeyChainHelper-Swift Basic actions for keychain. You can use it to store, update, delete, retrieve data in the KeyChain in iOS system. Swift 2.0 supported
f36964a0419c34fd5bb9183b1091b71103c39dc0
[ "Swift", "Markdown" ]
2
Swift
WEIHOME/KeyChainHelper-Swift
59ba6d2741e4e18bfd33f0121b7c789d01279ff5
41da91b55368878cadf9dc1d2cb6e46c0bcf7185
refs/heads/master
<file_sep>package com.subhag.api import com.subhag.api.services.newsapp.NewsApiClient import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Test class NewsApiTest { private val newsApi = NewsApiClient().newsApi @Test fun `Test GET top headlines from News API`() { runBlocking { val articlesResponse = newsApi.getTopHeadlinesFromAllSources() assertEquals(articlesResponse.isSuccessful, true) assertNotEquals(0, articlesResponse.body()?.articles?.size) } } @Test fun `Test GET search results given a query`() { runBlocking { val articlesResponse = newsApi.getAllArticles("<NAME>") assertEquals(articlesResponse.isSuccessful, true) assertNotEquals(0, articlesResponse.body()?.articles?.size) } } companion object { private const val STATUS_OK = "ok" } }<file_sep>rootProject.name = "InShortsClone" include ':app' include ':api' <file_sep>package com.subhag.api.models.responses import com.subhag.api.models.entities.Article data class ArticlesResponse( val articles: List<Article>, val status: String, val totalResults: Int )<file_sep>package com.subhag.api.services.harperdb import com.subhag.api.models.dto.UserDTO class SQLHelper { companion object { fun getSQLCommandForGetUser(email: String): HarperDbSqlModel { return HarperDbSqlModel("SELECT * FROM taskify.user WHERE email = '${email}' LIMIT 1") } fun getSQLCommandForStoringUser(userDTO: UserDTO): HarperDbSqlModel { return HarperDbSqlModel( "INSERT INTO taskify.user (username,email, profile_img) " + "VALUE ('${userDTO.username}','${userDTO.email}','${userDTO.profile_img}')" ) } } }<file_sep>package com.subhag.api.services.harperdb import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class HarperDbUserApiClient { private val retrofit = Retrofit .Builder() .baseUrl(HarperDbUserApi.BASE_URL) .addConverterFactory(MoshiConverterFactory.create()) .build() val harperUserApi: HarperDbUserApi = retrofit.create(HarperDbUserApi::class.java) }<file_sep>package com.subhag.api.models.entities data class UserEntity( val username: String = "", val email: String = "", val profileImage: String = "", val hasCustomImage:Boolean = false ) <file_sep>package com.subhag.api.services.harperdb import com.subhag.api.BASIC_AUTH import com.subhag.api.models.dto.UserDTO import retrofit2.Response import retrofit2.http.Body import retrofit2.http.Header import retrofit2.http.POST interface HarperDbUserApi { @POST("/") suspend fun persistUserOnBackend( @Body body: HarperDbSqlModel, @Header("Authorization") header: String = BASIC_AUTH, ): Response<Any> @POST("/") suspend fun getUsers( @Body sqlModel: HarperDbSqlModel, @Header("Authorization") header: String = BASIC_AUTH ): Response<List<UserDTO>> companion object { const val BASE_URL = "https://taskify-cloud-subhag.harperdbcloud.com" } }<file_sep>package com.subhag.api.services.newsapp import com.subhag.api.models.responses.ArticlesResponse import com.subhag.api.models.responses.TopHeadlinesFromAllSources import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface NewsApi { @GET("/v2/top-headlines") suspend fun getTopHeadlinesFromAllSources( @Query("category") category: String? = null, @Query("country") country: String? = "in", @Query("sources") sources: String? = null, @Query("q") query: String? = null, @Query("pagesize") pageSize: Int? = null, @Query("page") page: Int? = null ): Response<TopHeadlinesFromAllSources> @GET("/v2/everything") suspend fun getAllArticles( @Query("q") query: String ): Response<ArticlesResponse> companion object { const val BASE_URL = "https://newsapi.org" } }<file_sep>package com.subhag.api.services.newsapp import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.util.concurrent.TimeUnit class NewsApiClient { private val authInterceptor = Interceptor { chain -> val request = chain.request() val requestBuilder = request.newBuilder() requestBuilder.header(HEADER_X_API_KEY, API_KEY) chain.proceed(requestBuilder.build()) } private val okHttpBuilder = OkHttpClient.Builder() .readTimeout(5, TimeUnit.SECONDS) .callTimeout(2, TimeUnit.SECONDS) private val okHttpClient = okHttpBuilder .addInterceptor(authInterceptor) .build() private val retrofit = Retrofit .Builder() .client(okHttpClient) .baseUrl(NewsApi.BASE_URL) .addConverterFactory(MoshiConverterFactory.create()) .build() val newsApi: NewsApi = retrofit.create(NewsApi::class.java) companion object { private const val HEADER_X_API_KEY = "x-api-key" private const val API_KEY = "<KEY>" } }<file_sep>package com.subhag.api.models.responses import com.subhag.api.models.entities.Article import com.subhag.api.models.entities.Source data class TopHeadlinesFromAllSources( val sources: List<Source>, val status: String, val articles: List<Article> ) <file_sep>package com.subhag.inshortsclone.di import com.subhag.api.services.harperdb.HarperDbUserApiClient import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object AppModule { @Provides @Singleton fun providesHarperAuthClient(harperAuthClient: HarperDbUserApiClient) = harperAuthClient }<file_sep>package com.subhag.api.models.dto data class UserDTO( val username: String = "", val email:String = "", val profile_img:String = "" ) <file_sep>package com.subhag.api import com.subhag.api.models.dto.UserDTO import com.subhag.api.models.mapper.UserMapper import com.subhag.api.services.harperdb.HarperDbUserApiClient import com.subhag.api.services.harperdb.SQLHelper import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test class HarperDbUserApiTest { private val harperDbUserApi = HarperDbUserApiClient().harperUserApi private val userMapper = UserMapper() @Test fun `Test GET UserInfo`() { runBlocking { val sqlCommand = SQLHelper.getSQLCommandForGetUser("<EMAIL>") val userResponse = harperDbUserApi.getUsers(sqlCommand) val user = userMapper.toDomainModel(userResponse.body()!!.first()) assertEquals(userResponse.isSuccessful, true) assertEquals(user.username, "Subhag") assertEquals(user.email, "<EMAIL>") } } @Test fun `Test Persist User On Backend`() { runBlocking { val testUser = UserDTO("abc123", "<EMAIL>", "asdfasdf") val sqlCommand = SQLHelper.getSQLCommandForStoringUser(testUser) val addUserResponse = harperDbUserApi.persistUserOnBackend(sqlCommand) assertEquals(addUserResponse.isSuccessful, true) } } }<file_sep>package com.subhag.api.models.mapper interface Mapper <Network, Domain> { fun toDomainModel(network: Network): Domain fun toDomainList(network: List<Network>): List<Domain> fun toServiceModel(domain: Domain): Network }<file_sep>package com.subhag.inshortsclone import android.app.Application import android.util.Log import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class NewsApplication : Application() { override fun onCreate() { super.onCreate() Log.d(LOG_TAG,"") } companion object { var LOG_TAG: String = NewsApplication::class.java.simpleName } }<file_sep>package com.subhag.api.services.harperdb data class HarperDbSqlModel( val sql: String, val operation: String = "sql" ) <file_sep>package com.subhag.api const val BASIC_AUTH = "Basic <KEY>
bbf7d8f180e2b5089d9ebe811e5547c90072c06e
[ "Kotlin", "Gradle" ]
17
Kotlin
DhruvB007/NewsApp
7a08af0260a9a6fbb06cb99aa858d71a2870232c
79ccce52f3dabc5f667c56222f07d748b98dfa7e
refs/heads/master
<file_sep># Hey Orc A sample Ruby on Rails application that uses Orchestrate. <file_sep>class LocationsController < ApplicationController def index @locations = Location.all end def show @location = Location.find params[:id] @comments = @location.comments end def new @location = Location.new end def create @location = Location.create! attributes redirect_to :action => 'show', :id => @location.id end def search_results query_str = (params[:query_str].blank?) ? '*' : params[:query_str] @name = "Search results for '#{query_str}'" @locations = Location.search_results(query_str) end private def generate_primary_key params[:location][:name].downcase.tr(': ', '_') end def attributes params[:location].merge(:id => generate_primary_key) end end <file_sep>Rails.application.routes.draw do root to: "locations#index" get "search_results" => "locations#search_results" resources :locations end <file_sep>Orchestrate::Rails::Schema.define_collection( :name => 'locations', :classname => 'Location', :properties => [ :Name, :City, :State ], :event_types => [ :comments ] ) Orchestrate::Rails::Schema.define_event_type( :collection => 'locations', :event_type => :comments, :properties => [ :User, :Comment ] ) <file_sep>class Location < Orchestrate::Rails::Model def comments self.events('comments') end end
371db9260657e60d0ad8560cd0de2ff103c13658
[ "Markdown", "Ruby" ]
5
Markdown
muskanmahajan37/hey-orc
7d6b152e479ff4c2fa034dbe75ffa2f4777202b1
88edf3912ce4b5eba6dd371a71823564dfc08fb8
refs/heads/master
<file_sep>import React from 'react'; import { Nav, Navbar, Form, FormControl } from 'react-bootstrap'; import styled from 'styled-components'; const Styles = styled.div` .navbar { background-color: green; width: 100%; display: flex; flex-direction: row; } a, .navbar-nav, .navbar-light .nav-link { text-decoration: none; padding: 1%; color: #9FFFCB; &:hover { color: red; } } .navbar-brand { font-size: 1.4em; color: #9FFFCB; &:hover { color: white; } } .form-center { position: absolute !important; left: 25%; padding: 1%; right: 25%; } `; export const Header = () => ( <Styles> <Navbar expand="lg"> <Navbar.Brand href="/">AudioQUeen</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav"/> <Form className="form-center"> <FormControl type="text" placeholder="Search" className="p-2" /> </Form> <Nav className="ml-auto d-flex"> <Nav.Item><Nav.Link href="/">Home</Nav.Link></Nav.Item> <Nav.Item><Nav.Link href="/about">About</Nav.Link></Nav.Item> </Nav> </Navbar> </Styles> )
861b918cf95e0ae905dc05df76dfe5e26a987bd9
[ "JavaScript" ]
1
JavaScript
ampaire/AudioQueen
7345f32d22364d2794675bcce6b5dfb30fa8e43b
9f67260cbafd89a0f77da83e63d5c28bdd211393
refs/heads/master
<repo_name>rajesh452/shoppincartversion1<file_sep>/README.md # shoppincartversion1 backend of shopping cart <file_sep>/ShoppingCartVersion1/src/main/java/com/niit/shoppingcartdao/CategoryDAO.java package com.niit.shoppingcartdao; import java.util.List; import com.niit.shoppingcartversionmodel.Category; public interface CategoryDAO{ public List<Category> list(); public Category get(String id); public void saveOrUpdate(Category category); public void delete(String id); public List<Category>listCategory(); }
facc251cc465982a7235e9eb559689b97c460751
[ "Markdown", "Java" ]
2
Markdown
rajesh452/shoppincartversion1
c37745ab09dd96e1f3238f127bc2759b659d9e05
7f376d96131fd9f4752221d8fb004b9e49801cc3
refs/heads/master
<repo_name>MarkDaviesEsendex/BattleNetClient<file_sep>/src/BattleNetClient/Clients/BattleNetClient.cs using BattleNetClient.Diablo; namespace BattleNetClient.Clients { internal class BattleNetClient : IBattleNetClient { public IDiabloClient Diablo { get; } public bool IsClientValid => true; public BattleNetClient(IDiabloClient diabloClient) { Diablo = diabloClient; } } } <file_sep>/src/BattleNetClient.Testing/Data/Models/Token.cs using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BattleNetClient.Testing.Data.Models { public class Token { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string AccessToken { get; set; } } }<file_sep>/src/BattleNetClient.Testing/Models/Diablo/Act.cs using System.Collections.Generic; namespace BattleNetClient.Testing.Models.Diablo { public class Act { public string Slug { get; set; } public int Number { get; set; } public string Name { get; set; } public List<Quest> Quests { get; set; } = new List<Quest>(); } }<file_sep>/src/BattleNetClient.Testing/BattleNetServer.cs using System.IO; using System.Net.Http; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; namespace BattleNetClient.Testing { public interface IBattleNetServer { HttpClient GetClient(); string[] GetRequests(); } internal class BattleNetServer : IBattleNetServer { private readonly TestServer _server; private readonly HttpClient _client; public BattleNetServer() { _server = new TestServer(new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>()); _client = _server.CreateClient(); } public HttpClient GetClient() => _client; public string[] GetRequests() => new string[0]; } } <file_sep>/src/BattleNetClient/Diablo/NullActClient.cs using System.Net; using System.Threading.Tasks; using BattleNetClient.Diablo.Models; namespace BattleNetClient.Diablo { public class NullActClient : IActClient { public Task<IResult<Act>> GetByIdAsync(int actId) => Task.FromResult(Result<Act>.Failure(Act.Empty, HttpStatusCode.NotFound)); public Task<IResult<ActCollection>> GetAllAsync() => Task.FromResult(Result<ActCollection>.Failure(ActCollection.Empty, HttpStatusCode.NotFound)); } }<file_sep>/src/BattleNetClient/Diablo/NullDiabloClient.cs namespace BattleNetClient.Diablo { internal class NullDiabloClient : IDiabloClient { public NullDiabloClient() => Act = new NullActClient(); public IActClient Act { get; } } }<file_sep>/README.md # Battle Net Client This is a c# library that will allow you to interact with the blizzard apis, in a clean testable way - that's the hope anyway. # Usage ## Create a client: ``` var factory = new BattleNetClientFactory(Region.UnitedStates); var client = await _factory.CreateClientAsync("clientId", "clientSecret"); ``` *Note*: to aquire a client id and a client seecret please go and see the documentation for the blizzard api: https://develop.battle.net/, I am not in charge of this. ## Check validity If the api pases back an invalid status code (anything not in the 200 range) the sdk will pass back an invalid client, to check this please use the `IsClientValid` property, the client will allow you to interact with it (specified later in the readme) but will _always_ return invalid results. Whilst people may disagree with this approach, I always feel that a _good_ library will always return objects that the consuming code can interact with. ## Query the api: ``` var factory = new BattleNetClientFactory(Region.UnitedStates); var client = await factory.CreateClientAsync("clientId", "clientSecret"); if(client.IsValid) { // Get act by id var actualActResult = await client.Diablo.Act.GetByIdAsync(1); } ``` This will pass back a result object: ``` public interface IResult<out T> { bool IsValid { get; } T Data { get; } HttpStatusCode Code { get; } } ``` ## Check validaity Before using the object check that it is valid: ``` if(actualActResult.IsValid) { // do your thing --- make your body sing } ``` *Note*: Again if you have an invalid version of the object it will _not_ be null, it will be a real obejct that you can interact with it will just have no value in the properties i.e. string will be empty, ints will be -1. # Testing I have split the project into three libraries: * Client * Client Tests * Client Testing My hope is that I will post both the client and the client testing libraries onto nuget, and you can simply take advantage of the code I've used to test my code, for example, to test acts: ``` // Create fake server var server = new BattleNetServerBuilder() .CreateClientCredentials("clientId", "clientSecret") .Build(); // create client with fake server client _factory = new BattleNetClientFactory(Region.UnitedStates, server.GetClient()); ``` Maybe adding configurable data sometime down the line.<file_sep>/src/BattleNetClient.Testing/Models/GrantToken.cs using Newtonsoft.Json; namespace BattleNetClient.Testing.Models { public class GrantToken { [JsonProperty("grant_type")] public string GrantType { get; set; } } }<file_sep>/src/BattleNetClient/Diablo/Models/ActCollection.cs using System.Collections.Generic; namespace BattleNetClient.Diablo.Models { public class ActCollection { public static ActCollection Empty => new NullActCollection(); public virtual List<Act> Acts { get; } = new List<Act>(); } }<file_sep>/src/BattleNetClient/Clients/IBattleNetClient.cs using BattleNetClient.Diablo; namespace BattleNetClient.Clients { public interface IBattleNetClient { IDiabloClient Diablo { get; } bool IsClientValid { get; } } }<file_sep>/src/BattleNetClient.Testing/Data/AuthenticationDbContext.cs using BattleNetClient.Testing.Data.Models; using Microsoft.EntityFrameworkCore; namespace BattleNetClient.Testing.Data { public class AuthenticationDbContext : DbContext { public DbSet<ClientInfo> ClientInfo { get; set; } public DbSet<Token> Tokens { get; set; } public AuthenticationDbContext(DbContextOptions options) : base(options) { } } }<file_sep>/src/BattleNetClient.Testing/BasicAuthorization.cs namespace BattleNetClient.Testing { public class BasicAuthorization { public string ClientId { get; private set; } public string ClientSecret { get; private set; } public static BasicAuthorization Parse(string authentication) { var base64String = authentication.Split(' ')[1]; var token = Base64Decode(base64String); var clientInfo = token.Split(":"); return clientInfo.Length != 2 ? null : new BasicAuthorization {ClientId = clientInfo[0], ClientSecret = clientInfo[1]}; } private static string Base64Decode(string base64EncodedData) { var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } } }<file_sep>/src/BattleNetClient/Diablo/Models/Act.cs using System.Collections.Generic; namespace BattleNetClient.Diablo.Models { public class Act { public static Act Empty => new NullAct(); public virtual string Slug { get; } public virtual int Number { get; } public virtual string Name { get; } public virtual List<Quest> Quests { get; } = new List<Quest>(); } }<file_sep>/src/BattleNetClient/Diablo/ActClient.cs using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using BattleNetClient.Clients; using BattleNetClient.Diablo.Models; namespace BattleNetClient.Diablo { public interface IActClient { Task<IResult<Act>> GetByIdAsync(int actId); Task<IResult<ActCollection>> GetAllAsync(); } public class ActClient : IActClient { private readonly ClientHelper _clientHelper; public ActClient(ClientHelper clientHelper) { _clientHelper = clientHelper; } public async Task<IResult<Act>> GetByIdAsync(int actId) { var responseMessage = await _clientHelper.Client.GetAsync($"https://us.api.blizzard.com/d3/data/act/{actId}"); return !responseMessage.IsSuccessStatusCode ? Result<Act>.Failure(Act.Empty, responseMessage.StatusCode) : Result<Act>.Success(await responseMessage.Content.ReadAsAsync<Act>()); } public async Task<IResult<ActCollection>> GetAllAsync() { var responseMessage = await _clientHelper.Client.GetAsync($"https://us.api.blizzard.com/d3/data/act/"); return !responseMessage.IsSuccessStatusCode ? Result<ActCollection>.Failure(ActCollection.Empty, responseMessage.StatusCode) : Result<ActCollection>.Success(await responseMessage.Content.ReadAsAsync<ActCollection>()); } } }<file_sep>/src/BattleNetClient.Testing/Models/Diablo/ActCollection.cs using System.Collections.Generic; namespace BattleNetClient.Testing.Models.Diablo { public class ActCollection { public virtual List<Act> Acts { get; } = new List<Act>(); } }<file_sep>/src/BattleNetClient.Testing/Data/Models/ClientInfo.cs using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BattleNetClient.Testing.Data.Models { public class ClientInfo { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } } }<file_sep>/src/BattleNetClient.Testing/Data/AuthRepository.cs using System; using System.Linq; using BattleNetClient.Testing.Data.Models; namespace BattleNetClient.Testing.Data { public interface IRepository<T> where T : class { T InsertRecord(T record); T GetRecord(Func<T, bool> whereStatement); } public class AuthRepository<T> : IRepository<T> where T : class { private readonly AuthenticationDbContext _context; public AuthRepository(AuthenticationDbContext context) { _context = context; } public T InsertRecord(T record) { try { _context.Set<T>().Add(record); _context.SaveChanges(); return record; } catch (Exception) { return default(T); } } public T GetRecord(Func<T, bool> whereStatement) { return _context.Set<T>().First(whereStatement); } } }<file_sep>/src/BattleNetClient/Clients/ClientHelper.cs using System.Net.Http; namespace BattleNetClient.Clients { public class ClientHelper { public ClientHelper(HttpClient client, BattleNetRegion battleNetRegion) { Client = client; BattleNetRegion = battleNetRegion; } public HttpClient Client { get; } public BattleNetRegion BattleNetRegion { get; } } }<file_sep>/src/BattleNetClient/Clients/NullClient.cs using BattleNetClient.Diablo; namespace BattleNetClient.Clients { internal class NullClient : IBattleNetClient { public NullClient() => Diablo = new NullDiabloClient(); public IDiabloClient Diablo { get; } public bool IsClientValid => false; } }<file_sep>/src/BattleNetClient.Tests/Diablo/Acts/GetActById.cs using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using BattleNetClient.Diablo.Models; using BattleNetClient.Testing; using Newtonsoft.Json; using Xunit; namespace BattleNetClient.Tests.Diablo.Acts { public class GetActById { private readonly BattleNetClientFactory _factory; public GetActById() { var server = new BattleNetServerBuilder() .CreateClientCredentials("clientId", "clientSecret") .Build(); _factory = new BattleNetClientFactory(BattleNetRegion.UnitedStates, server.GetClient()); } [Theory] [MemberData(nameof(TestData))] public async Task WhenValidActIsRequested_ThenExpectedActIsReturned(int actId, string actString) { var client = await _factory.CreateClientAsync("clientId", "clientSecret"); var actualActResult = await client.Diablo.Act.GetByIdAsync(actId); var expectedAct = JsonConvert.DeserializeObject<Act>(actString); var actualAct = actualActResult.Data; Assert.True(actualActResult.IsValid); Assert.Equal(HttpStatusCode.OK, actualActResult.Code); Assert.Equal(expectedAct.Slug, actualAct.Slug); Assert.Equal(expectedAct.Number, actualAct.Number); Assert.Equal(expectedAct.Name, actualAct.Name); for (var i = 0; i < expectedAct.Quests.Count; i++) { Assert.Equal(expectedAct.Quests[i].Id, actualAct.Quests[i].Id); Assert.Equal(expectedAct.Quests[i].Name, actualAct.Quests[i].Name); Assert.Equal(expectedAct.Quests[i].Slug, actualAct.Quests[i].Slug); } } [Fact] public async Task WhenInvalidActIsRequested_ThenNoActIsReturned() { var client = await _factory.CreateClientAsync("clientId", "clientSecret"); var actualActResult = await client.Diablo.Act.GetByIdAsync(52); var actualAct = actualActResult.Data; Assert.False(actualActResult.IsValid); Assert.Equal(HttpStatusCode.NotFound, actualActResult.Code); Assert.Empty(actualAct.Slug); Assert.Equal(-1, actualAct.Number); Assert.Empty(actualAct.Name); Assert.Empty(actualAct.Quests); } public static IEnumerable<object[]> TestData => Data; private static readonly List<object[]> Data = new List<object[]> { new object[] {1, "{\"slug\":\"act-i\",\"number\":1,\"name\":\"Act I\",\"quests\":[{\"id\":87700,\"name\":\"The Fallen Star\",\"slug\":\"the-fallen-star\"},{\"id\":72095,\"name\":\"The Legacy of Cain\",\"slug\":\"the-legacy-of-cain\"},{\"id\":72221,\"name\":\"A Shattered Crown\",\"slug\":\"a-shattered-crown\"},{\"id\":72061,\"name\":\"Reign of the Black King\",\"slug\":\"reign-of-the-black-king\"},{\"id\":117779,\"name\":\"Sword of the Stranger\",\"slug\":\"sword-of-the-stranger\"},{\"id\":72738,\"name\":\"The Broken Blade\",\"slug\":\"the-broken-blade\"},{\"id\":73236,\"name\":\"The Doom in Wortham\",\"slug\":\"the-doom-in-wortham\"},{\"id\":72546,\"name\":\"Trailing the Coven\",\"slug\":\"trailing-the-coven\"},{\"id\":72801,\"name\":\"The Imprisoned Angel\",\"slug\":\"the-imprisoned-angel\"},{\"id\":136656,\"name\":\"Return to New Tristram\",\"slug\":\"return-to-new-tristram\"}]}"}, new object[] {2, "{\"slug\":\"act-ii\",\"number\":2,\"name\":\"Act II\",\"quests\":[{\"id\":80322,\"name\":\"Shadows in the Desert\",\"slug\":\"shadows-in-the-desert\"},{\"id\":93396,\"name\":\"The Road to Alcarnus\",\"slug\":\"the-road-to-alcarnus\"},{\"id\":74128,\"name\":\"City of Blood\",\"slug\":\"city-of-blood\"},{\"id\":57331,\"name\":\"A Royal Audience\",\"slug\":\"a-royal-audience\"},{\"id\":78264,\"name\":\"Unexpected Allies\",\"slug\":\"unexpected-allies\"},{\"id\":78266,\"name\":\"Betrayer of the Horadrim\",\"slug\":\"betrayer-of-the-horadrim\"},{\"id\":57335,\"name\":\"Blood and Sand\",\"slug\":\"blood-and-sand\"},{\"id\":57337,\"name\":\"The Black Soulstone\",\"slug\":\"the-black-soulstone\"},{\"id\":121792,\"name\":\"The Scouring of Caldeum\",\"slug\":\"the-scouring-of-caldeum\"},{\"id\":57339,\"name\":\"Lord of Lies\",\"slug\":\"lord-of-lies\"}]}"}, }; } }<file_sep>/src/BattleNetClient.Testing/Models/TokenResponse.cs using Newtonsoft.Json; namespace BattleNetClient.Testing.Models { public class TokenResponse { [JsonProperty("access_token")] public string AccessToken { get; set; } } }<file_sep>/src/BattleNetClient/BattleNetRegion.cs namespace BattleNetClient { public enum BattleNetRegion { UnitedStates } }<file_sep>/src/BattleNetClient.Testing/Controllers/AuthenticationController.cs using System; using System.Collections.Generic; using BattleNetClient.Testing.Data; using BattleNetClient.Testing.Data.Models; using BattleNetClient.Testing.Models; using Microsoft.AspNetCore.Mvc; namespace BattleNetClient.Testing.Controllers { [Route("oauth")] public class AuthenticationController : ControllerBase { private readonly IRepository<ClientInfo> _clientInfoRepository; private readonly IRepository<Token> _tokenRepository; public AuthenticationController(IRepository<ClientInfo> clientInfoRepository, IRepository<Token> tokenRepository) { _clientInfoRepository = clientInfoRepository; _tokenRepository = tokenRepository; } [HttpPost("token")] public ActionResult<TokenResponse> GenerateToken([FromHeader(Name = "Authorization")]string authentication, [FromForm]List<KeyValuePair<string, string>> content) { if (!authentication.StartsWith("Basic ")) return NotFound(); var authorization = BasicAuthorization.Parse(authentication); if (authorization == null) return NotFound(); var clientInfoFromDb = _clientInfoRepository.GetRecord(info => info.ClientId == authorization.ClientId && info.ClientSecret == authorization.ClientSecret); if (clientInfoFromDb == null) return NotFound(); var token = _tokenRepository.InsertRecord(new Token { AccessToken = Guid.NewGuid().ToString()}); return Ok(new TokenResponse { AccessToken = token.AccessToken}); } [HttpPost("clientInfo")] public void CreateClientInformation([FromBody]ClientInfoRequest infoRequest) => _clientInfoRepository.InsertRecord(new ClientInfo {ClientId = infoRequest.ClientId, ClientSecret = infoRequest.ClientSecret}); } }<file_sep>/src/BattleNetClient.Testing/BattleNetServerBuilder.cs using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; namespace BattleNetClient.Testing { public class BattleNetServerBuilder { private readonly IBattleNetServer _server; public BattleNetServerBuilder() => _server = new BattleNetServer(); public BattleNetServerBuilder CreateClientCredentials(string clientId, string clientSecret) { Task.Run(async () => { await _server.GetClient().PostAsync("/oauth/clientInfo", new {clientId, clientSecret}, new JsonMediaTypeFormatter()); }).Wait(); return this; } public IBattleNetServer Build() => _server; } }<file_sep>/src/BattleNetClient/Diablo/DiabloClient.cs namespace BattleNetClient.Diablo { public interface IDiabloClient { IActClient Act { get; } } internal class DiabloClient : IDiabloClient { public IActClient Act { get; } public DiabloClient(IActClient actClient) { Act = actClient; } } } <file_sep>/src/BattleNetClient/Diablo/Models/NullActCollection.cs using System.Collections.Generic; namespace BattleNetClient.Diablo.Models { public class NullActCollection : ActCollection { public override List<Act> Acts => new List<Act>(); } }<file_sep>/src/BattleNetClient/BattleNetClientFactory.cs using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using BattleNetClient.Clients; using BattleNetClient.Diablo; namespace BattleNetClient { public class BattleNetClientFactory { private readonly BattleNetRegion _battleNetRegion; private readonly HttpClient _client; public BattleNetClientFactory(BattleNetRegion battleNetRegion, HttpClient client = null) { _battleNetRegion = battleNetRegion; _client = client ?? new HttpClient(); } public async Task<IBattleNetClient> CreateClientAsync(string clientId, string clientSecret) { var response = await MakeAuthenticationRequest(clientId, clientSecret); if (!response.IsSuccessStatusCode) return new NullClient(); var tokenResponse = await response.Content.ReadAsAsync<TokenResponse>(); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken); return CreateClient(); } private async Task<HttpResponseMessage> MakeAuthenticationRequest(string clientId, string clientSecret) { var authenticationHeaderValue = CreateAuthenticationHeader(clientId, clientSecret); _client.DefaultRequestHeaders.Authorization = authenticationHeaderValue; return await _client.PostAsync("https://us.battle.net/oauth/token", new FormUrlEncodedContent( new List<KeyValuePair<string, string>> {new KeyValuePair<string, string>("grant_type", "client_credentials")})); } private Clients.BattleNetClient CreateClient() { var clientHelper = new ClientHelper(_client, _battleNetRegion); var actClient = new ActClient(clientHelper); var diabloClient = new DiabloClient(actClient); return new Clients.BattleNetClient(diabloClient); } private static AuthenticationHeaderValue CreateAuthenticationHeader(string clientId, string clientSecret) => new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}"))); } }<file_sep>/src/BattleNetClient.Tests/ClientFactoryTests/CreateClientTests.cs using System.Threading.Tasks; using BattleNetClient.Testing; using Xunit; namespace BattleNetClient.Tests.ClientFactoryTests { public class CreateClientTests { private readonly BattleNetClientFactory _factory; public CreateClientTests() { var server = new BattleNetServerBuilder() .CreateClientCredentials("clientId", "clientSecret") .Build(); _factory = new BattleNetClientFactory(BattleNetRegion.UnitedStates, server.GetClient()); } [Fact] public async Task WhenClientIsCreatedWithIncorrectCredential_ThenClientIsNonAuthenticated() { var client = await _factory.CreateClientAsync("", ""); Assert.False(client.IsClientValid); } [Fact] public async Task WhenClientIsCreated_ThenValidClientIsReturned() { var battleNetClient = await _factory.CreateClientAsync("clientId", "clientSecret"); Assert.True(battleNetClient.IsClientValid); } } }<file_sep>/src/BattleNetClient.Testing/Startup.cs using BattleNetClient.Testing.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace BattleNetClient.Testing { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AuthenticationDbContext>(op => op.UseInMemoryDatabase("Auth")); services.AddTransient<AuthenticationDbContext>(); services.AddTransient(typeof(IRepository<>), typeof(AuthRepository<>)); services.AddRouting(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); } } } <file_sep>/src/BattleNetClient/Result.cs using System.Net; using BattleNetClient.Diablo.Models; namespace BattleNetClient { public interface IResult<out T> { bool IsValid { get; } T Data { get; } HttpStatusCode Code { get; } } public class Result<T> : IResult<T> { private Result(bool isValid, T data, HttpStatusCode code) { IsValid = isValid; Data = data; Code = code; } public bool IsValid { get; } public T Data { get; } public HttpStatusCode Code { get; } public static IResult<T> Success(T data) => new Result<T>(true, data, HttpStatusCode.OK); public static IResult<T> Failure(T data, HttpStatusCode statusCode) => new Result<T>(false, data, statusCode); } }<file_sep>/src/BattleNetClient/Diablo/Models/NullAct.cs using System.Collections.Generic; namespace BattleNetClient.Diablo.Models { public class NullAct : Act { public override string Slug => ""; public override int Number => -1; public override string Name => ""; public override List<Quest> Quests => new List<Quest>(); } }
0ba22ceb572e3764d4c51ca9c320d9a8bb72960e
[ "Markdown", "C#" ]
31
C#
MarkDaviesEsendex/BattleNetClient
30af940321be495fbab962d5fa0ec65f7c4b2c96
6f5b16e95ed37508855d722d2ecff33354f48cc4