branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>nalberty/ordena-o-e-busca<file_sep>/bubble.c #include <stdio.h> #include <stdlib.h> #include <locale.h> // apagar essa linha para compilar no linux #define MAX 5 void bubble(int vetor[]); int binary_sort(int vetor[], int chave, int n); int main(int argc, char const *argv[]) { setlocale(LC_ALL, "Portuguese"); int vetor[MAX], num; puts("Digite 5 números inteiros: "); for (int i = 0; i < MAX; i++) { printf("Digite: "); scanf("%i", &vetor[i]); } puts("Vetor não ordenado: "); for (int i = 0; i < MAX; i++) printf("%i ", vetor[i]); bubble(vetor); puts("\nVetor ordenado: "); for (int i = 0; i < MAX; i++) printf("%i ", vetor[i]); puts("\nAgora digite um número para pesquisar no vetor: "); printf("Número: "); scanf("%i", &num); if (binary_sort(vetor, num, MAX) == 0) puts("Elemento não encontrado!"); else puts("Elemento encontrado!"); system("pause"); // apagar essa linha para compilar no linux return 0; } void bubble(int vetor[MAX]) // ordena o vetor usando busca binária { int aux; for (int contador = 1; contador < MAX; contador++) { for (int i = 0; i < MAX - 1; i++) { if (vetor[i] > vetor[i + 1]) { aux = vetor[i]; vetor[i] = vetor[i + 1]; vetor[i + 1] = aux; } } } } int binary_sort(int vetor[], int chave, int n) // faz uma busca binária num vetor ordenado { int inf, sup, meio; inf = 0; sup = n - 1; while (inf <= sup) { meio = (inf + sup) / 2; if (chave == vetor[meio]) return meio; else if (chave < vetor[meio]) sup = meio - 1; else inf = meio + 1; } return 0; /* não encontrado */ }
43b2c955918d8914104095499e70dbaa2ab3f454
[ "C" ]
1
C
nalberty/ordena-o-e-busca
2bef5330b327fec48ebb04c7aa91636b45167015
1f92dc288ddb2223a27f653ff2e26f899e9afec4
refs/heads/main
<repo_name>AraBlocks/TinyAra<file_sep>/certificate.js const { Cert } = require('@0xcert/cert') /** * The default JSON Schema * @public * @type {Object} */ const schema = Object.freeze({ type: 'object', properties: { name: { type: 'string' } } }) /** * A certificate container for various uses in Tiny Ara. * @public * @class Certificate * @extends Cert * @see {https://docs.0xcert.org/framework/v2/api/certification.html} */ class Certificate extends Cert { /** * A readonly instance of the default Certificate schema. * @public * @accessor * @type {Object} */ static get schema() { return schema } /** * Creates a `Certificate` instance from a variety of input. * @public * @static * @param {?(Object)} input * @return {Certificate} */ static from(input) { return new this(input) } /** * `Certificate` class constructor. * @protected * @constructor * @param {Object} opts * @see {https://docs.0xcert.org/framework/v2/api/certification.html} */ constructor(opts) { super({ schema, ...opts }) } } /** * A module to provide an API and data model for certificates. * @module certificate * @example * TODO */ module.exports = { Certificate, schema } <file_sep>/wallet.js const { Wallet } = require('ethers') const fromEncryptedJson = Wallet.fromEncryptedJsonSync.bind(Wallet) const fromPrivateKey = (privateKey, ...args) => new Wallet(privateKey, ...args) const fromMnemonic = Wallet.fromMnemonic.bind(Wallet) /** * @module wallet * @example * * const { fromMnemonic } = require('tinyara/wallet') * const walletPath = `m/44'/60'/0'/0/0` // index 0 (first account) * const wallet = fromMnemonic(mnemonicPhrase, walletPath) * * @example * const { Wallet } = require('tinyara/wallet') * const wallet = new Wallet(privateKey) */ module.exports = { fromEncryptedJson, fromPrivateKey, fromMnemonic, Wallet } <file_sep>/keystore.js // TODO(jwerle): use TinyBox format? eth keystore? <file_sep>/network.js // TODO(jwerle): port networking <file_sep>/ledger/erc721.js const { GenericProvider } = require('@0xcert/ethereum-generic-provider') const { AssetLedger } = require('@0xcert/ethereum-asset-ledger') const { getDefaultProvider } = require('../provider') /** * A mapping of tokens and their network addresses * @public * @type {Object} */ const tokens = { } /** * A factory for creating a `AssetLedger` instance for new or * known ERC721 ledgers. * @param {String} token * @param {?(Object)} opts * @return {AssetLedger} * @throws TypeError * @see {https://docs.0xcert.org/framework/v2/api/ethereum-connectors.html#asset-ledger} */ function createERC721Ledger(token, opts) { if (!opts || 'object' !== typeof opts) { opts = {} } if ('string' !== typeof token) { throw new TypeError('Expecting token to be a string.') } const provider = opts.provider instanceof GenericProvider ? opts.provider : new GenericProvider({ ...opts, client: opts.provider || getDefaultProvider() }) // determine ledger ID from options or network mapping // falling back to `token` input as an address const ledgerId = ( opts.ledgerId || opts.token || tokens[token.toUpperCase()].networks[opts.network || 'mainnet'] || token ) if ('string' !== typeof ledgerId) { throw new TypeError('Expecting token name or ledger ID to be a string.') } return new AssetLedger(provider, ledgerId) } /** * Defines a token mapping. * @public * @param {String} token * @param {Object} definition */ function defineToken(token, definition) { tokens[token] = { ...definition } return tokens[token] } /** *A module to provide higher level APIs for working value (fungible) tokens. * @module erc721 * @example * const { createERC721Ledger } = require('tinyara/ledger/erc721') * const ledger = createERC721Ledger('NFT token contract address') // mainnet by default * ledger.getInfo().then(console.log) // returns info like, supply */ module.exports = { createERC721Ledger, defineToken, tokens } <file_sep>/crypto.js /** * A module to provide cryptographic primitives for various functions * of Tiny Ara. * @module crypto * @see {https://github.com/arablocks/ara-crypto} */ module.exports = require('ara-crypto') <file_sep>/did.js const { DID, parse } = require('did-uri') module.exports = { DID, parse } <file_sep>/ledger/index.js const erc20 = require('./erc20') /** * A module for working with ERC20 and ERC721 ledgers. * @module ledger * @example * const ledger = require('tinyara/ledger') * const weth = ledger.erc20.weth() * const ara = ledger.erc20.ara() */ module.exports = { erc20 } <file_sep>/README.md # TinyAra An experiment focusing on simplicity and AFS-as-NFT > *Brainstorm: TinyAra could be immutable archives with an ERC 721 representation. The holder of the NFT is the creator so rights can be transferable. I was thinking ERC 1155 as a way to represent federation for servers. ARA needs to be deployed to polygon and L2 networks. Archive rights can be bought and sold on opensea. I think the UI needs to be web based. Desktop app is a progressive web app. No electron.*
833f70f6e1367aadb1808373db32c70be192ec18
[ "JavaScript", "Markdown" ]
9
JavaScript
AraBlocks/TinyAra
2a13c15b2cdcf64dc6de440e4bbac0c31be01811
e3375aa882b03b9bea84b57006364cea5097fcc2
refs/heads/master
<repo_name>cutecoley/PhotoLib<file_sep>/client/app.js angular.module('photolib', ['photolib.services', 'photolib.pages', 'ngRoute']) .config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'photo.html', controller: 'photoController' }) })
06a2812bfeefdc2efdfa5a4d767d78b94ce7157b
[ "JavaScript" ]
1
JavaScript
cutecoley/PhotoLib
0dfce2c286be312c57c13c0e0b137eefd91757b7
66f0c4b98e8412fc14d9283a6c523eda3dba57c0
refs/heads/master
<repo_name>jerv13/pipe-rat<file_sep>/config/dependencies.php <?php /** * dependencies.php */ return [ 'config_factories' => [ /* Extractors */ Reliv\PipeRat\Extractor\CollectionPropertyGetterExtractor::class => [], Reliv\PipeRat\Extractor\PropertyGetterExtractor::class => [], /* Resource Controllers */ Reliv\PipeRat\Middleware\ResourceController\DoctrineResourceController::class => [ 'arguments' => [ 'Doctrine\ORM\EntityManager', Reliv\PipeRat\Hydrator\PropertySetterHydrator::class ], ], Reliv\PipeRat\Middleware\ResourceController\RepositoryResourceController::class => [ 'arguments' => [ 'ServiceManager', Reliv\PipeRat\Hydrator\PropertySetterHydrator::class ], ], /* Hydrators */ Reliv\PipeRat\Hydrator\PropertySetterHydrator::class => [], /* Resource Middleware */ // ACL Reliv\PipeRat\Middleware\Acl\RcmUserAcl::class => [ 'arguments' => [ RcmUser\Service\RcmUserService::class, ], ], // Error Middleware Reliv\PipeRat\Middleware\Error\TriggerErrorHandler::class => [], Reliv\PipeRat\Middleware\Error\NonThrowingErrorHandler::class => [], // Extractor Reliv\PipeRat\Middleware\Extractor\CollectionPropertyGetterExtractor::class => [], Reliv\PipeRat\Middleware\Extractor\PropertyGetterExtractor::class => [], // Header Reliv\PipeRat\Middleware\Header\AddResponseHeaders::class => [], Reliv\PipeRat\Middleware\Header\CacheMaxAge::class => [], Reliv\PipeRat\Middleware\Header\Expires::class => [], // InputFilter Reliv\PipeRat\Middleware\InputFilter\ZfInputFilterClass::class => [ 'arguments' => [ \Reliv\PipeRat\ZfInputFilter\Hydrator\ZfInputFilterErrorHydrator::class, ], ], Reliv\PipeRat\Middleware\InputFilter\ZfInputFilterConfig::class => [ 'arguments' => [ \Reliv\PipeRat\ZfInputFilter\Hydrator\ZfInputFilterErrorHydrator::class, ], ], Reliv\PipeRat\Middleware\InputFilter\ZfInputFilterService::class => [ 'arguments' => [ \Reliv\PipeRat\ZfInputFilter\Hydrator\ZfInputFilterErrorHydrator::class, 'ServiceManager', ], ], Reliv\PipeRat\Middleware\InputFilter\ZfInputFilterServiceConfig::class => [ 'arguments' => [ \Reliv\PipeRat\ZfInputFilter\Hydrator\ZfInputFilterErrorHydrator::class, \ZfInputFilterService\InputFilter\ServiceAwareFactory::class, ], ], // Request Formatter Reliv\PipeRat\Middleware\RequestFormat\UrlEncodedCombinedFilter\Fields::class => [], Reliv\PipeRat\Middleware\RequestFormat\UrlEncodedCombinedFilter\Limit::class => [], Reliv\PipeRat\Middleware\RequestFormat\UrlEncodedCombinedFilter\Order::class => [], Reliv\PipeRat\Middleware\RequestFormat\UrlEncodedCombinedFilter\Skip::class => [], Reliv\PipeRat\Middleware\RequestFormat\UrlEncodedCombinedFilter\Where::class => [], Reliv\PipeRat\Middleware\RequestFormat\JsonParamsFilter\Fields::class => [], Reliv\PipeRat\Middleware\RequestFormat\JsonParamsFilter\Limit::class => [], Reliv\PipeRat\Middleware\RequestFormat\JsonParamsFilter\Order::class => [], Reliv\PipeRat\Middleware\RequestFormat\JsonParamsFilter\Skip::class => [], Reliv\PipeRat\Middleware\RequestFormat\JsonParamsFilter\Where::class => [], Reliv\PipeRat\Middleware\RequestFormat\JsonParamsRequestFormat::class => [], Reliv\PipeRat\Middleware\RequestFormat\JsonRequestFormat::class => [], // Response Formatter Reliv\PipeRat\Middleware\ResponseFormat\FileDataResponseFormat::class => [ 'arguments' => [ Reliv\PipeRat\Extractor\PropertyGetterExtractor::class, ], ], Reliv\PipeRat\Middleware\ResponseFormat\FileResponseFormat::class => [], //Reliv\PipeRat\Middleware\ResponseFormat\HtmlListResponseFormat::class => [ // 'arguments' => [ // Reliv\PipeRat\Extractor\CollectionPropertyGetterExtractor::class, // ], //], Reliv\PipeRat\Middleware\ResponseFormat\HtmlResponseFormat::class => [ 'arguments' => [ Reliv\PipeRat\Extractor\PropertyGetterExtractor::class, ], ], Reliv\PipeRat\Middleware\ResponseFormat\JsonErrorResponseFormat::class => [], Reliv\PipeRat\Middleware\ResponseFormat\JsonResponseFormat::class => [], Reliv\PipeRat\Middleware\ResponseFormat\XmlResponseFormat::class => [], // Main 'Reliv\PipeRat\Middleware\BasicConfigMiddleware' => [ 'class' => Reliv\PipeRat\Middleware\OperationMiddleware::class, 'arguments' => [ Reliv\PipeRat\Provider\BasicConfigRouteMiddlewareProvider::class, Reliv\PipeRat\Provider\BasicConfigErrorMiddlewareProvider::class, Reliv\PipeRat\Provider\BasicConfigMiddlewareProvider::class, ], ], 'Reliv\PipeRat\Middleware\Router' => [ 'class' => Reliv\PipeRat\Middleware\Router\CurlyBraceVarRouter::class, ], /* Middleware Providers */ Reliv\PipeRat\Provider\BasicConfigErrorMiddlewareProvider::class => [ 'arguments' => [ 'Config', 'ServiceManager', ], ], Reliv\PipeRat\Provider\BasicConfigMiddlewareProvider::class => [ 'arguments' => [ 'Config', 'ServiceManager', ], ], Reliv\PipeRat\Provider\BasicConfigRouteMiddlewareProvider::class => [ 'arguments' => [ 'Config', 'ServiceManager', ], ], /* ZfInputFilter */ Reliv\PipeRat\ZfInputFilter\Hydrator\ZfInputFilterErrorHydrator::class => [ 'arguments' => [ Reliv\PipeRat\ZfInputFilter\Service\FieldErrorsFactory::class ], ], Reliv\PipeRat\ZfInputFilter\Service\FieldErrorsFactory::class => [], ], ]; <file_sep>/src/Middleware/Acl/RcmUserAcl.php <?php namespace Reliv\PipeRat\Middleware\Acl; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use RcmUser\Service\RcmUserService; use Reliv\PipeRat\Middleware\AbstractMiddleware; use Reliv\PipeRat\Middleware\Middleware; /** * Class RcmUserAcl * * @author <NAME> <<EMAIL>> * @copyright 2016 Reliv International * @license License.txt * @link https://github.com/reliv */ class RcmUserAcl extends AbstractAcl implements Middleware { /** * @var RcmUserService */ protected $rcmUserService; /** * @param RcmUserService $rcmUserService */ public function __construct( RcmUserService $rcmUserService ) { $this->rcmUserService = $rcmUserService; } /** * __invoke * * @param Request $request * @param Response $response * @param callable|null $next * * @return mixed */ public function __invoke( Request $request, Response $response, callable $next = null ) { $isAllowed = $this->rcmUserService->isAllowed( $this->getOption($request, 'resourceId', null), $this->getOption($request, 'privilege', null) ); if ($isAllowed) { return $next($request, $response); } return $this->getResponseWithAclFailStatus($request, $response); } }
24bf60ceb0b1b4076a9e5502d1466c1ceb156543
[ "PHP" ]
2
PHP
jerv13/pipe-rat
9b3e4a968a6f5c57841bc5bc871216f051e1cd24
d04481ec4d70638e3ae7313d42be426291f329cb
refs/heads/master
<repo_name>muryliang/algorithmse<file_sep>/src/percolate.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #define ISUNION(p,q) (root(p) == root(q)) #define N 20 static int array[N * N]; static void init(int array[]); static int test(int p , int q); static void unify(int p , int q); static int root(int p); static int root2(int p); static int myrandom(int n); /* generate a number between 0 to n-1 */ static void printtable(int (*)[N]); int main(void) { int state[N][N]; int i , j; srand(time((time_t *)NULL )); init( array); /*initialize the array */ for( i = 0 ; i < N ; i++) for(j = 0 ; j < N ; j++){ state[i][j] = myrandom(2); /*initialize to 0(block) or 1(open)*/ } printtable(state); /* do the unify*/ for( i = 0 ; i < N ; i++){ for(j = 0; j < N ; j++){ if( state[i][j] != 0) { if( i -1 >= 0 && state[i-1][j] != 0) unify((i-1)*N + j , i*N + j); if( i +1 < N && state[i+1][j] != 0) unify((i+1)*N + j , i*N + j); if( j -1 >= 0 && state[i][j-1] != 0) unify(i*N + j-1 , i*N + j); if( j +1 < N && state[i][j+1] != 0) unify(i*N + j+1 , i*N + j); } } } /*unify is over , now test the percolate */ for( i = 0 ; i < N ; i++){ unify(array[0] , array[i]); unify(array[(N-1)*N ] , array[(N-1)*N+i]); } test( array[0] , array[N*N-1]); return 0; } static void init( int *array) { int i; for( i = 0 ; i < N*N ; i++) array[i] = i; } /* * test if p q belong to the same union */ static int test(int p , int q) { if(ISUNION(p,q) != 0) printf("yes\n"); else printf("no\n"); return 1; } /* * append the root of p to a child of the root * fo q */ static void unify(int p , int q) { static int sz[N*N]; static int flag = 0; int rp = root(p); int rq = root(q); int i; if( flag == 0){ flag = 1; for( i = 0 ; i < N*N ; i++ ) sz[i] = 1; } if( rp == rq) return; if(sz[rp] > sz[rq]) { array[rq] = rp; sz[rp] += sz[rq]; } else { array[rp] = rq; sz[rq] += sz[rp]; } } /* * get root */ static int root(int ori) { int p = ori; int tmp; while( array[p] != p) p = array[p]; /* * do the path compression; now p is the root; * let every node in the path from ori to root * be a direct child of the root */ /* * just fix a bug here , ori = tmp; * becareful !! */ while( array[ori] != p ) { tmp = array[ori]; array[ori] = p; ori = tmp; } return p; } static int root2(int ori) { int p = ori; /* * another method, on the path to the root * make every other node's parent(that is , keep step of 2) to its original grandparent * to halve the height of the tree */ while( array[p] != p){ array[p] = array[array[p]]; p = array[p]; } return p; } static void printtable(int (*a)[N]) { int i , j; for( i = 0; i < N ; i++){ for( j = 0 ; j < N ; j++) { printf("%3d" , a[i][j]); } putchar('\n'); } } /* * if you want to set the random of the p percent * then just use RAND_MAX * p , and then rand() , * test if result < the above result ,then 1 * else 0( use this to simulate the percent) */ static int myrandom( int n) { return (rand() / (RAND_MAX / n + 1)); } <file_sep>/src/union.c /* * this module implements quick find of union set, * very easy , when union , just set every value equal to * the first one to the value of the second one * ,when want to find , just compare two values */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 10 #define BUF 255 static int array[MAX]; static void test(int , int ); void initarray(void); int isunified(int , int); void unify(int , int); int main(void) { char linebuf[BUF];/*store the geted line*/ char cmd[BUF]; /*store the cmd*/ int a , b; /*store two numbers to test or unify*/ initarray(); printf("start , every thing is alone\n"); printf("now get input....\n"); while(1) { if(fgets(linebuf , BUF , stdin) == NULL ) exit(1); /*wrong something*/ if(3 != sscanf(linebuf , "%s %d %d" , cmd , &a , &b)) exit(2); /*wrong args input*/ if(strcmp(cmd , "test")) test(a , b); else if(strcmp(cmd , "unify")) unify(a , b); /* else if(strcmp(cmd , "init")) initarray(); */ else{ printf("unknown cmd\n"); } } /* test(3 , 5); test(1 , 6); unify(1 , 4); unify(1 , 6); unify(2 , 3); unify(5 , 0); unify(6 , 2); test(3 , 2); test(1 , 6); test(1 , 3); test(7 , 8); test(2 , 5); */ return 0; } static void test(int i , int j) { printf("testing %d %d... " , i , j); if(isunified(i , j) == 1) printf("yes\n"); else printf("no\n"); } void initarray(void) { int i; for(i = 0 ; i < MAX ; i++) { array[i] = i; } } void unify(int i , int j) { int srcval = array[i]; int destval = array[j]; /*convert every one whose value equal to srcval to the val destval*/ int index; printf("unifying %d %d... \n" , i , j); for(index = 0 ; index < MAX ; index++) { if(array[index] == srcval) array[index] = destval; } } int isunified(int i , int j) { return (array[i] == array[j]) ? 1 : 0; } <file_sep>/src/weightunion.c /* * use another array to record the every root's objects it has; * every time union , just merge the less one to the more one * that will keep log N most tree deep */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define ISUNION(p,q) (root(p) == root(q)) static int array[10]; static void init(int array[]); static int test(int p , int q); static void unify(int p , int q); static int root(int p); int main(void) { char buf[50]; char cmd[10]; int p , q; init(array); while( fgets(buf , 49 , stdin) != NULL ) { if(sscanf(buf , "%s %d %d" , cmd , &p , &q) == 3) { if(strcmp(cmd , "test") == 0) test(p , q); else if(strcmp(cmd , "unify") == 0) unify(p , q); else printf("unknow operations\n"); } else printf("input error\n"); } return 0; } static void init( int *array) { int i; for( i = 0 ; i < 10 ; i++) array[i] = i; } /* * test if p q belong to the same union */ static int test(int p , int q) { if(ISUNION(p,q) != 0) printf("yes\n"); else printf("no\n"); return 1; } /* * append the root of p to a child of the root * fo q */ static void unify(int p , int q) { static int sz[10] = {1,1,1,1,1,1,1,1,1,1}; int rp = root(p); int rq = root(q); if( rp == rq) return; if(sz[rp] > sz[rq]) { array[rq] = rp; sz[rp] += sz[rq]; } else { array[rp] = rq; sz[rq] += sz[rp]; } } /* * get root */ static int root(int p) { while( array[p] != p) p = array[p]; return p; } <file_sep>/Makefile CC = gcc CFLAGS = -g -Wall -pedantic -O0 LFLAGS = LDLIBS = SRC = $(wildcard ./src/*.c) TARGET = $(patsubst %.c,%,$(SRC)) all: $(TARGET) clean: rm -rf $(TARGET) <file_sep>/src/pathcompression.c /* * in addition to the weightunion , every time search the root * of one node , put every node in path to a child of the root(root()); * or put every other node's parent to its origin grandparent(root2()) */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define ISUNION(p,q) (root(p) == root(q)) static int array[10]; static void init(int array[]); static int test(int p , int q); static void unify(int p , int q); static int root(int p); static int root2(int p); int main(void) { char buf[50]; char cmd[10]; int p , q; init(array); while( fgets(buf , 49 , stdin) != NULL ) { if(sscanf(buf , "%s %d %d" , cmd , &p , &q) == 3) { if(strcmp(cmd , "test") == 0) test(p , q); else if(strcmp(cmd , "unify") == 0) unify(p , q); else printf("unknow operations\n"); } else printf("input error\n"); } return 0; } static void init( int *array) { int i; for( i = 0 ; i < 10 ; i++) array[i] = i; } /* * test if p q belong to the same union */ static int test(int p , int q) { if(ISUNION(p,q) != 0) printf("yes\n"); else printf("no\n"); return 1; } /* * append the root of p to a child of the root * fo q */ static void unify(int p , int q) { static int sz[10] = {1,1,1,1,1,1,1,1,1,1}; int rp = root(p); int rq = root(q); if( rp == rq) return; if(sz[rp] > sz[rq]) { array[rq] = rp; sz[rp] += sz[rq]; } else { array[rp] = rq; sz[rq] += sz[rp]; } } /* * get root */ static int root(int ori) { int p = ori; int tmp; while( array[p] != p) p = array[p]; /* * do the path compression; now p is the root; * let every node in the path from ori to root * be a direct child of the root */ while( array[ori] != p ) { tmp = array[ori]; array[ori] = p; p = tmp; } return p; } static int root2(int ori) { int p = ori; /* * another method, on the path to the root * make every other node's parent(that is , keep step of 2) to its original grandparent * to halve the height of the tree */ while( array[p] != p){ array[p] = array[array[p]]; p = array[p]; } return p; }
c5fd441ca569db28054e097ed52696ce99e24cb2
[ "C", "Makefile" ]
5
C
muryliang/algorithmse
929a121e98613200c83a4cfd907c51668c867778
ae4f4d8805698f8376c5aa0107548857cbc2c257
refs/heads/master
<file_sep>from flask import Flask import time application = Flask(__name__) @application.route("/") def index(): time.sleep(2) return str(int(time.time())) <file_sep>from multiprocessing import Process import time import socket import mechanize import random URL = "http://127.0.0.1:8000" TIMEOUT = 10 N = 1000 RUNNING = True class Worker: def __init__(self, URL, TIMEOUT, ID): self.url = URL self.timeout = TIMEOUT self.br = mechanize.Browser() self.br.set_handle_robots(False) self.id = ID def open_conn(self): global RUNNING while RUNNING: try: data = self.br.open(self.url, None, self.timeout).read().decode().strip() if time.time() - int(data) <= 30: print ("Thread %s - OK" % self.id) else: print ("Thread %s - Invalid data %s" % (self.id, data)) RUNNING = False except socket.error: print ("Thread %s - Timeout" % self.id) RUNNING = False time.sleep(random.randint(1, 35)) #time.sleep(100) pool = [] for i in range(N): w = Worker(URL, TIMEOUT, i) t = Process(target=w.open_conn) pool.append(t) t.start() <file_sep>//Задaние по Highload Dev src/main.rs - код прокси сервера ClientEmulation.py - эмуляция запросов от пользователей, требуется модуль mechanize (pip install mechanize) ServerEmulation/startwsgi.sh- эмуляция сервера с задержкой 2 секунды, требуются flask и uwsgi (pip install flask uwsgi) Так же во вкладке релизы выложенны исполняемые файлы для Windows и Linux. Запускается командой ./web_proxy_x64 -U <URL вебсайта, http://127.0.0.1:8000 по умолчанию> -B <хост:порт для подключений клиентов, 127.0.0.1:8888 по умолчанию> <file_sep>use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; use actix_web::{web, App, HttpServer, HttpRequest, HttpResponse}; extern crate reqwest; extern crate getopts; use getopts::Options; use std::env; static URL: &str = "http://127.0.0.1:8080/"; // URL веб-сервера по умолчанию static BIND: &str = "127.0.0.1:8000"; // хост:порт для подключений клиентов по умолчанию static VALID_TIME: u64 = 20; struct CacheObject { response:String, timestamp:SystemTime, url:String } fn fetch(co:&mut CacheObject) { let url = format!("{}", co.url); match reqwest::get(&url) { Ok(mut x) => { co.response = x.text().unwrap(); co.timestamp = SystemTime::now(); }, Err(_) => { println!("Warning: returning old reponse due to request error!"); } }; } fn index(co: web::Data<Mutex<CacheObject>>, _req: HttpRequest) -> HttpResponse { { let mut co = &mut *(co.lock().unwrap()); if SystemTime::now().duration_since(co.timestamp).unwrap().as_secs() >= VALID_TIME { fetch(&mut co); } } let co = &*(co.lock().unwrap()); HttpResponse::Ok().header("Cache-Control", format!("only-if-cached,max-age={}", VALID_TIME - co.timestamp.elapsed().unwrap().as_secs())).body(co.response.clone()) } fn print_usage(program: &str, opts: Options) { let brief = format!("{} -U <url> -B <local address>", program); print!("{}", opts.usage(&brief)); } fn main() { let mut localbind: String = BIND.to_string(); let mut url: String = URL.to_string(); let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("U", "url", "Forward URL (default http://127.0.0.1:8000)", "URL"); opts.optopt("B", "bind", "Bind address (default 127.0.0.1:8888)", "BIND"); opts.optflag("h", "help", "Help message"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(_) => { print_usage(&program, opts); return (); } }; if matches.opt_present("h") { print_usage(&program, opts); return (); } if matches.opt_present("U") { url = matches.opt_str("U").unwrap().clone(); } if matches.opt_present("B") { localbind = matches.opt_str("B").unwrap().clone(); } println!("Bind address: {}", localbind); println!("URL: {}", url); let mut co = CacheObject {response:"".to_string(), timestamp:UNIX_EPOCH, url:url.clone()}; match reqwest::get(&url) { Ok(mut x) => {co.response = x.text().unwrap(); }, Err(e) => {println!("Invalid URL: {}", e); return ();} } let cache = web::Data::new(Mutex::new(co)); let srv = HttpServer::new(move || { App::new() .register_data(cache.clone()) .service(web::resource("/").to(index)) }); match srv.bind(localbind) { Ok(srv) => {srv.run().unwrap();}, Err(e) => {println!("Bind error: {}", e);} } } <file_sep>uwsgi --http 127.0.0.1:8080 --queue 16 --wsgi-file server.py
a8565fcd1836fc6e7316add9503933b6211d3548
[ "Markdown", "Rust", "Python", "Shell" ]
5
Python
user37829/task587434
20bc22339ecd03871dcd249c1560625abd837d05
66e3d19ab3bee2b42f850be3f14f7d35b09d5749
refs/heads/master
<repo_name>crkjlive/HolaMundo<file_sep>/Js-holaMundo/trampolines.js // Trampolines // trampolines nos ayudan a mejorar la recursividad // muchos llamados recursivos genera un error que se llama // Maximum call stack size exceeded // limitandonos a hacer funciones que se llaman asi mismas muchas veces // para esto usamos una tecnica llamada trampolines, lo cual nos permite hacer llamados recursivos de una misma funcion cuantas veces nosotros queramos o cuanta memoria tenga la maquina lo cual nos permita hacer este llamado, eliminando la barrera del Tail call optimization. // code... const suma = (number, sum = 0) => ( number === 0 ? sum ? suma(number - 1, sum + number) ) const r = suma(100000) console.log(r) // 5050 // 500500 // Maximum call stack size exceeded // aqui ya nos dispara el error, // tecnica, para poder seguir desarrollando la recursividad const trampoline = fn => (...args) => { let result = fn(...args) while (typeof result === 'function') { result = result() } return result } const suma = (number, sum = 0) => { number === 0 ? sum ? : () => suma(number - 1, sum + number) } const tsuma = trampoline(suma) const r = tsuma(100000000) console.log(r); // trampolinizable. // con esta funcion ya queda optimizada para que la tecnica de trampolin funcione y evite el limite de javascript de llamar funciones asi misma. // trampoline nos permite generar una funcion de manera recursiva, ejecutando una y otra vez eliminando este limite.<file_sep>/Js-holaMundo/array.reduce.js // reduce // reduce es un metodo que tienen los arreglos en javascript, y permite ejecutar funciones reducer. (se llaman exactamente igual que los reducer en redux) // la funcion de reducer recibe dos argumentos, // el primero es un valor que esta siendo acumulado // el segundo es el elemento que se esta iterando del arreglo. // finalmente esta funcion debe devolver el nuevo elemento que se esta acumulando, siendo una de la funciones mas versatiles dentro de lso arreglos, // ya que permite no solo hacer reducciones de elementos, si no que permite hacer mas operaciones, bastantemente utiles en el munod real. // code... // funcion reducer // const reducer = (acumulado, valorActual) => nuevoAcumulador const reducido = [1,2].reduce((acc, el) => acc + el, 0) console.log(reducido) // 3 // por que da 3, la constate parte en 0, acc es el acumulador cuyo valor es 0, y el es él elemento que es el primer elemento 1, lugo pasa a la funcion, acc + el = 1, pues 0 + 1 = 1, ya el acumulador inicial vale 1, y vuelve a iterar. // acc = 1, el = 2, acc + el = 3. // ejemplo 2, // con el array de los números. const numeros = [1,2,3,4,5] const resultado = numeros.reduce((acc, el) => acc + el, 0) console.log(resultado) // 15 // esta es la implementacion correcta, para hacer la suma del total de una arreglo. // ejemplo 3 // caso de la vida real. // cuando queremos buscar un elemento en particular en un arreglo demasiado grande, usamos el metodo // array.find // este metoo se usa cuando se hacen cruce de arrays, donde mientra se itera una tabla, el metodo find busca en la otra mientras se itera. // rompiendo el preformans de la empresa. se debe indexar. // const indexed = mascotas.reduce((acc, el) => , {}) // se va a indexar, pero el valor inicial ya no va a ser un número si no un objeto {}. const mascotas = [ {nombre: 'Puchini', edad: 12, tipo: 'perro'}, {nombre: 'Chanchito', edad: 3, tipo: 'perro'}, {nombre: 'Pulga', edad: 10, tipo: 'perro'}, {nombre: 'Pelusa', edad: 16, tipo: 'gato'} ]; const indexed = mascotas.reduce((acc, el) => ({ ...acc, [el.nombre]: el, }),{}) console.log(indexed['Pelusa']); // {nombre: 'Pelusa', edad: 16, tipo: 'gato'} // de esta forma luego de indexar el arreglo, indexamos por el elemento específico que queremos encontrar, utilizando el método de reduce // ejemplo 4 // ahora vamos a tomar este arreglo que contiene elemento que estan anidado // osea una arreglo que contiene mas arreglos, end point. // que vamos hacer, volver este arreglo plano que no contenga anidaciones. // método concat = concatenación // objetivo. [1,2,3,4,5] const anidado = [1, [2,3], 4,[5]] const plano = anidado.reduce((acc, el) => acc.concat(el), [] ); console.log(plano) // resumen: // el elemento vacio [] = acc se concatena con el primer elemento del array, el, que es 1 del array original. luego el acumulado [1] se concatena con el segundo elemento, el, que es el segundo valor del array original que es [2,3] quedando el reduce en una array [1,2,3], vuelve a iterar y concatenar con los demas elementos del array original [4,5], hasta el ultimo elemento del array original creando una copia concatenada y plana, [1,2,3,4,5]. // recapitulemos. // el método de reduce, recibe una funcion llamada reducer, la cual recibe dos argumentos el primero es el acumulador y el segundo argumento es el elemento que se esta iterando, (acc,el) => nuevoAcc y el nuevoAcc sera el nuevo acumulador que se va a pasar como argumento, la segunda vez. // ademas el metodo de reduce, recibe un segundo argumento, que sera el valor inicial con el cual viene nuestro acumulado. reduce(reducer, inicial). <file_sep>/Js-holaMundo/arrow_functions.js // arrow functions // fat arrow functions // es una nueva forma de escribir las funciones, las sintaxis es mucho mas corta, sin la palabra reservada function. /* (a , b) => a + b */ //code... function suma( a,b ) { return a + b } const resultado = suma( 1 , 5 ) console.log(resultado) // 6 // fat arrow function // reescribamos la function. const sumar = (a, b) => a + b const resultados = sumar(1 , 5) console.log(resultados) // esto lo que quiere decir es que podemos tomar funciones como valores. // lo que quiere decir que podemos tomas una function y asignarce a una constante o una variable. /* const sumar = (a, b) => a + b */ // cuando las fat arrow function, son de una sola linea, tienen un return implicito, esto quiere decir, que no es necesario queq yo escriba la palabra reservada return, siempre y cuando la funcion tenga una sola ejecucion, o lo que se valla a ejecutar en una sola linea. y presendir de los corchetes. // si se requiere hacer mas de una resultado la sintaxis cambia. const suman = (a, b) => { const c = a + b return c + 1 } console.log(suman(1,5)) // 7 // ahora pasa a poder hacer mas ejecuciones. // recapitulando: // anteriormente se requeria la palabra reservada de function, ahora podemos declarar funciones anonimas, fat arrow function, y asignarlas a una constante. // return implicito, ya no es necesario utilizar la palabra de ruturn, siempre y cuando nuestra funcion dea de una sola linea, y se valla a returnar inmediatamente el valor, que logre evaluar. <file_sep>/Js-holaMundo/array.filter.js // filter // metodo para filtrar objetos dentro de una arreglo //objeto: crea un array de menos o igual tamaño al original // para capturar una parte del array original // sacando los elementos que se requieren // filter recibe unas condicines puras para poder sacar la informacion // code... const numeros = [1,2,3,4,5,6,7,8,9] const mascotas = [ {nombre: 'Puchini', edad: 12, tipo: 'perro'}, {nombre: 'Chanchito', edad: 3, tipo: 'perro'}, {nombre: 'Pulga', edad: 10, tipo: 'perro'}, {nombre: 'Pelusa', edad: 16, tipo: 'gato'} ]; console.log(numeros) console.log(mascotas) // objetivo... const numerosFiltrados = numeros.filter(x => x < 5) console.log(numerosFiltrados) // nos va a devolver un nuevo array filtrado siempre y cuando la funcion sea true. // los elemento se asignan a la nueva variable // el metodo que se esta aregando de filter es inmutable. ya que mantiene los elementos filtrados en esa varible. // ya que devuelve una nueva copia de nuestro arreglo. // *** ejemplo con las mascotas *** const perros = mascotas.filter(x => x.tipo == 'perro') console.log(perros) // nos muestra un arreglo filtrado con los objetos completos de tipo 'perro' const gatos = mascotas.filter(x => x.tipo == 'gato' ) console.log(gatos) const mayores = mascotas.filter(x => x.edad >= 11) console.log(mayores) // recapitular // el metodo de filter nos puede crear, un arreglo de igual o menor tamaño, del cual estamos generando. // este nuevo arreglo no va a ser el mismo arreglo mutado, si no va a ser una copia nueva, que va a mantener sus elementos si la funcion fue verdadera. por cada iteracion de los elementos. // filter es inmutable. <file_sep>/Js-holaMundo/closures.js // closures // programacion funcional. // son la combinacion de una funcion, y el alcance lexico que se tiene. // un closures, se crea por fuera de la funcion. //code... const x = 'Fluffy' const f = () => { const y = 'kins' console.log(x , y) } f() // una funcion puede acceder a las constantes que esten definidas dentro de la funcion y a variables que este definidas fuera de la funcion, esto se conoce como closure. // en que favorece? // ya que con los closure podemos realizar composicion, ya sea de objetos o tambien de funciones, ya ir modificando el comportamiento. // code... /* npm i -S isomorphic-ftech api que no permite hacer pruebas en node. */ require (isomorphic-ftech) const crudder = dominio => recurso => { const url = `${dominio}/${recurso}` return({ create: () => fetch(url, { method: 'POST', body: JSON.stringify(x), }).then( x => x.json()), get: () => fetch(url).then(x=>x.json()) }) } <file_sep>/Js-holaMundo/spread_operator.js // spread operator // ...gato Se esta indicando que se requiere una copia completa de la constante de gato, y sus propiedades, su nombre: y edad: y se la asigne a gato2. //code... const gato = { nombre: '<NAME>', edad: 7 } const gata = { ...gato } gata.nombre = 'lala' gata.edad = 8 const michu = { ...gato } michu.nombre = 'michin' michu.edad = 5 const gatos = [gato, gata, michu] console.log(gatos) /* [ { nombre: '<NAME>', edad: 7 }, { nombre: 'lala', edad: 8 }, { nombre: 'michin', edad: 5 } ] */ // spread operator // crea una arreglo, con 3 objetos, y el spread operator me ayuda a crear nuevos objetos, copiando sus propiedades y completamente reutilizables. <file_sep>/Js-holaMundo/array.map.js // map // map nos permite transformar los elementos de una arreglo, dejandolo de la misma longitud, pero cambiados. // generando una nueva copia. // funcion de suma total. // NO HACER ESTA IMPLEMENTACION. const suma = (ns) => { let acumulado = 0; for(i = 0; i < ns.length; i++){ acumulado += ns[i]; } return acumulado } const numeros = [1,2,3,4,5] // multiplicar * 2 const multiplicados = numeros.map(x => x * 2) console.log(multiplicados) // en este ejemplo vemos como toma el arreglo e iterando cada objeto crea un nuevo arreglo con la funcion true que se creo. // generando un nuevo array de la misma longitud. // vamos a crear parejas de numeros. const parejas = numeros.map(x => [x, x]) console.log(parejas) /* [ [ 1, 1 ], [ 2, 2 ], [ 3, 3 ], [ 4, 4 ], [ 5, 5 ] ] */ // se pueden hacer operaciones mas complejas. // ejemplo2 // obtener la edad promedio de todas las mascotas de este arreglo. const mascotas = [ {nombre: 'Puchini', edad: 12, tipo: 'perro'}, {nombre: '<NAME>', edad: 3, tipo: 'perro'}, {nombre: 'Pulga', edad: 10, tipo: 'perro'}, {nombre: 'Pelusa', edad: 12, tipo: 'gato'} ]; /* console.log(numeros) console.log(mascotas) */ // edad promedio. const resultado1 = suma(numeros) console.log(resultado1) // 15 // vamos a crear un arreglo de numeros, ya que no se pude usar la funcion suma sobre los objetos. // vamos a transformar el arreglo a numeros. const edades = mascotas.map(x => x.edad) console.log(edades) // [ 12, 3, 10, 16 ] const resultado = suma(edades) console.log(resultado / edades.length) // 9.25 es el promedio de edad de las mascotas. // recapitulemos. // map nos permite crear un nuevo arreglo, de misma longitud que el arreglo inicial al que le aplicamos el metodo de map. // el metodo de map permite tomar la funcion que le estamos pasando como argumento, y aplicar la funcion a cada uno de los elementos que se encuentran dentro de ese arreglo.<file_sep>/README.md # HolaMundo Mis apuntes del canal Hola Mundo de Javascript
b83a96cc3956d0bf51dbec88569aca4c460bfb04
[ "JavaScript", "Markdown" ]
8
JavaScript
crkjlive/HolaMundo
8691091531a999ce8ca9c85e5d1cf12313990488
a84028ceee994928b8c17e0701f4827e75f061c7
refs/heads/master
<file_sep><?php class JeuxController { public function index() { $list = Jeu::findAll(); var_dump($list); } public function read($slug) { $jeu = Jeu::findBySlug($slug); var_dump($jeu); } public function indexApi() { $list = Jeu::findAll(false); $json = json_encode($list); header('Content-Type: application/json'); echo $json; } public function searchApi($req) { $list = Jeu::find([ [Jeu::PREFIX.'nom', 'like', '%'.$req.'%'] ], false); $json = json_encode($list); header('Content-Type: application/json'); echo $json; } public function searchByCategoryApi($req) { Jeu::findByCategory($req); $json = json_encode($list); header('Content-Type: application/json'); echo $json; } }<file_sep><?php /** * Nous allons utiliser des méthodes issues de Db, nous disons que Article * est une classe enfant de la classe Db */ class User extends Db { /** * Attributs */ protected $id; protected $firstname; protected $surname; protected $created_at; /** * Constantes * Nous pouvons aussi définir des constantes. Ici, il s'agit du nom de la table. Ainsi, s'il venait à changer, nous n'aurons plus qu'à le changer à cet endroit. */ const TABLE_NAME = "User"; /** * Méthodes magiques */ public function __construct($firstname, $surname, $id = null, $created_at = null) { /** * Pour chaque argument, on utilise les Setters pour attribuer la valeur à l'objet. * Pour appeler une méthode non statique de la classe DANS la classe, on utilise $this. */ $this->setFirstname($firstname); $this->setSurname($surname); $this->setId($id); $this->setCreatedAt($created_at); } /** * Getters */ public function id() { return $this->id; } public function firstname() { return $this->firstname; } public function surname() { return $this->surname; } public function createdAt() { return $this->created_at; } /** * On peut bien sûr créer des getters pour des usages propres à l'application ! * On va par exemple créer les getters suivants : * - Date de création formatée en français * - Date de mise à jour formatée en français * - Intervalle entre la date de mise à jour et la date de création, en français */ public function createdAtFr() { $date = new DateTime($this->createdAt()); $dateFr = $date->format('d/m/Y H:i:s'); return $dateFr; } /** * Setters */ public function setId($id = null) { return $this->id = $id; } public function setFirstname($firstname = null) { return $this->firstname = $firstname; } public function setSurname($surname = null) { return $this->surname = $surname; } public function setCreatedAt($created_at = null) { return $this->created_at = $created_at; } /** * CRUD Methods */ public function save() { $data = [ "firstname" => $this->firstname(), "surname" => $this->surname() ]; if ($this->id > 0) return $this->update(); $nouvelId = Db::dbCreate(self::TABLE_NAME, $data); $this->setId($nouvelId); return $this; } public function update() { if ($this->id > 0) { $data = [ "firstname" => $this->firstname(), "surname" => $this->surname() ]; Db::dbUpdate(self::TABLE_NAME, $data); return $this; } return; } public function delete() { $data = [ 'id' => $this->id(), ]; Db::dbDelete(self::TABLE_NAME, $data); return; } public static function findAll($objects = true) { $data = Db::dbFind(self::TABLE_NAME); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new User($d['firstname'], $d['surname'], intval($d['id']), $d['created_at']); } return $objectsList; } return $data; } public static function find(array $request, $objects = true) { $data = Db::dbFind(self::TABLE_NAME, $request); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new User($d['firstname'], $d['surname'], intval($d['id']), $d['created_at']); } return $objectsList; } return $data; } public static function findOne(int $id, $object = true) { $request = [ ['id', '=', $id] ]; $element = Db::dbFind(self::TABLE_NAME, $request); if (count($element) > 0) $element = $element[0]; else return; if ($object) { $article = new User($element['firstname'], $element['surname'], intval($element['id']), $element['created_at']); return $article; } return $element; } public function articles() { $articles = Article::findByAuthor($this->id()); return $articles; } }<file_sep><?php /** * Composer Autoload */ require __DIR__ . '/vendor/autoload.php'; /** * Autoload du MVC : cette fonction nous permet de charger nos classes dynamiquement au moment précis où on en a besoin, plutôt que de charger toutes nos classes d'un seul coup. On passe en argument "CLASSES_SOURCES" qui est une constante qui est définie dans app.php */ spl_autoload_register (function ($class) { $sources = array_map(function($s) use ($class) { return $s . '/' . $class . '.php'; }, CLASSES_SOURCES); foreach ($sources as $source) { if (file_exists($source)) { require_once $source; } } }); /** * On récupère les fichiers de configuration dans le bon ordre */ require 'config/app.php'; require 'config/helpers.php'; require 'config/Db.php'; require 'config/routes.php';<file_sep><?php function dd($var) { echo "<pre>"; var_dump($var); echo "</pre>"; die; } function url($route) { return BASE_URL . '/'. $route; } function img_url($img) { return BASE_URL . '/public/assets/img' . $img; } function css_url($css) { return BASE_URL . '/public/assets/css' . $css; } function js_url($js) { return BASE_URL . '/public/assets/js' . $js; } function view($path, $vars = null, $include = true) { // Format : resource.page $pathArray = explode('.', $path); $url = ''; foreach($pathArray as $p) { $url .= $p . '/'; } $url = substr($url, 0, -1); $url .= '.php'; $fullUrl = VIEWS_URL . $url; if ($include) { if ($vars) { extract($vars); } include($fullUrl); } return $fullUrl; }<file_sep><?php /** * Don't be silly ! Do not commit this file. */ const DB_HOST = 'localhost'; const DB_PORT = '3308'; const DB_NAME = 'videoclub'; const DB_USER = 'root'; const DB_PWD = '';<file_sep><?php class Db { public function __construct() { /** */ } private static function getDb() { try { // Essaie de faire ce script... $bdd = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8;port='.DB_PORT, DB_USER, DB_PWD); } catch (Exception $e) { // Sinon, capture l'erreur et affiche la die('Erreur : ' . $e->getMessage()); } return $bdd; } /** * Permet d'enregistrer (INSERT) des données en base de données. * @param string $table Nom de la table dans lequel faire un INSERT * @param array $data Array contenant en clé les noms des champs de la table, en valeurs les values à enregistrer * * @return int Id de l'enregistrement. * * Exemple : * $table = "Category"; * $data = [ * 'title' => "Nouvelle catégorie", * 'description' => 'Ma nouvelle catégorie.', * ]; */ protected static function dbCreate(string $table, array $data) { $bdd = self::getDb(); // Construction de la requête au format : INSERT INTO $table($data.keys) VALUES(:$data.keys) $req = "INSERT INTO " . $table; $req .= " (`".implode("`, `", array_keys($data))."`)"; $req .= " VALUES (:".implode(", :", array_keys($data)).") "; $response = $bdd->prepare($req); var_dump($req, $data); $response->execute($data); return $bdd->lastInsertId(); } /** * Permet de supprimer (DELETE) des données en base de données. * @param string $table Nom de la table dans lequel faire un DELETE * @param array $data Array contenant en clé la PK de la table, en value la valeur à donner. * * @return void * * Exemple: * $table = "Movie"; * $data = [ 'id' => 3 ]; */ protected static function dbDelete(string $table, array $data) { $bdd = self::getDb(); // Construction de la requête au format : INSERT INTO $table($data.keys) VALUES(:$data.keys) $req = "DELETE FROM " . $table . " WHERE " . array_keys($data)[0] . " = :" . array_keys($data)[0]; $response = $bdd->prepare($req); $response->execute($data); return; } /** * Permet de récupérer (SELECT) des données en base de données. * @param string $table Nom de la table dans lequel faire un SELECT * @param array $request Array contenant une liste de trios ["champ", "opérateur", "valeur"]. * * @return array Données demandées. * * Exemple: * $table = "Movie"; * $request = [ * [ 'title', "like",'Rocky' ], * [ 'realease_date', '>', '2000-01-01'] * ]; */ protected static function dbFind(string $table, array $request = null) { $bdd = self::getDb(); $req = "SELECT * FROM " . $table; if (isset($request)) { $req .= " WHERE "; $reqOrder = ''; foreach($request as $r) { switch($r[0]): case "orderBy": $reqOrder = " ORDER BY `" . htmlspecialchars($r[1]) . "` " . htmlspecialchars($r[2]); break; default: $req .= "`". htmlspecialchars($r[0]) . "` " . htmlspecialchars($r[1]) . " '" . htmlspecialchars($r[2]) . "'"; $req .= " AND "; endswitch; } $req = substr($req, 0, -5); $req .= $reqOrder; } $response = $bdd->query($req); $data = []; while ($donnees = $response->fetch()) { $data[] = $donnees; } return $data; } /** * Permet de mettre à jour (UPDATE) des données en base de données. * @param string $table Nom de la table dans lequel faire un UPDATE * @param array $data Array contenant en clé les noms des champs de la table, en valeurs les values à enregistrer. * * @return int Id de l'élément modifié. * * OBLIGATOIRE : Passer un champ 'id' dans le tableau 'data'. * * Exemple : * $table = "Category"; * $data = [ * 'id' => 4, * 'title' => "Nouveau titre de catégorie", * 'description' => 'Ma nouvelle catégorie.', * ]; */ protected static function dbUpdate(string $table, array $data, string $idField = null) { $bdd = self::getDb(); $req = "UPDATE " . $table . " SET "; $whereIdString = ''; /** * Set du WHERE */ $whereIdString = ($idField !== null) ? " WHERE `" . $idField . "` = :" . $idField : " WHERE id = :id"; /** * Set des key = :value */ foreach($data as $key => $value) { if ($key !== 'id') { $req .= "`" . $key . "` = :" . $key . ", "; } } $req = substr($req, 0, -2); $req .= $whereIdString; $response = $bdd->prepare($req); $response->execute($data); return $bdd->lastInsertId(); } }<file_sep><?php class Jeu extends Db { private $id; private $nom; private $sortie_eu; private $lowerprice; private $slug; const PREFIX = "jeux_"; const TABLE_NAME = "site_jeux"; public function __construct(string $nom, int $id = null, string $sortie_eu = null, float $lowerprice =null, string $slug = null) { $this->setNom($nom); $this->setId($id); $this->setSortieEu($sortie_eu); $this->setLowerprice($lowerprice); $this->setSlug($slug); } /** * Getters */ public function id() { return $this->id; } public function nom() { return $this->nom; } public function sortieEu() { return $this->sortie_eu; } public function lowerprice() { return $this->lowerprice; } public function slug() { return $this->slug; } /** * Setters */ public function setId($id) { $this->id = $id; return $this; } public function setNom($nom) { $this->nom = $nom; return $this; } public function setSortieEu($sortie_eu) { $this->sortie_eu = $sortie_eu; return $this; } public function setLowerprice($lowerprice) { $this->lowerprice = $lowerprice; return $this; } public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Methods */ public static function find(array $request, $objects = true) { $data = Db::dbFind(self::TABLE_NAME, $request); // TODO: array map if ($objects) { $objectsList = []; foreach ($data as $d) { $object = new Jeu( $d[self::PREFIX.'nom'], $d[self::PREFIX.'id'], $d[self::PREFIX.'sortie_eu'], $d[self::PREFIX.'lowerprice'], $d[self::PREFIX.'slug']); } return; } return $data; } public static function findBySlug($slug, $object = true) { $request = [ [self::PREFIX.'slug', 'like', $slug] ]; $element = Db::dbFind(self::TABLE_NAME, $request); if (count($element) > 0) $element = $element[0]; else return; if ($object) { $jeu = new Jeu( $element[self::PREFIX.'nom'], $element[self::PREFIX.'id'], $element[self::PREFIX.'sortie_eu'], $element[self::PREFIX.'lowerprice'], $element[self::PREFIX.'slug']); return $jeu; } return $element; } public static function findAll($objects = true) { $data = Db::dbFind(self::TABLE_NAME); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new Jeu( $d[self::PREFIX.'nom'], $d[self::PREFIX.'id'], $d[self::PREFIX.'sortie_eu'], $d[self::PREFIX.'lowerprice'], $d[self::PREFIX.'slug']); } return $objectsList; } return $data; } public static function findByCategory($search) { $req = " SELECT * FROM jeux INNER JOIN categories on categories.id = jeux.category_id WHERE categories.name = " . $search; $res = $bdd->query($req); $results = $res->fetchAll(); } }<file_sep><?php class Category extends Db { private $id; private $title; private $description; const TABLE_NAME = 'category'; public function __construct($title, $description, $id = null) { $this->setTitle($title); $this->setDescription($description); $this->setId($id); } public function id() { return $this->id; } public function title() { return $this->title; } public function description() { return $this->description; } public function setTitle($title) { $this->title = $title; return $this; } public function setDescription($description) { $this->description = $description; return $this; } public function setId($id) { $this->id = $id; return $this; } public function save() { $data = [ "id" => $this->id(), "title" => $this->title(), "description" => $this->description(), ]; $nouvelId = Db::dbCreate(self::TABLE_NAME, $data); $this->id = $nouvelId; return $this; } public function addArticle(Article $article) { $ac = new ArticleCategory($article->id(), $this->id()); $ac->save(); } }<file_sep># Réalisation d'un MVC : mise en pratique (controllers) Maintenant que nous avons finalisé l'aspect "données" du projet, c'est à dire tout ce qui permet d'enregistrer des données, nous allons gérer la partie routeur et controller, c'est à dire écouter une URL et renvoyer vers la méthode correspondante dans le bon contrôleur. ## 1. Le fichier routes.php C'est dans ce fichier où nous allons répertorier la liste des routes de notre application, la liste des URL disponibles. > Si un utilisateur essaie une URL qui n'existe pas, il ne se passera rien. Vous pouvez chercher dans la documentation de Bramus/Router comment gérer ces exceptions qui sont des erreurs 404. On va rédiger une première route de test en suivant la documentation du routeur : ```php $router = new Router; // Grâce à l'alias dans app.php, on peut utiliser ce raccourci plutôt que \Bramus\Router\Router // On enregistre une nouvelle route GET : on écoute "lorsque l'utilisateur demande https://www.example.com/hello" // On associe à cela une fonction anonyme, c'est à dire une fonction qui va s'exécuter d'elle même (ça nous permet de faire des tests rapides) $router->get('/hello', function() { echo "hello world"; }); // Indispensable à la fin de la liste des routes pour que les routes fonctionnent ! $router->run(); ``` > Pour tester, allez sur votre application à l'adresse [/hello](#). Comme ça ne serait pas pratique d'effectuer nos actions dans des fonctions anonymes (aller lire tous les articles, modifier un article...), on va utiliser un fichier dédié à réagir aux routes : le **controller**. Créez le fichier /controllers/ArticlesController.php (pluriel, A en majuscule) : ```php class ArticlesController { } ``` On va en fait lier une route à une méthode du contrôleur, par exemple ajoutons dans `routes.php`: ```php $router->get('/articles', 'ArticlesController@index'); ``` ## 2. Le contrôleur On vient de lier la route `/articles` à la méthode `index()` dans le contrôleur `ArticlesController`. Il faut donc créer cette méthode ! Elle contiendra un appel vers la méthode `findAll()` du Model que nous avons créé plus tôt, qui nous permet de retrouver tous les éléments de la table `Article`. ```php class ArticlesController { public function index() { // On appelle le Model qui nous retrouvera tous les éléments $articles = Article::findAll(); var_dump($articles); // Un var_dump pour tester que nos données arrivent bien } } ``` C'est dans ce fichier où je peux faire des traitements complémentaires à `$articles` (gérer de la traduction, gérer les données à afficher selon le niveau d'autentification...) avant l'affichage à l'utilisateur. Comme il serait fastidieux d'afficher du HTML à cet endroit là, on va plutôt inclure ici des fichiers contenant du HTML à afficher. Dans le fichier `helper.php`, il y a une fonction qui vous permet d'afficher une vue en lui transmettant des données, on va l'utiliser dans le contrôleur : ```php public function index() { // On appelle le Model qui nous retrouvera tous les éléments $articles = Article::findAll(); view('articles.index', compact('articles')); } ``` 1. `view()` prend en premier paramètre le chemin virtuel vers la vue : en fait, il va chercher "public/views/articles/index.php". > Il faut donc créer le dossier `articles` dans `public/views/`, et le fichier `index.php` dans `public/views/articles/` ! L'intérêt d'écrire `articles.index` plutôt que `articles/index.php` voire `public/views/articles/index.php` est simplement pour améliorer la lisibilité (moins de symboles inutiles à la compréhension) et abstraire le fait que `view()` va chercher les vues dans `/public/views`. 2. Le deuxième paramètre est "compact()" : on passe en string la liste des variables à passer à la vue ([voir la doc](http://php.net/manual/fr/function.compact.php)). ### 3. La vue On va créer le fichier de vue qu'on demande dans le contrôleur : `/public/views/articles/index.php`, que l'on peut remplir pour commencer comme cela : ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <ul> <?php foreach($articles as $a) : ?> <li><strong><?= $a->title(); ?></strong>: <?= $a->content();?></li> <?php endforeach;?> </ul> </body> </html> ``` S'il y a des articles en base de données (ce qui devrait être le cas si vous avez testé votre Model dans le cours précédent), ils devraient s'afficher en liste.<file_sep><?php /** * Aliases : raccourcis pour les noms de classes */ class_alias('\Bramus\Router\Router', 'Router'); /** * Constantes : éléments de configuration propres au système */ const WEBSITE_TITLE = "Mon nouveau site en MVC"; const BASE_URL = "localhost/videoclub"; const VIEWS_URL = "public/views/"; /** * Liste des dossiers source pour l'autoload des classes */ const CLASSES_SOURCES = [ 'controllers', 'config', 'models', ];<file_sep><?php class ArticlesController { public function index() { $articles = Article::findAll(); view('articles.index', compact('articles')); } }<file_sep><?php class ArticleCategory extends Db { protected $id_article; protected $id_category; const TABLE_NAME = 'article_category'; public function __construct($id_article, $id_category) { $this->id_article = $id_article; $this->id_category = $id_category; } public function save() { $data = [ "id_category" => $this->id_category, "id_article" => $this->id_article ]; $nouvelId = Db::dbCreate(self::TABLE_NAME, $data); return $this; } public static function articlesCountByCategory() { $bdd = Db::getDb(); $req = "SELECT category.title, count(*) FROM `article_category` INNER JOIN category ON category.id = article_category.id_category GROUP BY id_category"; $res = $bdd->query($req); $data = $res->fetchAll(PDO::FETCH_ASSOC); var_dump($data); } }<file_sep><?php $router = new Router; $router->get('hello', function() { echo "hello world"; }); $router->get('/articles', 'ArticlesController@index'); $router->get('/jeux', 'JeuxController@index'); $router->get('/jeux/([^/]+)', 'JeuxController@read'); $router->get('/api/jeux', 'JeuxController@indexApi'); $router->get('/api/jeux/search/(\w+)', 'JeuxController@searchApi'); $router->get('/api/jeux/searchByCategory/(\w+)', 'JeuxController@searchByCategoryApi'); $router->run();<file_sep># Réalisation d'un MVC : mise en pratique (tables, models) > La structure de notre projet est enfin réalisée. Si besoin, vous retrouverez ce modèle de projet fonctionnel dans le dossier `_base_project` à utiliser de suite. ## Comment commencer à travailler ? Parmi tous ces fichiers à gérer (router, controllers, models, views, dépendances...), le travail peut paraître impressionnant à premier abord. Nous allons voir comment travailler de façon méthodique afin de profiter d'un des avantages du MVC : pouvoir travailler vite et efficacement grâce à un découpage logique ! > Principes de développement: [Keep It Simple, Stupid!](https://fr.wikipedia.org/wiki/Principe_KISS), [Don't Repeat Yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), [SOLID](https://fr.wikipedia.org/wiki/SOLID_(informatique)), [You Ain't Gonna Need It](https://fr.wikipedia.org/wiki/YAGNI), [Extreme Programming](https://fr.wikipedia.org/wiki/Extreme_programming). 1. Créer les **tables** dans sa base de données. 2. Créer les **Model**, un par ressource. 3. Créer des **routes**: pensez qu'à chaque ressource, on peut avoir besoin en général d'au moins: "browse", "read", "edit", "add", "delete" (BREAD). Faites des routes en fonction ! 4. Créer les **controllers**, un par ressource et une méthode par route nécessaire. 5. Créer les **views** pour chaque méthode de chaque ressource nécessitant une vue. 6. Répéter 1 à 5 pour chaque nouvelle ressource ! ## Exemple d'une ressource : "Article" Pour cet exemple, nous allons suivre pas à pas chacune des étapes pour créer une ressource Article. ### 1. Créer la table Article Nous allons créer une table Article en base de données définie comme suit : ``` Article -------- id int PK AI title varchar(150) short_content varchar(250) nullable content text id_author int nullable created_at datetime default: CURRENT_TIMESTAMP updated_at datetime default: CURRENT_TIMESTAMP ``` ### 2. Créer le model Article Nous allons créer le fichier `models/Article.php` (au singulier, A en majuscule) et le préparer comme cela : ```php /** * Nous allons utiliser des méthodes issues de Db, nous disons que Article * est une classe enfant de la classe Db */ class Article extends Db { ``` #### Attributs et constantes > Pour chaque champ de la table, nous créons un attribut. En effet, nous allons générer un objet Article qui sera en fait une "copie dynamique" de son homologue enregistré dans la base de données ! Il a donc besoin des même attributs. >On les met en "protected": cela nous évitera d'accéder aux propriétés avec $article->title, mais plutôt en passant par un Getter, lequel nous retournera bien le "title" mais avec des modifications ou validations si besoin est. >Private ferait la même chose, mais bloquerait aussi l'accès aux classes enfants. Au cas où nous aurions des enfants de cette classe, nous restons sur Protected. ```php /** * Attributs */ protected $id; protected $title; protected $short_content; protected $content; protected $id_author; protected $created_at; protected $updated_at; /** * Constantes * Nous pouvons aussi définir des constantes. Ici, il s'agit du nom de la table. Ainsi, s'il venait à changer, nous n'aurons plus qu'à le changer à cet endroit. */ const TABLE_NAME = "Article"; ``` #### Méthodes magiques > Les méthodes magiques sont des méthodes qui s'activent à un moment précis de l'instanciation d'un objet issu de cette classe. __construct se lance en fait lorsque nous demandons "new Article() par exemple. > On va pouvoir créer des articles grâce à ce constructeur. En paramètres, nous allons entrer tous les champs obligatoires (ici : $title et $content). > Nous ajoutons aussi un paramètre $id qui sera null par défaut : il ne sera rempli que si nous créons un objet depuis des données de la base de données. S'il n'est pas rempli, c'est que nous venons de le créer de toutes pièces (un nouvel article par exemple). ```php /** * Méthodes magiques */ public function __construct($title, $content, $id = null, $short_content = null, $id_author = null, $created_at = null, $updated_at = null) { /** * Pour chaque argument, on utilise les Setters pour attribuer la valeur à l'objet. * Pour appeler une méthode non statique de la classe DANS la classe, on utilise $this. */ $this->setTitle($title); $this->setContent($content); $this->setId($id); $this->setShortContent($short_content); $this->setIdAuthor($id_author); $this->setCreatedAt($created_at); $this->setUpdatedAt($updated_at); } ``` #### Getters > On va définir la liste des getters. C'est ces méthodes qui nous permettent d'accéder aux données avec si besoin est des modifications entre la donnée brute de la BDD et ce que l'on veut récupérer. > Pour chaque champ que l'on a droit de lire, on crée un getter (même nom que le champ, en camelCase par convention). ```php /** * Getters */ public function id() { return $this->id; } public function title() { return $this->title; } public function shortContent() { return $this->short_content; } public function content() { return $this->content; } public function idAuthor() { return $this->id_author; } public function createdAt() { return $this->created_at; } public function updatedAt() { return $this->updated_at; } /** * On peut bien sûr créer des getters pour des usages propres à l'application ! * On va par exemple créer les getters suivants : * - Date de création formatée en français * - Date de mise à jour formatée en français * - Intervalle entre la date de mise à jour et la date de création, en français */ public function createdAtFr() { $date = new DateTime($this->createdAt()); $dateFr = $date->format('d/m/Y H:i:s'); return $dateFr; } /** * Pour l'exercice, on rajoute une variable facultative $time qui permet de retourner ou non l'heure. A l'usage on aurait donc : * $article->updatedAtFr() // Retourne "21/12/2018 15:14:12" * $article->updatedAtFr(false) // Retourne "21/12/2018" */ public function updatedAtFr($time = true) { $date = new DateTime($this->updatedAt()); $format = ($time) ? 'd/m/Y H:i:s' : 'd/m/Y'; $dateFr = $date->format($format); return $dateFr; } /** * Grâce à la documentation PHP, on peut savoir comment comparer deux objets DateTime. * La variable $intervalle est un objet DateInterval : * http://www.php.net/manual/en/class.dateinterval.php * * Cette fonction retourne la différence en jours. */ public function daysSinceCreation() { $createdAt = new DateTime($this->createdAt()); $updatedAt = new DateTime($this->updatedAt()); $intervalle = $createdAt->diff($updatedAt); return $intervalle->d; } ``` #### Setters > On va définir la liste des setters. C'est ces méthodes qui nous permettent d'enregistrer les données avec si besoin est des modifications entre la donnée brute de la BDD et ce que l'on veut enregistrer. > Pour chaque champ que l'on a droit d'enregistrer, on crée un setter (même nom que le champ, en camelCase par convention, avec "set" devant). > C'est aussi ici où l'on doit faire les validations à l'enregistrement !! On va faire l'exemple pour setTitle. > Pour gérer une erreur, on utilisera dorénavant throw new Exception('message'); ```php /** * Setters */ public function setId($id) { $this->id = $id; return $this; } public function setTitle(string $title) { if (strlen($title) == 0) { throw new Exception('Le titre ne peut pas être vide.'); } if (strlen($title) > 150) { throw new Exception('Le titre ne peut pas être supérieur à 150 caractères.'); } $this->title = $title; return $this; } public function setShortContent(string $short_content = null) { $this->short_content = $short_content; return $this; } public function setContent(string $content) { $this->content = $content; return $this; } public function setIdAuthor($id_author = null) { $this->id_author = $id_author; return $this; } public function setCreatedAt(string $created_at) { $this->created_at = $created_at; return $this; } public function setUpdatedAt(string $updated_at) { $this->updated_at = $updated_at; return $this; } ``` #### Autres méthodes : CRUD > Nous avons créé les getters (récupérer la donnée filtrée si besoin) et les setters (enregistrer la donnée, filtrée si besoin). Il nous faut aussi des méthodes pour faire des opérations en BDD autour de notre objet. > Nous avons importé la classe `Db` lors de la mise en place de notre projet : il s'agit d'une bibliothèque de méthodes nous permettant de facilement faire une connexion avec PDO sans se soucier de comment se passe la connexion (eh oui, c'est le but de la classe `Db` : elle s'occupe de tout et nous donne des interfaces faciles à utiliser !) ##### Un exemple: Db::dbCreate(string $table, array $data) D'après la documentation de `Db` (on peut la retrouver au sein du fichier de la classe), pour utiliser dbCreate, il faut passer en premier paramètre un `string $table` (ça tombe bien, c'est la constante `TABLE_NAME` que l'on a défini plus haut) et en second paramètre un tableau de données au format `champ => valeur`. On va donc : 1. Créer un tableau $data contenant la liste des champs de ma table que je souhaite enregistrer (bien penser évidemment à passer tous les champs NON NULL au minimum, sinon MySQL n'aimera pas !) 2. Si mon objet possède un ID c'est qu'il existe forcément en base de données, j'appelle plutôt la méthode update du Model (elle est définie juste en dessous, elle fait pareil mais avec dbUpdate plutôt que dbCreate) 3. J'appelle la méthode dbCreate de la classe Db : `Db::dbCreate` à laquelle je passe tous les arguments dont j'ai besoin. > Note : pour accéder à une constante de classe au sein de la classe, on peut utiliser `self::TABLE_NAME`. 4. D'après la documentation, je sais que l'opération `Db::dbCreate` retourne l'ID créé. Je le récupère et l'attribue à mon objet ($this->id = $nouvelId). 5. Enfin, je retourne l'objet lui même car il faut en général toujours retourner quelque chose d'une fonction, autant retourner quelque chose de cohérent. > Pour les autres méthodes, je ne les décrit pas ici car elles suivent le même principe : on lit la documentation pour voir comment utiliser l'outil venant de la classe Db et on l'applique. ```php /** * CRUD Methods */ public function save() { $data = [ "title" => $this->title(), "content" => $this->content() ]; if ($this->id > 0) return $this->update(); $nouvelId = Db::dbCreate(self::TABLE_NAME, $data); $this->setId($nouvelId); return $this; } public function update() { if ($this->id > 0) { $data = [ "id" => $this->id(), "title" => $this->title(), "short_content" => $this->shortcontent(), "content" => $this->content(), "id_author" => $this->idAuthor(), "updated_at" => "CURRENT_TIMESTAMP" ]; Db::dbUpdate(self::TABLE_NAME, $data); return $this; } return; } public function delete() { $data = [ 'id' => $this->id(), ]; Db::dbDelete(self::TABLE_NAME, $data); return; } ``` > On peut aussi ajouter des méthodes de recherche qui nous facilitent la vie (findAll, find, findOne plutôt que de faire des SELECT c'est plus simple ! Mais il faut l'implémenter). > Là aussi, on effectue tout cela en s'inspirant de la documentation de la classe Db. > Nous précisons à chaque méthode un argument $objects = true qui nous permet de dire au Model de retourner des objets par défaut pour chaque entrée en base de données recherchée (ainsi on a directement accès aux méthodes sur la donnée), plutôt qu'un simple tableau de données brut. > On pourrait avoir besoin de cet argument mis sur false ($objects = false) dans les cas où on a besoin de la donnée brute plutôt qu'un objet (certaines API par exemple). ```php public static function findAll($objects = true) { $data = Db::dbFind(self::TABLE_NAME); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new Article($d['title'], $d['content'], $d['id'], $d['short_content'], $d['id_author'], $d['created_at'], $d['updated_at']); } return $objectsList; } return $data; } public static function find(array $request, $objects = true) { $data = Db::dbFind(self::TABLE_NAME, $request); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new Article($d['title'], $d['content'], $d['id'], $d['short_content'], $d['id_author'], $d['created_at'], $d['updated_at']); } return $objectsList; } return $data; } public static function findOne(int $id, $object = true) { $request = [ ['id', '=', $id] ]; $element = Db::dbFind(self::TABLE_NAME, $request); if (count($element) > 0) $element = $element[0]; else return; if ($object) { $article = new Article($d['title'], $d['content'], $d['id'], $d['short_content'], $d['id_author'], $d['created_at'], $d['updated_at']); return $article; } return $element; } } // Dernière accolade correspondant à la première ligne "class Article { ..." ``` ## Comment tester tout ça ? On peut maintenant tester notre model directement en bas du fichier index.php : ```php /** * On créée deux articles (test de save() ) */ $titre = 'Un nouvel article'; $contenu = 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit quidem, earum, expedita ex cum, voluptatum assumenda maiores delectus id eius provident cumque porro cupiditate quo necessitatibus eos aspernatur unde eaque.'; $article = new Article($titre, $contenu); $article->save(); /** * On met à jour le titre */ $article->setTitle('modif du premier titre'); $article->save(); $titre2 = 'Un autre article'; $contenu2 = 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit quidem, earum, expedita ex cum, voluptatum assumenda maiores delectus id eius provident cumque porro cupiditate quo necessitatibus eos aspernatur unde eaque.'; $article2 = new Article($titre2, $contenu2); $article2->save(); /** * Tous les articles en objects */ echo "<b>Tous les articles (objects) : </b>"; $articles = Article::findAll(); var_dump($articles); /** * Tous les articles en array */ echo "<hr>"; echo "<b>Tous les articles (arrays) : </b>"; $articlesArray = Article::findAll(false); var_dump($articlesArray); /** * Article "Un autre article" (title LIKE "autre") */ echo '<hr>'; echo "<b>Article 'un autre article' : </b>"; $autreArticle = Article::find([ ['title', 'like', '%autre%'] ]); var_dump($autreArticle); /** * Article # 1 */ echo '<hr>'; echo "<b>Article id = 1 : </b>"; $premierArticle = Article::findOne(1); var_dump($premierArticle); ``` > Supprimez bien ces tests une fois qu'ils fonctionnent ! Voilà, le **Model** est prêt. Vous pouvez bien sûr rajouter d'autres méthodes qui vous semblent intéressantes sur la gestion des données, selon vos propres données vous aurez sans doute des cas particuliers à gérer (des dates, des intervalles, mais aussi des types spéciaux, l'upload de fichiers se fait également ici en partie...).<file_sep># Réalisation d'un MVC : Composer, index.php et .htaccess Dorénavant, comme on l'a vu, quelle que soit l'adresse saisie par l'utilisateur, il passera par index.php qui appelera le router. Il nous faut donc, *après avoir créé un dossier de travail bien sûr*, 3 éléments : - Importer un router - Un fichier index.php appelant le router - Un fichier .htaccess qui redirigera chaque requête vers index.php ## Importer le router avec Composer Nous pourrions créer de toutes pièces notre router, néanmoins il existe des milliers de bibliothèques toutes prêtes en PHP, un router efficace, open-source et donc éprouvé existe donc déjà sans doute ! > Le gestionnaire de packages pour PHP s'appelle **Composer**. Il doit normalement déjà être installé sur votre système, si ça n'est pas déjà le cas vous pouvez trouver les instructions d'installation [sur getcomposer.org](https://getcomposer.org/doc/00-intro.md). > Où trouver des packages intéressants pour mon projet ? Vous pouvez bien sûr trouver des milliers d'idées sur Github, ou regarder sur [Packagist](https://packagist.org/) qui est le répertoire des paquets installables avec Composer. Nous allons utiliser le package `bramus/router` ([documentation sur Packagist.org](https://packagist.org/packages/bramus/router)). Pour installer une dépendance avec Composer, il faut se rendre avec un terminal dans le dossier de travail et saisir : `composer require *author*/*package* *version`. Pour notre cas, on va saisir dans un terminal : `$ composer require bramus/router ~1.3` > Attention ! Le `$` n'est pas à saisir ! Il s'agit juste d'une indication que nous sommes dans un terminal. > `~ 1.3` veut dire : "si une version supérieure est disponible lors d'un `composer install` (installer les dépendances d'un projet) ou d'un `composer update` (mettre à jour les dépendances d'un projet), je ne veux que les versions comprises dans l'intervalle `>=1.3.0.0-dev <2.0.0.0-dev`. > Plus d'informations sur le [Semantic Versioning](https://semver.org/) et les contraintes de [versions avec Composer](https://getcomposer.org/doc/articles/versions.md). Composer vient de créer plusieurs fichiers et dossiers : ``` /vendor # Dossier contenant les dépendances installées composer.json # Fichier indiquant la liste des dépendances du projet composer.json.lock # Fichier technique indiquant l'état des dépendances actuellement installées ``` ## index.php Il faut maintenant créer un fichier `index.php` et lui indiquer en tout premier lieu que nous allons inclure les dépendances grâce à l'autoloader de Composer : ```php require __DIR__ . '/vendor/autoload.php'; ``` D'après la documentation de `bramus/router`, on instancie le routeur avec `$router = new \Bramus\Router\Router();`. Testons si notre dépendance est bien détectée et installée ! ```php require __DIR__ . '/vendor/autoload.php'; $router = new \Bramus\Router\Router(); var_dump($router); ``` Si un `object(Bramus\Router\Router)` est retourné par le `var_dump()`, alors tout fonctionne. ## .htaccess Enfin, toujours d'après la documentation de la dépendance, pour que le routeur fonctionne, il faut rediriger toutes les requêtes vers index.php (en effet ! Il faut bien que l'URL demandée soit lue par notre routeur, et comme on instancie le routeur dans index.php, on envoie les requêtes vers ce fichier !). Pour cela, on créée un fichier nommé `.htaccess` avec dedans : ```htaccess RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php [L] ``` ## Conclusion Voilà, notre projet est presque prêt à démarrer. Il manque un dernier détail : le fichier `.gitignore`. Comme nous avons déjà la liste des dépendances du projet dans le fichier `composer.json`, et qu'il suffit d'une simple commande (`$ composer install`) pour les installer... Je n'ai pas besoin des importer dans mon versionnage Git ! De plus, comme ce sont des dépendances extérieures, il ne faut pas que je touche à ces fichiers. Je n'ai donc vraiment aucun intérêt à les versionner (en plus, comme les dépendances peuvent être très nombreuses, cela prendrait un temps énorme inutilement à chaque git push/pull). Pour éviter ce problème, on va créer à la racine du projet un fichier `.gitignore` contenant simplement : ```git vendor/ ``` Cela indiquera à Git de ne pas versionner les fichiers et dossiers contenus dans le dossier `vendor/`. Nous utiliserons encore ce fichier plus tard. > Attention: Dorénavant, si vous travaillez avec un projet comportant un fichier `composer.json`, vous devez absolument installer les dépendances du projet pour pouvoir l'utiliser avec un `$ composer install` à la racine du projet.<file_sep># Réalisation d'un MVC : La structure de fichiers, le routeur et autres dépendances ## Structure des fichiers Pour réaliser une architecture en MVC, nous allons systématiquement découper notre dossier de travail comme suit : ``` config/ app.php # Variables de configuration de l'app helpers.php # Des helpers si besoin routes.php # Liste des routes database.php # Identifiants de BDD Db.php # Une librairie à importer plus tard models/ # Contiendra un model par ressource controllers/ # Contiendra un controller par ressource public/ uploads/ # Les éventuels uploads d'utilisateurs assets/ # Ressources front img/ js/ css/ views/ # Les templates de views (un sous-dossier par ressource) index.php # Porte d'entrée de l'application vendor/ # On touche pas ! Il est généré par Composer .gitignore # Liste de ce que je ne veux pas versionner composer.json # La liste de mes dépendances composer.lock # On touche pas ! Etat des dépendances actuellement installées ``` Soyez vigilants sur cette organisation de dossier ! Vous pourrez bien sûr plus tard adapter cette organisation selon les besoins de votre projet, pour de l'optimisation... ## index.php Une fois le découpage effectué, nous allons remplir notre index.php afin qu'il importe le contenu de chaque dossier dans le bon ordre : ```php <?php /** * Composer Autoload */ require __DIR__ . '/vendor/autoload.php'; /** * Autoload du MVC : cette fonction nous permet de charger nos classes dynamiquement au moment précis où on en a besoin, plutôt que de charger toutes nos classes d'un seul coup. On passe en argument "CLASSES_SOURCES" qui est une constante qui est définie dans app.php */ spl_autoload_register (function ($class) { $sources = array_map(function($s) use ($class) { return $s . '/' . $class . '.php'; }, CLASSES_SOURCES); foreach ($sources as $source) { if (file_exists($source)) { require_once $source; } } }); /** * On récupère les fichiers de configuration dans le bon ordre */ require 'config/app.php'; require 'config/database.php'; require 'config/helpers.php'; require 'config/Db.php'; require 'config/routes.php'; ``` ## config/app.php Nous devons aussi remplir le fichier `app.php` afin de faire fonctionner l'application sans problèmes : ```php /** * Aliases : raccourcis pour les noms de classes */ class_alias('\Bramus\Router\Router', 'Router'); /** * Constantes : éléments de configuration propres au système */ const WEBSITE_TITLE = "Mon nouveau site en MVC"; const BASE_URL = "localhost/videoclub"; /** * Liste des dossiers source pour l'autoload des classes */ const CLASSES_SOURCES = [ 'controllers', 'config', 'models', ]; ``` ## config/database.php Et enfin, nous allons remplir le fichier `database.php` qui renseignera nos identifiants de base de données : ```php <?php /** * Don't be silly ! Do not commit this file. */ const DB_HOST = 'localhost'; const DB_PORT = '3308'; const DB_NAME = 'videoclub'; const DB_USER = 'root'; const DB_PWD = ''; ``` > Attention : ce fichier contient toutes les informations pour se connecter à votre base de données ! Il est important d'ajouter ce fichier dans le `.gitignore` dans un projet réel afin de ne jamais publier ces informations au grand public, et de re-créer à la main ce fichier à chaque fois que vous clonez le projet. > Pour tout de même garder une trace de ce que contient ce fichier, vous pouvez par exemple versionner un fichier `database.php.example` qui contient tous les champs avec des données d'exemple. Pour ce cours, nous pouvons laisser database.php tel qu'il est car nous sommes tous sur localhost avec des identifiants basiques (root/root). ## config/Db.php Vous devez récupérer le contenu de ce fichier dans le dépôt Git de ce cours. En effet, `Db.php` est une bibliothèque de fonctions que je mettrai à jour constamment, il faut la considérer comme une dépendance externe et prendre la dernière version à jour sans la modifier. ## config/helpers.php Idem, veuillez récupérer la version à jour dans le dépôt Git de ce cours. Ce fichier contient des helpers d'URL utilisant la constante `BASE_URL` définie dans `app.php` nous permettant de ne pas avoir de problèmes de liens relatifs selon les configurations. Il contient également une fonction très pratique permettant d'inclure un template de View et de lui transmettre des variables (`view()`). ## Conclusion Notre projet est enfin parfaitement configuré, nous allons pouvoir directement travailler avec un vrai MVC !<file_sep> # Gestion de données: MCD et relations (pratique) > Rappel : avant de passer à la mise en place des models, il faut absolument que votre MCD soit dessiné même de façon sommaire afin de comprendre quelles relations vont avec quelles autres models. > Note : Nous partirons du principe que les models pour chaque table sont créés, qu'il existe des getters et setters pour chaque champ ainsi que des attributs pour chaque champs. ## 1. Implémenter une relation 1-1 ou 1-N Une relation 1-1 ou 1-N veut dire que, depuis User par exemple (la partie "1" du schéma "1-1" et "1-N", la partie qui "possède" une autre ressource), il existe une table où un champ "id_user" existe. En effet : il existe bien "id_user" dans la table Adresse et "id_user" dans la table Article ! Il nous faut donc des accesseurs depuis le model User qui nous permettent d'accéder aux données de ces deux tables (d'où l'intérêt de dessiner le MCD ! On sait tout de suite quelles méthodes il faudra implémenter). La différence néanmoins entre 1-1 et 1-N est que dans le cas de 1-1, on ne va chercher qu'une seule ressource (une adresse). Dans le cas 1-N, on va chercher plusieurs ressources (des articles). Ce qui nous amène à nommer nos méthodes ainsi : `adresse()` (au singulier) et `articles()` (au pluriel). ### Code ```php // User.php class User extends Db { // ... public function adresse() { } public function articles() { } } ``` ### Explications L'idée est de pouvoir faire des choses comme : ```php $user = User::findOne(1); // On récupère le user #1 $user->adresse(); // On récupère l'adresse de l'user sous forme d'objet $user->articles(); // On récupère un tableau d'articles appartenant à l'user, sous forme d'objets // On affiche la liste des articles de l'user foreach($user->articles() as $article) { echo $article->title(); echo "<br>"; } ``` L'avantage de récupérer ainsi les données, toujours sous forme d'objets, est que grâce à cela je peux utiliser toutes les méthodes de la classe `Adresse` sur l'objet `$user->adresse()`, et toutes les méthodes de la classe `Article` sur les éléments du tableau `$user->articles()` ! Exemple : `$user->adresse()` étant bien un objet de la classe `Adresse`, je peux faire : ```php $user = User::findOne(1); $user->adresse()->setCity('Nancy'); $user->adresse()->save(); ``` Ou en raccourci (parce que mon setter me retourne $this... donc l'objet lui même) : ```php $user = User::findOne(1); $user->adresse()->setCity('Nancy')->save(); ``` ### Code On va donc remplir nos méthodes : pour cela, on va devoir appeler dans Adresse et Articles des méthodes qui nous permettent de faire une recherche non pas par rapport à leur id (`Adresse::findOne()`), mais par rapport à l'id user. Puisque nous sommes dans la classe User (c'est User qui va chercher l'adresse et les articles), on passe bien sûr l'ID de l'user cherchant ces données aux méthodes de Adresse et de Article, d'où le `$this->id()` en paramètres : ```php // User.php class User extends Db { // ... public function adresse() { return Adresse:findByUser($this->id()); } public function articles() { return Article::findByUser($this->id()); } } ``` > On créée bien sûr les méthodes correspondantes. Attention : vérifiez bien dans quel fichier vous travaillez ! On a modifié `User.php` ci-dessus, on travaille sur `Adresse.php` puis `Article.php` ci-dess**o**us! ```php // Adresse .php class Adresse extends Db { // ... public static function findByUser($id_user) { // J'utilise la fonction find qui est déjà dans Adresse, et qui utilise Db::dbFind // dont la syntaxe est expliquée dans la documentation de Db.php. return self::find([ ['id_user', '=', $id_user] ]); } } ``` ```php // Article.php class Article extends Db { // ... public static function findByUser($id_user) { // J'utilise la fonction find qui est déjà dans Adresse, et qui utilise Db::dbFind // dont la syntaxe est expliquée dans la documentation de Db.php. return self::find([ ['id_user', '=', $id_user] ]); } } ``` ### Utilisation Et voilà, la classe User a dorénavant accès à l'objet `Adresse` et aux objets `Article` ! Pour tester, vous pouvez vous inspirer du code présent dans le point **Explications** ci-dessus. ## 2. Implémenter une relation N-N Une relation N-N veut dire que, depuis Article et vers Category par exemple, il existe une table de jointure qui lie les deux tables. Il nous faut donc des accesseurs depuis le model Article **et** depuis le model Category, qui nous permettent d'accéder respectivement à : - aux catégories depuis un article (pouvoir faire `$article->categories();`) - aux articles depuis une catégorie (pouvoir faire `$category->articles();`) Ici, comme il y a un "N" des deux côtés (plusieurs articles pour une catégorie, plusieurs catégories pour un article), les méthodes seront nommées au pluriel dans chaque model. ### Code ```php // Article.php class Article extends Db { // ... public function categories() { return ArticleCategory::findCategoriesByArticle($this->id()); } } ``` ```php // Category.php class Category extends Db { // ... public function articles() { return ArticleCategory::findArticlesByCategory($this->id()); } } ``` > **Note** : on voit cette fois, à la différence du cas 1-1 et 1-N qui appelait `Adresse:findByUser()` et `Category::findByUser()` que l'on appelle une méthode définie dans la table de jointure, et pas dans la table d'arrivée elle même : `ArticleCategory::findByCategory()`. Et bien sûr, comme toutes les tables, la table de jointure a son Model (avec ses getters/setters, constructeur et méthodes CRUD comme les autres). On y ajoute les deux méthodes `findByCategory()` et `findByArticle()`. Ces deux méthodes sont un peu plus complexes à mettre en place. Par exemple, pour `findArticlesByCategory($id_category)` l'autre fonctionne de façon identique à l'inverse) : - On est dans la table de jointure. On retrouve tous les éléments dont l'id_category est celui demandé afin d'avoir la liste des articles pour cette catégorie ; - Ensuite, pour chacun des éléments récupérés (donc la liste couples id_article/id_category ayant l'id_category demandé... Donc en fait la liste des id_articles de la catégorie !), on va récupérer grâce à `Article::findOne($id)` l'objet article. - On met tout cela dans un tableau $articles et on retourne ce tableau ! ```php // ArticleCategory.php class ArticleCategory extends Db { // ... public function findArticlesByCategory($id_category) { // On retrouve la liste des couples id_article/id_category qui ont l'id de catégorie donné : $elements = self::find([ ['id_category', '=', $id_category] ]); $articles = []; // Tableau qui contiendra les articles // Pour chaque élément trouvé dans la table de jointure, on retrouve l'article correspondant : foreach($elements as $el) { $articles[] = Article::findOne($el['id_article']); } return $articles; } // Idem pour l'inverse ! public function findCategoriesByArticle($id_article) { $elements = self::find([ ['id_article', '=', $id_article] ]); $categories = []; foreach($elements as $el) { $categories[] = Category::findOne($el['id_category']); } return $categories ; } } ``` ### Explications L'idée est de pouvoir faire des choses comme : ```php $article = Article::findOne(1); $article->categories(); // On récupère la liste des catégories de l'article // On peut par exemple afficher la liste des catégories : foreach($article->categories() as $category) { echo $category->title(); echo '<br>'; } // Idem pour l'inverse : d'une catégorie, je veux ses articles. $category = Category::findOne(1); // J'affiche la liste des articles de la catégorie : foreach($category->articles() as $article) { echo $article->title(); echo "<br>"; } ``` > Comme pour le cas 1-1 et 1-N, on utilise bien des objets dans `$category->articles()` et `$articles->categories()`. On a donc accès à toutes les méthodes de ces objets là dans le foreach ! Par exemple faire une modification sur chaque article... > **Comment ajouter un article à une catégorie ?** Pour cela, il faudra simplement créer un nouvel objet ArticleCategory avec dans en constructeur quelque chose comme : `__construct($id_article, $id_category){}`, puis l'enregistrer avec `->save()` comme n'importe quel autre objet ! ## 3. Requêtes complexes: exécuter du SQL directement depuis le Model ### A. Rappels sur les requêtes effectuées Avec les points 1 et 2, nous avons vu comment traiter les cas classiques de communication entre plusieurs tables (1-1/1-N/N-N) : concrètement, sous couvert de l'abstration offerte par la classe Db, on a simplement fait : #### Récupérer l'adresse d'un utilisateur (1-1) ```sql SELECT * FROM Adresse WHERE id_user = $idUser ```` #### Récupérer les articles d'un utilisateur (1-N) ```sql SELECT * FROM Article WHERE id_user = $idUser ```` Et pour les cas N-N : #### Récupérer les catégories d'un article (N-N) ```sql SELECT * FROM ArticleCategory WHERE id_article = $idArticle // Pour chacun des résultats retournés ci-dessus: SELECT * FROM Category WHERE id_category = $idCategory ```` #### Récupérer les articles d'une catégorie (N-N) ```sql SELECT * FROM ArticleCategory WHERE id_category = $idCategory // Pour chacun des résultats retournés ci-dessus: SELECT * FROM Article WHERE id_article = $idArticle ```` En réalité, les cas N-N sont gérés de façon sous-optimale : comme on utilise la classe Db qui ne nous permet que de faire des `SELECT` simples éventuellement agrémentés de `WHERE`, on n'a pas pu faire proprement les requêtes avec un `INNER JOIN` qui auraient plutôt du ressembler à : #### Récupérer les catégories d'un article (N-N) ```sql SELECT * FROM ArticleCategory INNER JOIN Category ON Category.id = ArticleCategory.id_category WHERE ArticleCategory.id_article = $idArticle ```` #### Récupérer les articles d'une catégorie (N-N) ```sql SELECT * FROM ArticleCategory INNER JOIN Article ON Article.id = ArticleCategory.id_article WHERE ArticleCategory.id_category= $idCategory ```` Soit en 1 select, récupérer tous les résultats, plutôt que 1 select par article ou par catégorie ! Une optimisation vraiment conséquente. ### B. Comment effectuer des requêtes personnalisées Pour cela, nous allons réutiliser `PDO` comme nous l'avons déjà fait en programmation fonctionnelle. Il se trouve que la classe Db nous fournit déjà un pointeur de base de données avec PDO, on va pouvoir l'utiliser : #### Exemple: requête pour récupérer le nombre d'articles par catégorie > Où placer cette requête ? Est-il plus cohérent de la placer dans Article (depuis l'usine Article, est-ce que je peux avoir accès au nombre d'articles par catégorie ?) ou dans Category (depuis l'usine Category, est-ce que je peux avoir accès au nombre d'articles par catégorie ?) > La réponse est oui pour les deux cas. Au lieu de placer la fonction dans l'une ou l'autre classe... Autant la placer dans la classe de jointure ! ```php class ArticleCategory extends Db { // ... // La méthode est statique afin d'être appelée depuis "l'usine" public static function articlesCountByCategory() { // J'utilise getDb de la classe Db qui me donne un pointeur PDO. $bdd = Db::getDb(); // Définition de la requête $req = "SELECT category.title as title, count(*) as count FROM `article_category` INNER JOIN category ON category.id = article_category.id_category GROUP BY id_category"; // Execution de la requête $res = $bdd->query($req); // Récupération des résultats $data = $res->fetchAll(PDO::FETCH_ASSOC); // On retourne les résultats return $data; } } ``` Utilisation : ```php // Comme la méthode est statique, je peux l'appeler depuis "l'usine" à ArticleCategory : $articlesCountByCategory = ArticleCategory::articlesCountByCategory(); // Un foreach pour retourner quelque chose comme : "Catégorie Sciences: 6 articles" foreach($articlesCountByCategory as $artCount) { echo "Catégorie " . $artCount['title'] . ": " . $artCount['count'] . " articles"; } ``` > **Note** : Comment se fait-il que je puisse utiliser `title` et `count` dans `$artCount['title']` et `$artCount['count']` ? Car je les ai définis en aliases dans ma requête SQL ! En effet, dans le SELECT, il y a : `SELECT category.title as title, count(*) as count`. ### C. Conclusion On peut évidemment placer n'importe quelle requête SQL dans n'importe quel Model. Il faut bien penser à instancier le pointeur de base de données avec `$bdd = Db::getDb();`. En réalité, s'il n'y avait pas eu la classe `Db`, toutes les méthodes de CRUD (find, findOne, findBy, save, update, delete...) auraient toutes pu être rédigées en SQL de cette manière ! > Il n'y a aucune problème à faire des requêtes SQL à chaque méthode CRUD d'un Model si vous ne souhaitez pas utiliser l'abstraction offerte par la classe Db. Pour exemple ,la classe Article avec des méthodes uniquement en SQL est dans le fichier `/models/ArticlesSQLVERSION.php`.<file_sep># Réalisation d'un MVC : Comment ça fonctionne ? ## Les grandes lignes Avec un pattern MVC (*Model-View-Controller*), nous allons gérer nos projets en **ressources** : en général, une ressource correspond à une **table** dans la base de données. Pour chaque ressource, nous allons créer 2 à 3 fichiers : - Le Controller, c'est la classe qui contiendra toutes les actions que l'on peut réaliser autour de cette ressource (consulter des données, modifier des données, faire des opérations sur ces données...) - Le Model, c'est la classe qui va *représenter* la base de données: lorsque le controller aura besoin de faire des opérations qui nécessitent de parler à la BDD (lire les données, les modifier, les enregistrer, les supprimer...), il va demander au Model d'effectuer ces opérations. - La View, c'est en fait le rendu visuel : par exemple, lorsque je vais sur la page du film "Rocky" dans mon projet Vidéoclub, le **Controller** va *demander* au **Model** les données correspondant au film. Une fois reçues, le controller va **envoyer** les données à la **View**, c'est à dire le rendu HTML que l'utilisateur va voir ! - > Parfois nous n'aurons pas de view, c'est le cas pour une API où le controller va renvoyer une donnée en JSON mais sans passer par un fichier contenant du HTML, ou bien pour une méthode POST (enregistrer un nouveau film par exemple) qui redirigera plutôt vers la liste des films plutôt qu'une vue disant simplement "le film est enregistré". L'intérêt d'une architecture en MVC est de séparer les ressources en petits modules qui fonctionnent tous de la même manière. Pour orchestrer tout ce fonctionnement, nous nous servons d'un **router** : c'est un outil qui permet d'associer une *route* (l'URL !) demandée par l'utilisateur à un controller et une action en particulier. ## Le détail des étapes Voilà comment le tout fonctionne : 1. L'**utilisateur** va sur la page https://www.example.com/movies/3 > Grâce à un fichier .htaccess (un fichier qui donne des instructions au serveur Apache, celui qui gère les requêtes HTTP!), toute URL tapée par l'utilisateur ou par l'action d'un formulaire est redirigée vers... https://www.example.com/index.php. En effet, dans index.php, on inclut tous les fichiers nécessaires au bon fonctionnement du MVC, et notamment le router ! C'est lui qui prend le relai et qui va comprendre qu'on veut aller sur `/movies/3`. 2. Le **router** va réagir à cette demande: "On me demande la route `/movies/3` ! Je transmet la requête au **controller** correspondant, c'est `MoviesController`. De plus, vu comme est composée la requête, je sais que l'utilisateur veut consulter un film : je demande la méthode `read()`. Et comme je sais qu'on veut le film #3, je transmet cette variable aussi ! Je demande donc précisément `read($id)`, avec `$id = 3`." > En effet, par convention on appellera nos controllers par le nom de la ressource, au pluriel. Eh oui : c'est le "contrôleur des films" (`MoviesController`) ! Et comme c'est une classe, avec une première lettre majuscule. > Par convention encore, lorsque l'on consultera une donnée, on demandera la méthode `read()` : comme ça, quelle que soit la nouvelle ressource que j'ai à mettre dans mon projet, les méthodes seront toujours les même ! (On verra la liste des méthodes conventionnelles plus bas). 3. Le **controller** `MoviesController` reçoit la demande venant du router : on lui a demandé la méthode `read($id)` avec `$id = 3`. La méthode `read($id)` va demander au **model** `Movie` le film ayant l'id 3, éventuellement faire des petits traitements sur la donnée reçue (si je suis un utilisateur Allemand, je traduis les données automatiquement, si je suis logué comme un utilisateur Admin, je prévois d'afficher les boutons d'édition et de suppression du film...). Lorsque mes données sont prêtes, j'envoie le tout à une **view** qui sera affichée à l'utilisateur. > En fait, le controller est juste une classe, qui contient des méthodes (l'équivalent des fonctions mais dans une classe). Son but est de recevoir les demandes dispatchées par le router, et faire les opérations nécessaires à ce que l'on voulait faire en saisissant quelque chose dans l'URL. > Par convention là aussi, nous appelerons nos models par le nom de la ressource au singulier : `Movie` est le modèle d'un film ! Et comme c'est une classe, avec une première lettre majuscule. 4. Le **Model** se voit demander par le controller le film ayant l'ID numéro 3. C'est son rôle que de se connecter à la base de données (avec PDO par exemple) et de renvoyer le film demandé. > De même que le controller, le Model est juste une classe avec des méthodes. En fait, le controller a demandé au model `Movie` une méthode que l'on écrira par exemple `findOne($id)`. Cela aurait pu être `select($request)`, il y a des tas de façons d'implémenter un Model. 5. La donnée venant du Model envoyée au Controller, `MoviesController` peut maintenant la traiter s'il en a besoin, et enfin envoyer ces données à la **View** : c'est en fait simplement un template en HTML qui va accueillir des variables en PHP là où nécessaire (le titre de la page, le titre du film, les données du film...). 6. Enfin, l'utilisateur qui au départ a demandé la page https://www.example.com/movies/3... se voit afficher la page du film dont l'ID est 3 ! ## Pourquoi faire tout cela plutôt qu'une série de pages par table, comme par exemple un CRUD par table ? On pourrait tout à fait bâtir notre application comme on l'a fait pour les CRUD et faire quelque chose comme cela : ``` localhost/project/ index.php movies/ add.php save.php list.php show.php categories/ add.php save.php list.php show.php actors/ add.php save.php list.php show.php ``` Ce système fonctionnerait tout à fait ! Néanmoins, nous serions obligés de (1) répéter du code de partout, (2) un peu trop mélanger du HTML et du PHP, (3) éparpiller les grands axes de traitement de la donnée (réception d'une requête, traitements en base de données, réponse à la demande...) : si une modification s'opère au niveau de la base de données (changer le nom d'un champ par exemple), ce sont tous les fichiers impliqués qu'il faudrait modifier. En MVC, il n'y aurait que le Model de la table que l'on a modifié qu'il faudrait adapter. De plus, grâce aux classes et à l'héritage, on peut économiser beaucoup de code en le transmettant de classes parents à classes enfants ! Voyons maintenant comment mettre en place un projet MVC !<file_sep><?php /** * Exemple de la classe Article avec des méthodes toutes rédigées en SQL * * La classe est évidemment résumée ! */ class Article extends Db { // [...] /** * CRUD Methods */ public function save() { $bdd = Db::getDb(); $req = "INSERT INTO Article(title, content, id_author) VALUES ($this->title(), $this->content(), $this->idAuthor()"; $res = $bdd->execute($req); $this->setId($bdd->lastInsertId()); return $this; } public function update() { if ($this->id > 0) { $bdd = Db::getDb(); $req = "UPDATE Article SET ( title = $this->title(), content = $this->content(), id_author = $this->idAuthor(), updated_at = CURRENT_TIMESTAMP )"; $res = $bdd->execute($req); return $this; } return; } public function delete() { $bdd = Db::getDb(); $req = "DELETE FROM Article WHERE id = " . $this->id(); $res = $bdd->execute($req); return; } public static function findAll($objects = true) { $bdd = Db::getDb(); $req = "SELECT * FROM Articles"; $res = $bdd->query($req); $data = $res->fetchAll(PDO::FETCH_ASSOC); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new Article($d['title'], $d['content'], intval($d['id']), $d['short_content'], $d['content'], intval($d['id_author']), $d['created_at'], $d['updated_at']); } return $objectsList; } return $data; } public static function find(array $request, $objects = true) { // Impossible à faire, find recherche par champs/valeur, ce que Db nous permettait de faire. // Si on veut faire une requête sur un champ particulier, il faudra procéder comme findOne ou findByAuthor ci-dessous. } public static function findOne(int $id, $object = true) { $bdd = Db::getDb(); $req = "SELECT * FROM Articles WHERE id = " . $id; $res = $bdd->query($req); $data = $res->fetch(PDO::FETCH_ASSOC); if (count($data) > 0) $data = $data[0]; else return; if ($object) { $article = new Article($data['title'], $data['content'], $data['id']); return $article; } return $data; } public static function findByAuthor($id_author) { $bdd = Db::getDb(); $req = "SELECT * FROM Articles WHERE id_author = " . $id_author; $res = $bdd->query($req); $data = $res->fetchAll(PDO::FETCH_ASSOC); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new Article($d['title'], $d['content'], intval($d['id']), $d['short_content'], $d['content'], intval($d['id_author']), $d['created_at'], $d['updated_at']); } return $objectsList; } return $data; } public function categories() { return ArticleCategory::findByCategory($this->id()); } public function addCategory(Category $category) { $ac = new ArticleCategory($this->id(), $category->id()); $ac->save(); return; } } // Dernière accolade correspondant à la première ligne "class Article { ..."<file_sep><?php /** * Nous allons utiliser des méthodes issues de Db, nous disons que Article * est une classe enfant de la classe Db */ class Article extends Db { /** * Attributs */ protected $id; protected $title; protected $short_content; protected $content; protected $id_author; protected $created_at; protected $updated_at; /** * Constantes * Nous pouvons aussi définir des constantes. Ici, il s'agit du nom de la table. Ainsi, s'il venait à changer, nous n'aurons plus qu'à le changer à cet endroit. */ const TABLE_NAME = "Article"; /** * Méthodes magiques */ public function __construct($title, $content, User $user, $id = null, $short_content = null, $created_at = null, $updated_at = null) { /** * Pour chaque argument, on utilise les Setters pour attribuer la valeur à l'objet. * Pour appeler une méthode non statique de la classe DANS la classe, on utilise $this. */ $this->setTitle($title); $this->setContent($content); $this->setId($id); $this->setShortContent($short_content); $this->setIdAuthor($user); $this->setCreatedAt($created_at); $this->setUpdatedAt($updated_at); } /** * Getters */ public function id() { return $this->id; } public function title() { return $this->title; } public function shortContent() { return $this->short_content; } public function content() { return $this->content; } public function idAuthor() { return $this->id_author; } public function createdAt() { return $this->created_at; } public function updatedAt() { return $this->updated_at; } /** * On peut bien sûr créer des getters pour des usages propres à l'application ! * On va par exemple créer les getters suivants : * - Date de création formatée en français * - Date de mise à jour formatée en français * - Intervalle entre la date de mise à jour et la date de création, en français */ public function createdAtFr() { $date = new DateTime($this->createdAt()); $dateFr = $date->format('d/m/Y H:i:s'); return $dateFr; } /** * Pour l'exercice, on rajoute une variable facultative $time qui permet de retourner ou non l'heure. A l'usage on aurait donc : * $article->updatedAtFr() // Retourne "21/12/2018 15:14:12" * $article->updatedAtFr(false) // Retourne "21/12/2018" */ public function updatedAtFr($time = true) { $date = new DateTime($this->updatedAt()); $format = ($time) ? 'd/m/Y H:i:s' : 'd/m/Y'; $dateFr = $date->format($format); return $dateFr; } /** * Grâce à la documentation PHP, on peut savoir comment comparer deux objets DateTime. * La variable $intervalle est un objet DateInterval : * http://www.php.net/manual/en/class.dateinterval.php * * Cette fonction retourne la différence en jours. */ public function daysSinceCreation() { $createdAt = new DateTime($this->createdAt()); $updatedAt = new DateTime($this->updatedAt()); $intervalle = $createdAt->diff($updatedAt); return $intervalle->d; } /** * Setters */ public function setId($id) { $this->id = $id; return $this; } public function setTitle(string $title) { if (strlen($title) == 0) { throw new Exception('Le titre ne peut pas être vide.'); } if (strlen($title) > 150) { throw new Exception('Le titre ne peut pas être supérieur à 150 caractères.'); } $this->title = $title; return $this; } public function setShortContent(string $short_content = null) { $this->short_content = $short_content; return $this; } public function setContent(string $content) { $this->content = $content; return $this; } public function setIdAuthor($id_author = null) { $this->id_author = $id_author; return $this; } public function setCreatedAt(string $created_at) { $this->created_at = $created_at; return $this; } public function setUpdatedAt(string $updated_at) { $this->updated_at = $updated_at; return $this; } /** * CRUD Methods */ public function save() { $data = [ "title" => $this->title(), "content" => $this->content(), "id_author" => $this->idAuthor() ]; //if ($this->id > 0) return $this->update(); $nouvelId = Db::dbCreate(self::TABLE_NAME, $data); $this->setId($nouvelId); return $this; } public function update() { if ($this->id > 0) { $data = [ "id" => $this->id(), "title" => $this->title(), "short_content" => $this->shortcontent(), "content" => $this->content(), "id_author" => $this->idAuthor(), "updated_at" => "CURRENT_TIMESTAMP" ]; Db::dbUpdate(self::TABLE_NAME, $data); return $this; } return; } public function delete() { $data = [ 'id' => $this->id(), ]; Db::dbDelete(self::TABLE_NAME, $data); return; } public static function findAll($objects = true) { $data = Db::dbFind(self::TABLE_NAME); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new Article($d['title'], $d['content'], intval($d['id']), $d['short_content'], $d['content'], intval($d['id_author']), $d['created_at'], $d['updated_at']); } return $objectsList; } return $data; } public static function find(array $request, $objects = true) { $data = Db::dbFind(self::TABLE_NAME, $request); if ($objects) { $objectsList = []; foreach ($data as $d) { $objectsList[] = new Article($d['title'], $d['content'], intval($d['id']), $d['short_content'], $d['content'], intval($d['id_author']), $d['created_at'], $d['updated_at']); } return $objectsList; } return $data; } public static function findOne(int $id, $object = true) { $request = [ ['id', '=', $id] ]; $element = Db::dbFind(self::TABLE_NAME, $request); if (count($element) > 0) $element = $element[0]; else return; if ($object) { $article = new Article($element['title'], $element['content'], $element['id']); return $article; } return $element; } public static function findByAuthor($id_author) { return Article::find(self::TABLE_NAME, [ ['id_author', '=', $id_author] ]); } public function categories() { return ArticleCategory::findByCategory($this->id()); } public function addCategory(Category $category) { $ac = new ArticleCategory($this->id(), $category->id()); $ac->save(); return; } } // Dernière accolade correspondant à la première ligne "class Article { ..."<file_sep> # Gestion de données: MCD et relations (théorie) Le MVC étant enfin prêt, il s'agit maintenant de reproduire les étapes depuis le routeur jusqu'à la vue pour réaliser votre projet. Nous allons voir quelques méthodes à implémenter dans les classes qui peuvent être plus complexes : les différentes cardinalités d'un MCD (1-1, 1-N, N-N). ## 1. Rappels sur les cardinalités > Note : pour les cardinalités suivantes, on va supposer que : > - Un utilisateur n'a qu'une seule adresse > - Une adresse n'appartient qu'à un seul utilisateur > - Un utilisateur peut être auteur de plusieurs articles > - Un article ne peut appartenir qu'à un seul auteur > - Un article peut avoir plusieurs catégories > - Une catégorie peut avoir plusieurs articles > Ce travail d'inventaire des relations possibles entre mes données est **extrêmement** important : il faut le faire avant même de commencer à coder. Il nous permet de savoir à l'avance les features qui seront disponibles, possibles, celles qui sont actuellement impossibles et qui demanderaient des tables supplémentaires, etc. ### 1-1 - 1 élément de A possède 1 seul élément de B. - 1 élément de B possède 1 seul élément de A. ![Cardinalité 1-1](https://i.imgur.com/GzSNMXg.png) ![Cardinalité 1-1 bis](https://i.imgur.com/qgK84bX.png) Une cardinalité 1-1 est une relation entre deux tables qui pourraient être fusionnées en une seule. C'est à dire qu'on pourrait clairement mettre les données de la table Address dans la table User, puisque un utilisateur n'a qu'une seule adresse et une adresse n'appartient qu'à un utilisateur. On a deux exemples en image: on peut aussi bien dire qu'une adresse appartient à un utilisateur (en mettant `id_user` dans Address), ou bien dire qu'un utilisateur possède une adresse (en mettant `id_address` dans la table User). > **Où placer l'id ?** Le choix de l'une ou l'autre table revient à vous et à l'aspect métier de votre projet : quel sens de lecture vous semble le plus cohérent ? ### 1-N - 1 élément de A possède plusieurs élements de B. - 1 élément de B n'appartient qu'à 1 seul élément de A. ![Cardinalité 1-N](https://i.imgur.com/zVmzYxW.png) Une cardinalité 1-N est une relation d'appartenance d'une table avec une autre. Ici, un article appartient à un utilisateur (on a un `id_user` du côté de la table possédée, Article), et un utilisateur possède plusieurs articles. > **Où placer l'id ?** Cette fois, la clé étrangère est la clé primaire de la table qui possède : ici, les utilisateurs possèdent. On place donc leur clé primaire (`id_user`) en tant que clé étrangère dans la table qui est possédée (les articles sont possédés par des utilisateurs, c'est dans Article que l'on met `id_user`). ### N-N - Un élément de A possède plusieurs éléments de B - Un élément de B possède plusieurs éléments de A![Relation N-N](https://i.imgur.com/QI8sIe0.png) Une cardinalité N-N est un peu plus complexe : ici, on a un article qui peut avoir plusieurs catégories, ainsi que l'inverse: une catégorie peut avoir plusieurs articles. - Si nous avions qu'une seule des deux phrases, *un article peut avoir plusieurs catégories*, on n'aurait juste à mettre un `id_article` dans la table Categorie (l'id du possesseur va dans la table du possédé, une relation 1-N) : on répond à la phrase, puisque les id d'articles sont bien dans la table Catégorie (les catégories peuvent avoir un id_article, on a bien "un article peut avoir plusieurs catégories". - Or, on a également l'autre phrase qui est vraie : *une catégorie peut avoir plusieurs articles*. Si on mettait une autre relation 1-N avec un `id_category` dans la table Article (le possédé, article, prend l'id du possesseur, catégorie), on on répondrait aussi à la phrase : puisque les id de catégories sont bien dans la table Article (les articles peuvent avoir un id_category), on a bien *une catégorie peut avoir plusieurs articles*. - ![Lexomil](https://i.imgur.com/B71Ksv1.jpg?1) - Le problème, c'est qu'en faisant ainsi, les 2 phrases ne pourront pas être vraies en même temps ! On ne peut pas dire qu'un article appartient à plusieurs catégories, et qu'une catégorie appartient à plusieurs articles à la fois. - La phrase correcte serait plutôt : "plusieurs articles peuvent avoir plusieurs catégories, plusieurs catégories peuvent avoir plusieurs articles". - La solution est créer une table de jointure (`article_category`) : |id_article|id_category | |--|--| | 1 | 1 | | 1 | 2 | | 1 | 3 | | 2| 1 | | 3 | 2 | | 3| 4 | > L'article 1 a les catégories 1, 2, 3, l'article 2 a la catégorie 1, l'article 3 a les catégories 2 et 4 > La catégorie 1 a les articles 1 et 2, la catégorie 2 a les articles 1 et 3, etc. Comme on le voit, cette table de jointure possède deux clés **qui seront forcément primaires** et qui correspondent aux ID d'autres tables : on a donc : - une relation 1-N entre Article et article_category, - une relation 1-N entre Category et article_category Ce qui nous donne le schéma ci-dessus ! ## 2. Vue d'ensemble ![MVC : vue d'ensemble](https://i.imgur.com/iiHoK0l.png)
a80db89480297e2d4ebb64abe5c94ab887c4e746
[ "Markdown", "PHP" ]
21
PHP
tomsihap/MVC-course
ff28db8fb47bb683a1416d3507f8873f2b2f3a62
9a3039f45d71af72e0309a58c5a0e46d3a4c39e4
refs/heads/master
<repo_name>ManuelLG92/react-forum<file_sep>/src/components/posts/postsHooks.jsx import React, { useState, useEffect } from 'react'; import axios from 'axios' import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import CardHeader from '@material-ui/core/CardHeader'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import Container from '@material-ui/core/Container'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; function Postsprueba () { const [loaded, setLoaded] = useState(null); const [items, setItems] = useState([]); /* constructor(props){ super(props); this.state = { items: [], loaded: false }; }*/ const useStyles = makeStyles((theme: Theme) => createStyles({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, /* title: { flexGrow: 1, },*/ links: { margin: '0.5em', color: 'white', textDecoration: 'none', display: 'inline-block', "&:hover, &:focus": { textDecoration: 'none', color: 'white', } }, logout: { marginLeft: '0.1em' }, icons: { marginleft: '4em' }, cardStyle: { width: '80%' } } ) ); useEffect( () => { console.log("usa el efecto") // Actualiza el título del documento usando la API del navegador // document.title = `You clicked ${count} times`; return () => { async function getValues () { await axios.get (`http://localhost:2000/users/posts/`) console.log("Entra en axios") .then (res => { let posts = res.data; setLoaded(true) setItems(posts.data) //this.setState({items : posts.data, loaded: true}) // console.log(res.status) // console.log(posts) // const lista = this.state.items // console.log(Array.isArray(lista)) }) } } //this.getValues() }, []); /*componentDidMount() { this.getValues() }*/ const pStyle = { fontSize: '15px', textAlign: 'center', padding: '2em', border: '1px solid black', width: '25em', borderRadius: '5px', margin: '0 auto', marginTop: '3em', marginBottom: '1em', backgroundColor: "#92B4A7" }; if (loaded) { console.log("No recorre el array") return <h2>Loading..</h2> } else { return ( items.map(p => { console.log("Recorre el array") return ( <Container maxWidth="xl"> <Card className={Posts.useStyles}> <div key={p.id} style={pStyle}> <CardHeader title={"#" + JSON.stringify(p.id) + " " + p.title + " by user ID " + JSON.stringify(p.user_id)} style={ { backgroundColor: "#B7CDC4"}} /> <Divider /> <CardContent style={ { backgroundColor: "#C3D5CD"}}> <Typography gutterBottom variant="h5" component="h2"> {p.content} </Typography> </CardContent> </div> </Card> </Container> ) }) ) } }export default Postsprueba;<file_sep>/src/components/posts/newPost.jsx import React from 'react'; import axios from 'axios' //import { FormControl } from '@material-ui/core'; import {Container, Button, Grid, TextField }from '@material-ui/core'; import DoneOutlineIcon from '@material-ui/icons/DoneOutline'; //import SaveIcon from '@material-ui/icons/Save'; import {UserContext} from '../users/userContext' import MyStyles from '../styles' import { Redirect } from 'react-router-dom' import Cookies from 'universal-cookie'; const NewPost = () => { const user = React.useContext(UserContext) //console.log(user.id) //const [userId, SetUserId] = React.useState(null) const [titleState, SetTitle] = React.useState(null) const [descriptionState, SetDescription] = React.useState(null) const [created, SetCreated] = React.useState(null) const [errorForm, SetErrorForm] = React.useState(null) //const [loaded, SetLoaded] = React.useState(null) const createPost = async (event) => { const cookies = new Cookies(); var newPostStore = { user_id: user.id, uuid: cookies.get("Go_session"), title: titleState, content: descriptionState } let axiosConfig = { headers: { 'Content-Type': 'application/json', } } event.preventDefault(); console.log(newPostStore) // console.log("fields control: ", validFields()) if (validFields()) { console.log("Correct fields") axiosConfig["withCredentials"] = true await axios.post(`http://localhost:2000/posts/newPost/`, newPostStore, axiosConfig) .then(response =>{ // console.log("all response" , response) console.log("Response status", response.status) SetCreated(true) // SetLoaded(true) }) .catch(err => console.log(err)) } else { console.log("Some field empty") } } const validFields = () => { if (titleState !== null && descriptionState !== null ) { // console.log("Not null fields") if ( titleState.length > 0 && titleState.length <51 && descriptionState.length > 0 && descriptionState.length <266 ) { //console.log("Not null length fields") return true } } SetErrorForm(true) console.log("Null fields") return false } if (created) { return <Redirect to="/posts"></Redirect> } return ( <Container style={MyStyles.newPostStyle} maxWidth="sm" > <Grid container justify="center"> <form id="newPost"> <h2>Title</h2> <TextField variant="outlined" margin="normal" required fullWidth id="title" label="Title" type="text" name="title" autoComplete="title" autoFocus onChange={(e) => SetTitle(e.target.value)} /> <h2>Descripcion</h2> <TextField variant="outlined" margin="normal" required fullWidth name="description" label="description" type="text" id="description" autoComplete="description" onChange={(e) => SetDescription (e.target.value)} /> <Grid item md={12} > <Button color="primary" variant="outlined" onClick={createPost}> <DoneOutlineIcon/> Submit </Button> <br/> <br/> </Grid> {errorForm === true ? <p>Fields Cannot be empty and Title cannot has length higher than 50 nor description cannot has length higher than 255</p> : "" } </form> </Grid> </Container> ) } export default NewPost<file_sep>/src/components/users/profile.jsx import React from 'react'; import {UserContext} from './components/users/userContext' const UserProfile = () => { const user = React.useContext(UserContext) return ( <div> {user} </div> ) } export default UserProfile<file_sep>/src/components/styles.jsx const MyStyles = { newPostStyle: { backgroundColor : 'white', padding: '3em', borderRadius: '0px', background: 'white' }, textField: { margin: '1em' }, pStyle : { fontSize: '15px', textAlign: 'center', padding: '1em', paddingBottom: '2em', border: '1px solid black', borderRadius: '5px', margin: '0 auto', marginTop: '3em', marginBottom: '3em', backgroundColor: "#92B4A7", display: 'flex', flexDirection: 'row', flexWrap: 'wrap', width: '100%' } } export default MyStyles<file_sep>/src/components/users/SingUp.jsx import React from 'react'; import {Container, Button, Grid, TextField, Box }from '@material-ui/core'; import {Base, styles, pStyle } from './Base'; import axios from 'axios' import { Link } from "react-router-dom"; export default class SignUp extends Base { constructor(props){ super(props); this.submit = this.submit.bind(this); } async submit () { var userRegistration = { name: this.state.name, last_name: this.state.last_name, email: this.state.email, password: <PASSWORD>, } let axiosConfig = { headers: { 'Content-Type': 'application/json' } } /* console.log("name: ", this.state.nameSubmit) console.log("LastName: ", this.state.lastNameSubmit ) console.log("password: ", <PASSWORD>) console.log("Email: ", this.state.emailSubmit) console.log("Password confirm: ", this.state.confirmPasswordSubmit) console.log("Email: ", this.state.email) console.log(userRegistration)*/ if (this.state.nameSubmit && this.state.lastNameSubmit && this.state.passwordSubmit && this.state.emailSubmit && this.state.passwordSubmit) { console.log(userRegistration) await axios.post(`http://localhost:2000/users/sign-up/`, userRegistration, axiosConfig) .then(response => { console.log(response) console.log(response.data) document.getElementById("formRegister").reset() window.location.reload() // this.clearFields() }).catch(err => console.log(err))} else { console.log("Error en la validacion") } } /* clearFields(){ document.getElementById("formRegister").reset() }*/ render() { return ( <Container > <Grid container justify="center"> <p>{this.state.error}</p> <Box> <form style={pStyle} id="formRegister" > <h2>Register</h2> <TextField variant="outlined" margin="normal" required fullWidth id="name" label="Type your name.." type="text" name="name" autoComplete="name" autoFocus onChange={(e) => this.syncName(e)} /> <TextField variant="outlined" margin="normal" required fullWidth id="last_name" label="Type your last name or surname.." type="text" name="last_name" autoComplete="last_name" onInput={(e) => this.syncLastName(e)} /> <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Type your email address" type="email" name="email" autoComplete="email" onChange={(e) => this.syncEmail(e)} /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Type your password" type="password" id="password" autoComplete="current-password" onChange={(e) => this.syncPassword(e)} /> <TextField variant="outlined" margin="normal" required fullWidth name="passwordConfirmation" label="Password confirm." type="password" id="passwordConfirmation" autoComplete="current-password" onChange={(e) => this.syncConfirmpassword(e)} /> <Grid item md={12} > <Button variant="contained" color="primary" style={styles.buttonTop} onClick={() => this.submit()}> Sign Up! </Button> <br/> <br/> <span> Already have an account? </span> <Button color="inherit" component={Link} to="/sign-in" >Sign-in!</Button> </Grid> </form> </Box> </Grid> </Container> ); } }<file_sep>/src/components/users/SingIn.jsx import React from 'react'; import {Container, Button, Grid, TextField, Box }from '@material-ui/core'; import {Base, styles, pStyle } from './Base'; //import Cookies from 'universal-cookie'; //import { v4 as uuidv4 } from 'uuid'; import { Redirect } from 'react-router-dom' import axios from 'axios' import { Link } from "react-router-dom"; /* const cookieName = 'LoginCookie' const cookieVal = uuidv4()*/ export default class SignIn extends Base{ constructor(props){ super(props); this.submit = this.submit.bind(this); this.state = { signedIn : false } } async submit (event) { var userLogin = { email: this.state.email, password: <PASSWORD> } let axiosConfig = { headers: { 'Content-Type': 'application/json', } } event.preventDefault(); axiosConfig["withCredentials"] = true await axios.post(`http://localhost:2000/users/sign-in/`, userLogin, axiosConfig) .then(response => { console.log(response) console.log(response.data) console.log(response.data.status) if (response.data.status === 200) { this.setState({signedIn : true}) window.location.reload() } console.log(response.data.cookie) this.clearFieldLogin() }).catch(err => console.log(err)) } clearFieldLogin(){ document.getElementById("formLogin").reset() } render() { if (this.state.signedIn) { return <Redirect to="/"></Redirect> } else { return ( <Container > <Grid container justify="center"> <p>{this.state.error}</p> <Box > <form style={pStyle} id="formLogin"> <h2>Login</h2> <div>{this.state.error}</div> <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" type="email" name="email" autoComplete="email" autoFocus onChange={(e) => this.syncEmail(e)} /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" onChange={(e) => this.syncPassword(e)} /> <Grid item md={12} > <Button variant="contained" color="primary" disabled={this.state.canSubmit} style={styles.buttonTop} onClick={this.submit} > Sign Up! </Button> <br/> <br/> <span>Haven't you an account yet?</span> <Button color="inherit" component={Link} to="/sign-up" >register now!</Button> </Grid> </form> </Box> </Grid> </Container> ); } } } /* <EMAIL> manuel92 */<file_sep>/src/components/posts/apiPost.jsx import React from 'react'; import axios from 'axios' import { createStyles, makeStyles, withStyles } from '@material-ui/core/styles'; import CircularProgress from '@material-ui/core/CircularProgress'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper' import {UserContext} from '../users/userContext' import Button from '@material-ui/core/Button'; import PostAddIcon from '@material-ui/icons/PostAdd'; import { Link } from "react-router-dom"; //import { Redirect } from 'react-router-dom' const StyledTableCell = withStyles((theme) => ({ head: { backgroundColor: theme.palette.common.black, color: theme.palette.common.white, }, body: { fontSize: 14, }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ root: { '&:nth-of-type(odd)': { backgroundColor: theme.palette.action.hover, }, }, }))(TableRow); const useStyles = makeStyles((theme) => createStyles({ /* title: { flexGrow: 1, },*/ rootLoading: { display: 'flex', '& > * + *': { marginLeft: theme.spacing(2), }, margin: '0 auto' }, table: { minWidth: 700, border: '1px solid black' }, } ) ); const styles = { buttonStyle: { marginTop: '2em', marginLeft: '75%' } } /* const newPost = { marginTop: '2em', marginLeft: '70%' } */ const Posts = () => { //console.log({auth}) // const location = useLocation(); //const deletedPost = location.state.deletedPost const user = React.useContext(UserContext) const [posts, SetPosts] = React.useState([]) const [load, SetLoad] = React.useState(false) //console.log(user) const getPosts = async () => { await axios.get (`http://localhost:2000/posts/`) .then (res => { let posts = res.data; SetPosts(posts.data) //this.setState({items : posts.data, loaded: true}) console.log(posts) // console.log(posts) // const lista = this.state.items // console.log(Array.isArray(lista)) /* component={Link} to={ { pathname: '/edit-post', state: { user_id: post.user_id, post_id: post.id, title: post.title, content: post.content, }, } } */ }) .catch(error => console.log(error)) } React.useEffect(() => { getPosts() SetLoad(true) }, [] ) if (!load) { return ( <div className={useStyles.rootLoading}> <h2>Loading..</h2> <CircularProgress /> </div> ) } else { return ( <div style={{paddingBottom: '1em', marginBottom: '2em'}}> <TableContainer component={Paper}> <Table className={useStyles.table} aria-label="customized table"> <TableHead> <TableRow> <StyledTableCell>Theme</StyledTableCell> <StyledTableCell align="right">Author</StyledTableCell> <StyledTableCell align="center">Date</StyledTableCell> <StyledTableCell align="center">Responses</StyledTableCell> </TableRow> </TableHead> <TableBody> {posts.map((post) => ( <StyledTableRow key={post.id}> <StyledTableCell component="th" scope="row" > <Link to={`/post/${post.id}`} color="inherit"> {post.title} </Link> </StyledTableCell> <StyledTableCell align="right">{post.user_name}</StyledTableCell> <StyledTableCell align="center">{post.created_at}</StyledTableCell> <StyledTableCell align="center">0</StyledTableCell> </StyledTableRow> ))} </TableBody> </Table> </TableContainer> {user !== null ? <Button variant="outlined" color="primary" style={styles.buttonStyle} component={Link} to="/create-post"> <PostAddIcon/> Create new post </Button> : ""} </div> ) } } export default Posts<file_sep>/src/components/routes/routes.jsx import React from 'react'; import { //BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom"; import NewPost from '../posts/newPost' import PrivateRoute from '../privateRoutes' import {PublicRoute} from '../privateRoutes' import Posts from '../posts/apiPost.jsx' import Logout from '../users/logout' import IndexLayout from '../indexLayout' import Container from '@material-ui/core/Container'; import SinglePost from '../posts/postById' import SignUp from '../users/SingUp.jsx' import SignIn from '../users/SingIn.jsx' import EditPost from '../posts/editPost' const Routes = ({auth}) => { // console.log({auth}) // <PrivateRoute auth={auth} path="/edit-post/:postId/:title/:description" component={EditPost} exact /> return ( <Switch> <Route path="/" exact> <Container style={{ backgroundColor : 'white', paddingTop: '1em', paddingBottom: '1em'}} maxWidth="md"> <div> <IndexLayout/> </div> </Container> </Route> <Route path="/posts" exact> <Container style={{ backgroundColor : 'white', paddingTop: '1em'}} maxWidth="md"> <Posts auth={auth}/> </Container> </Route> <PublicRoute auth={auth} path="/sign-up" component={SignUp} exact /> <PublicRoute auth={auth} path="/sign-in" component={SignIn} exact /> <Route path="/post/:id" exact> <Container style={{ paddingTop: '1em', paddingBottom: '1em'}} maxWidth="xl"> <SinglePost auth={auth}/> </Container> </Route> <PrivateRoute auth={auth} path="/create-post" component={NewPost} exact /> <PrivateRoute auth={auth} path="/edit-post" component={EditPost} exact /> <PrivateRoute auth={auth} path="/delete-post:id" component={EditPost} exact /> <PrivateRoute auth={auth} path="/log-out" component={Logout} exact /> <Redirect path="*" to="/"></Redirect> </Switch> ) } export default Routes<file_sep>/src/components/posts/postById.jsx import React from 'react'; import axios from 'axios' import { useParams} from "react-router-dom"; //import { makeStyles, createStyles, Theme } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import CardHeader from '@material-ui/core/CardHeader'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import Avatar from '@material-ui/core/Avatar'; import Input from '@material-ui/core/Input'; import AccountCircleIcon from '@material-ui/icons/AccountCircle'; import Button from '@material-ui/core/Button'; import {UserContext} from '../users/userContext' import { Link, Redirect } from 'react-router-dom' import CircularProgress from '@material-ui/core/CircularProgress'; import Cookies from 'universal-cookie'; import Dialog from '@material-ui/core/Dialog'; import {DialogActions,DialogContent, DialogContentText, DialogTitle } from '@material-ui/core'; import MyStyles from '../styles' //import { confirmAlert } from 'react-confirm-alert'; // Import //import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css const SinglePost = () => { const cookies = new Cookies(); const user = React.useContext(UserContext) const {id} = useParams() const [post, Setpost] = React.useState([]) const [load, SetLoad] = React.useState(false) const [deleted, SetDeleted] = React.useState(false) // const [submitDelete, SetSubmitDelete] = React.useState(false) const [open, setOpen] = React.useState(false); //console.log(useParams()) React.useEffect(() => { const getPost = () => { axios.get(`http://localhost:2000/post/${id}/`) .then(response => { // console.log(response) Setpost(response.data) SetLoad(true) //console.log(response.data) // console.log(post) }) .catch(error => console.log(error) ) // console.log(post) } getPost() },[id]) //console.log(id) const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; /**/ const deletePost = () => { //SetLoad(false) // console.log(user.id) // console.log(post.user_id) if (user.id === post.user_id) { var postToDelete = { user_id: post.user_id, uuid: cookies.get("Go_session"), } let axiosConfig = { headers: { 'Content-Type': 'application/json', } } axios.post(`http://localhost:2000/post/delete/${id}/`, postToDelete, axiosConfig) .then(response => { // console.log(response) // Setpost(response.data) if (response.status === 202 ) { SetDeleted(true) } console.log(response) console.log(response.status) // console.log(post) }) .catch(error => console.log(error) ) } else { return ( <Redirect to='/posts'></Redirect> ) } } const uStyle = { height: '100%', marginRight: '1em' }; const postStyle = { width: '100%', height: '100%', justifyContent: 'flex-start' } const btnStyles = { marginTop: '2em', marginLeft: '75%' } // const toEdit = `/edit-post/${post.id}/${post.title}/${post.description}` /* */ if (deleted) { return ( /*<div></div> <h1>Your post has been deleted successfully!</h1>*/ <Redirect to='/posts'></Redirect> ) } if (!load) { return ( <div > <h2>Loading..</h2> <CircularProgress /> </div> ) } else { return ( <div > <div style={{ background: '#2E3B55', color: 'white', padding: '1em', border: '1px solid black' }}> <h2 >{post.title}</h2> <p>By: {post.user_name + " " + post.last_name} at {post.created_at} </p> </div> <Card key={post.id} style={MyStyles.newPostStyle}> <div style={uStyle}> <Input type="hidden" value={post.user_id}></Input> <CardHeader title={"#" + JSON.stringify(post.id) + " " + post.title + " by user ID " + JSON.stringify(post.user_id)} subheader={"Created at: " + post.created_at} /> </div> <div style={postStyle}> <CardHeader avatar={ <Avatar aria-label="post" > <AccountCircleIcon fontSize="large"/> </Avatar>} title= {post.user_name + " " + post.last_name + "\n\n" } subheader= {"Country: " + post.country} style={ { backgroundColor: "#B7CDC4",alignSelf: 'center' }} /> <Divider /> <CardContent style={ { backgroundColor: "#C3D5CD"}}> <Typography component="h6"> {post.content} </Typography> {user.id === post.user_id ? <div style={btnStyles}> <Button variant="outlined" color="primary" component={Link} to={ { pathname: '/edit-post', state: { user_id: post.user_id, post_id: post.id, title: post.title, content: post.content, }, } } > Edit</Button> <Button color="primary" style= {{ marginRigth: "2em" }}onClick={handleClickOpen}> Delete</Button> <Dialog open={open} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{"Are you sure to delete this post?"}</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> If you delete this post, It will be not longer available anymore. </DialogContentText> </DialogContent> <DialogActions> <Button onClick={deletePost}> Yes, Delete </Button> <Button onClick={handleClose} color="primary"> No, cancel </Button> </DialogActions> </Dialog> </div> : ""} </CardContent> <Button color="primary" > Reply </Button> </div> </Card> </div> ) } } export default SinglePost<file_sep>/src/components/users/logout.jsx import React from 'react'; import axios from 'axios' import { Redirect } from 'react-router-dom' export default class Logout extends React.Component { constructor(props){ super(props); this.logOutServer = this.logOutServer.bind(this); this.state = { logoutSucces : false } } async logOutServer (event) { let axiosConfig = { headers: { 'Content-Type': 'application/json', } } event.preventDefault(); axiosConfig["withCredentials"] = true await axios.get(`http://localhost:2000/users/log-out/`, axiosConfig) .then(response => { console.log(response.data) if (response.status === 200) { this.setState({logoutSucces: true}) window.location.reload() } }) .catch(err => { console.log(err) }) } render() { if (this.state.logoutSucces) { return <Redirect to="/"/> } return ( <button onClick={this.logOutServer}>Log Out</button> ) } } /* const logOutServerRequest = async(event) => { const [logout, setLogout] = useState(false); let axiosConfig = { headers: { 'Content-Type': 'application/json', } } event.preventDefault(); axiosConfig["withCredentials"] = true await axios.get(`http://localhost:2000/users/log-out/`, axiosConfig) .then(response => { console.log(response.data) if (response.status === 200) { this.setState({logoutSucces: true}) window.location.reload() } }) .catch(err => { console.log(err) }) } if (this.state.logoutSucces) { return <Redirect to="/"/> } return ( <button onClick={this.logOutServerRequest}>Log Out</button> ) export default logOutServerRequest;*/<file_sep>/src/components/privateRoutes.jsx import React from 'react'; import { Route, Redirect } from "react-router-dom"; import {UserContext} from './users/userContext' function PrivateRoute ({component: Component, auth, ...rest}) { return ( <Route {...rest} render={(props) => auth === true ? <Component {...props} /> : <Redirect to={{pathname: '/sign-in' }} />} /> ) } export function PublicRoute ({component: Component, auth, ...rest}) { //console.log(auth) return ( <Route {...rest} render={(props) => auth === false ? <Component {...props} /> : <Redirect to={{pathname: '/' }} />} /> ) } export function PersonalRoutes ({component: Component, auth, user_id, ...rest}) { const user = React.useContext(UserContext) //console.log(auth) return ( <Route {...rest} render={(props) => auth === true && user_id === user.id ? <Component {...props} /> : <Redirect to={{pathname: '/posts' }} />} /> ) } export default PrivateRoute<file_sep>/src/components/navigation/navigationGeneral.jsx import React from 'react'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import ListAltIcon from '@material-ui/icons/ListAlt'; import HomeIcon from '@material-ui/icons/Home'; import {makeStyles } from '@material-ui/core/styles'; import { Link } from "react-router-dom"; const NavBar = () => { const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, /* title: { flexGrow: 1, },*/ links: { margin: '0.5em', color: 'white', textDecoration: 'none', display: 'inline-block', "&:hover, &:focus": { textDecoration: 'none', color: 'white', } }, logout: { marginLeft: '0.1em' }, icons: { marginleft: '4em' }, cardStyle: { width: '80%' } } ) ); const classes = useStyles(); return ( <AppBar position="static" style={{ background: '#2E3B55', marginBottom: '1em' }}> <Toolbar> <Typography variant="h6" className={classes.title}> ForoDogs </Typography> <div style={{marginLeft:'30%',flexGrow: 1}}> <Typography variant="h6" className={classes.links}> <HomeIcon className={classes.icons}/> <a href="/" className={classes.links}>Index</a> </Typography> <Typography variant="h6" className={classes.links}> <ListAltIcon className={classes.icons}/> <a href="/posts" className={classes.links}>Posts</a> </Typography> </div> <div> <Button color="inherit" component={Link} to="/sign-up" style={{marginRight:'2em'}} >Sign-UP!</Button> <Button color="inherit" component={Link} to="/sign-in" style={{marginRight:'2em'}} >Login</Button> </div> </Toolbar> </AppBar> ) } export default NavBar<file_sep>/src/Login.jsx import React from 'react'; import {Container, Button, Grid, TextField, Box }from '@material-ui/core'; <file_sep>/src/components/users/Base.jsx import React from 'react'; //import Axios from 'axios'; //import { blueA400 } from '@material-ui/core/colors'; //import {Container, Button, Grid, TextField, Box }from '@material-ui/core'; export class Base extends React.Component { constructor(props) { super(props); this.state = { //estado inicial canSubmit: false, name: '', last_name: '', email: '', password: '', passwordConfirmation: '', error: '', nameSubmit: false, lastNameSubmit: false, emailSubmit: false, passwordSubmit: false, confirmPasswordSubmit: false }; } validateEmail (email) { const regexp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; let valid = regexp.test(email); return valid } validatePass (password) { let valid; if (password.length < 8 || password.length > 24 ) { valid = false return valid } else { valid = true return valid } } syncEmail(event) { let value = event.target.value; if (this.validateEmail(value) === true) { this.setState({ email: value, emailSubmit: true }) this.submitSignUp() } else { this.setState({ emailSubmit: false }) this.submitSignUp() } this.submitSignUp() } syncPassword(event) { let value = event.target.value; this.setState({ password: value }) if (this.validatePass(value) === true) { this.setState({ passwordSubmit: true }) this.submitSignUp() } else { this.setState({ passwordSubmit: false }) this.submitSignUp() } } syncName(event) { this.submitSignUp() let nameForm = event.target.value if( nameForm.length > 0 || nameForm.length < 31) { this.setState({ nameSubmit: true, name: nameForm }) this.submitSignUp() } else { this.setState({ nameSubmit: false }) this.submitSignUp() } } syncLastName(event) { this.submitSignUp() let lastNameForm = event.target.value if( lastNameForm.length > 0 || lastNameForm.length < 31) { this.setState({ lastNameSubmit: true, last_name: lastNameForm }) this.submitSignUp() } else { this.setState({ lastNameSubmit: false }) this.submitSignUp() } } syncConfirmpassword(event) { let confirmPasswordForm = event.target.value console.log("password: ", <PASSWORD>) console.log("confirmation password: ",confirmPasswordForm) this.setState({ passwordConfirmation: confirmPasswordForm }) var samePassword = this.passwordComparision(this.state.password,confirmPasswordForm) console.log("comparision", samePassword) if (samePassword){ this.setState({ confirmPasswordSubmit: true }) this.submitSignUp() } else { this.setState({ confirmPasswordSubmit: false }) this.submitSignUp() } this.submitSignUp() } passwordComparision (password, confirmPass) { var samePassword = password.localeCompare(confirmPass); console.log("comparision password: ", <PASSWORD>Password) if (samePassword === 0) { this.setState({ confirmPasswordSubmit: true }) return true } else { this.setState({ confirmPasswordSubmit: false }) return false } } submitSignUp () { if (this.state.nameSubmit && this.state.lastNameSubmit && this.state.passwordSubmit && this.state.emailSubmit ) { if (this.state.password === this.state.passwordConfirmation) { this.setState({ canSubmit: true }) } } else { this.setState({ canSubmit: false }) } } } export const styles = { buttonTop: { marginTop: '1em', "&:hover, &:focus": { textDecoration: 'none', color: 'white', } }, underlineStyle: { borderColor: 'blue', }, floatingLabelFocusStyle: { color: 'blue', }, leftSpace: { marginLeft: '1em' }, margin: { margin: '3em' } } export const pStyle = { fontSize: '15px', textAlign: 'center', padding: '2em', border: '1px solid black', marginTop: '3em', width: '25em', borderRadius: '5px', background: 'white' }; <file_sep>/src/App.jsx import React from 'react'; import Dashboard from './components/dashboard.jsx' import Index from './components/indexMain.jsx' import axios from 'axios' import Cookies from 'universal-cookie'; import {UserContext} from './components/users/userContext' export default function App() { const [load, Setload] = React.useState(null) //const UserContext = React.createContext(null) const [auth, SetAuth] = React.useState(false) const [userAuth, SetUserAuth ] = React.useState([]) React.useEffect(() => { isAuth() }, [] ) const isAuth = async() => { const cookies = new Cookies(); const cookieName = "Go_session" const cookieValue = cookies.get(cookieName) // console.log(cookieValue) if (cookieValue !== undefined) { // console.log("Si cookie") let axiosConfig = { headers: { 'Content-Type': 'application/json', } } axiosConfig["withCredentials"] = true await axios.get(`http://localhost:2000/auth/`, axiosConfig) .then(response => { // SetLoaded(true) // console.log(response.status) if (response.status === 202) { SetAuth(true) SetUserAuth(response.data) } Setload(true) //console.log(response.data) }) .catch(error => { // SetLoaded(true) 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); } 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); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); console.log("El error fue: " , error) // return // } ) } else { Setload(true) } } // console.log(auth) if (!load) { return ( <h1>Loading...</h1> ) } else { if (auth) { return ( <UserContext.Provider value={userAuth}> <Dashboard auth={auth}/> </UserContext.Provider> ) } else if (!auth){ return ( <Index auth={auth}/> ) } } }<file_sep>/src/components/indexLayout.jsx import React from 'react'; import Jumbotron from 'react-bootstrap/Jumbotron' //import Container from 'react-bootstrap/Container' import Button from 'react-bootstrap/Button' const IndexLayout = () => { return ( <div> <Jumbotron> <h1>Hello, Welcome to Forodogs!!!</h1> <p> This is a forum applicacion, their back-end is an API rest written in Golang, and the front end is in react. </p> <p> This is just for fun, I am not good in material desing, I just checking my back-end in working properly </p> <p> <Button variant="primary"><NAME></Button> </p> </Jumbotron> </div> ) } export default IndexLayout
bed36e0804e9935270533baed38f23c66ea84916
[ "JavaScript" ]
16
JavaScript
ManuelLG92/react-forum
1b8e58d6b84c623b4e73a48d8bde1a96d8b5d567
80c45e755de3c3e733be5d60ca640072cf36c459
refs/heads/master
<repo_name>lumiazdk/meteorvue<file_sep>/README.md # meteorvue NO_HMR=1 meteor 启动 ui https://materializecss.com <file_sep>/server/lronrouter.js Router.route("/upload", { where: "server" }).post(function() { console.log('req') let req = this.request; let res = this.response; res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); let formidable = require("formidable"); let path = require("path"); let cloudinary = require("cloudinary").v2; cloudinary.config({ cloud_name: 'lumiazdk', api_key: '368961618787419', api_secret: '<KEY>', folders:'blog' }); let form = formidable.IncomingForm(); // 文件上传 form.parse(req, function(err, fields, files) { if (err) { console.log(err); } cloudinary.uploader.upload(files.files.path,{folder: 'blog'}, function(error, result) { if (result) { let data = { code: 0, data: result, message: "上传成功" }; res.end(JSON.stringify(data), "utf-8"); } else { console.log(respInfo.statusCode); console.log(error); } }); }); }); <file_sep>/lib/methods/upload.js var cloudinary = require("cloudinary").v2; cloudinary.config({ cloud_name: "lumiazdk", api_key: "368961618787419", api_secret: "<KEY>" }); Meteor.methods({ upload(file) { console.log("----"); console.log(file); // console.log(cloudinary) cloudinary.uploader.upload(file, function(error, result) { console.log(result, error); }); } }); <file_sep>/client/main.js import Vue from 'vue'; import VueMeteorTracker from 'vue-meteor-tracker'; import App from './App.vue'; import router from './router' import store from './store/store.js' import './main.html'; import Vant from 'vant'; import { Lazyload,Panel } from 'vant'; import 'vant/lib/index.css'; import VueAwesomeSwiper from 'vue-awesome-swiper' // require styles import 'swiper/dist/css/swiper.css' import './sourse/moment' moment.locale('zh-cn'); Vue.prototype.$moment=moment // 注册组件 Vue.use(VueAwesomeSwiper, /* { default global options } */) Vue.use(VueMeteorTracker); Vue.use(Lazyload); Vue.use(Panel); Router.route('/', { onBeforeAction: function () { this.next() }, }, function () { });//解决空路由问题 Vue.use(Vant); Vue.use(store) Meteor.startup(() => { new Vue({ el: '#app', router, store, ...App, }); });<file_sep>/lib/publications/Post.js Meteor.publish("Post", function tasksPublication() { // 实时订阅 todos 总数 Counts.publish(this, "PostCounts", Post.find({})); return Post.find({}); }); <file_sep>/lib/methods/post.js Meteor.methods({ post(op) { return { data: Post.find({}, { limit: op.limit * op.page }).fetch(), page: Math.ceil(Post.find({}).count() / op.limit) }; } }); <file_sep>/server/main.js import { Meteor } from "meteor/meteor"; import "/lib/collections/Time"; import "/lib/collections/Post"; // import '/lib/collections/User'; import "/lib/publications/Time"; import "/lib/publications/Post"; import "/lib/publications/User"; import "/lib/methods/UpdateTime"; import "/lib/methods/upload"; import "/lib/methods/post"; import "./lronrouter"; Meteor.startup(() => { // Update the current time Meteor.call("UpdateTime"); // Add a new doc on each start. Time.insert({ time: new Date() }); Post.insert({ name: "zdkkk", userId: "gZxBSF784aBhS9jeX", content: "asdfasdgf" }); // Print the current time from the database console.log(`The time is now ${Time.findOne().time}`); });
909535de9ee5457b073afd4bc994482217d3257b
[ "Markdown", "JavaScript" ]
7
Markdown
lumiazdk/meteorvue
e55e50819b66c7ba99e2f515c6d31252f48cb7ba
a9b8e6043ef3d9ce9f9835e7e7f6c38757719ff2
refs/heads/main
<file_sep>to run this website system must have nodejs installed. 1. intall nodejs (if you don't have) 2. run command " npm install " 3. run command " npm start " <file_sep>var mongoose = require('mongoose'); //Set up default mongoose connection var uri = 'mongodb+srv://P2dppOAbUfXjf5HM:<EMAIL>/myFirstDatabase?retryWrites=true&w=majority'; const connectDb = async() => { return mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true }); } module.exports = connectDb<file_sep>const sha256 = require('sha256') const User = require('./Models/userSchema') function Blockchain() { this.chain = [] this.pendingaccount = [] this.createNewBlock(3088, '', '#') } Blockchain.prototype.createNewBlock = function(nonce, prehash, hash) { return new Promise((resolve, reject) => { const newBlock = { index: this.chain.length + 1, username: this.pendingaccount[0] ? this.pendingaccount[0].username : '', timestamp: Date.now(), nonce, hash, prehash } this.pendingaccount = [] this.chain.push(newBlock) resolve(newBlock) }) } Blockchain.prototype.getLastBlock = function() { return this.chain[this.chain.length - 1] } Blockchain.prototype.createNewAccount = function(username, password) { const newAccount = { username, <PASSWORD> } this.pendingaccount.push(newAccount) return this.getLastBlock()['index'] + 1 } Blockchain.prototype.hashBlock = function(nonce, prehash, blockdata) { return new Promise((resolve, reject) => { const dataString = nonce + prehash + JSON.stringify(blockdata) const hash = sha256(dataString) resolve(hash) }); } Blockchain.prototype.proofOfWork = async function(prehash, blockdata) { return new Promise(async(resolve, reject) => { let nonce = 0; let hash = await this.hashBlock(nonce, prehash, blockdata) while (hash.substring(0, 4) != '0000') { nonce++ hash = await this.hashBlock(nonce, prehash, blockdata) } resolve(nonce) }) } module.exports = Blockchain
f7c07da822ae1f775dc783e11220aec41e51567d
[ "JavaScript", "Text" ]
3
Text
LUCIFEREXTON/BLOCKCHAINCertificateverifier
1d9b1ef6ca6655bf3ba6f5ab517d4c7006a0bc8b
08db27ae77ddb466df23a0e216cdef8155a3496d
refs/heads/master
<file_sep>package edu.depauw.csc480.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import edu.depauw.csc480.model.Alumni; import edu.depauw.csc480.model.Specialties; import edu.depauw.csc480.model.Company; import edu.depauw.csc480.model.Address; /** * Data Access Object for the Department table. * Encapsulates all of the relevant SQL commands. * Based on Sciore, Section 9.1. * * @author ducnguyen */ public class SpecialtiesDAO { private Connection conn; private DatabaseManager dbm; public SpecialtiesDAO(Connection conn, DatabaseManager dbm) { this.conn = conn; this.dbm = dbm; } /** * Create the Specialties table via SQL * * @param conn * @throws SQLException */ static void create(Connection conn) throws SQLException { Statement stmt = conn.createStatement(); String s = "create table Specialties(" + "Sid int not null, " + "Name varchar(100) not null, " + "Definition varchar(255) not null, " + "primary key(Sid))"; stmt.executeUpdate(s); } /** * Modify the Specialties table to add foreign key constraints (needs to * happen after the other tables have been created) */ static void addConstraints(Connection conn) throws SQLException { } /** * Retrieve a Specialties object given its key. * */ public Specialties find(int Sid) { try { String qry = "select Name, Definition from Specialties where Sid = ?"; PreparedStatement pstmt = conn.prepareStatement(qry); pstmt.setInt(1, Sid); ResultSet rs = pstmt.executeQuery(); // return null if department doesn't exist if (!rs.next()) return null; String name = rs.getString("Name"); String definition = rs.getString("Definition"); rs.close(); Specialties spec = new Specialties(this, Sid, name, definition); return spec; } catch (SQLException e) { dbm.cleanup(); throw new RuntimeException("error finding specialties", e); } } /** * Retrieve a Specialties object by name. * */ public Specialties findByName(String name) { try { String qry = "select Sid, Definition from Specialties where Name = ?"; PreparedStatement pstmt = conn.prepareStatement(qry); pstmt.setString(1, name); ResultSet rs = pstmt.executeQuery(); // return null if department doesn't exist if (!rs.next()) return null; int sid = rs.getInt("Sid"); String definition = rs.getString("Definition"); rs.close(); Specialties spec = new Specialties(this, sid, name, definition); return spec; } catch (SQLException e) { dbm.cleanup(); throw new RuntimeException("error finding specialties by name", e); } } /** * Add a new Specialties with the given attributes. */ public Specialties insert(int sid, String name, String definition) { try { // make sure that the deptid is currently unused if (find(sid) != null) return null; String cmd = "insert into Specialties(Sid, Name, Definition) " + "values(?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(cmd); pstmt.setInt(1, sid); pstmt.setString(2, name); pstmt.setString(3, definition); pstmt.executeUpdate(); Specialties spec = new Specialties(this, sid, name, definition); return spec; } catch (SQLException e) { dbm.cleanup(); throw new RuntimeException("error inserting new specialties", e); } } public void changeDefinition(int sid, String newDef) { try { String cmd = "update Specialties set Definition = ? where Sid = ?"; PreparedStatement pstmt = conn.prepareStatement(cmd); pstmt.setString(1, newDef); pstmt.setInt(2, sid); pstmt.executeUpdate(); } catch (SQLException e) { dbm.cleanup(); throw new RuntimeException("error changing definition", e); } } public Collection<Alumni> getAlumni(int sid) { try { Collection<Alumni> alumni = new ArrayList<Alumni>(); String qry = "select SSN from ALUMNI where Sid = ?"; PreparedStatement pstmt = conn.prepareStatement(qry); pstmt.setInt(1, sid); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int ssn = rs.getInt("SSN"); alumni.add(dbm.findAlumni(ssn)); } rs.close(); return alumni; } catch (SQLException e) { dbm.cleanup(); throw new RuntimeException("error getting Alumni", e); } } /** * Retrieve a Collection of all Company in the specialty. */ public Collection<Company> getCompany(int sid) { try { Collection<Company> companies = new ArrayList<Company>(); String qry = "select Cid from Company where Industry = ?"; PreparedStatement pstmt = conn.prepareStatement(qry); pstmt.setInt(1, sid); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int cid = rs.getInt("Cid"); companies.add(dbm.findCompany(cid)); } rs.close(); return companies; } catch (SQLException e) { dbm.cleanup(); throw new RuntimeException("error getting Company", e); } } /** * Clear all data from the Department table. * * @throws SQLException */ void clear() throws SQLException { Statement stmt = conn.createStatement(); String s = "delete from Specialties"; stmt.executeUpdate(s); } } <file_sep>#Mon Apr 15 10:49:16 EDT 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.7.2.v20171130-0510 <file_sep>package edu.depauw.csc480; import java.util.Collection; import edu.depauw.csc480.dao.DatabaseManager; import edu.depauw.csc480.model.Address; import edu.depauw.csc480.model.Alumni; import edu.depauw.csc480.model.Specialties; import edu.depauw.csc480.model.Company; /** * @author ducnguyen */ public class Test2 { /** * @param args */ public static void main(String[] args) { DatabaseManager dbm = new DatabaseManager(); Specialties compsci = dbm.findSpecsByName("Computer Science"); // Now retrieve a table of MathCS faculty and their courses; // each course also lists the head of the department offering the course Collection<Company> comps = compsci.getCompany(); for (Company comp : comps) { System.out.println(comp); } dbm.commit(); dbm.close(); System.out.println("Done"); } } <file_sep>package edu.depauw.csc480.model; import edu.depauw.csc480.dao.CompanyDAO; public class Company { private CompanyDAO dao; private int cid; private String name; private String email; private String phone; private int salary; private Specialties industry; private Address address; public Company(CompanyDAO dao, int cid, String name, String email, String phone, int salary, Specialties industry, Address address){ this.dao = dao; this.cid = cid; this.name = name; this.email = email; this.phone = phone; this.salary = salary; this.industry = industry; this.address = address; } public String toString() { return name + "," + email + "," + phone + "," + salary + "," + industry + "," + address; } public int getCid() { return cid; } public String getName() { return name; } public String getEmail() { return email; } public String getPhone() { return phone; } public int getSalary() { return salary; } public Specialties getIndustry() { return industry; } public Address getAddress() { return address; } public void setSalary(int newsal) { this.salary = newsal; dao.changeSalary(cid, salary); } public void setAddress(Address add) { this.address = add; dao.changeAddress(cid,address); } }
0cace933b6b024a5177937baefdde90f0a3ca0db
[ "Java", "INI" ]
4
Java
ducnguyen2020/Alumni-Database-Project
b08a0ff80582dc9ada13efd70540af51a966f202
b347dd1b54d2912d5c0e06e3e5566f1e3c739b74
refs/heads/master
<file_sep>package com.example.yunsuphong.hello; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ConfigurationInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Point; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.DisplayMetrics; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.text.DateFormat; import java.util.Date; import java.util.Enumeration; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button myButton = (Button)findViewById(R.id.myButton); MyOnClickListener myOnClickListener = new MyOnClickListener(); myButton.setOnClickListener(myOnClickListener); //Get our hands on the TextView in the activity_main.xml file. TextView textView = (TextView)findViewById(R.id.textView); //Erase the existing text in the TextView, if any. textView.setText(""); //Dimensions of the screen WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE); Display defaultDisplay = windowManager.getDefaultDisplay(); Point point = new Point(); //import android.graphics.Point; defaultDisplay.getSize(point); //Number of pixels per inch DisplayMetrics metrics = new DisplayMetrics(); defaultDisplay.getMetrics(metrics); //Orientation Resources resources = getResources(); Configuration configuration = resources.getConfiguration(); int orientation = configuration.orientation; String[] ori = {"", "ORIENTATION_PORTRAIT", "ORIENTATION_LANDSCAPE"}; //App Name Resources nameResources = getResources(); String appName = nameResources.getString(R.string.app_name); //Process ID and User ID int pid = android.os.Process.myPid(); int uid = android.os.Process.myUid(); //OpenGL ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); int v = configurationInfo.reqGlEsVersion; //Date and time Date date = new Date(); //current date and time DateFormat dateFormat = DateFormat.getDateTimeInstance(); //Internet connectivity ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); //Print String s = "SDK version: " + Build.VERSION.SDK_INT + "\n" + "Android release: " + Build.VERSION.RELEASE + "\n" + "Width: " + point.x + "\n" + "Height: " + point.y + " pixels\n" + "Density: " + metrics.density * DisplayMetrics.DENSITY_DEFAULT + " dpi" + "\n" + "Orientation: " + ori[orientation] + "\n" + "App name: " + appName + "\n" + "App Process ID: " + pid + "\n" + "App User ID: " + uid + "\n" + "Thread: " + Thread.currentThread().getName() + "\n" + "major version: " + (v & 0xFF00) + "\n" + "minor version: " + (v & 0x00FF) + "\n" + dateFormat.format(date) + "\n" + networkInfo.toString(); textView.append(s); //IP Address try { for (Enumeration<NetworkInterface> ei = NetworkInterface.getNetworkInterfaces(); ei.hasMoreElements();) { NetworkInterface networkInterface = ei.nextElement(); for (Enumeration<InetAddress> ea = networkInterface.getInetAddresses(); ea.hasMoreElements();) { InetAddress inetAddress = ea.nextElement(); if (!inetAddress.isLoopbackAddress()) { String ip = inetAddress.getHostAddress(); textView.append("IP address: " + ip + "\n"); } } } } catch (SocketException socketException) { textView.append(socketException.getMessage() + "\n"); } Toast.makeText(this, "MainActivity onCreate", Toast.LENGTH_LONG).show(); //textView.setText("Debuging output in a TextView."); /* for (int i = 1; i <= 10; i = i + 1) { textView.append(String.valueOf(i) + "\n"); } */ int k = 10; System.out.println("standard output: k = " + k); System.err.println("standard error output: k = " + k); } @Override public boolean onCreateOptionsMenu(Menu menu) { //Menu menu is an empty object created by the OS. The inflate fills that menu with info // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } if (id == R.id.action_settings2) { Toast toastMessage = Toast.makeText(this, "Option 2 Selected", Toast.LENGTH_LONG); toastMessage.show(); return true; } return super.onOptionsItemSelected(item); } //Generally should be a separate Java file class MyOnClickListener implements View.OnClickListener { @Override //Receives the object that was clicked, View v public void onClick(View v) { //Convert into a button object. Assuming view being received is a button. Need if statement to ensure Button button = (Button) v; button.setText("Thanks for pressing this button."); } } }
d7ee3ee9e1e72b3f80ccee3d036a4935dc4d4a9d
[ "Java" ]
1
Java
albertyhong/Hello
b5c131dccab0e8656f2b4b0304c2a4b01f55574f
a25781ef9622d5824ccd4113e1e441caaa038ebc
refs/heads/master
<repo_name>oleachka/dog-directory-mvc<file_sep>/Services/DogBreedServiceException.cs using System; namespace DogDirectory.Services { public class DogBreedServiceException : Exception { public DogBreedServiceException(string message) : base(message) { } } } <file_sep>/Models/DogBreedRandomImageResponse.cs namespace DogDirectory.Models { public class DogBreedRandomImageResponse : DogBreedResponse<string> { } } <file_sep>/Models/DogBreedWithSubBreedsResponse.cs using System.Collections.Generic; namespace DogDirectory.Models { public class DogBreedWithSubBreedsResponse : DogBreedResponse<IDictionary<string, string[]>> { } } <file_sep>/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using DogDirectory.Models; using DogDirectory.Services; namespace DogDirectory.Controllers { public class HomeController : Controller { private readonly IDogBreedService _dogBreedSvc; public HomeController(IDogBreedService dogBreedSvc) { this._dogBreedSvc = dogBreedSvc; } public async Task<IActionResult> Index() { var model = await _dogBreedSvc.GetBreedsAsync(); return View(model); } public async Task<IActionResult> Details(string id) { var url = await _dogBreedSvc.GetRandomImage(id); return View(new DogBreedImage { Breed = id, ImageUrl = url } ); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>/Services/DogBreedService.cs using DogDirectory.Models; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; namespace DogDirectory.Services { public class DogBreedService : IDogBreedService, IDisposable { HttpClient _http; private const string SvcUrl = "https://dog.ceo"; public DogBreedService() { _http = new HttpClient { BaseAddress = new Uri(SvcUrl) }; } public void Dispose() { _http.Dispose(); } public async Task<IEnumerable<string>> GetBreedsAsync() { var response = await _http.GetAsAsync<DogBreedListResponse>("/api/breeds/list"); if (response.IsSuccess) { return response.Message; } throw new DogBreedServiceException("failed to retrieve dogbreeds"); } public async Task<string> GetRandomImage(string breed) { var response = await _http.GetAsAsync<DogBreedRandomImageResponse>($"/api/breed/{breed}/images/random"); if (response.IsSuccess) { return response.Message; } throw new DogBreedServiceException("failed to retrieve dogbreeds"); } } } <file_sep>/README.md # Dog Directory Project ## Running The code You can either open this solution in Visual Studio and Run it or use the commandline. To use the commandline you will have to have the dotnetcore cli tools installed (https://download.microsoft.com/download/2/9/3/293BC432-348C-4D1C-B628-5AC8AB7FA162/dotnet-sdk-2.1.3-win-gs-x64.exe) * Clone repository * Run the following from the root folder ```powershell dotnet restore dotnet build dotnet run ``` The server will start running and show you the port e.g. ` http://localhost:57787` ## Answers to Questions #### Is there an elegant way we can handle deserializing the JSON so we don't have to repeat some boilerplate for each call to get at the message property? I addressed this by making a generic DogBreed response class ```c# public abstract class DogBreedResponse<TMessage> { public string Status { get; set; } public bool IsSuccess => Status == "success"; public TMessage Message { get; set; } } ``` All other response classes will inherit from it and specify the type of the `TMessage` generic. An example is the `DogListBreedResponse` class and the `DogBreedRandomImageResponse` class ```c# public class DogBreedListResponse : DogBreedResponse<IEnumerable<string>> { } public class DogBreedRandomImageResponse : DogBreedResponse<string> { } ``` ### Is there a better way the API could have been implemented to obviate the need for the status property? Yes. It would be better if the Responses from the API only had the Payloads (e.g. Message property). Statuses could be the HTTP codes such as `404` or `500` if something went wrong <file_sep>/Models/DogBreedImage.cs namespace DogDirectory.Models { public class DogBreedImage { public string Breed { get; set; } public string ImageUrl { get; set; } } } <file_sep>/Models/DogBreedResponse.cs  namespace DogDirectory.Models { public abstract class DogBreedResponse<TMessage> { public string Status { get; set; } public bool IsSuccess => Status == "success"; public TMessage Message { get; set; } } } <file_sep>/Models/DogBreed.cs using System.Collections.Generic; using System.Linq; namespace DogDirectory.Models { public class DogBreed { public DogBreed() { } public DogBreed(string breed, params string[] subBreeds) { Breed = breed; SubBreeds = subBreeds ?? new string[] { }; } public string Breed { get; set; } public IEnumerable<string> SubBreeds { get; set; } public bool HasSubBreeds => SubBreeds?.Any() == true; } } <file_sep>/Models/DogBreedListResponse.cs using System.Collections.Generic; namespace DogDirectory.Models { public class DogBreedListResponse : DogBreedResponse<IEnumerable<string>> { } } <file_sep>/Services/IDogBreedService.cs using System.Collections.Generic; using System.Threading.Tasks; namespace DogDirectory.Services { public interface IDogBreedService { Task<IEnumerable<string>> GetBreedsAsync(); Task<string> GetRandomImage(string breed); } }
216e2c99d4acc825c4a2be5511491020e24dbd11
[ "Markdown", "C#" ]
11
C#
oleachka/dog-directory-mvc
f9301471a7182cdb0132bafb36f969774a4d482a
b6358f9295438328102953ee319a4dcafce5bf36
refs/heads/master
<file_sep><?php var_dump($argv); printf("Test from MoodleTW"); <file_sep><?php /* s__enablewebservices="1" s__mnet_dispatcher_mode="strict" lib/adminlib.php function admin_write_settings() enablewebservices public function config_read($name) { } public function config_write($name, $value) { } enabledwebservice "1" lib/moodlelib.php function get_config($plugin, $name = null) { null, "enablewebservice" function set_config($name, $value, $plugin=null) { Roam to a remote application via MNet moodle/site:mnetlogintoremote $this->changed[] = 'moodle/site:mnetlogintoremote'; /**/ define('CLI_SCRIPT', true); require(__DIR__.'/config.php'); require_once($CFG->libdir.'/clilib.php'); // cli only functions require_once($CFG->libdir.'/moodlelib.php'); require_once($CFG->libdir.'/adminlib.php'); //set_config("enablewebservices", "1"); set_config("mnet_dispatcher_mode", "strict"); enable_roamauth('roam'); //debugBreak(); enable_roamenrol('roam'); $roleid = 7; $syscontext = context_system::instance(); function enable_roamauth($auth = 'roam'){ get_enabled_auth_plugins(true); // fix the list of enabled auths if (empty($CFG->auth)) { $authsenabled = array(); } else { $authsenabled = explode(',', $CFG->auth); } if (!empty($auth) and !exists_auth_plugin($auth)) { print_error('pluginnotinstalled', 'auth', '', $auth); } // add to enabled list if (!in_array($auth, $authsenabled)) { $authsenabled[] = $auth; $authsenabled = array_unique($authsenabled); set_config('auth', implode(',', $authsenabled)); } \core\session\manager::gc(); // Remove stale sessions. core_plugin_manager::reset_caches(); } function enable_roamenrol($enrol = 'roam'){ $enabled = enrol_get_plugins(true); $all = enrol_get_plugins(false); $syscontext = context_system::instance(); if (!isset($all[$enrol])) { print_error('pluginnotinstalled', 'enrol', '', $enrol); return false; } $enrolenabled = array_keys($enabled); if (!in_array($enrol, $enrolenabled)) { $enrolenabled[] = $enrol; set_config('enrol_plugins_enabled', implode(',', $enrolenabled)); } core_plugin_manager::reset_caches(); $syscontext->mark_dirty(); // resets all enrol caches } function check_mnet(){ if (!extension_loaded('openssl')) { print_error('requiresopenssl', 'mnet'); } if (!function_exists('curl_init') ) { print_error('nocurl', 'mnet'); } if (!function_exists('xmlrpc_encode_request')) { print_error('xmlrpc-missing', 'mnet'); } if (!isset($CFG->mnet_dispatcher_mode)) { set_config('mnet_dispatcher_mode', 'off'); } } require_once($CFG->libdir.'/accesslib.php'); check_mnet(); /* User role permission */ $syscontext = context_system::instance(); $changedcap = "moodle/site:mnetlogintoremote"; assign_capability($changedcap, CAP_ALLOW, $roleid, $syscontext->id, true); $syscontext->mark_dirty(); /* XMLRPC */ $webservice = 'xmlrpc'; $available_webservices = core_component::get_plugin_list('webservice'); $active_webservices = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols); if (!in_array($webservice, $active_webservices)) { $active_webservices[] = $webservice; $active_webservices = array_unique($active_webservices); } set_config('webserviceprotocols', implode(',', $active_webservices)); <file_sep># modshell "# modshell" https://sites.google.com/a/click-ap.com/mod-install/ ## Create courses sudo wget -qO- https://raw.githubusercontent.com/martinliao/modshell/master/uploadcourse.php | sudo -u apache MODE=createorupdate php ## uploaduser, enrolment sudo -u apache wget -qO- https://raw.githubusercontent.com/martinliao/modshell/master/uploaduser.php | sudo -u apache MODE=createorupdate php <file_sep><?php /* http://192.168.50.226/isu3ap/ http://192.168.50.226/isu3web/ Roam to a remote application via MNet moodle/site:mnetlogintoremote $this->changed[] = 'moodle/site:mnetlogintoremote'; /**/ define('CLI_SCRIPT', true); require(__DIR__.'/config.php'); require_once($CFG->libdir.'/clilib.php'); // cli only functions require_once($CFG->libdir.'/moodlelib.php'); require_once($CFG->libdir.'/adminlib.php'); set_config("enablewebservices", "1"); set_config("mnet_dispatcher_mode", "strict"); $roleid = 7; $syscontext = context_system::instance(); #$remoteapurl = "http://192.168.50.91/isu3web/"; debugBreak(); // Now get cli options. list($options, $unrecognized) = cli_get_params(array( 'help' => false, 'weburl' => '' ), array( 'h' => 'help', 'w' => 'weburl' )); if ($unrecognized) { $unrecognized = implode("\n ", $unrecognized); cli_error(get_string('cliunknowoption', 'admin', $unrecognized)); } $help = "Execute Roaming AP Setup. Options: -h, --help Print out this help -w, --weburl Web(Portal) url for setup. Example: \$sudo -u www-data /usr/bin/php roam_ap-set.php --weburl=http://192.168.50.91/isu3web "; if ($options['help']) { echo $help; die(); } echo "Moodle AP setup running ...\n"; if (!isset($options['weburl']) || empty($options['weburl'])) { echo " Invalid WEB url.\n"; echo $help; die(); } $weburl = $options['weburl']; require_once($CFG->libdir.'/accesslib.php'); check_mnet(); init_xmlrpc(); $mnet = get_mnet_environment(); echo $mnet->public_key; echo userdate($mnet->public_key_expires) . '\n'; $peerid = add_host($weburl); setup_ap_services($peerid); function check_mnet(){ if (!extension_loaded('openssl')) { print_error('requiresopenssl', 'mnet'); } if (!function_exists('curl_init') ) { print_error('nocurl', 'mnet'); } if (!function_exists('xmlrpc_encode_request')) { print_error('xmlrpc-missing', 'mnet'); } //if (!isset($CFG->mnet_dispatcher_mode)) { // set_config('mnet_dispatcher_mode', 'off'); //} } function init_xmlrpc() { /* XMLRPC */ $webservice = 'xmlrpc'; $available_webservices = core_component::get_plugin_list('webservice'); $active_webservices = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols); if (!in_array($webservice, $active_webservices)) { $active_webservices[] = $webservice; $active_webservices = array_unique($active_webservices); } set_config('webserviceprotocols', implode(',', $active_webservices)); } function add_host($remoteapurl) { $apid = 1; $apname = 'moodle'; $mnet_peer = new mnet_peer(); $mnet_peer->set_applicationid($apid); $mnet_peer->bootstrap($remoteapurl, null, $apname); $public_key = clean_param(mnet_get_public_key($remoteapurl, $apname), PARAM_PEM); //if ($mnet_peer->public_key_expires < time()) { // $expires = get_string('expired', 'mnet') . ' '; //} //$expires .= userdate($mnet_peer->public_key_expires); $lastconnect = ''; if ($mnet_peer->last_connect_time == 0) { $lastconnect = get_string('never', 'mnet'); } else { $lastconnect = date('H:i:s d/m/Y', $mnet_peer->last_connect_time); } #$credentials = $mnet_peer->check_credentials($mnet_peer->public_key); #if(!$credentials ){ # print_error('error'); #} // sslverification', mnet_peer::SSL_HOST_AND_PEER //$mnet_peer->set_applicationid($formdata->applicationid); $mnet_peer->deleted = 0; //$mnet_peer->public_key = $formdata->public_key; $credentials = $mnet_peer->check_credentials($mnet_peer->public_key); $mnet_peer->public_key_expires = $credentials['validTo_time_t']; $mnet_peer->sslverification = mnet_peer::SSL_HOST_AND_PEER; if (!$mnet_peer->commit() ) { print_error('invalidaction', 'roaming', ''); } //echo "HOST-ID: " . $hostid; return $mnet_peer->id; } /* http://192.168.50.226/isu3ap/ http://192.168.50.226/isu3web/ */ function setup_ap_services($hostid) { global $DB; //$hostid = $mnet_peer->id; $publishs = array(2, 3, 4, 5, 7); $subscribes= array(1); foreach($subscribes as $key) { $host2service = new stdClass(); $host2service->hostid = $hostid; $host2service->serviceid = $key; $host2service->publish = "0"; $host2service->subscribe = "1"; try { $host2service->id = $DB->insert_record('mnet_host2service', $host2service); } catch(Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } } foreach($publishs as $key) { $host2service = new stdClass(); $host2service->hostid = $hostid; $host2service->serviceid = $key; $host2service->publish = "1"; $host2service->subscribe = "0"; try { $host2service->id = $DB->insert_record('mnet_host2service', $host2service); } catch(Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } } } <file_sep><?php define('CLI_SCRIPT', true); require(__DIR__.'/config.php'); require_once($CFG->libdir.'/clilib.php'); // cli only functions // Now get cli options. list($options, $unrecognized) = cli_get_params(array( 'help' => false, 'course' => '' ), array( 'h' => 'help', 'c' => 'course' )); if ($unrecognized) { $unrecognized = implode("\n ", $unrecognized); cli_error(get_string('cliunknowoption', 'admin', $unrecognized)); } $help = "Execute Roaming AP Setup. Options: -h, --help Print out this help -c, --course coruse-id for add Roaming enrol. Example: \$sudo -u www-data /usr/bin/php roamap-add-roam-enrol.php --course=2 "; if ($options['help']) { echo $help; die(); } echo "Add Roaming enrol to course ...\n"; if (!isset($options['course']) || empty($options['course'])) { echo " Invalid course id.\n"; echo $help; die(); } $courseid = $options['course']; $type = 'roam'; //$courseid = 2; debugBreak(); if( !$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST)) { throw new moodle_exception('invalidcourse', 'error'); } $plugin = enrol_get_plugin($type); if (!$plugin || !enrol_is_enabled($type)) { throw new moodle_exception('invaliddata', 'error'); } $fields = array('customint1' => '0', 'roleid' => '5', 'name' => '', 'courseid' => 2, 'type' => 'roam'); $plugin->add_instance($course, $fields); print_r("done"); <file_sep><?php define('CLI_SCRIPT', true); require(__DIR__ . '/config.php'); require_once($CFG->libdir . '/clilib.php'); // Now get cli options. list($options, $unrecognized) = cli_get_params(array( 'help' => false, 'lang' => 'zh_tw' ), array( 'h' => 'help', 'l' => 'lang', )); if ($unrecognized) { $unrecognized = implode("\n ", $unrecognized); cli_error(get_string('cliunknowoption', 'admin', $unrecognized)); } $help = "Execute Course Upload. Options: -h, --help Print out this help -l, --lang=CODE Installation and default site language. Example: \$sudo -u www-data /usr/bin/php admin/tool/langimport/cli/langimport.php --lang=zh_tw "; if ($options['help']) { echo $help; die(); } echo "Moodle language uploader running ...\n"; //if (!isset($encodings[$options['lang']])) { // echo get_string('invalidencoding', 'tool_uploadcourse')."\n"; // echo $help; // die(); //} // set up language $lang = clean_param($options['lang'], PARAM_SAFEDIR); //debugBreak(); ////$languages = get_string_manager()->get_list_of_languages(); //$languages = get_string_manager()->get_list_of_translations(); //if (array_key_exists($lang, $languages)) { // $CFG->lang = $lang; // $pack = $lang; //} if (isset($lang)) { $pack = $lang; } $purgecaches = true; define('INSTALLATION_OF_SELECTED_LANG', 2); define('DELETION_OF_SELECTED_LANG', 4); define('UPDATE_ALL_LANG', 5); get_string_manager()->reset_caches(); $controller = new tool_langimport\controller(); // $mode == INSTALLATION_OF_SELECTED_LANG core_php_time_limit::raise(); $controller->install_languagepacks($pack); get_string_manager()->reset_caches(); echo get_string('cliinstallfinished', 'install')."\n"; exit(0); // 0 means success
88c32f6a843feb7c55612fbc65bc7cda6eb7e8aa
[ "Markdown", "PHP" ]
6
PHP
martinliao/modshell
4ecfe68c3944f9654e4c6d7904ec939c18c9a994
84592eb98fb79ad200d984c3e18b5917b35db5e3
refs/heads/master
<repo_name>jessicawang225/caltech-ee148-spring2020-hw01<file_sep>/run_visualizations.py import json import numpy as np from PIL import Image, ImageDraw import os def draw(I, boxes): for box in boxes: draw = ImageDraw.Draw(I) # Draw bounding box in neon yellow draw.rectangle(box, outline=(204, 255, 0)) del draw return I # set the path to the downloaded data: data_path = './data' # set a path for saving predictions: preds_path = './predictions' # set a path for saving visualizations: vis_path = './visualizations' os.makedirs(preds_path, exist_ok=True) # create directory if needed os.makedirs(vis_path, exist_ok=True) # create directory if needed # get sorted list of files: file_names = sorted(os.listdir(data_path)) # remove any non-JPEG files: file_names = [f for f in file_names if '.jpg' in f] # get bounding boxes with open(os.path.join(preds_path, 'preds.json')) as f: bounding_boxes = json.load(f) for i in range(len(file_names)): # read image using PIL: I = Image.open(os.path.join(data_path, file_names[i])) I = draw(I, bounding_boxes[file_names[i]]) I.save(os.path.join(vis_path, file_names[i]))<file_sep>/run_predictions.py # import os import numpy as np import json from PIL import Image def compute_bounding_box(I): ''' This function takes a numpy array <I> and returns a list <bounding_boxes>. The list <bounding_boxes> should have one element for each red light in the image. Each element of <bounding_boxes> should itself be a list, containing four integers that specify a bounding box: the row and column index of the top left corner and the row and column index of the bottom right corner (in that order). ''' height, width = np.shape(I) I = np.array(I) redCoords = list(zip(*np.where(I == 2))) blackCoords = list(zip(*np.where(I == 1))) if len(redCoords) == 0 or len(redCoords) == 1: return [] redCoords = sorted(redCoords, key=lambda element: (redCoords[0], redCoords[1])) blackCoords = sorted(blackCoords, key=lambda element: (blackCoords[0], blackCoords[1])) # Determine the coordinates of the bounding box coords = [] i = 1 widths = set() heights = set() widths.add(redCoords[0][0]) heights.add(redCoords[0][1]) while i < len(redCoords): x, y = redCoords[i] if (x > max(widths) + 1 or x < min(widths) - 1) and (y > max(heights) + 1 or y < min(heights) - 1): left = min(widths) top = min(heights) right = max(widths) bottom = max(heights) if abs(left - right) > 3 or abs(top - bottom) > 3: coords.append([int(left), int(top), int(right), int(bottom)]) widths = set() heights = set() widths.add(redCoords[i][0]) heights.add(redCoords[i][1]) else: widths.add(x) heights.add(y) i += 1 coordsCopy = coords[:] for box in coordsCopy: left, top, right, bottom = box # The bounding box of a red light should be square-like if (right - left) >= 3 * (bottom - top) or (bottom - top) >= 3 * (right - left): if box in coords: coords.remove(box) # Traffic lights boxes are typically black so check that the outer edges of the bounding box are black for i in range(-1, 1): for j in range(-1, 1): if 0 <= left + i < width and 0 <= right + i < width and 0 <= top + j < height and 0 <= bottom + j < height: if (I[left + i][top + j] == 0 and I[right + i][top + j] == 0 and I[left + i][bottom + j] == 0 and I[right + i][bottom + j] == 0): if box in coords: coords.remove(box) return coords def detect_black_and_red(I): ''' This function takes a numpy array <I> and returns a 2D array. This 2D array has the same dimensions as the image of interest. A '1' is used to indicate the color of that pixel as black or approximately black and a '2' is used to indicate the color of that pixel as red or approximately red. All other pixels are indicated with a '0'. ''' height, width, channels = np.shape(I) newI = [[0 for y in range(height)] for x in range(width)] for x in range(width): for y in range(height): r = int(I[y, x, 0]) g = int(I[y, x, 1]) b = int(I[y, x, 2]) # Check if the pixel color is red or approximately red if r > 2.5 * g and r > 2.5 * b: newI[x][y] = 2 # Check if the pixel color is black or approximately black elif r < 70 and g < 70 and b < 70: newI[x][y] = 1 else: newI[x][y] = 0 return newI def detect_red_light(I): ''' This function takes a numpy array <I> and returns a list <bounding_boxes>. The list <bounding_boxes> should have one element for each red light in the image. Each element of <bounding_boxes> should itself be a list, containing four integers that specify a bounding box: the row and column index of the top left corner and the row and column index of the bottom right corner (in that order). Note that PIL loads images in RGB order, so: I[:,:,0] is the red channel I[:,:,1] is the green channel I[:,:,2] is the blue channel ''' newI = detect_black_and_red(I) bounding_boxes = compute_bounding_box(newI) for i in range(len(bounding_boxes)): assert len(bounding_boxes[i]) == 4 return bounding_boxes # set the path to the downloaded data: data_path = './data' # set a path for saving predictions: preds_path = './predictions' os.makedirs(preds_path, exist_ok=True) # create directory if needed # get sorted list of files: file_names = sorted(os.listdir(data_path)) # remove any non-JPEG files: file_names = [f for f in file_names if '.jpg' in f] preds = {} for i in range(len(file_names)): if i % 5 == 0: print('Red light image detection completed for : {}/{} images'.format(i, len(file_names))) # read image using PIL: I = Image.open(os.path.join(data_path, file_names[i])) # convert to numpy array: I = np.asarray(I) preds[file_names[i]] = detect_red_light(I) # save preds (overwrites any previous predictions!) with open(os.path.join(preds_path, 'preds.json'), 'w') as f: json.dump(preds, f)
02c6ea9246db52b7c3ce085dba8d44e3a3567029
[ "Python" ]
2
Python
jessicawang225/caltech-ee148-spring2020-hw01
6c1f2fc50170cd2fe5a7b02896feca7743e552fc
35a92a88f5f55d7514a7340d9f9074a4bf19f883
refs/heads/master
<file_sep><!--<script type="text/javascript" src="http://tinymce.moxiecode.com/js/tinymce/jscripts/tiny_mce/jquery.tinymce.js"></script> <script type="text/javascript" src="http://tinymce.moxiecode.com/js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>--> <script src="<?php echo Yii::app()->theme->baseUrl; ?>/tinymce/js/tinymce/tinymce.min.js"></script> <script>tinymce.init({selector:'textarea', plugins: [ "advlist autolink link image lists charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking", "table contextmenu directionality emoticons paste textcolor responsivefilemanager" ], toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect", toolbar2: "| responsivefilemanager | link unlink anchor | image media | forecolor backcolor | print preview code ", image_advtab: true, external_filemanager_path:"<?php echo Yii::app()->theme->baseUrl; ?>/filemanager/", filemanager_title:"Responsive Filemanager" , external_plugins: { "filemanager" : "<?php echo Yii::app()->theme->baseUrl; ?>/tinymce/js/tinymce/plugins/responsivefilemanager/plugin.min.js"} }); </script> <div class="form"> <?php /** @var NoticiaController $this */ /** @var Noticia $model */ /** @var AweActiveForm $form */ $form = $this->beginWidget( 'booster.widgets.TbActiveForm', array( 'id' => 'verticalForm', 'htmlOptions' => array('class' => 'well'), // for inset effect ) ); ?> <p class="note"> <?php echo Yii::t('AweCrud.app', 'Fields with') ?> <span class="required">*</span> <?php echo Yii::t('AweCrud.app', 'are required') ?>. </p> <?php echo $form->errorSummary($model) ?> <?php echo $form->textFieldGroup($model, 'titulo', array('class' => 'span5', 'maxlength' => 255)) ?> <?php // $this->widget('application.extensions.tinymce.ETinyMce', // array( // 'model'=>$model, // 'attribute'=>'contenido', // 'editorTemplate'=>'full', // 'plugins'=>array('upload'), // 'htmlOptions'=>array('rows'=>6, 'cols'=>50, 'class'=>'tinymce'), // )); ?> <?php echo $form->textAreaGroup($model, 'contenido', array('class' => 'span5', 'maxlength' => 255)) ?> <?php // $this->widget('zii.widgets.jui.CJuiDatePicker', array( // 'model'=>$model, // 'attribute'=>'fecha', // 'flat'=>false, // 'options'=>array( //// 'firstDay'=>6, // 'showOn'=>"both", // 'showAnim'=>'slide', // //'buttonImage'=>"images/calendar.gif", // 'buttonImageOnly'=> false, // //'minDate'=>-31, // //'maxDate'=>0, // 'constrainInput'=>true, // 'currentText'=>'Now', // 'dateFormat'=>'yy-mm-dd', // 'readonly' =>true, // ), // 'htmlOptions'=>array( // ), // )); ?> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array( 'buttonType'=>'submit', 'type'=>'primary', 'label'=>$model->isNewRecord ? Yii::t('AweCrud.app', 'Create') : Yii::t('AweCrud.app', 'Save'), )); ?> <?php $this->widget('bootstrap.widgets.TbButton', array( //'buttonType'=>'submit', 'label'=> Yii::t('AweCrud.app', 'Cancel'), 'htmlOptions' => array('onclick' => 'javascript:history.go(-1)') )); ?> </div> <?php $this->endWidget(); ?> </div><file_sep><?php /* @var $this Controller */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <!-- THEME CLASSIC MAIN MENU --> <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"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Administralo</title> <!--<link href="<?php // echo Yii::app()->theme->baseUrl; ?>/css/screen.css" rel="stylesheet"/>--> <link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/style.css" rel="stylesheet"/> <!-- Bootstrap --> <link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/boostrap/css/bootstrap.css" rel="stylesheet"/> <link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/boostrap/js/bootstrap.min.js" rel="javascript" type="text/javascript"/> <!-- <link href="<?php // echo Yii::app()->theme->baseUrl; ?>/css/boostrap/css/bootstrap.min.css" rel="stylesheet"/>--> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <title><?php // echo CHtml::encode($this->pageTitle); ?></title> </head> <body class="container <?php if(Yii::app()->user->checkAccess('admin')): ?> "> <?php else: ?> padding_heading"> <?php endif; ?> <div id="page "> <div id="header"> <div class="row"> <!--<div class="col-lg-3"><img src="<?php // echo Yii::app()->theme->baseUrl; ?>/images/logo_lugano.png"/></div>--> <div class="col-lg-12"> <?php if(Yii::app()->user->checkAccess('admin')): ?> <?php $items= Yii::app()->user->rbac->getMenu(); ?> <?php $ingresar = array('label'=>'Ingreso' , 'url'=>Yii::app()->user->ui->loginUrl , 'visible'=>Yii::app()->user->isGuest); $salir= array('label'=>'Salir ('.Yii::app()->user->name.')' , 'url'=>Yii::app()->user->ui->logoutUrl , 'visible'=>!Yii::app()->user->isGuest); $menu_admin = array('label'=>'Administrar Usuarios' , 'url'=>Yii::app()->user->ui->userManagementAdminUrl , 'visible'=>Yii::app()->user->isSuperAdmin); if(Yii::app()->user->isSuperAdmin) array_push($items, $menu_admin); array_push($items, $ingresar); array_push($items, $salir); ?> <div id="mainmenu"> <?php $this->widget('booster.widgets.TbNavbar',array( 'brand' => false, 'fixed' => false, 'fluid' => true, 'items' => array( array( 'class' => 'booster.widgets.TbMenu', 'type' => 'navbar', 'items' => $items, )))); ?> </div><!-- mainmenu --> <?php else: ?> <?php echo Yii::app()->menuuser->getMenu(); ?> <?php endif; ?> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <?php if(isset($this->breadcrumbs)):?> <?php $this->widget('booster.widgets.TbBreadcrumbs', array( 'links'=>$this->breadcrumbs, )); ?><!-- breadcrumbs --> <?php endif?> </div> </div> <?php echo $content; ?> <div class="clear"></div> <?php include('_footer.php'); ?> </div><!-- page --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </body> </html> <file_sep>2<?php /* @var $this Controller */ ?> <?php $this->beginContent('//layouts/mainmenu'); ?> <legend> <?php echo CHtml::encode($this->pageTitle); ?> </legend> <div class="row"> <div class="col-lg-12"> <div id="sidebar"> <?php $this->beginWidget('zii.widgets.CPortlet', array( 'htmlOptions' => array('class' => 'nav-header') )); $this->widget( 'booster.widgets.TbNavbar', array( 'brand' => '', 'fixed' => false, 'fluid' => true, 'items' => array( array( 'class' => 'booster.widgets.TbMenu', 'type' => 'navbar', 'items' => $this->menu, ) ) ) ); $this->endWidget(); ?> </div><!-- sidebar --> </div> </div> <div class="row"> <div class="col-lg-12"> <div id="content"> <?php echo $content; ?> </div><!-- content --> </div> </div> <?php $this->endContent(); ?> <file_sep><?php class ProcesoCommand extends CConsoleCommand { public function actionIndex(){ $mails = Mailqueque::model()->getmail_no_process(); foreach($mails as $mail) { Yii::app()->crugemailer->sendEmail($mail->to,$mail->subjet,$mail->content); // $mail->process = 1; // $mail->update(); //mail($mail->to,$mail->subjet,$mail->content); } } public function actionHola(){ echo 'HOLAAA yii friends INDEX'; } } <file_sep><?php class m150428_003322_noticia extends CDbMigration { public function up() { $columns= array ( 'id'=>'pk', 'titulo'=>'varchar(255)', 'contenido'=> 'BLOB', 'fecha' => 'datetime' ); $this->createTable("noticia", $columns); } public function down() { echo "m150428_003322_noticia does not support migration down.\n"; return false; } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }<file_sep><h1><?php echo CrugeTranslator::t("Recuperar la clave"); ?></h1> <?php if(Yii::app()->user->hasFlash('pwdrecflash')): ?> <div class="flash-success"> <?php echo Yii::app()->user->getFlash('pwdrecflash'); ?> </div> <?php else: ?> <div class="form"> <?php $form = $this->beginWidget( 'booster.widgets.TbActiveForm', array( 'id' => 'verticalForm', 'htmlOptions' => array('class' => 'well'), // for inset effect ) ); ?> <div class="row"> <div class="col-lg-12"> <?php echo $form->errorSummary($model) ?> </div> </div> <div class="row"> <div class="col-md-4"> <?php echo $form->textFieldGroup($model,'username'); ?> </div> </div> <div class="row"> <div class="col-md-4"> <div class="g-recaptcha" data-sitekey="<KEY>"></div> <br/> </div> </div> <div class="row"> <div class="col-md-4"> <?php Yii::app()->user->ui->tbutton("Recuperar la Clave"); ?> </div> </div> <?php $this->endWidget(); ?> </div> <?php endif; ?> <file_sep><?php class MenuUser extends CApplicationComponent{ public function getMenu() { $logo = CHtml::image(Yii::app()->theme->baseUrl.'/images/logo_lugano.png','Administralo'); $link_logo= CHtml::link($logo,array('site/index',array('class'=>"navbar-brand"))); $home = CHtml::image(Yii::app()->theme->baseUrl.'/images/inicio.png','Noticias'); $link_home= CHtml::link($home,array('site/admin')); $noticias = CHtml::image(Yii::app()->theme->baseUrl.'/images/noticias.png','Noticias'); $link_noticias= CHtml::link($noticias,array('site/noticias')); $mensajes = CHtml::image(Yii::app()->theme->baseUrl.'/images/mensajes.png','Mensajes'); $link_mensaje= CHtml::link($mensajes,array('site/mensaje')); $recomendanos = CHtml::image(Yii::app()->theme->baseUrl.'/images/recomendanos.png','Recomendanos'); $link_recomendanos= CHtml::link($recomendanos,array('site/recomendanos')); $salir = CHtml::image(Yii::app()->theme->baseUrl.'/images/salir.png','Mensajes'); $link_salir= CHtml::link($salir,array('site/logout')); $ingresar = CHtml::image(Yii::app()->theme->baseUrl.'/images/ingresar.png','Mensajes'); $link_ingresar= CHtml::link($ingresar,array('site/index')); $str= '<nav class="navbar navbar-default navbar-fixed-top"><div class="container-fluid"><div class="navbar-header">' . '<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">' . ' <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> '. $link_logo .' </div><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav">'; if(Yii::app()->user->checkAccess('usuario')) { $str.= "<li><a href='#'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></li><li class='active'>". $link_home . '<span class="sr-only">(current)</span></li> <li>'. $link_noticias . "</li>"; } if(!Yii::app()->user->isGuest) { $str.="<li>".$link_salir."</li>"; }else { $str.="<li>" . $link_ingresar . "</li>"; } $str.= "</ul></div></div></nav>"; return $str; } } /* * 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. */ <file_sep><?php Yii::import('application.models._base.BaseMailqueque'); class Mailqueque extends BaseMailqueque { /** * @return Mailqueque */ public static function model($className = __CLASS__) { return parent::model($className); } public static function label($n = 1) { return Yii::t('app', 'Mailqueque|Mailqueques', $n); } /** * GET_MAIL_NO_PROCESS * * @description Devuelve todos los correos no procesados de la tabla mail_queque. Array de MailQueque * * * @return array */ public static function getmail_no_process() { $criteria = New CDbCriteria; $criteria->addCondition("process=0"); $criteria->limit= 20; return Mailqueque::model()->findAll($criteria); } }<file_sep><?php // esta clase va en: 'protected/components/MiClaseCrugeMailer.php' (no dentro de cruge!!) class Cruge_Mailer extends CrugeMailerBase { public $debug; public function sendEmail($to,$subject,$body){ // usa esto para que el correo se envíe por la via estandar mail() // si quieres usar otro método deberás comentar esta linea e implementar // tu propio mecanismo. parent::sendEmail($to,$subject,$body); } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ ?><file_sep><?php class m150609_214215_names extends CDbMigration { public function up() { $this->addColumn("cruge_user", "nombre", "varchar(255)"); $this->addColumn("cruge_user", "apellido", "varchar(255)"); } public function down() { echo "m150609_214215_names does not support migration down.\n"; return false; } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }<file_sep><?php $texto_mensaje = "<br/><br/>Para enviar un mensaje a la Administración, Consejo de Administración o al Comité de Convivencia, ingrese aquí " ?> <?php $texto_recibo = "<br/><br/>Podrá enviar los recibos de pago en forma automática. <br><br> <h3>Próximanente</h3> " ?> <?php $texto_quejas = "<br/><br/>Sus quejas y reclamos serán recibidas y se gestionarán desde aquí. Podrá realizarle seguimiento. <br><br> <h3>Próximanente</h3>" ?> <?php $texto_incidentes = "<br/><br/>Sus incidentes y problemas edilicios podrá gestionarlos aquí mismo.<br><br> <h3>Próximanente</h3> " ?> <div class="row text-center "> <div class="col-lg-1 "></div> <div class="col-lg-4 bg-transparent redondeado" style="min-height: 283px;"><?php echo CHtml::link(CHtml::image(Yii::app()->theme->baseUrl.'/images/mensajes_privados.png','Mensajes').$texto_mensaje ,array('site/mensaje')); ?></div> <div class="col-lg-2 "></div> <div class="col-lg-4 bg-transparent redondeado" style="min-height: 283px;"><?php echo CHtml::image(Yii::app()->theme->baseUrl.'/images/recibos_de_pago.png','Mensajes').$texto_recibo; ?></div> <div class="col-lg-1 "></div> </div> <br> <div class="row text-center redondeado"> <div class="col-lg-1 "></div> <div class="col-lg-4 bg-transparent redondeado " style="min-height: 283px;"><?php echo CHtml::image(Yii::app()->theme->baseUrl.'/images/quejas_y_reclamos.png','Mensajes'). $texto_quejas ?></div> <div class="col-lg-2 "></div> <div class="col-lg-4 bg-transparent redondeado "style="min-height: 283px;"><?php echo CHtml::image(Yii::app()->theme->baseUrl.'/images/incidentes_personales.png','Mensajes'). $texto_incidentes ?></div> <div class="col-lg-1 "></div> </div> <file_sep><?php //class m150427_172247_initial_cruge extends CDbMigration class m150427_172247_initial_cruge extends CDbMigration { public function up() { $query= "CREATE TABLE `cruge_system` ( `idsystem` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(45) NULL , `largename` VARCHAR(45) NULL , `sessionmaxdurationmins` INT(11) NULL DEFAULT 30 , `sessionmaxsameipconnections` INT(11) NULL DEFAULT 10 , `sessionreusesessions` INT(11) NULL DEFAULT 1 COMMENT '1yes 0no' , `sessionmaxsessionsperday` INT(11) NULL DEFAULT -1 , `sessionmaxsessionsperuser` INT(11) NULL DEFAULT -1 , `systemnonewsessions` INT(11) NULL DEFAULT 0 COMMENT '1yes 0no' , `systemdown` INT(11) NULL DEFAULT 0 , `registerusingcaptcha` INT(11) NULL DEFAULT 0 , `registerusingterms` INT(11) NULL DEFAULT 0 , `terms` BLOB NULL , `registerusingactivation` INT(11) NULL DEFAULT 1 , `defaultroleforregistration` VARCHAR(64) NULL , `registerusingtermslabel` VARCHAR(100) NULL , `registrationonlogin` INT(11) NULL DEFAULT 1 , PRIMARY KEY (`idsystem`) ) ENGINE = InnoDB; CREATE TABLE `cruge_session` ( `idsession` INT NOT NULL AUTO_INCREMENT , `iduser` INT NOT NULL , `created` BIGINT(30) NULL , `expire` BIGINT(30) NULL , `status` INT(11) NULL DEFAULT 0 , `ipaddress` VARCHAR(45) NULL , `usagecount` INT(11) NULL DEFAULT 0 , `lastusage` BIGINT(30) NULL , `logoutdate` BIGINT(30) NULL , `ipaddressout` VARCHAR(45) NULL , PRIMARY KEY (`idsession`) , INDEX `crugesession_iduser` (`iduser` ASC) ) ENGINE = InnoDB; CREATE TABLE `cruge_user` ( `iduser` INT NOT NULL AUTO_INCREMENT , `regdate` BIGINT(30) NULL , `actdate` BIGINT(30) NULL , `logondate` BIGINT(30) NULL , `username` VARCHAR(64) NULL , `email` VARCHAR(45) NULL , `password` VARCHAR(64) NULL COMMENT 'Hashed password' , `authkey` VARCHAR(100) NULL COMMENT 'llave de autentificacion' , `state` INT(11) NULL DEFAULT 0 , `totalsessioncounter` INT(11) NULL DEFAULT 0 , `currentsessioncounter` INT(11) NULL DEFAULT 0 , PRIMARY KEY (`iduser`) ) ENGINE = InnoDB; delete from `cruge_user`; ALTER TABLE `cruge_user` AUTO_INCREMENT = 1; insert into `cruge_user`(username, email, password, state) values ('admin', '<EMAIL>','admin',1) ,('invitado', 'invitado','nopassword',1) ; ALTER TABLE `cruge_user` AUTO_INCREMENT = 10; delete from `cruge_system`; INSERT INTO `cruge_system` (`idsystem`,`name`,`largename`,`sessionmaxdurationmins`,`sessionmaxsameipconnections`,`sessionreusesessions`,`sessionmaxsessionsperday`,`sessionmaxsessionsperuser`,`systemnonewsessions`,`systemdown`,`registerusingcaptcha`,`registerusingterms`,`terms`,`registerusingactivation`,`defaultroleforregistration`,`registerusingtermslabel`,`registrationonlogin`) VALUES (1,'default',NULL,30,10,1,-1,-1,0,0,0,0,'',0,'','',1); CREATE TABLE `cruge_field` ( `idfield` INT NOT NULL AUTO_INCREMENT , `fieldname` VARCHAR(20) NOT NULL , `longname` VARCHAR(50) NULL , `position` INT(11) NULL DEFAULT 0 , `required` INT(11) NULL DEFAULT 0 , `fieldtype` INT(11) NULL DEFAULT 0 , `fieldsize` INT(11) NULL DEFAULT 20 , `maxlength` INT(11) NULL DEFAULT 45 , `showinreports` INT(11) NULL DEFAULT 0 , `useregexp` VARCHAR(512) NULL , `useregexpmsg` VARCHAR(512) NULL , `predetvalue` MEDIUMBLOB NULL , PRIMARY KEY (`idfield`) ) ENGINE = InnoDB; CREATE TABLE `cruge_fieldvalue` ( `idfieldvalue` INT NOT NULL AUTO_INCREMENT , `iduser` INT NOT NULL , `idfield` INT NOT NULL , `value` BLOB NULL , PRIMARY KEY (`idfieldvalue`) , INDEX `fk_cruge_fieldvalue_cruge_user1` (`iduser` ASC) , INDEX `fk_cruge_fieldvalue_cruge_field1` (`idfield` ASC) , CONSTRAINT `fk_cruge_fieldvalue_cruge_user1` FOREIGN KEY (`iduser` ) REFERENCES `cruge_user` (`iduser` ) ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT `fk_cruge_fieldvalue_cruge_field1` FOREIGN KEY (`idfield` ) REFERENCES `cruge_field` (`idfield` ) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE = InnoDB; CREATE TABLE `cruge_authitem` ( `name` VARCHAR(64) NOT NULL , `type` INT(11) NOT NULL , `description` TEXT NULL DEFAULT NULL , `bizrule` TEXT NULL DEFAULT NULL , `data` TEXT NULL DEFAULT NULL , PRIMARY KEY (`name`) ) ENGINE = InnoDB; CREATE TABLE `cruge_authassignment` ( `userid` INT NOT NULL , `bizrule` TEXT NULL DEFAULT NULL , `data` TEXT NULL DEFAULT NULL , `itemname` VARCHAR(64) NOT NULL , PRIMARY KEY (`userid`, `itemname`) , INDEX `fk_cruge_authassignment_cruge_authitem1` (`itemname` ASC) , INDEX `fk_cruge_authassignment_user` (`userid` ASC) , CONSTRAINT `fk_cruge_authassignment_cruge_authitem1` FOREIGN KEY (`itemname` ) REFERENCES `cruge_authitem` (`name` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_cruge_authassignment_user` FOREIGN KEY (`userid` ) REFERENCES `cruge_user` (`iduser` ) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE = InnoDB; CREATE TABLE `cruge_authitemchild` ( `parent` VARCHAR(64) NOT NULL , `child` VARCHAR(64) NOT NULL , PRIMARY KEY (`parent`, `child`) , INDEX `child` (`child` ASC) , CONSTRAINT `crugeauthitemchild_ibfk_1` FOREIGN KEY (`parent` ) REFERENCES `cruge_authitem` (`name` ) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `crugeauthitemchild_ibfk_2` FOREIGN KEY (`child` ) REFERENCES `cruge_authitem` (`name` ) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; "; Yii::app()->db->createCommand($query)->execute(); } public function down() { echo "m150427_172247_initial_cruge does not support migration down.\n"; return false; } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }<file_sep> <div class="row"> <div class="col-lg-3"></div> <div class="col-lg-6 color"> <h1><?php echo ucwords(CrugeTranslator::t("registrarse"));?></h1> <div class="form"> <?php $form = $this->beginWidget( 'booster.widgets.TbActiveForm', array( 'id' => 'verticalForm', 'htmlOptions' => array('class' => 'well'), // for inset effect ) ); ?> <?php echo $form->errorSummary($model); ?> <h5><?php echo ucfirst(CrugeTranslator::t("datos de la cuenta"));?></h5> <?php foreach (CrugeUtil::config()->availableAuthModes as $authmode){ echo $form->textFieldGroup($model,$authmode); } ?> <?php echo $form->passwordFieldGroup($model,'newPassword'); ?> <p class='hint'><?php echo CrugeTranslator::t( "Su contraseña, letras o digitos o los caracteres @#$%. minimo 6 simbolos.");?></p> <?php echo $form->dropDownListGroup( $model, 'apartamento', array( 'wrapperHtmlOptions' => array( 'class' => 'col-sm-5', ), 'widgetOptions' => array( 'data' => CHtml::listData(Apartamentos::model()->findAll(),'idapartamentos','apartamento_nro'), 'htmlOptions' => array(), ) ) ); ?> <?php echo $form->passwordFieldGroup($model,'nombre'); ?> <?php echo $form->passwordFieldGroup($model,'apellido'); ?> <div class="g-recaptcha" data-sitekey="<KEY>"></div> <br/> <script> function fnSuccess(data){ $('#CrugeStoredUser_newPassword').val(data); } function fnError(e){ alert("error: "+e.responseText); } </script> <?php echo CHtml::ajaxbutton( CrugeTranslator::t("Generar una nueva clave") ,Yii::app()->user->ui->ajaxGenerateNewPasswordUrl ,array('success'=>new CJavaScriptExpression('fnSuccess'), 'error'=>new CJavaScriptExpression('fnError')) ); ?> <?php Yii::app()->user->ui->tbutton("Registrarse"); ?> </div> <!-- inicio de campos extra definidos por el administrador del sistema --> <?php if(count($model->getFields()) > 0){ echo "<div class='row form-group-vert'>"; echo "<h6>".ucfirst(CrugeTranslator::t("perfil"))."</h6>"; foreach($model->getFields() as $f){ // aqui $f es una instancia que implementa a: ICrugeField echo "<div class='col'>"; echo Yii::app()->user->um->getLabelField($f); echo Yii::app()->user->um->getInputField($model,$f); echo $form->error($model,$f->fieldname); echo "</div>"; } echo "</div>"; } ?> <!-- fin de campos extra definidos por el administrador del sistema --> </div> <!-- inicio - terminos y condiciones --> <?php if(Yii::app()->user->um->getDefaultSystem()->getn('registerusingterms') == 1) { ?> <div class='form-group-vert'> <h6><?php echo ucfirst(CrugeTranslator::t("terminos y condiciones"));?></h6> <?php echo CHtml::textArea('terms' ,Yii::app()->user->um->getDefaultSystem()->get('terms') ,array('readonly'=>'readonly','rows'=>5,'cols'=>'80%') ); ?> <div><span class='required'>*</span><?php echo CrugeTranslator::t(Yii::app()->user->um->getDefaultSystem()->get('registerusingtermslabel')); ?></div> <?php echo $form->checkBox($model,'terminosYCondiciones'); ?> <?php echo $form->error($model,'terminosYCondiciones'); ?> </div> <!-- fin - terminos y condiciones --> <?php } ?> <!-- inicio pide captcha --> <?php if(Yii::app()->user->um->getDefaultSystem()->getn('registerusingcaptcha') == 1) { ?> <div class='form-group-vert'> <h6><?php echo ucfirst(CrugeTranslator::t("codigo de seguridad"));?></h6> <div class="row"> <div> <?php $this->widget('CCaptcha'); ?> <?php echo $form->textField($model,'verifyCode'); ?> </div> <div class="hint"><?php echo CrugeTranslator::t("por favor ingrese los caracteres o digitos que vea en la imagen");?></div> <?php echo $form->error($model,'verifyCode'); ?> </div> </div> <?php } ?> <!-- fin pide captcha--> <?php $this->endWidget(); ?> <div class="col-lg-3"></div> </div> <file_sep><?php class SiteController extends Controller { /** * Declares class-based actions. */ var $layout = "//layouts/mainlogin"; public function actions() { return array( // captcha action renders the CAPTCHA image displayed on the contact page 'captcha'=>array( 'class'=>'CCaptchaAction', 'backColor'=>0xFFFFFF, ), // page action renders "static" pages stored under 'protected/views/site/pages' // They can be accessed via: index.php?r=site/page&view=FileName 'page'=>array( 'class'=>'CViewAction', ), ); } public function actionWelcome() { $this->render('welcome'); } public function actionPwdRec() { //$this->layout = CrugeUtil::config()->resetPasswordLayout; $this->layout = "//layouts/mainlogin"; // $model = new CrugeStoredUser('recovery'); $model = Yii::app()->user->um->getPwdRec('pwdrecovery'); Yii::app()->user->setFlash('pwdrecflash', null); if(isset($_POST['g-recaptcha-response'])) { if($_POST['g-recaptcha-response']<>"") { $model->attributes = $_POST[CrugeUtil::config()->postNameMappings['CrugeLogon']]; if ($model->validate()) { $newPwd = CrugeUtil::passwordGenerator(); Yii::app()->user->um->changePassword($model->getModel(), $newPwd); Yii::app()->crugemailer->sendPasswordTo($model->getModel(), $newPwd); Yii::app()->user->um->save($model->getModel()); Yii::app()->user->setFlash( 'pwdrecflash' , CrugeTranslator::t('Una nueva clave ha sido enviada a su correo') ); } } else { $model->addError("iduser","El código 'NO SOY UN ROBOT' ha sido inválido "); } } $this->render('pwdrec', array('model' => $model)); } public function actionAdmin() { $this->layout = "//layouts/mainmenu"; $this->render("admin"); } /** * This is the default 'index' action that is invoked * when an action is not explicitly requested by users. */ public function actionRegistro($datakey = '') { Yii::import('application.modules.cruge.controllers.*'); // $this->layout = CrugeUtil::config()->registrationLayout; $model = Yii::app()->user->um->createBlankUser(); $model->bypassCaptcha = false; $model->terminosYCondiciones = false; if (Yii::app()->user->um->getDefaultSystem()->getn('registerusingterms') == 0) { $model->terminosYCondiciones = true; } // para que cargue los campos del usuario Yii::app()->user->um->loadUserFields($model); // 'datakey' es el nombre de una variable de sesion // establecida por alguna parte que invoque a actionRegistration // y que se le pasa a este action para de ahi se lean datos. // // el dato esperado alli es un array indexado ('attribuye'=>'value') // tales valores deberan usarse para inicializar el formulario // del usuario como se indica aqui: // // ejemplo de array en sesion: // array('username'=>'csalazar','email'=>'<EMAIL>' // ,'nombre'=>'christian', 'apellido'=>'salazar') // // siendo: "nombre" y "apellido" los nombre de campos personalizados // que inmediantamente tras registro seran inicializados. // if ($datakey != null) { // leo la data de la varibale de sesion $s = new CHttpSession(); $s->open(); $values = $s[$datakey]; $s->close(); // asumo que es un array, asi que aqui vamos // $model->username = $values['username']; $model->email = $values['email']; // ahora, procesa los campos personalizados, // rellenando aquellos mapeados contra los campos existentes: foreach ($model->getFields() as $f) { if (isset($values[$f->fieldname])) { $f->setFieldValue($values[$f->fieldname]); } } } if(isset($_POST['g-recaptcha-response'])) { if($_POST['g-recaptcha-response']<>"") { if (isset($_POST[CrugeUtil::config()->postNameMappings['CrugeStoredUser']])) { $model->attributes = $_POST[CrugeUtil::config()->postNameMappings['CrugeStoredUser']]; if ($model->validate()) { $newPwd = trim($model->newPassword); Yii::app()->user->um->changePassword($model, $newPwd); Yii::app()->user->um->generateAuthenticationKey($model); if (Yii::app()->user->um->save($model, 'insert')) { $controllerCruge = New UiController($model->iduser); $controllerCruge->onNewUser($model, $newPwd); $UserApart = New UserApart; $UserApart->iduser = $model->iduser; $UserApart->idapart = $model->apartamento; $UserApart->save(); $this->redirect(array('welcome')); } } } }else { $model->addError("iduser","El código 'NO SOY UN ROBOT' ha sido inválido "); } } $this->render("registro", array('model' => $model)); } public function actionNoticias() { $this->layout = "//layouts/column2_menu"; $noticias = Noticia::model()->getNoticias(); $this->render('noticias', array('noticias' => $noticias)); } public function actionIndex() { // Yii::app()->user->setFlash('loginflash',null); if(!Yii::app()->user->isGuest){ $this->layout= "//layouts/mainmenu"; $noticias = Noticia::model()->getNoticias(); $this->render('noticias', array('noticias' => $noticias)); } else { $model = Yii::app()->user->um->getNewCrugeLogon('login'); // por ahora solo un metodo de autenticacion por vez es usado, aunque sea un array en config/main // $model->authMode = CrugeFactory::get()->getConfiguredAuthMethodName(); Yii::log(__CLASS__ . "\nactionLogin\n", "info"); if (isset($_POST[CrugeUtil::config()->postNameMappings['CrugeLogon']])) { $model->attributes = $_POST[CrugeUtil::config()->postNameMappings['CrugeLogon']]; if ($model->validate()) { if ($model->login(false) == true) { Yii::log(__CLASS__ . "\nCrugeLogon->login() returns true\n", "info"); // a modo de conocimiento, Yii::app()->user->returnUrl es // establecida automaticamente por CAccessControlFilter cuando // preFilter llama a accessDenied quien a su vez llama a // CWebUser::loginRequired que es donde finalmente se llama a setReturnUrl $this->redirect(Yii::app()->user->returnUrl); } else { Yii::app()->user->setFlash('loginflash', Yii::app()->user->getLastError()); } } else { Yii::log( __CLASS__ . "\nCrugeUser->validate es false\n" . CHtml::errorSummary($model) , "error" ); } } $this->render('index', array('model' => $model)); } } /** * This is the action to handle external exceptions. */ public function actionError() { $this->layout= "//layouts/mainmenu"; if($error=Yii::app()->errorHandler->error) { if(Yii::app()->request->isAjaxRequest) echo $error['message']; else $this->render('error', $error); } } /** * Displays the contact page */ public function actionMensaje() { $this->layout= "//layouts/mainmenu"; $model = new SendMail('mensaje'); if(isset($_POST['SendMail'])) { $model->attributes=$_POST['SendMail']; $model->nombre= Yii::app()->user->username; if($model->validate()) { $from = Yii::app()->user->email; $name='=?UTF-8?B?'.base64_encode($model->nombre).'?='; $subject='=?UTF-8?B?'.base64_encode($model->asunto).'?='; $headers="From: $name <{$from}>\r\n". "Reply-To: {$from}\r\n". "MIME-Version: 1.0\r\n". "Content-Type: text/plain; charset=UTF-8"; mail($model->para,$subject,$model->mensaje,$headers); Yii::app()->user->setFlash('contact','Gracias por Escribirnos. Alguien le respondera lo antes posible'); $this->refresh(); } } $this->render('mensaje',array('model'=>$model)); } public function actionSugerencia() { $this->layout= "//layouts/mainmenu"; $model = new SendMail('sugerencia'); if(isset($_POST['SendMail'])) { $model->attributes=$_POST['SendMail']; $model->nombre= Yii::app()->user->getField('nombre'); //var_dump($model);exit; if($model->validate()) { $from = Yii::app()->user->email; $name='=?UTF-8?B?'.base64_encode($model->nombre).'?='; $subject='=?UTF-8?B?'.base64_encode($model->asunto).'?='; $headers="From: $name <{$from}>\r\n". "Reply-To: {$from}\r\n". "MIME-Version: 1.0\r\n". "Content-Type: text/plain; charset=UTF-8"; mail("<EMAIL>", "[" . $model->categoria . "]" . $subject,$model->mensaje,$headers); Yii::app()->user->setFlash('contact','Gracias por Escribirnos. Alguien le respondera lo antes posible'); $this->refresh(); } } $this->render('sugerencias',array('model'=>$model)); } public function actionContact() { $model=new ContactForm; if(isset($_POST['ContactForm'])) { $model->attributes=$_POST['ContactForm']; if($model->validate()) { $name='=?UTF-8?B?'.base64_encode($model->name).'?='; $subject='=?UTF-8?B?'.base64_encode($model->subject).'?='; $headers="From: $name <{$model->email}>\r\n". "Reply-To: {$model->email}\r\n". "MIME-Version: 1.0\r\n". "Content-Type: text/plain; charset=UTF-8"; mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers); Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.'); $this->refresh(); } } $this->render('contact',array('model'=>$model)); } /** * Displays the login page */ public function actionLogin() { $model=new LoginForm; // if it is ajax validation request if(isset($_POST['ajax']) && $_POST['ajax']==='login-form') { echo CActiveForm::validate($model); Yii::app()->end(); } // collect user input data if(isset($_POST['LoginForm'])) { $model->attributes=$_POST['LoginForm']; // validate user input and redirect to the previous page if valid if($model->validate() && $model->login()) $this->redirect(Yii::app()->user->returnUrl); } // display the login form $this->render('login',array('model'=>$model)); } /** * Logs out the current user and redirect to homepage. */ public function actionLogout() { Yii::app()->user->logout(); $this->redirect(Yii::app()->homeUrl); } }<file_sep><?php Yii::import('application.models._base.BaseNoticia'); class Noticia extends BaseNoticia { /** * @return Noticia */ public static function model($className = __CLASS__) { return parent::model($className); } public static function label($n = 1) { return Yii::t('app', 'Noticia|Noticias', $n); } public function getNoticias(){ $criteria = new CDbCriteria; $criteria->order= "fecha DESC"; return $this->findAll($criteria); } public function noticiaRecortada(){ return "<div class='mostrar'>" . $this->contenido . "</div>"; } }<file_sep><?php // if(Yii::app()->user->hasFlash('loginflash')): ?> <!--<div class="flash-error"> <?php // echo Yii::app()->user->getFlash('loginflash'); ?> </div>--> <?php // else: ?> <div class="row"> <div class="col-lg-3"></div> <div class="col-lg-6 text-center color"> <h1><?php echo CrugeTranslator::t('logon',"Login"); ?></h1> <div class="form"> <?php $form = $this->beginWidget( 'booster.widgets.TbActiveForm', array( 'id' => 'verticalForm', 'htmlOptions' => array('class' => 'well'), // for inset effect ) );?> <?php echo $form->textFieldGroup($model,'username'); ?> <?php echo $form->passwordFieldGroup($model,'<PASSWORD>'); ?> <div class="row rememberMe"> <?php echo $form->checkBox($model,'rememberMe'); ?> <?php echo $form->label($model,'rememberMe'); ?> <?php echo $form->error($model,'rememberMe'); ?> </div> <div class="row buttons"> <?php Yii::app()->user->ui->tbutton(CrugeTranslator::t('logon', "Login")); ?> <br/> <?php echo CHtml::link("Olvidó su Contraseña?", array("/site/PwdRec")) ?> <?php if(Yii::app()->user->um->getDefaultSystem()->getn('registrationonlogin')===1) //echo Yii::app()->user->ui->registrationLink; echo CHtml::link("Registrarse", array("/site/registro")) ?> </div> <?php // si el componente CrugeConnector existe lo usa: // if(Yii::app()->getComponent('crugeconnector') != null){ if(Yii::app()->crugeconnector->hasEnabledClients){ ?> <div class='crugeconnector'> <span><?php echo CrugeTranslator::t('logon', 'You also can login with');?>:</span> <ul> <?php $cc = Yii::app()->crugeconnector; foreach($cc->enabledClients as $key=>$config){ $image = CHtml::image($cc->getClientDefaultImage($key)); echo "<li>".CHtml::link($image, $cc->getClientLoginUrl($key))."</li>"; } ?> </ul> </div> <?php }} ?> <?php $this->endWidget(); ?> </div> </div> <div class="col-lg-3"></div> </div> <?php // endif; ?> <file_sep><?php $commonParams = array( // CONFIGURACION DE APP 'nameapp'=> 'Administralo', 'language'=> 'es', 'theme'=>'classic', 'debug'=>false, 'rbacSetupEnabled'=>false, 'allowUserAlways'=>true, 'useEncryptedPassword' => false, 'hash' => 'md5', 'version'=>'1.5', // CONFIGURACIÓN DE CORREO 'usermail' => '<EMAIL>', 'password' => '<PASSWORD>', 'hostSMTP' => 'smtp.gmail.com', 'SMTPAuth' => true, 'SMTPSecure' => "tls", 'Port' => 587, 'HeaderMail' => '<EMAIL>', 'NameHeader' => 'Administralo', 'adminEmail'=>'<EMAIL>', // CONFIGURACIÓN DE BASE DE DATOS 'basedatos' => 'administralo', 'localhost' => 'localhost', 'userdb' => 'root', 'passdb' => '<PASSWORD>', );<file_sep> <?php $logo = CHtml::image(Yii::app()->theme->baseUrl.'/images/logo-CK-soluciones.png','CK Soluciones'); ?> <?php $link_logo= CHtml::link("Copyright &copy; " . date('Y'). " By $logo",'http://www.cksoluciones.com', array('target'=>'_blank')); ?> <div id="footer"> <div class="row "> <div class="col-lg-3 text-center "></div> <div class="col-lg-6 text-center linkck "><?php echo $link_logo ?><br/> <div class="text-blank"> All Rights Reserved.<br/> <?php echo "Versión " . Yii::app()->params['version']; ?> </div> </div> <div class="col-lg-3"></div> </div> </div><!-- footer --><file_sep><?php class SendMail extends CFormModel { public $nombre; public $para; public $asunto; public $mensaje; public $categoria; public function rules() { return array( // name, email, subject and body are required array('nombre, para, asunto, mensaje', 'required','on'=>'mensaje'), array('nombre, asunto, mensaje,categoria', 'required','on'=>'sugerencia'), // email has to be a valid email address array('para', 'email'), // verifyCode needs to be entered correctly ); } public function attributeLabels() { return array( 'nombre'=>'Nombre', 'para'=>'Para', 'asunto'=>'Asunto del mensaje', 'mensaje'=>'Escriba su mensaje', ); } } <file_sep><?php /** @var NoticiaController $this */ /** @var Noticia $model */ $this->breadcrumbs=array( 'Noticias'=>array('index'), Yii::t('AweCrud.app', 'Manage'), ); $this->menu=array( // array('label' => Yii::t('AweCrud.app', 'List') . ' ' . Noticia::label(2), 'icon' => 'list', 'url' => array('index')), array('label' => Yii::t('AweCrud.app', 'Create') , 'icon' => 'plus', 'url' => array('create')), ); Yii::app()->clientScript->registerScript('search', " $('.search-button').click(function(){ $('.search-form').toggle(); return false; }); $('.search-form form').submit(function(){ $.fn.yiiGridView.update('noticia-grid', { data: $(this).serialize() }); return false; }); "); Yii::app()->clientScript->registerScript('noticias', " $('.mostrar').bind('click', function(e) { // Prevents the default action to be triggered. e.preventDefault(); // Triggering bPopup when click event is fired $(this).bPopup(); }); "); ?> <fieldset> <?php $this->widget( 'booster.widgets.TbExtendedGridView',array( 'id' => 'noticia-grid', 'filter' => $model, 'fixedHeader' => true, 'type' => 'striped bordered', 'headerOffset' => 40, // 40px is the height of the main navigation at bootstrap 'dataProvider' => $model->search(), 'columns' => array( array('name'=>'titulo', 'value'=>'$data->titulo', 'header'=>'Título', 'htmlOptions'=>array('width'=>'138','class'=>'bg-transparent') ), array('name'=>'contenido', 'type'=>'html', 'value'=>'$data->noticiaRecortada()', 'header'=>'Contenido', 'htmlOptions'=>array('width'=>'400','class'=>'bg-transparent') ), array('name'=>'fecha', 'value'=>'$data->fecha', 'header'=>'Fecha', 'htmlOptions'=>array('width'=>'138','class'=>'bg-transparent') ), array( 'class'=>'booster.widgets.TbButtonColumn', 'htmlOptions'=>array('width'=>'100', 'class'=>'bg-transparent'), ), ), )); ?> </fieldset><file_sep><?php /* @var $this Controller */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="es"> <!-- THEME CLASSIC MAIN LOGIN --> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Administración - Lugano Apartamentos</title> <!-- Bootstrap --> <link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/boostrap/css/bootstrap.css" rel="stylesheet"/> <!-- <link href="<?php // echo Yii::app()->theme->baseUrl; ?>/css/boostrap/css/bootstrap.min.css" rel="stylesheet"/>--> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <title><?php echo CHtml::encode($this->pageTitle); ?></title> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <div class="container" id="page"> <div id="header"> <div class="row"> <div class="col-lg-3"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/logo_lugano.png"/></div> <div class="col-lg-6"></div> <div class="col-lg-3 text-center"><br/><br/> <?php $ingresar = CHtml::image(Yii::app()->theme->baseUrl.'/images/ingresar.png','Mensajes'); $link_ingresar= CHtml::link($ingresar,array('site/index')); ?> <?php echo $link_ingresar ?> </div> </div> </div> <?php echo $content; ?> <div class="clear"></div> <?php include('_footer.php'); ?> </div><!-- page --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </body> </html> <file_sep><?php class m150501_230949_apartamentos extends CDbMigration { public function up() { $columns= array ( 'idapartamentos'=>'pk', 'apartamento_nro' => 'int(4)', 'fechaingreso' => 'datetime' ); $tableName = 'apartamentos'; if (Yii::app()->db->schema->getTable($tableName,true)===null) { $this->createTable($tableName, $columns); } else { echo "table exists"; } } public function down() { echo "m150501_230949_apartamentos does not support migration down.\n"; return false; } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ } <file_sep><?php class m150511_033651_user_apart extends CDbMigration { public function up() { $columns= array( "iduser"=>"int not null", "idapart"=>"int not null", ); $this->createTable("user_apart", $columns); $this->addForeignKey("fK_user", "user_apart", "iduser", "cruge_user", "iduser", "CASCADE"); $this->addForeignKey("fK_apart", "user_apart", "idapart", "apartamentos", "idapartamentos", "CASCADE"); } public function down() { $this->dropTable("user_apart"); } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }<file_sep><div class="container bg-transparent"> <?php foreach($noticias as $noticia): ?> <div class="row"> <div class="col-lg-12 text-left"> <h1> <?php echo $noticia->titulo; ?></h1></div> </div> <div class="row"> <div class="col-lg-12"> <?php echo $noticia->contenido; ?> </div> </div> <hr> <hr> <?php endforeach; ?> </div> <file_sep><div class="form"> <?php /** @var ApartamentosController $this */ /** @var Apartamentos $model */ /** @var AweActiveForm $form */ Yii::app()->bootstrap->registerAssetCss('bootstrap-datepicker.css'); Yii::app()->bootstrap->registerAssetJs('bootstrap.datepicker.js'); $form = $this->beginWidget('booster.widgets.TbActiveForm', array( 'id' => 'horizontalForm', 'type' => 'horizontal', )); ?> <p class="note"> <?php echo Yii::t('AweCrud.app', 'Fields with') ?> <span class="required">*</span> <?php echo Yii::t('AweCrud.app', 'are required') ?>. </p> <?php echo $form->errorSummary($model) ?> <?php echo $form->textFieldGroup($model, 'apartamento_nro', array('class' => 'span5')) ?> <?php echo $form->datePickerGroup( $model, 'fechaingreso', array( 'widgetOptions' => array( 'options' => array( 'language' => 'es', ), ), 'wrapperHtmlOptions' => array( 'class' => 'col-sm-5', ), 'hint' => 'Click inside! This is a super cool date field.', ) ); ?> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array( 'buttonType'=>'submit', 'type'=>'primary', 'label'=>$model->isNewRecord ? Yii::t('AweCrud.app', 'Create') : Yii::t('AweCrud.app', 'Save'), )); ?> <?php $this->widget('booster.widgets.TbButton', array( //'buttonType'=>'submit', 'label'=> Yii::t('AweCrud.app', 'Cancel'), 'htmlOptions' => array('onclick' => 'javascript:history.go(-1)') )); ?> </div> <?php $this->endWidget(); ?> </div><file_sep><?php /* @var $this Controller */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <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"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Administralo - Software Web de Propiedad Horizontal</title> <link href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" rel="stylesheet"/> <!-- Bootstrap --> <link href="<?php echo Yii::app()->request->baseUrl; ?>/css/boostrap/css/bootstrap.css" rel="stylesheet"/> <link href="<?php echo Yii::app()->request->baseUrl; ?>/css/boostrap/js/bootstrap.min.js" rel="javascript" type="text/javascript"/> <!-- <link href="<?php // echo Yii::app()->request->baseUrl; ?>/css/boostrap/css/bootstrap.min.css" rel="stylesheet"/>--> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <title><?php echo CHtml::encode($this->pageTitle); ?></title> </head> <body class="container"> <div class="container" id="page"> <div id="header"> <div class="row"> <div class="col-lg-3"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/logo_lugano.png"/></div> <div class="col-lg-6"></div> <div class="col-lg-3"></div> </div> <?php $items= Yii::app()->user->rbac->getMenu(); ?> <?php $ingresar = array('label'=>'Ingreso' , 'url'=>Yii::app()->user->ui->loginUrl , 'visible'=>Yii::app()->user->isGuest); $salir= array('label'=>'Salir ('.Yii::app()->user->name.')' , 'url'=>Yii::app()->user->ui->logoutUrl , 'visible'=>!Yii::app()->user->isGuest); $menu_admin = array('label'=>'Administrar Usuarios' , 'url'=>Yii::app()->user->ui->userManagementAdminUrl , 'visible'=>Yii::app()->user->isSuperAdmin); if(Yii::app()->user->isSuperAdmin) array_push($items, $menu_admin); array_push($items, $ingresar); array_push($items, $salir); ?> <div id="mainmenu"> <?php $this->widget('booster.widgets.TbNavbar',array( 'brand' => false, 'fixed' => false, 'fluid' => true, 'items' => array( array( 'class' => 'booster.widgets.TbMenu', 'type' => 'navbar', 'items' => $items, )))); ?> </div><!-- mainmenu --> </div> <?php if(isset($this->breadcrumbs)):?> <?php $this->widget('booster.widgets.TbBreadcrumbs', array( 'links'=>$this->breadcrumbs, )); ?><!-- breadcrumbs --> <?php endif?> <?php echo $content; ?> <div class="clear"></div> <div id="footer"> <div class="row"> <div class="col-lg-3 text-center"></div> <div class="col-lg-6 text-center">Copyright &copy; <?php echo date('Y'); ?> by CKSoluciones.<br/> All Rights Reserved.<br/> <?php echo "Versión " . Yii::app()->params['version']; ?></div> <div class="col-lg-3"></div> </div> </div><!-- footer --> </div><!-- page --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </body> </html> <file_sep><?php class ApartamentosMejorado extends Apartamentos { /** * Giovani ...rescatate!!!. * If update is successful, the browser will be redirected to the 'view' page. * @sinparametro integer $id the ID of the model to be updated */ public function algo(){ return true; } }<file_sep><?php /** @var NoticiaController $this */ /** @var Noticia $model */ $this->breadcrumbs=array( 'Noticias'=>array('index'), $model->id, ); $this->menu=array( //array('label' => Yii::t('AweCrud.app', 'List') . ' ' . Noticia::label(2), 'icon' => 'list', 'url' => array('index')), array('label' => Yii::t('AweCrud.app', 'Create'), 'icon' => 'plus', 'url' => array('create')), array('label' => Yii::t('AweCrud.app', 'Update'), 'icon' => 'pencil', 'url' => array('update', 'id' => $model->id)), array('label' => Yii::t('AweCrud.app', 'Delete'), 'icon' => 'trash', 'url' => '#', 'linkOptions' => array('submit' => array('delete', 'id' => $model->id), 'confirm' => Yii::t('AweCrud.app', 'Are you sure you want to delete this item?'))), array('label' => Yii::t('AweCrud.app', 'Manage'), 'icon' => 'list-alt', 'url' => array('admin')), ); ?> <fieldset> <legend> <?php echo CHtml::encode($model) ?></legend> <?php ?> <?php $this->widget('bootstrap.widgets.TbDetailView',array( 'data' => $model, 'attributes' => array( 'titulo', 'fecha', ), )); ?> <?php $this->beginWidget( 'booster.widgets.TbModal', array('id' => 'myModal') ); ?> <div class="modal-header"> <a class="close" data-dismiss="modal">&times;</a> <h4><?php echo $model->titulo ?></h4> </div> <div class="modal-body"> <p><?php echo $model->contenido ?></p> </div> <?php $this->endWidget(); ?> <?php $this->widget( 'booster.widgets.TbButton', array( 'label' => 'Ver noticia', 'context' => 'secondary', 'htmlOptions' => array( 'data-toggle' => 'modal', 'data-target' => '#myModal', ), ) ); ?> <script lang="javascript"> console.log( <?php var_dump($model->contenido) ?>); </script> </fieldset><file_sep><?php class CrugeController extends Controller { public function filters() { return array( array('CrugeAccessControlFilter') // 'accessControl', // perform access control for CRUD operations // 'postOnly + delete', // we only allow deletion via POST request ); } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ ?><file_sep><?php class m150503_163135_mail_queque extends CDbMigration { public function up() { $columns = array( "id" => "pk", "from" => "varchar(255) not null", "to" => "varchar(255) not null", "subjet" => "varchar(255) not null", "content" =>"blob not null", "attachement" => "varchar(255) not null", "process"=>"bit not null", "read" => "bit not null", "parent" => "int", ); $this->createTable("mailqueque", $columns); } public function down() { $this->dropTable("mailqueque"); } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }<file_sep><?php /* @var $this SiteController */ /* @var $model ContactForm */ /* @var $form CActiveForm */ $this->pageTitle=Yii::app()->name . ' - Contact Us'; //$this->breadcrumbs=array( // 'Contact', //); ?> <?php if(Yii::app()->user->hasFlash('contact')): ?> <div class="flash-success"> <?php echo Yii::app()->user->getFlash('contact'); ?> </div> <?php else: ?> <p> Si tiene una sugerencia , queja o reclamo, por favor, escribanos y pronto se contactarán con usted. </p> <div class="form"> <?php $form = $this->beginWidget( 'booster.widgets.TbActiveForm', array( 'id' => 'mensaje_form', 'htmlOptions' => array('class' => 'well'), // for inset effect ) );?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary($model); ?> <?php // echo $form->textFieldGroup($model,'nombre'); ?> <?php echo $form->dropDownListGroup( $model, 'categoria', array( 'wrapperHtmlOptions' => array( 'class' => 'col-sm-5', ), 'widgetOptions' => array( 'data' =>array( "Nueva idea"=> "Una Nueva Idea", "Algún Error" => "Algún Error", "Comentario" => "Dejanos tu comentario", ), 'htmlOptions' => array('empty' => 'Seleccione..'), ) ) ); ?> <?php echo $form->textFieldGroup($model,'asunto',array('size'=>60,'maxlength'=>128)); ?> <?php echo $form->textAreaGroup($model,'mensaje',array('rows'=>6, 'cols'=>50)); ?> <br/> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array( 'buttonType'=>'submit', 'type'=>'primary', 'label'=>'Enviar', )); ?> </div> <?php $this->endWidget(); ?> </div><!-- form --> <?php endif; ?>
8f0ba80a67beec7cd9a274eff5cc2a524f2bb95b
[ "PHP" ]
31
PHP
CKSoluciones/Administralo
cfca45f01b45f3c3e07e715289852f42eb647a9d
9382093c5922f335017d8986a747ecb36579742a
refs/heads/master
<repo_name>chiuannica/professorCitationsStreamlitApp<file_sep>/README.md # Computer Science Department Professors' Citations ## How to run the application: Install dependencies * Python 3.8 * pip * Streamlit Within the folder that contains the excel sheet and the python file, enter this command in the terminal. `streamlit run professor_citations_app.py ` <file_sep>/app.py import streamlit as st import numpy as np import pandas as pd import altair as alt # *===========================* # *===* Intro Information *===* # *===========================* st.title("Computer Science Department Professors' Citations") st.subheader("Purpose of Data") st.write("This is the display of data I spent months collecting as a research assistant.") st.write("The purpose of this data is to predict peer review scores based on computer science departments' citation values.") st.write('''The ranking of universities is a significant factor in students’ decisions to attend a university, government organizations deciding where to allocate funding, and universities in deciding how to grow their programs. Rankings have been based on multiple factors, including location, student to faculty ratio, and student happiness.''') st.write('''This dataset includes the professors at computer science programs, the number of citations they have, and scraped citation measures from their Google Scholar page.''') st.subheader("Things to know to interpret data") st.markdown('''<ul> <li>The t10 value refers to the number of citations of the professors' 10th highest cited paper</li> <li>The h-index measures a scholars's productivity and citation impact. It is defined as the maximum number of <em>h</em> papers that have been cited <em>h</em> times.</li> <li>The graphs are filtered by the sidebar fields</li> </ul>''', unsafe_allow_html=True) # *======================* # *===* LOADING DATA *===* # *======================* # load data def load_data(): path = "all_professors_04.07.2021_streamlit.csv" df = pd.read_csv(path) # cut out old records (* means these are current) df = df[df.trim == '*'] # limit the df to some columns df = df[["first", "last", "university", "citations", "h-index", "t10", "rank"]] # strip spaces from rank and university (prevent mismatching) df["university"] = df["university"].str.replace(' ', '') df["rank"] = df["rank"].str.strip() # fill empty spaces df = df.replace('NaN', 0) df = df.fillna(0) return df def load_utl_data(): # load df ult_path = "utilities.csv" df = pd.read_csv(ult_path) df = df[["university"]] # remove nulls df = df.dropna() # strip all spaces df["university"] = df["university"].replace(' ', '') return df df_limited = load_data() # show df (all of it) st.subheader("Raw Full Data") st.write(df_limited) # *=========================* # *===* SIDEBAR FILTERS *===* # *=========================* # --- CITATION SLIDERS --- # citation sliders df_citations = df_limited["citations"] df_limited["citations"] = pd.to_numeric(df_limited["citations"], downcast="float") min_citations = int(df_citations.min()) max_citations = int(df_citations.max()) st.sidebar.write('**Adjust citation values**') max_citation_slider = st.sidebar.slider('Adjust the slider to the maximum citation value', min_value=min_citations, max_value=max_citations, value=max_citations ) min_citation_slider = st.sidebar.slider('Adjust the slider to the minimum citation value', min_value=min_citations, max_value=max_citations) # limit the df based on the sliders df_limited = df_limited[df_limited.citations <= max_citation_slider] df_limited = df_limited[df_limited.citations >= min_citation_slider] # --- t10 SLIDERS --- # t10 sliders df_t10 = df_limited["t10"] min_t10 = int(df_t10.min()) max_t10 = int(df_citations.max()) st.sidebar.write('**Adjust t10 values**') max_t10_slider = st.sidebar.slider('Adjust the slider to the maximum t10 value', min_value=min_t10, max_value=max_t10, value=max_t10) min_t10_slider = st.sidebar.slider('Adjust the slider to the minimum t10 value', min_value=min_t10, max_value=max_t10) # limit the df based on the sliders df_limited = df_limited[df_limited.t10 <= max_t10_slider] df_limited = df_limited[df_limited.t10 >= min_t10_slider] # --- h-index SLIDERS --- # h-index sliders df_h = df_limited["h-index"] min_h = int(df_h.min()) max_h = int(df_h.max()) st.sidebar.write('**Adjust h-index values**') max_h_slider = st.sidebar.slider('Adjust the slider to the maximum h-index value', min_value=min_h, max_value=max_h, value=max_h) min_h_slider = st.sidebar.slider('Adjust the slider to the minimum h-index value', min_value=min_h, max_value=max_h) # limit the df based on the sliders df_limited = df_limited[df_limited["h-index"] <= max_h_slider] df_limited = df_limited[df_limited["h-index"] >= min_h_slider] # --- RANK MULTISELECT --- # select rank st.sidebar.write('**Professor Rank**') rank_radio = st.sidebar.radio( "Select the professor to filter", ("All", "Full", "Associate", "Assistant")) if (rank_radio == "Full"): df_limited = df_limited[ (df_limited['rank'] == "Full") ] elif (rank_radio == "Associate"): df_limited = df_limited[ (df_limited['rank'] == "Associate") ] elif (rank_radio == "Assistant"): df_limited = df_limited[ (df_limited['rank'] == "Assistant") ] # --- UNIVERSITY MULTISELECT --- # !!! eventually I want to select multiple universities, but doesn't work :( st.sidebar.write('**Select Universities**') # button to click if wants to filter universities filter_uni_button = st.sidebar.button("Filter Universities") # if click button if (filter_uni_button): # get list of universities uni_options = df_limited["university"].value_counts().to_frame().index # select uni_select = st.sidebar.selectbox("(Work in Progress). ", options=uni_options); # if something is selected, filter if (uni_select): df_limited = df_limited.loc[df_limited['university']==(uni_select)] # remove filter. if click, reload df remove_filter_uni_button = st.sidebar.button("Remove Filter") if (remove_filter_uni_button): df_limited = load_data() st.subheader("Filtered dataset") st.write(df_limited) # *===========================* # *===* DISPLAYING GRAPHS *===* # *===========================* # display bar graph of universities st.subheader("Number of records at each university") # --- COUNT FOR EACH UNIVERSITY --- df_uni_counts = df_limited["university"].value_counts().to_frame() df_uni_counts.rename(columns = {'university' : 'count' }, inplace = True) df_uni_counts["university"] = df_uni_counts.index st.write(df_uni_counts["count"]) c = alt.Chart(df_uni_counts).mark_bar().encode( x="count:Q", y="university:N", color="university:N" ).interactive() st.altair_chart(c, use_container_width=True) #st.bar_chart(df_uni_counts) # measures for university size st.subheader("Measures for sizes of university") st.write(df_uni_counts.describe()) # display bar graph of professor rank st.subheader("Bar graph of the number of professors of each rank") df_rank_counts = df_limited["rank"].value_counts() #df_rank_counts = df_rank_counts.loc[["Full", "Associate", "Assistant"]] st.bar_chart(df_rank_counts) # --- BUBBLE CHARTS --- # --- t10 to citations bubble chart --- st.subheader("t10 to citations") df_t10_citations = df_limited[["t10", "citations"]] c = alt.Chart(df_t10_citations).mark_circle().encode( x='t10', y='citations', size='t10', color='t10', tooltip=['t10', 'citations', 't10']) st.altair_chart(c, use_container_width=True) # --- t10 to h-index bubble chart --- st.subheader("t10 to h-index") df_t10_h = df_limited[["t10", "h-index"]] c = alt.Chart(df_t10_h).mark_circle().encode( x='t10', y='h-index', size='t10', color='t10', tooltip=['t10', 'h-index', 't10']) st.altair_chart(c, use_container_width=True) st.subheader("t10 to university") # --- t10 to universities bubble --- df_t10_uni_counts = df_limited[["t10", "university"]] c = alt.Chart(df_t10_uni_counts).mark_circle().encode( x="t10:Q", y="university:N", size="t10:Q", color="t10:Q", tooltip=['t10', 'university', 't10'] ).interactive() st.altair_chart(c, use_container_width=True) st.subheader("citations to university") df_citation_uni_counts = df_limited[["citations", "university"]] c = alt.Chart(df_citation_uni_counts).mark_circle().encode( x="citations:Q", y="university:N", size="citations:Q", color="citations:Q", tooltip=['citations', 'university', 'citations'] ).interactive() st.altair_chart(c, use_container_width=True) st.subheader("h-index to university") df_h_uni_counts = df_limited[["h-index", "university"]] c = alt.Chart(df_h_uni_counts).mark_circle().encode( x="h-index:Q", y="university:N", size="h-index:Q", color="h-index:Q", tooltip=['h-index', 'university', 'h-index'] ).interactive() st.altair_chart(c, use_container_width=True) # st.write('''Correlation between faculty size and US News CS ranking: # 1.0000 0.0103 # 0.0103 1.0000 # #Correlation between US News CS ranking and university ranking: # 1.0000 0.6792 # 0.6792 1.0000 # #Correlation between h-index and t10-index: # 1.0000 0.8077 # 0.8077 1.0000 # #Correlation between logs of h-index and t10-index: # 1.0000 0.9488 # 0.9488 1.0000 ''') <file_sep>/ranking.py import streamlit as st import numpy as np import pandas as pd import altair as alt # *===========================* # *===* RESULTS OF SCRIPT *===* # *===========================* # --- LOAD THE DATA --- path_2017 = "scholar_ranking_data_USN2017.csv" path_2018 = "scholar_ranking_data_USN2018.csv" def load_rank(path): df = pd.read_csv(path) # Full nulls with 0 df = df.fillna(0) df = df.replace(' NaN', 0) # Strip all spaces df = df.replace(' ', '') df.set_index("Rank") return df # load 2017, 2018 ranking data df_2017 = load_rank(path_2017); df_2018 = load_rank(path_2018) # *===========================* # *======* RAW DATASET *======* # *===========================* # --- RAW DATA --- # show the full raw ranking data for 2017 and 2018 st.header("Scholar scores and ranking") st.write("Scores based on Google Scholar citations measures were generated") st.write("These measures are M10, G10, P10, C40, C60, C80") st.subheader("2017 USN Ranking and 2020 professor data") st.write(df_2017) st.subheader("2018 USN Ranking and 2020 professor data") st.write(df_2018) # restrict to a few important columns df_2017_trimmed = df_2017[["Rank", "University", "Size", "USN", "Scholar"]] df_2018_trimmed = df_2018[["Rank", "University", "Size", "USN", "Scholar"]] # --- SHOW THE SCORES --- # Cut to show the USN and Scholar only st.subheader("2017 University Scores") st.write(df_2017[["University", "USN", "Scholar"]]) st.subheader("2018 University Scores") st.write(df_2018[["University", "USN", "Scholar"]]) c = alt.Chart(df_2017[["University", "USN", "Scholar"]]).mark_bar().encode( alt.X("USN:Q"), alt.X2("Scholar:Q"), alt.Y("University:Q"), color="University:N" ).interactive() st.altair_chart(c, use_container_width=True) # --- MERGE 2017 and 2018 --- df_2017_2018 = pd.merge(df_2017_trimmed, df_2018_trimmed, on='University', how='inner') # rename columns df_2017_2018.rename(columns = {'Size_x' : '2017 Size', 'Size_y' : '2018 Size', 'Scholar_x' : '2017 Scholar', 'Scholar_y' : '2018 Scholar', 'USN_x' : '2017 USN', 'USN_y' : '2018 USN', 'Rank_x' : '2017 Rank', 'Rank_y' : '2018 Rank' }, inplace = True) # *================================* # *===* COMPARING 2017 to 2018 *===* # *================================* st.header("2017 vs 2018") st.subheader("Size") df_2017_2018_size = df_2017_2018[['University', '2017 Size', '2018 Size']] st.write(df_2017_2018_size) st.subheader("Rank") df_2017_2018_rank = df_2017_2018[['University', '2017 Rank', '2018 Rank']] st.write(df_2017_2018_rank) st.subheader("Scholar score") df_2017_2018_scholar = df_2017_2018[['University', '2017 Scholar', '2018 Scholar']] st.write(df_2017_2018_scholar) st.subheader("USN score") df_2017_2018_usn = df_2017_2018[['University', '2017 USN', '2018 USN']] st.write(df_2017_2018_usn)
a2b1e6e0e2235d655581c4e680dc0311b8b3bca6
[ "Markdown", "Python" ]
3
Markdown
chiuannica/professorCitationsStreamlitApp
b8fcbb54f0b48872dcdecd22c2101ab079c554d6
5d3c1560fa25abc5bf0d61282bb509004fbbca40
refs/heads/master
<repo_name>Dsrocha74/Prova<file_sep>/src/prova/TestaEquipamento.java package prova; public class TestaEquipamento{ public static void main(String[] args){ Equipamento e1 = new Equipamento(); e1.preço = 29.99; System.out.println(""+e1.adicionarImposto(29.99)); } } <file_sep>/src/prova/Produto.java package prova; public class Produto{ String nome; double peso; Data dataDeFabricacao; } <file_sep>/src/prova/TestaProduto.java package prova; public class TestaProduto{ public static void main(String[] args){ Data data1 = new Data(); data1.dia = 15; data1.mes = 9; data1.ano = 2019; Produto p1 = new Produto(); p1.nome = "chinelo"; p1.peso = 250; p1.dataDeFabricacao = data1; data1.imprimir(); } } <file_sep>/src/prova/TestaTriangulo.java package prova; public class TestaTriangulo{ public static void main(String[] args){ Triangulo t1 = new Triangulo(); t1.altura = 10; t1.base = 10; t1.calcularArea(); } } <file_sep>/src/prova/Prova.java package prova; public class Prova{ public static void main(String[] args){ Data data = new Data(); data.dia = 1; data.mes = 15; data.ano = 1996; data.imprimir(); } } <file_sep>/src/prova/Data.java package prova; public class Data{ int dia; int mes; int ano; public void imprimir(){ System.out.println("Data: "+dia +mes +ano); } } <file_sep>/src/prova/Equipamento.java package prova; public class Equipamento{ double preço; public double adicionarImposto(double taxa){ taxa = (preço * 0.15) + preço; return taxa; } }
3db067207bad1064243eb2d650fbc5b9a5c8a609
[ "Java" ]
7
Java
Dsrocha74/Prova
507b6abeb1219ee208fa2702efddfc9dd5d140ff
2f9d680226ae11134766b8d54e60ec37ebe34b9c
refs/heads/main
<repo_name>medhavibasera/Dice-Game<file_sep>/index.js //alert("helllooooo"); var randomNumber1 = Math.floor(Math.random() * 6)+1; var randomDiceImage="images/dice"+randomNumber1+".png"; var image1=document.querySelectorAll("img")[0].setAttribute("src",randomDiceImage); // for second image var randomNumber2=Math.floor(Math.random()*6)+1; var randomDiceImage2="images/dice"+randomNumber2+".png"; var image2=document.querySelectorAll("img")[1].setAttribute("src",randomDiceImage2); if(randomNumber1>randomNumber2) { document.querySelector("h1").textContent="🚩Player 1 Wins !"; } else if(randomNumber1<randomNumber2) { document.querySelector("h1").textContent="🚩Player 2 Wins !"; } else { document.querySelector("h1").textContent="❤️It's a Tie" ; }
98ca77206e22252c6b822aa4cceeb76fc5e85b6e
[ "JavaScript" ]
1
JavaScript
medhavibasera/Dice-Game
3b8ca900a8d085707ebcbeef22878504cbd9e311
d5719b25086ecb6cfc62e7dcb5b7d53a7420fef8
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { Http,Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import {app} from './app'; import {Repos} from './repos'; import {environment} from '../environments/environment'; @Injectable() export class AppService { private username:string; private clientid:'617211a9b5a5d0b33ca4'; private clientsecret:"<KEY>"; constructor(private http:Http) { console.log("service is now ready!"); this.username = "sammwaura"; } getappInfo(){ return this.http.get("https://api.github.com/users/"+ this.username + "?client_id=" + this.clientid + "&clientservice=" + this.clientsecret) .map(res => res.json()); } getappRepos() { return this.http.get("https://api.github.com/users/"+ this.username + "/repos?client_id=" + this.clientid + "&clientservice=" + this.clientsecret) .map(res => res.json()); } updateapp(username:string){ this.username = username; } } <file_sep>import { Component, OnInit } from '@angular/core'; import {AppService} from '../app.service'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-github-clone', templateUrl: './github-clone.component.html', styleUrls: ['./github-clone.component.css'] }) export class GithubCloneComponent implements OnInit { public app:any[]; private repos: any[]; username:string; constructor(private appService: AppService) { this.appService.getappInfo().subscribe(app => { console.log(app); this.app = app; }); this.appService.getappRepos().subscribe(repos => { console.log(repos); this.repos = repos; }); } ngOnInit() { } findapp() { this.appService.updateapp(this.username); this.appService.getappInfo().subscribe(app =>{ console.log(app); this.app = app; }); this.appService.getappRepos().subscribe(repos => { console.log(repos); this.repos = repos; }); } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { GithubCloneComponent } from './github-clone.component'; describe('GithubCloneComponent', () => { let component: GithubCloneComponent; let fixture: ComponentFixture<GithubCloneComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ GithubCloneComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(GithubCloneComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>export class app { constructor(private access_token:string,){} }<file_sep>export class GithubClone { } <file_sep># BY MwauraSamuel ## GITHUB Clone ## Description This is a website where users may enter a Github username into a form, submit it and see names & description of that persons public repositories. The User can also look for repositories. ## LiveLink https://sammwaura.github.io/Github-Clone/ ## Technologies Used * HTML * Type Script * Bootstrap ## To SetUp And Run The Project You Need To; * Open GitHub and search my username ## Sammwaura * Locate the Repository GitHub-Clone and open it *On the Download/Clone tab select the download option and save to a folder that is easily accesible(or still you could clone the repo to your computer) * Unzip the file and the entire repo will be available on your machine * Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files. * Run ng test to execute the unit tests via Karma. Feel free to explore my other repositories! ## LICENSE
8e70a55b90a23520102f727ec454b76802428bb8
[ "Markdown", "TypeScript" ]
6
TypeScript
tatonka21/Github-Clone-1
101b9d3931381dbaa24f593892c0e8ea40337b08
ff856fae61a4a7855232e633bfc04cd85685648d
refs/heads/master
<file_sep>// Note: All authentication dispatch functions are defined here...! import { SIGN_UP_USER, LOG_IN_USER, LOG_OUT_USER } from "../constant/action-types"; /***** Note: SignUp function *****/ const signUpUserDispatch = (user) => { return (dispatch) => { // console.log(user); dispatch({ type: SIGN_UP_USER, payload: user }); } } /***** Note: Login function *****/ const logInUserDispatch = (user) => { return (dispatch) => { // console.log(user); dispatch({ type: LOG_IN_USER, payload: user }); } } /***** Note: logout function *****/ const logOutUser = () => { return (dispatch) => { dispatch({ type: LOG_OUT_USER }); } } export { signUpUserDispatch, logInUserDispatch, logOutUser };<file_sep>// Note: Routes component...! import React from 'react'; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; // import Cookies from "js-cookie"; import { useSelector } from 'react-redux'; // Note: Importing reuseabale components...! import SignUp from "./components/auth components/signup"; import LogIn from "./components/auth components/login"; import Home from "./components/other components/home"; import NotFound from "./components/other components/not-found"; const AppRoutes = () => { // Note: One way for maintain user session using cookies...! // const getUser = Cookies.get('user'); // console.log(getUser); // Note: One way for maintain user session using cookies redux...! let getUser = useSelector(({ users }) => { return users.authenticatedUser }); console.log(getUser); return ( <React.Fragment> <Router> <Routes> { (getUser) ? (<Route path="/" element={<Home />} />) : (<Route path="/" element={<LogIn />} />) } <Route path="signup" element={<SignUp />} /> <Route path="*" element={<NotFound />} /> </Routes> </Router> </React.Fragment> ); } export default AppRoutes;<file_sep>// Note: SignUp component...! import React, { useState } from 'react'; import { Button, Grid, Paper, TextField, Typography, FormControlLabel, Checkbox } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import { Link } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import { signUpUserDispatch } from '../../store/action/dispatch-functions'; import "./style.css"; // Note: Handeling Material UI styling here...! const useStyle = makeStyles((theme) => ({ Paper: { width: '520px', [theme.breakpoints.down('sm')]: { width: "auto" }, color: '#f6f6f6', borderRadius: '17px', padding: '2em', backgroundColor: "transparent" }, Heading: { fontSize: '1.3em', fontFamily: 'sans-serif', color: `#212943`, }, Link: { textDecoration: 'none' }, Button: { borderRadius: '20px', padding: '13px', backgroundColor: `#212943`, color: '#fff', '&:hover': { backgroundColor: '#1976D2', }, }, })); const SignUp = () => { // Note: To access Material UI...! const classes = useStyle(); // Note: Handeling states here...! const [formData, setformData] = useState({ name: '', email: '', password: '' }); const [validationHelper, setValidationHelper] = useState({ nameHelper: '', emailHelper: '', passwordHelper: '', }); const [checkedState, setCheckedState] = useState(false); const { name, email, password } = formData; const { nameHelper, emailHelper, passwordHelper } = validationHelper; // Note: Handling redux here...! const dispatch = useDispatch(); // Note: Function to handle form...! const onChange = (e) => { setformData({ ...formData, [e.target.name]: e.target.value }); }; // Note: Function to handle checkbox...! const handleCheckBox = (event) => { setCheckedState(event.target.checked); } // Note: Function to submit form data...! const onSubmit = () => { let validEmailFormat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; if ( formData.name != 0 && (formData.email != 0 && formData.email.match(validEmailFormat)) && formData.password.length > 5 ) { dispatch(signUpUserDispatch(formData)); clearAll(); } else { validationHelper.nameHelper = "Name is Required"; validationHelper.emailHelper = "Email is Required or Inavlid Email Format"; validationHelper.passwordHelper = "Password is Required or Password length should be greater than six"; setTimeout(() => { setValidationHelper({ nameHelper: '', emailHelper: '', passwordHelper: '' }); }, 5000); setValidationHelper({ ...validationHelper }); } }; // Note: Function to clear all input fields...! const clearAll = () => { setformData({ name: '', email: '', password: '', }); setValidationHelper({ nameHelper: '', emailHelper: '', passwordHelper: '', }); setCheckedState(false); } // Note: This is just for testing purpose...! let getUser = useSelector(({ users }) => { return users.usersArr }); console.log(getUser); /***** Note: UI *****/ return ( <div id="custom-body"> <Grid item container style={{ display: "flex", justifyContent: "center" }}> <Grid item container component={Paper} elevation={3} className={classes.Paper} justify='center' alignItems='center'> <Grid item container justify='center' className={classes.Heading}> <Typography variant='h4'> Sign Up </Typography> </Grid> <Grid item container direction='row' justify='center' alignItems='center' style={{ marginTop: '2em' }}> <Grid item container justify='center'> <TextField id='name' variant='outlined' placeholder='Name' name='name' fullWidth size='small' inputProps={{ style: { padding: 13, fontSize: '1.1rem', borderColor: "none", color: "white" }, }} value={name || ""} error={nameHelper.length !== 0} helperText={nameHelper} onChange={onChange} /> </Grid> <Grid item container justify='center' style={{ marginTop: '2em' }}> <TextField id='email' variant='outlined' placeholder='Email' name='email' fullWidth size='small' inputProps={{ style: { padding: 13, fontSize: '1.1rem', borderColor: "none", color: "white" }, }} value={email || ""} error={emailHelper.length !== 0} helperText={emailHelper} onChange={onChange} /> </Grid> <Grid item container justify='center' style={{ marginTop: '2em' }}> <TextField type='password' id='outlined-basic' variant='outlined' fullWidth placeholder='<PASSWORD>' size='small' inputProps={{ style: { padding: 13, fontSize: '1.1rem', color: "white" }, }} name='password' value={password || ""} error={passwordHelper.length !== 0} helperText={passwordHelper} onChange={onChange} /> </Grid> <Grid item container justify='center' style={{ marginTop: '1em' }}> <FormControlLabel control={ <Checkbox checked={checkedState} onChange={handleCheckBox} name="checkedState" color="primary" />} label="I accept all terms and conditions" /> </Grid> <Grid item container justify='center' style={{ marginTop: '1em' }}> <Button disabled={(checkedState) ? (false) : (true)} onClick={onSubmit} fullWidth variant='contained' className={classes.Button}> Submit </Button> </Grid> </Grid> <Grid item container justify='center' style={{ marginTop: '2em' }}> <Link to='/' className={classes.Link}> <Typography variant='h6'> Already have an account ? <span style={{ color: 'white' }}> Login </span> </Typography> </Link> </Grid> </Grid> </Grid> </div> ); } export default SignUp;
1eb01ffc1c7cebb28966f5da1a1d62652445ae93
[ "JavaScript" ]
3
JavaScript
Shahzadaahmed/User-Authentication-using-React-Stack
f63177b659424536c2bc33baf0b9a9faf1a9c3e2
11ce1176b27fae20b1f1df1a48ca4908c3e83ee3
refs/heads/master
<file_sep>from os import environ from fabric.api import run, sudo from fabric.contrib.files import exists from offregister_fab_utils.apt import apt_depends from offregister_fab_utils.ubuntu.systemd import ( install_upgrade_service, restart_systemd, ) from offregister_opencv.base import dl_install_opencv from offregister_tensorflow.ubuntu.utils import ( build_from_source, instantiate_virtual_env, setup_gpu, ) def install_tensorflow0( python3=False, virtual_env=None, virtual_env_args=None, *args, **kwargs ): apt_depends( c, "build-essential", "sudo", "git", "libffi-dev", "libssl-dev", "software-properties-common", "libatlas-base-dev", ) home = kwargs.get("HOMEDIR", c.run("echo $HOME", hide=True).stdout.rstrip()) virtual_env = virtual_env or "{home}/venvs/tflow".format(home=home) if python3: apt_depends( c, "python3-numpy", "python3-dev", "python3-pip", "python3-wheel", "python3-venv", ) else: apt_depends( c, "python2.7", "python2.7-dev", "python-dev", "python-pip", "python-apt", "python-numpy", "python-wheel", ) run_cmd = c.sudo if kwargs.get("use_sudo", False) else c.run pip_version = kwargs.get("pip_version", False) instantiate_virtual_env(pip_version, python3, virtual_env, virtual_env_args) if not exists(c, runner=c.run, path=virtual_env): raise ReferenceError("Virtualenv does not exist") env = dict(VIRTUAL_ENV=virtual_env, PATH="{}/bin:$PATH".format(virtual_env)) if pip_version: c.run( "python -m pip install pip=={pip_version}".format(pip_version=pip_version), env=env, ) else: c.run("python -m pip install -U pip setuptools", env=env) c.run("python -m pip install -U jupyter", env=env) build_env = {} if kwargs.get("from") == "source": gpu = kwargs.get("GPU") if gpu: build_env.update( setup_gpu(download_dir="{home}/Downloads".format(home=home)) ) whl = build_from_source( repo_dir="{home}/repos".format(home=home), gpu=gpu, build_env=build_env, tensorflow_tag=kwargs.get("tensorflow_tag", "v1.14.0"), tensorflow_branch=kwargs.get("tensorflow_branch"), force_rebuild=kwargs.get("force_rebuild"), use_sudo=kwargs.get("use_sudo"), python3=python3, run_cmd=run_cmd, virtual_env=virtual_env, extra_build_args=kwargs.get("extra_build_args"), ) if whl.endswith(".whl"): c.run("python -m pip install {whl}".format(whl=whl), env=env) elif kwargs.get("from") == "pypi" or "from" not in kwargs: c.run("python -m pip install -U tensorflow", env=env) if kwargs.get("skip_tflow_example"): return c.run( 'python -c "from tensorflow import __version__;' " print('Installed TensorFlow {} successfully'.format(__version__))\"", env=env, ) hello_world = "".join( l.strip() for l in """import tensorflow as tf; hello = tf.constant('TensorFlow works!'); sess = tf.Session(); print(sess.run(hello)) """.splitlines() ) return c.run('python -c "{}"'.format(hello_world), env=env) def install_jupyter_notebook1(virtual_env=None, *args, **kwargs): home = kwargs.get("HOMEDIR", c.run("echo $HOME", hide=True).stdout.rstrip()) virtual_env = virtual_env or "{home}/venvs/tflow".format(home=home) user, group = (lambda ug: (ug[0], ug[1]) if len(ug) > 1 else (ug[0], ug[0]))( c.run( '''printf '%s\t%s' "$USER" "$GROUP"''', hide=True, shell_escape=False ).split("\t") ) notebook_dir = kwargs.get("notebook_dir", "{home}/notebooks".format(home=home)) (sudo if kwargs.get("use_sudo") else run)( "mkdir -p '{notebook_dir}'".format(notebook_dir=notebook_dir) ) return install_upgrade_service( "jupyter_notebook", conf_local_filepath=kwargs.get("systemd-conf-file"), context={ "ExecStart": " ".join( ( "{virtual_env}/bin/jupyter".format(virtual_env=virtual_env), "notebook", "--NotebookApp.notebook_dir='{notebook_dir}'".format( notebook_dir=notebook_dir ), "--NotebookApp.ip='{listen_ip}'".format( listen_ip=kwargs.get("listen_ip", "127.0.0.1") ), "--NotebookApp.port='{listen_port}'".format( listen_port=kwargs.get("listen_port", "8888") ), "--Session.username='{User}'".format(User=user), "--NotebookApp.password='{<PASSWORD>}'".format( password=environ["PASSWORD"] ), "--NotebookApp.password_required='<PASSWORD>'", "--NotebookApp.allow_remote_access='True'", "--NotebookApp.iopub_data_rate_limit='2147483647'", "--no-browser", "--NotebookApp.open_browser='False'", ) ), "Environments": kwargs["Environments"], "WorkingDirectory": notebook_dir, "User": user, "Group": group, }, ) def install_opencv2(virtual_env=None, python3=False, *args, **kwargs): home = kwargs.get("HOMEDIR", c.run("echo $HOME", hide=True).stdout.rstrip()) virtual_env = virtual_env or "{home}/venvs/tflow".format(home=home) site_packages = c.run( '{virtual_env}/bin/python -c "import site; print(site.getsitepackages()[0])"'.format( virtual_env=virtual_env ) ) dl_install_opencv( extra_cmake_args="OPENCV_PYTHON3_INSTALL_PATH={site_packages}".format( site_packages=site_packages ) if python3 else "-D PYTHON2_PACKAGES_PATH='{virtual_env}/lib/python2.7/site-packages' " "-D PYTHON2_LIBRARY='{virtual_env}/bin'".format(virtual_env=virtual_env) ) def install_tensorboard3( extra_opts=None, virtual_env=None, pip_install_args=None, *args, **kwargs ): home = kwargs.get("HOMEDIR", c.run("echo $HOME", hide=True).stdout.rstrip()) virtual_env = virtual_env or "{home}/venvs/tflow".format(home=home) tensorboard_logs_dir = kwargs.get( "tensorboard_logs_dir", "{home}/tensorboard_logs_dir".format(home=home) ) c.run( "mkdir -p {tensorboard_logs_dir}".format( tensorboard_logs_dir=tensorboard_logs_dir ) ) conf_name = "tensorboard" env = dict(PATH="{}/bin:$PATH".format(virtual_env), VIRTUAL_ENV=virtual_env) c.run( "python -m pip install {pip_install_args} -U tensorboard".format( pip_install_args=pip_install_args or "" ), env=env, ) """ listen_ip, notebook_dir, pythonpath, listen_port='8888', conf_name='jupyter_notebook', extra_opts=None, **kwargs) """ tensorboard_exec = c.run("command -v tensorboard", env=env) install_upgrade_service( conf_name, conf_local_filepath=kwargs.get("systemd-conf-file"), context={ "ExecStart": " ".join( ( tensorboard_exec, "--logdir '{tensorboard_logs_dir}'".format( tensorboard_logs_dir=tensorboard_logs_dir ), extra_opts if extra_opts else "", ) ), "Environments": kwargs["Environments"], "WorkingDirectory": tensorboard_logs_dir, "User": kwargs["User"], "Group": kwargs["Group"], }, ) return restart_systemd(c, conf_name) <file_sep>https://api.github.com/repos/offscale/offregister-fab-utils/zipball#egg=offregister_fab_utils https://api.github.com/repos/offscale/offregister-web-servers/zipball#egg=offregister_web_servers https://api.github.com/repos/offscale/offregister-jupyter/zipball#egg=offregister_jupyter <file_sep>from fabric.contrib.files import exists from offregister_fab_utils.apt import apt_depends from offregister_fab_utils.fs import cmd_avail from offregister_fab_utils.git import clone_or_update from offutils import update_d def instantiate_virtual_env(c, pip_version, python3, virtual_env, virtual_env_args): virtual_env_dir = virtual_env[: virtual_env.rfind("/")] if not exists(c, runner=c.run, path=virtual_env_dir) or not exists( c, runner=c.run, path=virtual_env ): c.sudo('mkdir -p "{virtual_env_dir}"'.format(virtual_env_dir=virtual_env_dir)) user_group = c.run("echo $(id -un):$(id -gn)", hide=True).stdout.rstrip() c.sudo( 'chown -R {user_group} "{virtual_env_dir}"'.format( user_group=user_group, virtual_env_dir=virtual_env_dir ) ) if python3: if pip_version: c.sudo( "pip3 install pip=={pip_version}".format(pip_version=pip_version) ) else: c.sudo("pip3 install -U pip setuptools") # `--system-site-packages` didn't install a pip c.run( 'python3 -m venv "{virtual_env}" {virtual_env_args}'.format( virtual_env=virtual_env, virtual_env_args=virtual_env_args or "" ) ) c.sudo("pip3 install keras_applications==1.0.6 --no-deps") c.sudo("pip3 install keras_preprocessing==1.0.5 --no-deps") c.sudo("pip3 install h5py==2.8.0") else: c.sudo("pip2 install pip=={pip_version}".format(pip_version=pip_version)) if not cmd_avail(c, "virtualenv"): c.sudo("pip2 install virtualenv") c.run( 'virtualenv --system-site-packages "{virtual_env}"'.format( virtual_env=virtual_env ) ) c.sudo("pip2 install keras_applications==1.0.6 --no-deps") c.sudo("pip2 install keras_preprocessing==1.0.5 --no-deps") c.sudo("pip2 install h5py==2.8.0") def setup_gpu(download_dir): if not cmd_avail(c, "nvidia-smi"): c.run("mkdir -p {download_dir}".format(download_dir=download_dir)) with c.cd(download_dir): c.sudo( "apt-key adv --fetch-keys " "https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub" ) repo_pkg = "nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb" for pkg, url in ( ( "cuda-repo-ubuntu1804_10.0.130-1_amd64.deb", "https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/", ), ( repo_pkg, "http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/", ), ): c.run("curl -OL {url}{pkg}".format(url=url, pkg=pkg)) c.sudo("apt install ./{pkg}".format(pkg=pkg)) c.sudo("apt update") c.sudo("apt install ./{repo_pkg}".format(repo_pkg=repo_pkg)) c.sudo("apt-get install -y --no-install-recommends nvidia-driver-418") raise NotImplementedError("You must restart machine for NVIDIA driver to work") c.run("nvidia-smi") c.sudo( "apt-get install -y --no-install-recommends " "cuda-10-0 " "libcudnn7=7.6.2.24-1+cuda10.0 " "libcudnn7-dev=7.6.2.24-1+cuda10.0" ) c.sudo( "apt-get install -y --no-install-recommends libnvinfer5=5.1.5-1+cuda10.0 " "libnvinfer-dev=5.1.5-1+cuda10.0" ) apt_depends(c, "clang") return dict( LD_LIBRARY_PATH="/usr/local/cuda/extras/CUPTI/lib64", TF_NEED_CUDA="1", TF_CUDA_CLANG="1", TF_NEED_TENSORRT="1", TF_CUDA_COMPUTE_CAPABILITIES="3.7", # TODO: Check device against NVIDIA website list of supported CUDA versions CLANG_CUDA_COMPILER_PATH="/usr/bin/clang" # TF_DOWNLOAD_CLANG='1' ) def build_from_source( repo_dir, force_rebuild, tensorflow_tag, tensorflow_branch, build_env, gpu, use_sudo, python3, run_cmd, virtual_env, extra_build_args="", ): apt_depends(c, "unzip") c.run("pip uninstall -y tensorflow", warn=True, hide=True) c.run("mkdir -p {repo_dir}".format(repo_dir=repo_dir)) tf_repo = "{repo_dir}/{repo}".format( repo_dir=repo_dir, repo="tensorflow-for-py3" if python3 else "tensorflow" ) clone_or_update( repo="tensorflow", team="tensorflow", to_dir=tf_repo, skip_reset=True, skip_checkout=True, use_sudo=use_sudo, **( {"branch": tensorflow_branch} if tensorflow_branch else {"tag": tensorflow_tag} ) ) with c.cd(tf_repo): version = 3 if python3 else 2 processor = "gpu" if gpu else "cpu" # 'tpu' release_to = "{repo_dir}/tensorflow_pkg-{version}-{processor}".format( repo_dir=repo_dir, version=version, processor=processor ) if force_rebuild: run_cmd("rm -rf '{}'".format(release_to)) whl = "{release_to}/*cp{version}-{processor}*.whl".format( release_to=release_to, version=version, processor=processor ) if exists(c, runner=c.run, path=release_to) and exists( c, runner=c.run, path=whl ): return "Already built" if python3: run_cmd("python -m pip install numpy wheel") run_cmd("python -m pip install keras_preprocessing") # install_bazel() if not cmd_avail(c, "bazel"): with c.cd( "{parent}/Downloads".format( parent=c.run( "dirname {repo_dir}".format(repo_dir=repo_dir), hide=True ) ) ): script = "bazel-0.25.2-installer-linux-x86_64.sh" c.run( "curl -OL https://github.com/bazelbuild/bazel/releases/download/0.25.2/" "{script}".format(script=script) ) c.sudo("bash {script}".format(script=script)) default_build_env = dict( PYTHON_BIN_PATH="{}/bin/python".format(virtual_env), PYTHON_LIB_PATH=virtual_env, TF_DOWNLOAD_MKL="1", TF_NEED_MKL="1", CC_OPT_FLAGS="-march=native", TF_NEED_JEMALLOC="1", TF_NEED_GCP="0", TF_NEED_HDFS="0", TF_ENABLE_XLA="0", # JIT TF_NEED_VERBS="0", TF_NEED_OPENCL="0", TF_NEED_OPENCL_SYCL="0", TF_NEED_COMPUTECPP="0", TF_NEED_CUDA="0", TF_NEED_MPI="0", TF_NEED_S3="0", TF_NEED_GDR="0", TF_SET_ANDROID_WORKSPACE="0", TF_NEED_KAFKA="0", TF_CUDA_CLANG="0", TF_DOWNLOAD_CLANG="0", TF_NEED_ROCM="0", TF_NEED_TENSORRT="0", ) env = dict(**update_d(default_build_env, build_env)) c.run("env", env=env) c.run("./configure", env=env) c.run( "bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package {}".format( extra_build_args ) ) c.run( "bazel-bin/tensorflow/tools/pip_package/build_pip_package --nightly_flag {}".format( release_to ) ) return whl
532fc93d5e9b7bc75ed7059dbcb342a2c89089c4
[ "Python", "Text" ]
3
Python
offscale/offregister-tensorflow
0990bdbcd299adc6caadf0cb17e523b5af5e4b8c
b2f946a30b822943a18636e79e4f66693420873f
refs/heads/master
<repo_name>cvorak/stopwatch<file_sep>/assets/js/main.js function format(tim) { var rest = 0; var seconds = 0; var minutes = 0; var seconds_string; var minutes_string; if (tim < 10) { rest = tim; seconds = 0; minutes = 0; } else if ((tim >= 10) && (tim < 600)) { seconds = Math.floor(tim / 10); rest = tim % 10; minutes = 0; } else if ((tim >= 600) && (tim < 36000)) { var temp = tim minutes = Math.floor(tim / 600); temp = temp - minutes * 600; seconds = Math.floor(temp / 10); rest = temp % 10; } if (seconds < 10) { seconds_string = "0" + String(seconds); } else { seconds_string = String(seconds); } if (minutes < 10) { minutes_string = "0" + String(minutes); } else { minutes_string = String(minutes); } return minutes_string + ":" + seconds_string + ":" + String(rest); }; $(document).ready(function() { // global variable that starts and resets by butons var time = 0; var on = false; var ono = "<p>" + "00:00:0" + "</p>"; var timerId = 0; $('#start-stop-button').click(function() { if (on) { on = false; } else { on = true; } if (on) { $('#start-stop-button').text('Stop'); timerId = setInterval(function() { time += 1; var umetak = format(time); var ono = "<p>" + umetak + "</p>"; $('#time').empty(); $('#time').append(ono); } , 100); } if (!(on)) { clearInterval(timerId); $('#start-stop-button').text('Start'); } }); $('#reset-button').click(function() { time = 0; var ono = "<p>" + "00:00:0" + "</p>"; clearInterval(timerId); $('#time').empty(); $('#time').append(ono); $('#start-stop-button').text('Start'); on = false; }); $('#start-stop-button').mousedown(function() { $(this).removeClass('big-shadow'); $(this).addClass('small-shadow'); }); $('#start-stop-button').mouseup(function() { $(this).removeClass('small-shadow'); $(this).addClass('big-shadow'); }); $('#reset-button').mousedown(function() { $(this).removeClass('big-shadow'); $(this).addClass('small-shadow'); }); $('#reset-button').mouseup(function() { $(this).removeClass('small-shadow'); $(this).addClass('big-shadow'); }); });
c4f6e8c78d55412791f6517d49e4086427e87fd5
[ "JavaScript" ]
1
JavaScript
cvorak/stopwatch
b06f961da7b4f49ea38e422b16a3f463a8f398c1
0842525697f3d3b2c39fb3621f46d9b8b2cd96a2
refs/heads/master
<repo_name>benediktvaldez/apis<file_sep>/endpoints/car/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('flight', function() { it("should return an array of objects containing correct fields", function(done) { var fieldsToCheckFor = ["registryNumber","number","factoryNumber","type","subType","color","registeredAt","status","nextCheck","pollution","weight"]; var params = helpers.testRequestParams("/car", { carPlate: "AA031" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request.get(params, resultHandler); }); }); <file_sep>/endpoints/golf/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('golf', function() { // The only thing that changes is the form attribute, so why not just re-use the object var fieldsToCheckFor = ['abbreviation', 'club', 'location']; it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/golf/clubs"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); }); describe('golf', function() { // The only thing that changes is the form attribute, so why not just re-use the object var fieldsToCheckFor = ['time', 'name', 'club', 'handicap']; it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/golf/teetimes", { club: 61 }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); }); <file_sep>/endpoints/company/index.js var request = require('request'); var cheerio = require('cheerio'); var h = require('apis-helpers'); var app = require('../../server'); app.get('/company', function(req, res, next){ var queryString = { nafn: req.query.name || '', heimili: req.query.address || '', kt: req.query.socialnumber || '', vsknr: req.query.vsknr || '' }; request.get({ headers: {'User-Agent': h.browser()}, url: 'http://www.rsk.is/fyrirtaekjaskra/leit', qs: queryString }, function(error, response, body){ if(error || response.statusCode !== 200) { return res.status(500).json({error:'www.rsk.is refuses to respond or give back data'}); } var obj = { results: [] }, $ = cheerio.load(body, {decodeEntities: false}); if($('.resultnote').length === 0){ var tr = $('.boxbody > .nozebra tbody tr').first(); if (tr.length > 0) { var name = $('.boxbody > h1').html(), sn = $('.boxbody > h1').html(); obj.results.push({ name: name.substring(0,name.indexOf('(')-1), sn: sn.substring(sn.length-11,sn.length-1), active: $('p.highlight').text().length === 0 ? 1 : 0, address: tr.find('td').eq(0).text() }); } } else { $('table tr').slice(1).each(function() { var td = $(this).find('td'); var nameRoot = td.eq(1).text(); var felagAfskrad = "(Félag afskráð)"; obj.results.push({ name: nameRoot.replace("\n","").replace(felagAfskrad,"").replace(/^\s\s*/, '').replace(/\s\s*$/, ''), sn: td.eq(0).text(), active: nameRoot.indexOf(felagAfskrad) > -1 ? 0 : 1, address: td.eq(2).text() }); }); } return res.cache(86400).json(obj); }); }); <file_sep>/endpoints/sarschool/index.js var request = require('request'); var app = require('../../server'); var cheerio = require('cheerio'); String.prototype.replaceArray = function(find, replace) { var replaceString = this; for (var i = 0; i < find.length; i++) { replaceString = replaceString.replace(find[i], replace[i]); } return replaceString; }; function pad(n){return n<10 ? '0'+n : n} app.get('/sarschool', function(req, res) { getRequest(function(body) { return res.cache().json({ results: parseList(body) }); }); }); var getRequest = function(callback, url) { url = 'http://skoli.landsbjorg.is/Open/Seminars.aspx?'; var params = { url: url }; request(params, function (error, res, body) { if (error) throw new Error(error); if (res.statusCode != 200) { throw new Error("HTTP error from endpoint, status code " + res.statusCode); } return callback(body); }); }; var parseList = function ( body ) { try { var $ = cheerio.load(body); } catch(error) { throw new Error("Could not parse body"); } var results = []; var tr = $('.rgMasterTable').find('tbody').find('tr'); tr.each(function (i) { var td = $(this).find('td'); // Change start time from d.m.YYYY to YYYY-mm-dd var start_date = td.eq(6).text().trim(); if(start_date=="") { var start_date_final = "n/a"; } else { var sd_split = start_date.split("."); var sd = new Date(sd_split[2],sd_split[1],sd_split[0]); var start_date_final = sd.getFullYear()+"-"+pad(sd.getMonth())+"-"+pad(sd.getDate()); } // Change end time from d.m.YYYY to YYYY-mm-dd var end_date = td.eq(7).text().trim(); if(end_date=="") { var end_date_final = "n/a"; } else { var ed_split = end_date.split("."); var ed = new Date(ed_split[2],ed_split[1],ed_split[0]); var end_date_final = ed.getFullYear()+"-"+pad(ed.getMonth())+"-"+pad(ed.getDate()); } var find = [".", " kr."]; var replace = ["", ""]; results.push({ id: (td.eq(3).text().trim()==""?"":parseFloat(td.eq(3).text().trim())), name: (td.eq(4).text().trim()==""?"":td.eq(4).text().trim()), time_start: start_date_final, time_end: end_date_final, sar_members_only: (td.eq(0).find('img').length > 0 ? 1:0), host: (td.eq(5).find('input').attr('checked') == 'checked' ? 'Squad' : 'Other'), location: (td.eq(8).text().trim()==""?"":td.eq(8).text().trim()), price_regular: (td.eq(9).text().trim()==""?"":parseFloat(td.eq(9).text().trim().replace(".",""))), price_members: (td.eq(10).text().trim()==""?"":parseFloat(td.eq(10).text().trim().replace(".",""))), link: 'http://skoli.landsbjorg.is/Open/Course.aspx?Id=' + td.eq(3).text().trim() }); }); return results; }; <file_sep>/endpoints/currency/index.js var request = require('request'); var moment = require('moment'); var app = require('../../server'); app.get('/currency', function(req, res){ var provider = req.query.provider || 'arion'; var providers = ['m5', 'arion', 'lb', 'borgun']; if (providers.indexOf(provider) >= 0) { return res.redirect(301,'/currency/'+ provider); } else { return res.status(404).json({error:'This provider does not exist',code:2}); } }); <file_sep>/endpoints/frontpage/index.js var app = require('../../server'); app.get('/', function(req, res) { res.redirect(301,'http://docs.apis.is'); }); app.post('/', function(req, res) { res.json({ 'info':'Velkominn á apis.is! Kíktu á docs.apis.is í vafranum þínum fyrir frekari upplýsingar!' }); }); <file_sep>/endpoints/tv/skjarinn.js var request = require('request'); var moment = require('moment'); var parseString = require('xml2js').parseString; var h = require('apis-helpers'); var app = require('../../server'); /* Skjar 1 */ app.get('/tv/:var(skjar1|skjareinn)', function (req, res) { res.status(503).json({error: 'Source page has changed. Scraping needs to be re-implemented'}); return; var url = 'http://www.skjarinn.is/einn/dagskrarupplysingar/?channel_id=7&output_format=xml'; request.get({ headers: {'User-Agent': h.browser()}, url: url }, function (error, response, body) { if(error || response.statusCode !== 200){ return res.status(504).json({error:'skjarinn.is is not responding with the right data'}); } parseSkjar1(function (data) { res.cache(1800).json(200, { results: data }); }, body); }); }); /* Parse feed from Skjarinn */ var parseSkjar1 = function (callback, data) { parseString(data, function (err, result, title) { if (err) throw new Error('Parsing of XML failed. Title '+title); var schedule = []; for (var i = 0; i < result.schedule.service[0].event.length; ++i) { var event = result.schedule.service[0].event[i]; if (moment().add('d',1).startOf('day').hour(6) > moment(event.$['start-time'])) { schedule.push({ title: event.title[0], originalTitle: event['original-title'][0], duration: event.$.duration, description: event.description[0], shortDescription: event['short-description'][0], live: event.live[0] == 'yes' ? true : false, premier: event.rerun[0] == 'yes' ? false : true, startTime: event.$['start-time'], aspectRatio: event['aspect-ratio'][0].size[0], series: { episode: event.episode[0].$.number, series: event.episode[0].$['number-of-episodes'] } }); } } return callback(schedule); }); }; <file_sep>/test/integration/endpoints.js //Turn test mode on process.env.INTEGRATION = true; var fs = require('fs'); var path = require('path'); var fileModule = require('file'); var testDir = 'tests'; var testFileName = 'integration_test.js'; describe('endpoint', function() { it('should load the server and set everything up properly',function(done){ this.timeout(10000); //Server should not take more than 1 sek to boot var app = require(process.cwd() + '/server'); app.on('ready',function(){ fileModule.walkSync('./endpoints', function(dirPath, dirs, files){ if (dirPath.indexOf(testDir) < 0) return; files.forEach(function(file){ if (file != testFileName) return; var fullPath = dirPath + '/' + file; if (!fs.existsSync(fullPath)) return; if (path.extname(fullPath) !== '.js') return; require('../../' + fullPath); }); }); done(); }); }); }); <file_sep>/endpoints/hospital/index.js var request = require('request'); var app = require('../../server'); var cheerio = require('cheerio'); var _ = require('underscore'); app.get('/hospital', function(req, res){ request.get({ url: 'http://www.landspitali.is/' }, function(err, response, body) { if(err || response.statusCode !== 200) return res.status(500).json({error: 'www.landspitali.is refuses to respond or give back data'}); var $; try { $ = cheerio.load( body ); } catch (e) { return res.status(500).json({ error: 'An error occured when parsing the data from landspitali.is' }); } var data = {}; _.each($('.activityNumbers.activityNumbersNew').children('div'), function(elem) { data[elem.attribs.class] = parseInt($(elem).children().eq(1).html()); }); return res.cache(3600).json({ results: [data] }); // Cache for a hour. }); }); <file_sep>/endpoints/metrics/index.js import axios from 'axios'; import app from '../../server'; app.get('/metrics', (req,res,next) => { axios .get('http://localhost:8091/metrics') .then((response) => { res.json(response.data); }) .catch(next); }); <file_sep>/endpoints/golf/index.js var request = require('request'); var app = require('../../server'); var cheerio = require('cheerio'); var _ = require('underscore'); var h = require('apis-helpers'); var getParamFromURL = function(url, param) { // This feels wrong. var params = url.split('?')[1].split('&'); for (var p in params) { var pieces = params[p].split('='); if (pieces[0] === param) { return pieces[1]; } } throw 'Key not found in query parameters'; }; app.get('/golf/teetimes', function(req, res) { var clubId = req.query.club; if(!clubId) { return res.status(431).json({error: 'Please provide a valid club id to lookup'}); } request.get({ rejectUnauthorized: false, // http://stackoverflow.com/a/20091919 headers: {'User-Agent': h.browser()}, url: 'http://mitt.golf.is/pages/rastimar/rastimayfirlit/?club=' + clubId }, function(err, response, html) { if(err || response.statusCode !== 200) { return res.status(500).json({error: 'mitt.golf.is refuses to respond or give back data'}); } var $ = cheerio.load(html); var rows = $('table.teeTimeTable tbody').children(); var time = ''; return res.cache().json({ results: _.map(rows, function(row) { var row = $(row); time = row.children('td.time').html() === null ? time : row.children('td.time').html(); return { time: time, name: $(row.children('td.name')).html(), club: $(row.children('td.club')).html(), handicap: $(row.children('td.handicap')).html() }; })}); }); }); app.get('/golf/clubs', function(req, res) { request.get({ rejectUnauthorized: false, // http://stackoverflow.com/a/20091919 headers: {'User-Agent': h.browser()}, url: 'http://mitt.golf.is/pages/rastimar/' }, function(err, response, html) { if(err || response.statusCode !== 200) return res.status(500).json({error: 'mitt.golf.is refuses to respond or give back data'}); var $ = cheerio.load(html); var rows = $('table.golfTable tr').slice(2); // Skip the first element. return res.cache(3600).json({ results: _.map(rows, function(row) { var row = $(row); return { abbreviation: row.children('td.abbreviation').html(), club: { id: getParamFromURL(row.children('td.club').children('a').attr('href'), 'club'), name: row.children('td.club').children('a').html() }, location: row.children('td.location').html() }; })}); }); }); <file_sep>/endpoints/sarschool/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('sarschool', function() { // The only thing that changes is the form attribute, so why not just re-use the object var fieldsToCheckFor = ["id", "name", "time_start", "time_end", "sar_members_only", "host", "location", "price_regular", "price_members", "link"]; it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/sarschool"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); }); <file_sep>/endpoints/currency/borgun.js var request = require('request'); var parseString = require('xml2js').parseString; var app = require('../../server'); app.get('/currency/borgun', function(req, res) { request.get( {url: 'https://www.borgun.is/currency/Default.aspx?function=all'}, function(err, response, xml){ if(err || response.statusCode !== 200) { return res.status(500).json({ error: 'www.borgun.is refuses to respond or give back data' }); } var currencies = []; parseString(xml, {explicitRoot: false}, function(err, result){ if(err || result.Status[0].ResultCode[0] !== '0'){ return res.status(500).json({ error: 'Unable to parse Borgun data: ' + JSON.stringify(err) }); } for(var i=0; i<result.Rate.length; i++){ var rate = result.Rate[i]; currencies.push({ currencyCode: rate.CurrencyCode[0], currencyDescription: rate.CurrencyDescription[0], currencyRate: parseFloat(rate.CurrencyRate[0]), country: rate.Country[0], countryEnglish: rate.CountryEnglish[0], countryCode: rate.CountryCode[0], rateDate: rate.RateDate[0] }); } return res.json({ results: currencies }); }); } ); }); <file_sep>/endpoints/lottery/index.js var request = require('request'); var app = require('../../server'); var cheerio = require('cheerio'); var getLotto = function (req, res, next) { getLottery(function(err, body) { if (err) { return next(502) } return res.cache(3600).json({ results: parseList(body) }); }); }; app.get('/lottery', getLotto); app.get('/lottery/lotto', getLotto); app.get('/lottery/vikingalotto', function(req, res, next) { getLottery(function(err, body) { if (err) { return next(502) } return res.cache(3600).json({ results: parseList(body) }); }, 'https://games.lotto.is/lottoleikir/urslit/vikingalotto/'); }); app.get('/lottery/eurojackpot', function(req, res, next) { getLottery(function(err, body) { if (err) { return next(502) } return res.cache(3600).json({ results: parseList(body) }); }, 'https://games.lotto.is/lottoleikir/urslit/eurojackpot/'); }); var getLottery = function(callback, url) { url = url || 'https://igvefur.lotto.is/lottoleikir/urslit/lotto/'; var params = { url: url }; request(params, function (error, res, body) { if (error) return callback(error); if (res.statusCode != 200) { return callback(new Error("HTTP error from endpoint, status code " + res.statusCode)); } return callback(null, body); }); }; var parseList = function ( body ) { try { var $ = cheerio.load(body); } catch(error) { throw new Error("Could not parse body"); } var results = []; var tr = $('table').eq(1).find('tr'); tr.each(function (i) { if ( i === 0 ) return; var td = $(this).find('td'); results.push({ date: td.eq(0).text().trim(), lotto: td.eq(1).html().match(/\d{1,2}/g).join(' ').replace(/(\d{1,2})$/, '($1)'), joker: td.eq(2).text().trim(), prize: td.eq(3).text().trim(), link: 'http://lotto.is' + td.eq(4).find('a').attr('href').trim() }); }); return results; }; <file_sep>/endpoints/hljomaholl/index.js var request = require('request'); var cheerio = require('cheerio'); var _ = require('underscore'); var app = require('../../server'); app.get('/hljomaholl', function(req, res, next) { var url = 'http://www.hljomaholl.is/vidburdir'; request.get(url, function(error, response, body) { if (error || response.statusCode !== 200) { return res.status(500).json({ error:'www.hljomaholl.is refuses to respond or give back data' }); } try { var $ = cheerio.load(body); } catch (error) { return res.status(500).json({error:'Could not parse body'}); } var obj = {results: []}; var fields = [ 'date', 'time', 'image', 'title', 'description', 'location', 'buyTicketURL', 'moreInfoURL' ]; try { $('.main-content-body ul').find('li').each(function(key) { var event = {}; var counter = 0; $('.time', this).find('time').each(function(key1) { if (counter === 2) { return false; } var val = $(this).text(); event[fields[key1]] = val; counter++; }); event[fields[2]] = $('img', this).attr('src'); event[fields[3]] = $('.time h1', this).text().trim(); event[fields[4]] = $('p', this).text().trim(); event[fields[5]] = $('.time h2', this).text().trim(); event[fields[6]] = $('.btn-wrapper', this) .find('.btn-green').attr('href') || false; event[fields[7]] = ( 'http://www.hljomaholl.is' + $('.btn-wrapper', this).find('.btn-blue').attr('href') ); obj.results.push(event); }); } catch (error) { return res.status(500).json({error: 'Could not parse event data'}); } return res.json(obj); }); }); <file_sep>/endpoints/static_endpoints/phone.js var phone = function(req, res, next){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.status(410).json({error:"This api endpoint has been closed and it will not be available in the foreseeable future."}); next(); } exports.setup = function(server){ server.post({path: '/phone', version: '1.0.0'}, phone); server.get({path: '/phone', version: '1.0.0'}, phone); server.post({path: '/phone', version: '2.0.0'}, phone); server.get({path: '/phone', version: '2.0.0'}, phone); } <file_sep>/lib/test_helpers.js var assert = require('assert'), config = require('../config'); function assertResults(json, canBeEmpty) { assert(json.results && typeof json.results.length !== "undefined", "Does not contain a 'results' field"); if (!canBeEmpty) { assert(json.results.length > 0, "Results are empty"); } }; function assertPresenceOfFields(fields, arr) { arr.forEach(function(result, i) { fields.forEach(function(field) { assert(typeof result[field] !== "undefined", "Missing field '" + field + "' in result #" + i); }); }); }; /* Asserts that all fields provided are of the expected type (Date is a bit messy, since it will be a string until we actually try to parse it as a Date). */ function assertTypesOfFields(fields, arr) { arr.forEach(function(result, i) { for (var key in fields) { var type = fields[key], value = result[key], constructor = value.constructor; if (type === Date && !Number.isNaN(Date.parse(value))) { constructor = Date; } assert(constructor === type, "Field " + key + " should be " + type.name + ", but is " + constructor.name); } }); }; // always returns the same fields, so we'll just reuse this function for both cases // (I may be going a bit overboard on this) exports.testRequestHandlerForFields = function(done, fieldsToCheckFor, customCallback, canBeEmpty) { return function(err, res, body) { if (err) throw err; var json; try{ json = JSON.parse(body); }catch(e){ throw e; } // Check for the presence of the results property assertResults(json, canBeEmpty); var fieldsIsObject = fieldsToCheckFor.constructor === Object; var fields = fieldsIsObject ? Object.keys(fieldsToCheckFor) : fieldsToCheckFor; if (!canBeEmpty) { // Check for the presence of all expected fields assertPresenceOfFields(fields, json.results); } if (fieldsIsObject) { assertTypesOfFields(fieldsToCheckFor, json.results); } if (customCallback) { customCallback.call(null, json); } done(); }; }; // Generate http request params for a particular endpoint exports.testRequestParams = function(path, form) { return { url: "http://localhost:3101" + path, method: "GET", qs: form, headers: [ "Content-type: application/json" ] }; }; exports.assertPresenceOfFields = assertPresenceOfFields; <file_sep>/endpoints/isbolti/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('isboltinn', function() { it('Should return an array of objects with fixed amount of fields.', function(done) { var fields = ['place','team','gamesPlayed', 'gamesWon','gamesDraw','gamesLost', 'goals','goalDifference','points']; var params = helpers.testRequestParams("/isbolti", {}); var resultHandler = helpers.testRequestHandlerForFields(done, fields); request.get(params, resultHandler); }); }); <file_sep>/Makefile bootstrap: npm install tests: npm test run: npm start <file_sep>/endpoints/flight/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('flight', function() { it("should return an array of objects containing correct fields", function(done) { var fieldsToCheckFor = ["date","flightNumber","airline","to","plannedArrival","realArrival","status"]; var params = helpers.testRequestParams("/flight", { language: "en", type: "departures" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request.get(params, resultHandler); }); }); <file_sep>/endpoints/particulates/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('particulates', function() { // The only thing that changes is the form attribute, so why not just re-use the object var fieldsToCheckFor = ["PM10nuna", "PM10medaltal", "Counter", "Dags", "nanariuppl"]; it.skip("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/particulates"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); }); <file_sep>/endpoints/concerts/index.js var request = require('request'); var cheerio = require('cheerio'); var _ = require('underscore'); var app = require('../../server'); app.get('/concerts', function (req, res, next) { var url = 'http://midi.is/Home/LoadMoreEventsByDate?eventType=Concerts&pageNumber=' var page = req.query.page || 1; request.get(url + page, function (error, response, body) { if (error || response.statusCode !== 200) { return res.status(500).json({ error: 'Something came up when contacting the midi.is server!'}); } var events = JSON.parse(body); var filtered = _.map(events, function(event) { return _.pick(event, "eventDateName", "name", "dateOfShow", "userGroupName", "eventHallName", "imageSource") }); return res.json({ results: filtered }); }); }); <file_sep>/config/index.js var _ = require('underscore'); var env = process.env.NODE_ENV ? process.env.NODE_ENV + '.config' : 'dev.config'; var defaultConfig = require('./default.json'); var envConfig = {}; if (process.env.INTEGRATION){ env = 'integration'; } try { envConfig = require('./' + env + '.json'); } catch (e) { console.log(e.code == 'MODULE_NOT_FOUND' ? 'Please create a dev.config.json file in the config folder' : e); } module.exports = _.extend(defaultConfig, envConfig);<file_sep>/endpoints/weather/index.js /***************************** * Name: Weather API * Author: <NAME> * Created: Sep 2013 */ var request, parseString, h, app, cheerio, Q, xregexp, validTypes, measurements, stationListURL; /** Requires **/ request = require('request'), parseString = require('xml2js').parseString, h = require('apis-helpers'), app = require('../../server'), cheerio = require('cheerio'), xregexp = require('xregexp'); /** Variable initialization **/ /* ids (tegundir textaspáa) */ validTypes = ['2','3','5','6','7','9','10','11','12','14','27','30','31','32','33','34','35','36','37','38','39','42']; /* can later be used to include a readable version of the measurement names*/ measurements = { is: { 'F' : 'Vindhraði (m/s)', 'FX' : 'Mesti vindhraði (m/s)', 'FG' : 'Mesta vindhviða (m/s)', 'D' : 'Vindstefna', 'T' : 'Hiti (°C)', 'W' : 'Veðurlýsing', 'V' : 'Skyggni (km)', 'N' : 'Skýjahula (%)', 'P' : 'Loftþrýstingur (hPa)', 'RH' : 'Rakastig (%)', 'SNC' : 'Lýsing á snjó', 'SND' : 'Snjódýpt', 'SED' : 'Snjólag', 'RTE' : 'Vegahiti (°C)', 'TD' : 'Daggarmark (°C)', 'R' : 'Uppsöfnuð úrkoma (mm/klst) úr sjálfvirkum mælum' }, en: { 'F' : 'Wind speed (m/s)', 'FX' : 'Top wind speed (m/s)', 'FG' : 'Top wind gust (m/s)', 'D' : 'Wind direction', 'T' : 'Air temperature (°C)', 'W' : 'Weather description', 'V' : 'Visibility (km)', 'N' : 'Cloud cover (%)', 'P' : 'Air pressure', 'RH' : 'Humidity (%)', 'SNC' : 'Snow description', 'SND' : 'Snow depth', 'SED' : 'Snow type', 'RTE' : 'Road temperature (°C)', 'TD' : 'Dew limit (°C)', 'R' : 'Cumulative precipitation (mm/h) from automatic measuring units' } }; stationListURL = 'http://www.vedur.is/vedur/stodvar?t=3'; /** Methods **/ /* Fetches the weather data and returns a JS object in a callback */ function getJsonData(url, callback){ request.get({ headers: {'User-Agent': h.browser()}, url: url }, function (error, response, body) { if (error) throw new Error(url + ' did not respond'); parseString(body, function (err, result, title) { callback(result); }); }); } /** Routes **/ /* Root weather handler */ app.get('/weather', function (req, res, next) { return res.json({ results: [ { info: "This is an api for Icelandic weather reports and observations", endpoints: { forecasts: "/weather/forecasts/", observations: "/weather/observations/", texts: "/weather/texts/" }, other: { availableStations: "/weather/getAvailableStations" } } ] }); next(); }); /* Available stations handler */ app.get('/weather/getAvailableStations', function (req, res, next) { request(stationListURL, function (error, response, body) { if (error) throw new Error( stationListURL + ' not responding correctly...' ); var $, idRegex, titleRegex, stations, hrefs; try { $ = cheerio.load( body ); } catch (e) { throw new Error( 'Error loading DOM' ); } idRegex = 'station=(\\d*)' titleRegex = '^(([\\p{L}0-9-]*[\\s-]?)*)\\s-'; stations = []; hrefs = $(".listtable td a:contains('A')"); for (var i = 0; i < hrefs.length; i++) { var elem, idMatch, titleMatch; elem = $(hrefs[i]); // get the station title and id titleMatch = xregexp.cache(titleRegex).exec(elem.attr('title')); idMatch = xregexp.cache(idRegex).exec(elem.attr('href')); if (!idMatch || !titleMatch) { throw new Error( 'Parsing error -- Source is changed' ); } stations.push({name: titleMatch[1], id: idMatch[1]}); }; return res.cache(86400).json({results: stations}); }); }); /* Initial weather handler */ app.get('/weather/:type/:lang?', function (req, res, next) { var lang = req.params.lang; // handle both ';' and ',' between stations and types if(req.query.stations) req.query.stations = req.query.stations.split(',').join(';'); if(req.query.types) req.query.types = req.query.types.split(',').join(';'); // make sure lang is correct if (lang && ['is','en'].indexOf(lang) == -1) { return res.status(400).json({ results: [ { error: "incorrect language -- only 'is' or 'en' allowed" } ] }); } next(); }); /* Forecasts */ app.get('/weather/forecasts/:lang?', function (req, res) { var lang = req.params.lang || 'is', stations = req.query.stations, descriptions = req.query.descriptions === '' || req.query.descriptions === '1' || req.query.descriptions === 'true', url = 'http://xmlweather.vedur.is/?op_w=xml&view=xml&type=forec&lang='+lang+'&ids='+stations+'&params='+Object.keys(measurements.is).join(';'), syntax = '/weather/forecasts[/(is|en)]?stations=<station1(,|;)...>', example = '/weather/forecasts/is?stations=1,422'; if (!stations) { return res.status(400).json({ results: [ { error : 'stations missing', syntax : syntax, example : example, moreInfo : 'http://www.vedur.is/um-vi/vefurinn/xml/' } ] }); }; getJsonData(url, function(forecasts){ // make some nice changes to the object for cleaner JSON forecasts.results = forecasts.forecasts.station; delete forecasts.forecasts.station; delete forecasts.forecasts; h.deArrayfy(forecasts.results); forecasts.results.forEach(function(result){ result.id = result.$.id; result.valid = result.$.valid; delete result.$; if (lang === 'is') { result.forecast.forEach(function(f){ Object.keys(f).forEach(function(m){ f[m] = f[m].replace(/,/g, '.'); }) }) }; }); if (descriptions) { forecasts.descriptions = measurements[lang]; }; return res.cache(300).json(forecasts); }); }); /* Observations */ app.get('/weather/observations/:lang?', function (req, res) { var lang = req.params.lang || 'is', stations = req.query.stations, descriptions = req.query.descriptions === '' || req.query.descriptions === '1' || req.query.descriptions === 'true', time = req.query.time, anytime = req.query.anytime, url = 'http://xmlweather.vedur.is/?op_w=xml&view=xml&type=obs&lang='+lang+'&ids='+stations+'&params='+Object.keys(measurements.is).join(';'), syntax = '/weather/observations[/(is|en)]?stations=<station1(,|;)...>[&time=(1h|3h)][&anytime=(0|1)]', example = '/weather/observations/is?stations=1,422&time=1h&anytime=0]'; if (!stations) { return res.status(400).json({ results: [ { error : 'stations missing', syntax : syntax, example : example, moreInfo : 'http://www.vedur.is/um-vi/vefurinn/xml/' } ] }); }; if (time) { url += '&time=' + time; }; if (anytime) { url += '&anytime=' + anytime; }; getJsonData(url, function(observations){ // make some nice changes to the object for cleaner JSON observations.results = observations.observations.station; delete observations.observations.station; delete observations.observations; h.deArrayfy(observations.results); for (var i = observations.results.length - 1; i >= 0; i--) { var observation = observations.results[i]; observation.id = observation.$.id; observation.valid = observation.$.valid; delete observation.$; // fix decimal if (lang === 'is') { Object.keys(observation).forEach(function(m){ observation[m] = observation[m].replace(/,/g, '.'); }) }; }; if (descriptions) { observations.descriptions = measurements[lang]; }; return res.cache(300).json(observations); }); }); /* Texts */ app.get('/weather/texts/:lang?', function (req, res) { var lang = req.params.lang || 'is', types = req.query.types, url = 'http://xmlweather.vedur.is/?op_w=xml&view=xml&type=txt&lang='+lang+'&ids='+types, syntax = '/weather/texts[/(is|en)]?types=<type1(,|;)...>', example = '/weather/texts/is?types=5,6'; if (!types) { return res.status(400).json({ results: [ { error : 'types missing', syntax : syntax, example : example, validTypes : validTypes, moreInfo : 'http://www.vedur.is/um-vi/vefurinn/xml/' } ] }); }; getJsonData(url, function(texts){ // make some nice changes to the object for cleaner JSON texts.results = texts.texts.text; delete texts.texts.text; delete texts.texts; h.deArrayfy(texts.results); for (var i = texts.results.length - 1; i >= 0; i--) { var text = texts.results[i]; text.id = text.$.id; delete text.$; if (text.content instanceof Object) { delete text.content.br; text.content = text.content._; }; }; return res.cache(300).json(texts); }); }); /* * observation * ids http://www.vedur.is/vedur/stodvar params (mælistærðir) 'F','FX','FG','D','T','W','V','N','P','RH','SNC','SND','SED','RTE','TD','R' time 1h | 3h anytime 0 | 1 * forecast * ids http://www.vedur.is/vedur/stodvar params (mælistærðir) 'F','FX','FG','D','T','W','V','N','P','RH','SNC','SND','SED','RTE','TD','R' * text * ids (svæði) ['2','3','5','6','7','9','10','11','12','14','27','30','31','32','33','34','35','36','37','38','39','42'] */ <file_sep>/endpoints/cyclecounter/index.js var request = require('request'); var parseString = require('xml2js').parseString; var app = require('../../server'); app.get('/cyclecounter', function(req, res){ request.get({ url: 'http://www.bicyclecounter.dk/BicycleCounter/GetCycleInfo?ran=1379500208853&StationId=235&LaneId=0' }, function(err, response, xml) { if(err || response.statusCode !== 200) return res.status(500).json({error: 'www.bicyclecounter.dk refuses to respond or give back data'}); var cyclecounter = []; parseString(xml, { explicitRoot: false }, function(err, result) { cyclecounter.push({ DayCount: result.DayCount[0], YearCount: result.YearCount[0], Time: result.Time[0], Date: result.Date[0], }); return res.json({results: cyclecounter}); }); } ); }); <file_sep>/endpoints/carparks/index.js var request = require('request'); var $ = require('cheerio'); var h = require('apis-helpers'); var app = require('../../server'); app.get('/carparks', function(req, res){ var url = 'http://www.bilastaedasjodur.is/'; request.get({ headers: {'User-Agent': h.browser()}, url: url }, function(error, response, body){ if(error || response.statusCode !== 200) return res.status(500).json({error:'www.bilastaedasjodur.is refuses to respond or give back data'}); try{ var data = $(body); }catch(error){ return res.status(500).json({error:'Could not parse body'}); } var obj = { results: []}; var hus = $('.hus', $(body)); var js = body.match(/LatLng\((.*?)\)/g); function parseCoordinates(str) { try { var Regexp = /(?:^|\s)LatLng.(.*?)\)(?:\s|$)/g; var match = Regexp.exec(str); return match[1].split(', '); }catch(error) { return null; } } for(var i=0; i<hus.length; i++) { var that = hus[i]; var freeSpaces = parseInt($(that).find('.ib.free h1').text()); var totalSpaces = parseInt($(that).find('.ib.total h1').text()); obj.results.push({ name: $(that).find('aside h2').text(), address: $(that).find('h5').text(), parkingSpaces: { free: !isNaN(freeSpaces) ? freeSpaces : null, total: !isNaN(totalSpaces) ? totalSpaces : null }, coordinates: parseCoordinates(js[i]) }); } return res.cache(180).json(obj); }); }); <file_sep>/endpoints/currency/lb.js var request = require('request'); var parseString = require('xml2js').parseString; var app = require('../../server'); app.get('/currency/lb', function(req, res){ // A = Almennt gengi, S = Seðlagengi var type = req.params['type'] || 'A'; request.get({ url: 'http://www.landsbankinn.is/modules/markets/services/XMLGengi.asmx/NyjastaGengiByType?strTegund=' + type }, function(err, response, xml) { if(err || response.statusCode !== 200) return res.status(500).json({error: 'www.landsbankinn.is refuses to respond or give back data'}); var currencies = []; parseString(xml, { explicitRoot: false }, function(err, result) { var arr = result.GjaldmidillRow; for (var i = 0, currency; currency = arr[i]; i++) { currencies.push({ shortName: currency.Mynt[0], longName: currency.Heiti[0], value: parseFloat(currency.Midgengi), askValue: parseFloat(currency.Sala), bidValue: parseFloat(currency.Kaup), changeCur: parseFloat(currency.Breyting[0]), changePer: parseFloat((parseFloat(currency.Breyting) / parseFloat(currency.Midgengi)).toFixed(2)) }); } return res.json({ results: currencies }); }); } ); }); <file_sep>/endpoints/carparks/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('carparks', function() { it("should return an array of objects containing correct fields", function(done) { var fieldsToCheckFor = ["name","address","parkingSpaces","coordinates"]; var params = helpers.testRequestParams("/carparks"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request.get(params, resultHandler); }); }); <file_sep>/endpoints/bus/search.js var app = require('../../server'); app.post('/bus/search', function(req,res){ res.status(404).json({error: 'This api endpoint has been closed temporarily, because Bus.is changed it\'s markup.'}); }); //Old app.get('/bus/search', function(req,res){ res.status(404).json({error: 'This api endpoint has been closed temporarily, because Bus.is changed it\'s markup.'}); }); <file_sep>/endpoints/tv/ruv.js var request = require('request'); var moment = require('moment'); var parseString = require('xml2js').parseString; var h = require('apis-helpers'); var app = require('../../server'); /* RUV */ app.get('/tv/ruv', function (req, res, next) { var url = 'http://muninn.ruv.is/files/xml/ruv/'; if (req.params.date) { if (moment(req.params.date).isValid()) { var date = moment(req.params.date); // Example : http://muninn.ruv.is/files/xml/ruv/2013-06-11/ url += date.format('YYYY-MM-DD'); } } serve(url, res, next); }); /* RUV Ithrottir*/ app.get('/tv/ruvithrottir', function (req, res, next) { var url = 'http://muninn.ruv.is/files/xml/ruvithrottir/'; serve(url, res, next); }); var serve = function(url, res, next) { getFeed(url, function (err, data) { if (err) { console.error(err); return next(502); } res.cache(1800).json({ results: data }); }); }; var getFeed = function(url, callback) { request.get({ headers: {'User-Agent': h.browser()}, url: url }, function (error, response, body) { if (error) return callback(new Error(url + ' did not respond')); parseFeed(callback, body); }); }; /* Parse feeds from RUV */ var parseFeed = function (callback, data) { parseString(data, function (err, result, title) { if (err) return callback(new Error('Parsing of XML failed. Title '+title)); var schedule = []; if (result.schedule.error || !result.schedule.service[0].hasOwnProperty('event')) { return(callback(schedule)); } for (var i = 0; i < result.schedule.service[0].event.length; ++i) { var event = result.schedule.service[0].event[i]; schedule.push({ title: event.title[0], originalTitle: event['original-title'][0], duration: event.$.duration, description: event.description[0], shortDescription: event['short-description'][0], live: event.live[0] == 'yes' ? true : false, premier: event.rerun[0] == 'yes' ? false : true, startTime: event.$['start-time'], aspectRatio: event['aspect-ratio'][0].size[0], series: { episode: event.episode[0].$.number, series: event.episode[0].$['number-of-episodes'] } }); } return callback(null, schedule); }); }; <file_sep>/endpoints/horses/index.js var request = require('request'); var iconv = require('iconv-lite'); var $ = require('cheerio'); var h = require('apis-helpers'); var app = require('../../server'); function query_data(id, name, origin, microchip, callback) { var url = 'http://www.worldfengur.com/freezone_horse.jsp?c=EN'; var headers = { 'User-Agent': h.browser(), 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Content-Type': 'application/x-www-form-urlencoded' }; // Encoding parameters so Icelandic characters will work // Hacking around to get ISO 8859-1 encoded string, pls unhack if you know better way var encoded_name = encodeURIComponent(escape(name)).replace(/%25/g,"%"); var encoded_origin = encodeURIComponent(escape(origin)).replace(/%25/g,"%"); var form_data = ( 'fnr=' + id + '&nafn=' + encoded_name + '&uppruni=' + encoded_origin + '&ormerki=' + microchip + '&leitahnappur=Search+&leita=1' ); request.post({ headers: headers, url: url, body: form_data, encoding: null }, function(error, response, body) { if(error || response.statusCode !== 200) { callback(error, response, ''); } var html_page = iconv.decode(body, 'iso-8859-1'); callback(error, response, html_page); }); } function parse_data(html_page) { var data = $(html_page); // td_elements: // is a list of text strings from all td elements in the returned html_page // we find data from the list by searching for key labels // we assume the next value in the list after a key label is a corresponding value var td_elements = []; data.find('div.complete div table').each(function() { $(this).find('td').each(function() { td_elements.push($(this).text()); }); }); // params: // name is the name of a single param // label is the label used on the webpage for a given param // value is the value of a given param, and null if it wasn't found in td_elements var params = [ {name: 'id', label: 'FEIF ID', value: null}, {name: 'name_and_origin', label: 'Name and origin', value: null}, {name: 'ueln', label: 'UELN', value: null}, {name: 'date_of_birth', label: 'Date of birth', value: null}, {name: 'color_code', label: 'Colour code', value: null}, {name: 'color', label: 'Colour ', value: null}, {name: 'country_located', label: 'Country of current location', value: null}, {name: 'fate', label: 'Fate ', value: null}, {name: 'microchip', label: 'Microchip', value: null}, {name: 'father', label: 'Sire', value: null}, {name: 'mother', label: 'Dam', value: null}, ]; var labels = params.map(function(x){return x['label'];}); // we do the following health checks // - check if label is in td_elements // - make sure the next field doesn't hold one of the labels // - also make sure it isn't '' // Note: we use 'lastIndexOf' because td_elements from the post form are included in td_elements // which are identical to some of our labels, this isn't an issue though because the next // value in td_elements for those elements is always '' for (var i = 0; i < labels.length; i++) { var label_location = td_elements.lastIndexOf(labels[i]); if (label_location !== -1 && labels.lastIndexOf(td_elements[label_location+1]) == -1) { if (td_elements[label_location+1] !== '') { if (i < 9) { // first nine params values are strings params[i]['value'] = td_elements[label_location+1]; } else { // father and mother params are objects // parent strings look like this: '{id} - {name_and_origin}' var parent_info = td_elements[label_location+1].split(' - '); params[i]['value'] = { id: parent_info[0], name_and_origin: parent_info[1] }; } } } } var results = []; if (params[0]['value'] && params[1]['value']) { // here we successfully found id and name of horse // we 'correctly' assume we received a single-record result var result = {}; for (var i = 0; i < params.length; i++) { result[params[i]['name']] = params[i]['value']; } results.push(result); } else { // there is a chance we received a multi-records result // then we have string like 'Number: 2' in td_elements if number of records were 2 // we check if multi-records are in result var multi_records = false; var count_index = -1; for (var i = 0; i < td_elements.length; i++) { if (td_elements[i].indexOf('Number: ') === 0) { multi_records = true; count_index = i; break; } } if (multi_records) { // for multi-records we receive less data for each horse than in single-record result // we get 5 td elements for each horse, explaining the i*5 below // we fish out only id and name for each horse and return list of those var num_records = Number(td_elements[count_index].replace('Number: ','')); for (var i = 0; i < num_records; i++) { var horse_info = td_elements[count_index + 1 + i*5].split(' - '); results.push({ id: horse_info[0], name_and_origin: horse_info[1], }); } } } return results; } function asyncLoop(obj) { // http://stackoverflow.com/a/7654602/2401628 var i = -1; var loop = function() { i++; if (i==obj.length) { obj.callback(); return; } obj.functionToLoop(loop, i); } loop(); // init } app.get('/horses', function(req, res){ var id = req.query.id || ''; var name = req.query.name || ''; var origin = req.query.origin || ''; var microchip = req.query.microchip || ''; if (!id && !(name && origin) && !microchip) { return res.status(400).json({ error:'Please provide at least one of the following: id, name and origin or microchip' }); } query_data(id, name, origin, microchip, function(error, response, html_page) { if (error || response.statusCode !== 200) { return res.status(500).json({ error:'www.worldfengur.com refuses to respond or give back data' }); } var results = parse_data(html_page); if (results.length > 1) { // we receive less data for multi-records, so we do additional query for each result // which we 'correctly' assume returns a single-record result var complete_multi_results = []; asyncLoop({ length: results.length, functionToLoop: function(loop, i) { query_data(results[i]['id'], '', '', '', function(err, res, fields) { var single_result = parse_data(fields)[0]; complete_multi_results.push(single_result); loop(); }); }, callback: function() { return res.cache().json({results: complete_multi_results}); } }); } else { return res.cache().json({results: results}); } }); }); <file_sep>/endpoints/cinema/tests/integration_test.js var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); describe('cinema', function() { // The only thing that changes is the form attribute, so why not just re-use the object var fieldsToCheckFor = ["image", "imdb", "released", "restricted", "showtimes", "title"]; it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/cinema"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); }); describe('cinema theaters', function() { // The only thing that changes is the form attribute, so why not just re-use the object var fieldsToCheckFor = ["image", "name", "location", "movies"]; it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/cinema/theaters"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); });<file_sep>/endpoints/declension/tests/integration_test.js var request = require('request'), assert = require('assert'), helpers = require('../../../lib/test_helpers.js'); describe('declension', function() { it("should return an array of objects containing correct fields", function(done) { var fieldsToCheckFor = ["predicate", "value", "category"]; var params = helpers.testRequestParams("/declension/laugavegur"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request.get(params, resultHandler); }); }); <file_sep>/lib/cache.js var config = require('../config'); var redis = require('./redis'); module.exports = function(){ return function(req,res,next){ if(config.testing || !redis.connected){ res.cache = function(){ return this; } return next(); } var end = res.end, write = res.write, cache = [], key = req.originalUrl; redis.get(key,function(error,reply){ if(error){ console.log('Error in caching layer:',error); return next(); }else if(reply){ res.type('json'); res.send(reply); }else{ res.cache = function(timeout) { if(typeof timeout === 'undefined') timeout = 21600; //Default timeout is 6 hours console.log('INSIDE CACHE') res.write = function(chunk, encoding){ cache.push(chunk) write.call(res,chunk,encoding); } res.end = function(chunk, encoding){ if(chunk) this.write(chunk,encoding); //console.log('Chunk norris:', chunk.toString()) console.log('Expiration is :',timeout); redis.setex(key, timeout , cache.join('')); end.call(res); }; return this; }; return next(); } }) } }<file_sep>/README.md [![Build Status](https://travis-ci.org/apis-is/apis.svg?branch=master)](https://travis-ci.org/apis-is/apis) # [APIs.is](http://apis.is) - Making data pretty since 2012! The purpose of [APIs.is](http://apis.is) is to make data readily available to anyone interested. All data that is delivered through APIs.is is JSON formatted and scraped from open public websites. The code that is running the service is open source under the [MIT licence](https://en.wikipedia.org/wiki/MIT_License). The platform itself is hosted on a load balanced setup by [GreenQloud](http://www.greenqloud.com) to be as antifragile as possible. The hosted service does not store any information, so all data is gathered on runtime and disregarded immediately afterwards. **Don't hesitate to lend a hand - All knowledge and help is much appreciated!** ##Maintainers [@kristjanmik](https://github.com/kristjanmik/) [@benediktvaldez](https://github.com/benediktvaldez/) [@koddsson](https://github.com/koddsson/) [@MiniGod](https://github.com/minigod/) ## Tests Currently there are two types of tests, integration and unit tests. All tests are created using [Mocha](http://visionmedia.github.io/mocha/). To run the integration tests: ```sh $ npm test ``` ## Adding a new Endpoint ### Step by Step 1. View current endpoints for structure and hierarchy. 2. Add a new folder to the `endpoints/` directory with the name of your endpoint. 3. The file will be loaded automatically. Remember to require the server. Bare minimum example endpoint: ```javascript var app = require('../../server'); app.get('/path',function(req,res){ return res.json({}); //Sends out empty json object }); ``` ### Additional requirements Add [integration tests](http://en.wikipedia.org/wiki/Integration_testing) to the endpoint by creating a file called `integration_test.js` inside a `tests/` folder within your endpoint directory. For reference, please take a look at one of the integration tests. Add [documentation](https://github.com/kristjanmik/apis-docs) for your endpoint ### More servers To ensure close to zero downtime, the plan is to start up more workers/servers around the world so that projects relying on this service will not be affected. Want to help out with that? Feel free to send us a [line](mailto:<EMAIL>)! ### Helpful pointers - Endpoints can implement any node module. - Information on how to handle requests and responses can be found [here](http://expressjs.com/api.html). - It is much appreciated that endpoints are thoroughly documented and written with care. - Issues are managed by the [GitHub issue tracker](https://github.com/kristjanmik/apis/issues). - Have fun and eat some cake! (preferrably chocolate, but whatever floats your boat) <file_sep>/endpoints/static_endpoints/help_out.js exports.setup = function(server){ server.post({path: '/help_out', version: '1.0.0'}, helpOut); server.get({path: '/help_out', version: '1.0.0'}, helpOut); server.post({path: '/help', version: '1.0.0'}, helpOut); server.get({path: '/help', version: '1.0.0'}, helpOut); } var helpOut = function(req, res, next){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.status(200).json({message:'Send us mail: <EMAIL> ,thanks for your interest!'}); next(); } <file_sep>/endpoints/earthquake/tests/integration_test.js var request = require('request'), assert = require('assert'), helpers = require('../../../lib/test_helpers.js'); describe('earthquake/is', function() { // Which fields we expect and of which type they should be var fieldsToCheckFor = { "timestamp": Date, "latitude": Number, "longitude": Number, "depth": Number, "size": Number, "quality": Number, "humanReadableLocation": String }; it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/earthquake/is"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); }); describe('earthquake/is/sec', function() { // Which fields we expect and of which type they should be var fieldsToCheckFor = { "timestamp": Date, "latitude": Number, "longitude": Number, "depth": Number, "size": Number, "quality": Number, "humanReadableLocation": String }; it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/earthquake/is"); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); request(params, resultHandler); }); });
8cba8df3a06b71f454d4e37d26fdc662ba56efcf
[ "JavaScript", "Makefile", "Markdown" ]
37
JavaScript
benediktvaldez/apis
9074841294d8e28bb4b9b1f7918ed64708a022d0
d721f9994c6ccd6da358e7900a27f9ff910796af
refs/heads/main
<file_sep>package com.kris.demo2.demo2.restcontroller; import com.kris.demo2.demo2.model.AuthUser; import com.kris.demo2.demo2.repo.UserRepository; import org.springframework.http.HttpStatus; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import java.util.List; @RestController @RequestMapping("/api/user") public class UserRestController { final UserRepository userRepository; public UserRestController(UserRepository userRepository) { this.userRepository = userRepository; } @GetMapping("/all") private List<AuthUser> getAllUsers(){ return userRepository.findAll(); } @PostMapping("/create") private long createAuthUser(@RequestBody AuthUser user) { // private long createAuthUser(HttpEntity<String> httpEntity) throws JsonProcessingException { // System.out.println(httpEntity.getBody()); // AuthUser user = new ObjectMapper().readerFor(AuthUser.class).readValue(httpEntity.getBody()); if(userRepository.findByUserName(user.getUserName()).isEmpty()){ userRepository.save(user); return user.getId(); } throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Username already Exists!!!"); } @DeleteMapping("/delete/{userName}") private void deleteAuthUser(@PathVariable("userName") String userName){ AuthUser user = userRepository.findByUserName(userName).orElseThrow(() -> new UsernameNotFoundException("Not found: " + userName)); userRepository.delete(user); } }<file_sep>//package com.kris.demo2.demo2.converter; // //import com.kris.demo2.demo2.dto.PassengerDto; //import com.kris.demo2.demo2.model.AuthUser; //import com.kris.demo2.demo2.model.Passenger; //import org.springframework.stereotype.Component; // //import java.util.List; //import java.util.stream.Collectors; // //@Component //public class PassengerConverter { // // AuthUser dtoToEntity(PassengerDto passengerDto){ // Passenger passenger = new Passenger(); // AuthUser user = new AuthUser(); // passenger.setName(passengerDto.getName()); // return user; // } // // PassengerDto entityToDto(Passenger passenger){ // PassengerDto passengerDto = new PassengerDto(); // passengerDto.setName(passenger.getName()); // return passengerDto; // } // // List<Passenger> dtoToEntity(List<PassengerDto> passengerDtos){ // return passengerDtos.stream().map(this::dtoToEntity).collect(Collectors.toList()); // } // // List<PassengerDto> entityToDto(List<Passenger> passengers){ // return passengers.stream().map(this::entityToDto).collect(Collectors.toList()); // } //} <file_sep>package com.kris.demo2.demo2.converter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kris.demo2.demo2.model.Location; import javax.persistence.AttributeConverter; public class LocationJsonConverter implements AttributeConverter<Location,String> { @Override public String convertToDatabaseColumn(Location location) { ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(location); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } @Override public Location convertToEntityAttribute(String json) { try { return new ObjectMapper().readerFor(Location.class).readValue(json); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } } <file_sep>"# springboot-online-cab-booking" <file_sep>package com.kris.demo2.demo2.repo; import com.kris.demo2.demo2.model.AuthUser; import com.kris.demo2.demo2.model.Passenger; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface PassengerRepository extends JpaRepository<Passenger,Long> { List<Passenger> findAllByUserIsNotNull(); List<Passenger> findAllByUserUserName(String userName); Optional<Passenger> findByUserUserName(String userName); } <file_sep>package com.kris.demo2.demo2.restcontroller; import com.kris.demo2.demo2.dto.LocationDto; import com.kris.demo2.demo2.model.AuthUser; import com.kris.demo2.demo2.model.Driver; import com.kris.demo2.demo2.repo.DriverRepository; import com.kris.demo2.demo2.repo.UserRepository; import org.springframework.http.HttpStatus; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import java.util.List; import java.util.stream.Collectors; import static com.kris.demo2.demo2.converter.LocationDtoConverter.entityToLocation; import static com.kris.demo2.demo2.converter.LocationDtoConverter.locationToEntity; @CrossOrigin @RestController @RequestMapping("/api/driver") public class DriverRestController { final UserRepository userRepository; final DriverRepository driverRepository; public DriverRestController(DriverRepository driverRepository, UserRepository userRepository) { this.driverRepository = driverRepository; this.userRepository = userRepository; } @GetMapping("/all") private List<AuthUser> getAllDrivers(){ return driverRepository.findAllByUserIsNotNull().stream() .map(Driver::getUser).collect(Collectors.toList()); } @GetMapping("/{userName}") private AuthUser getDriversByUsername(@PathVariable("userName") String userName){ Driver driver = driverRepository.findByUserUserName(userName).orElseThrow(() -> new UsernameNotFoundException("Not found: " + userName)); return driver.getUser(); } @PostMapping("/create") private long createDriver(@RequestBody AuthUser user){ // System.out.println(driver.toString()); if(userRepository.findByUserName(user.getUserName()).isEmpty()){ userRepository.save(user); return user.getId(); } throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Username already Exists!!!"); } @GetMapping("/{userName}/location") private LocationDto getLocationByUserName(@PathVariable("userName") String userName){ Driver driver = driverRepository.findByUserUserName(userName).orElseThrow(() -> new UsernameNotFoundException("Username Not found!!! ")); return entityToLocation(driver.getLocation()); } @PutMapping("/{userName}/location") private boolean putLocationByUserName(@PathVariable("userName") String userName,@RequestBody LocationDto locationDto){ Driver driver = driverRepository.findByUserUserName(userName).orElseThrow(() -> new UsernameNotFoundException("Username Not found!!! ")); driver.setLocation(locationToEntity(locationDto)); driverRepository.save(driver); return true; } } <file_sep>package com.kris.demo2.demo2.model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.kris.demo2.demo2.converter.LocationJsonConverter; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Entity @JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="uuid") public class Driver { @Id @GeneratedValue(strategy = GenerationType.AUTO) private UUID uuid; private String name; @OneToOne(mappedBy = "driver") private AuthUser user; @OneToOne(targetEntity = Cab.class ,cascade = CascadeType.ALL) @JoinColumn(name = "cab_uuid", referencedColumnName = "uuid") private Cab cab; @Convert(converter = LocationJsonConverter.class) private Location location; @OneToMany(mappedBy = "driver") private List<Journey> journeyList = new ArrayList<>(); public Driver() { } public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public AuthUser getUser() { return user; } public void setUser(AuthUser user) { this.user = user; } public Cab getCab() { return cab; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public void setCab(Cab cab) { this.cab = cab; } public List<Journey> getJourneyList() { return journeyList; } public void setJourneyList(List<Journey> journeyList) { this.journeyList = journeyList; } } <file_sep>var detail = document.getElementById("detail"); var booking = document.getElementById("booking"); var originName = document.getElementById("origin"); var destinationName = document.getElementById("destination"); async function getLink(value) { let link = `https://nominatim.openstreetmap.org/search.php?q=${value}&polygon_geojson=1&format=jsonv2`; await fetch(link) .then(data => data.json()) .then(data => { lat = data[0].lat lng = data[0].lon }); return {lat,lng}; } async function getDetails(value1,value2) { var origin,destination; await getLink(value1) .then(data=> origin=data); await getLink(value2) .then(data=> destination=data); return `<iframe id="map_journey" src="https://www.google.com/maps/embed?pb= !1m24!1m12!1m3!1d945263.6526381834!2d87.51985212440944!3d22. 26146273206699!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m9!3e0!4m3!3m2!1d ${origin.lat}!2d${origin.lng}!4m3!3m2!1d${destination.lat}!2d${destination.lng} !5e0!3m2!1sen!2sin!4v1615145602931!5m2!1sen!2sin" style="border:0;" allowfullscreen="" loading="lazy"></iframe>`; } getDetails(originName.value,destinationName.value).then(data=>detail.innerHTML=data); booking.onclick = ()=>{getDetails(originName.value,destinationName.value).then(data=>detail.innerHTML=data);} <file_sep>package com.kris.demo2.demo2.repo; import com.kris.demo2.demo2.model.Driver; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Arrays; import java.util.List; import java.util.Optional; public interface DriverRepository extends JpaRepository<Driver,Long> { Optional<Driver> findByUserUserName(String userName); List<Driver> findAllByUserIsNotNull(); } <file_sep>package com.kris.demo2.demo2.dto; public class AuthUserDto { private String userName; private String password; private String email; private String phoneNumber; private String address; } <file_sep>package com.kris.demo2.demo2.repo; import com.kris.demo2.demo2.model.Journey; import org.springframework.data.jpa.repository.JpaRepository; import java.util.UUID; public interface JourneyRepository extends JpaRepository<Journey, UUID> { } <file_sep>package com.kris.demo2.demo2.restcontroller; import com.kris.demo2.demo2.model.Cab; import com.kris.demo2.demo2.repo.CabRepository; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/api/cab") public class CabRestController { final CabRepository cabRepository; public CabRestController(CabRepository cabRepository) { this.cabRepository = cabRepository; } @GetMapping("/all") private List<Cab> getAllCabs(){ // List<Cab> cabs = new ArrayList<Cab>(); // cabRepository.findAll().forEach(cab1 -> cabs.add(cab1)); return cabRepository.findAll(); } } <file_sep>// var map = document.getElementById("mapid"); var booking = document.getElementById("booking"); var originName = document.getElementById("origin"); var destinationName = document.getElementById("destination"); function putLocation(){ if(userlocation) { document.getElementById("loclat").value = userlocation.lat; document.getElementById("loclng").value = userlocation.lng; document.getElementById("locput").submit(); } } var userlocation; // fetch("http://6d63914df1e9.ngrok.io/api/passenger/passenger2/location") // .then(response => response.json()) // .then(data => destinationLocation=data); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { console.log("Geolocation is not supported by this browser."); } } function showPosition(position) { userlocation = { lat: position.coords.latitude, lng: position.coords.longitude } console.log(userlocation); } getLocation(); function putLocation(){ if(userlocation) { document.getElementById("loclat").value = userlocation.lat; document.getElementById("loclng").value = userlocation.lng; document.getElementById("locput").submit(); } } async function getLink(value) { let link = `https://nominatim.openstreetmap.org/search.php?q=${value}&polygon_geojson=1&format=jsonv2`; await fetch(link) .then(data => data.json()) .then(data => { lat = data[0].lat lng = data[0].lon }); return {lat,lng}; } async function getDetails(value1,value2) { var origin,destination; await getLink(value1) .then(data=> origin=data); await getLink(value2) .then(data=> destination=data); mapCreate(JSON.parse(document.querySelector("#myLocation").innerText),destination); // return {origin,destination}; } // getDetails(originName.value,destinationName.value).then(data=>data); booking.onclick = ()=>{getDetails(originName.value,destinationName.value).then(data=>data);} var mymap=0; function mapCreate(origin,destination){ if(mymap) mymap.remove(); mymap= L.map('mapid'); mymap.setView([(origin.lat/2 + destination.lat/2),(origin.lng/2 + destination.lng/2)],8); L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=<KEY>', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', maxZoom: 18, id: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1, accessToken: 'your.mapbox.access.token' }).addTo(mymap); let bookedDriverLoc=nearestCab(); var circle = L.circle([bookedDriverLoc.lat,bookedDriverLoc.lng], { color: '#6f8', fillColor: '#6f8', fillOpacity: 0.5, radius: 500 }).addTo(mymap); L.Routing.control({ waypoints: [ L.latLng(bookedDriverLoc.lat,bookedDriverLoc.lng), L.latLng(origin.lat,origin.lng), L.latLng(destination.lat,destination.lng) ] }).addTo(mymap); var driverIcon = L.icon({ iconUrl: 'https://images.vexels.com/media/users/3/154385/isolated/preview/184aacae8933089983daa66c9f2c037b-compact-car-top-view-silhouette-by-vexels.png', iconSize: [50, 50], iconAnchor: [20, 20] }); var userIcon = L.icon({ iconUrl: 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/d8/Person_icon_BLACK-01.svg/962px-Person_icon_BLACK-01.svg.png', iconSize: [50, 50], iconAnchor: [20, 20] }); function addItemToMap(){ JSON.parse(document.querySelector("#allDrivers").innerText).forEach(driver => { L.marker([driver.location.lat,driver.location.lng], {icon: driverIcon}).addTo(mymap); }); L.marker([origin.lat,origin.lng], {icon: userIcon}).addTo(mymap); } function nearestCab(){ let driverdistance=10000; let driverLocation,driverName; JSON.parse(document.querySelector("#allDrivers").innerText).forEach(driver => { if(driverdistance>driver.distanceFromUser){ driverLocation=driver.location; driverdistance=driver.distanceFromUser; driverName=driver.userName; } }); console.log(driverName); return driverLocation; } addItemToMap(); // getDistance([origin.lat,origin.lng], [destination.lat,destination.lng]) } <file_sep>package com.kris.demo2.demo2.dto; import com.kris.demo2.demo2.model.AuthUser; import com.kris.demo2.demo2.model.Cab; import com.kris.demo2.demo2.model.Driver; import com.kris.demo2.demo2.model.Location; public class DriverCreateDto { private String name; private String userName; private String password; private String email; private String phoneNumber; private String address; private String cabName; private String cabModelNumber; private Integer cabTotalSeats; private double lat; private double lng; public DriverCreateDto() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCabName() { return cabName; } public void setCabName(String cabName) { this.cabName = cabName; } public String getCabModelNumber() { return cabModelNumber; } public void setCabModelNumber(String cabModelNumber) { this.cabModelNumber = cabModelNumber; } public Integer getCabTotalSeats() { return cabTotalSeats; } public void setCabTotalSeats(Integer cabTotalSeats) { this.cabTotalSeats = cabTotalSeats; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public AuthUser getUser(){ AuthUser user = new AuthUser(); Driver driver = new Driver(); Cab cab = new Cab(); cab.setName(cabName); cab.setModelNumber(cabModelNumber); cab.setTotalSeats(cabTotalSeats); driver.setName(name); driver.setCab(cab); driver.setLocation(new Location(lat,lng)); user.setDriver(driver); user.setUserName(userName); user.setPassword(<PASSWORD>); user.setEmail(email); user.setPhoneNumber(phoneNumber); user.setAddress(address); return user; } } <file_sep>package com.kris.demo2.demo2.repo; import com.kris.demo2.demo2.model.Cab; import org.springframework.data.jpa.repository.JpaRepository; import java.util.UUID; public interface CabRepository extends JpaRepository<Cab, UUID> { } <file_sep>package com.kris.demo2.demo2.dto; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kris.demo2.demo2.model.Location; public class DriverGetDto { private String name; private String userName; private String phoneNumber; private Location location; private String cabModelNumber; private int cabTotalSeats; private double distanceFromUser; public DriverGetDto() { } public DriverGetDto(String name, String userName, String phoneNumber, Location location, String cabModelNumber, int cabTotalSeats, double distanceFromUser) { this.name = name; this.userName = userName; this.phoneNumber = phoneNumber; this.location = location; this.cabModelNumber = cabModelNumber; this.cabTotalSeats = cabTotalSeats; this.distanceFromUser = distanceFromUser; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public String getCabModelNumber() { return cabModelNumber; } public void setCabModelNumber(String cabModelNumber) { this.cabModelNumber = cabModelNumber; } public int getCabTotalSeats() { return cabTotalSeats; } public void setCabTotalSeats(int cabTotalSeats) { this.cabTotalSeats = cabTotalSeats; } public double getDistanceFromUser() { return distanceFromUser; } public void setDistanceFromUser(double distanceFromUser) { this.distanceFromUser = distanceFromUser; } @Override public String toString() { ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); } return "DriverGetDto{" + "name='" + name + '\'' + ", userName='" + userName + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", location=" + location + ", cabModelNumber='" + cabModelNumber + '\'' + ", cabTotalSeats=" + cabTotalSeats + '}'; } }
5cb51f1354eda4ee71bdc97f78d8007399aad435
[ "Markdown", "Java", "JavaScript" ]
16
Java
krishnendu/springboot-online-cab-booking
370f0c4d6159d94925a80327681bcc1dbab4dd66
6f7582c43f411e3ae2d1fcc9fb6db88c2b532474
refs/heads/master
<repo_name>Crateral/invincibleprogram<file_sep>/src/app/models/clase.model.ts export class Clase { constructor( public horaInicio: string, public horaFinal: string, public fecha: string, public descripcion: string, public coach: string, public wod: string, public cupo?: number, public estado?: string, public _id?: string ) { } }<file_sep>/src/app/services/clase/clase.service.ts import { Injectable } from '@angular/core'; import { URL_SERVICIOS } from 'src/app/config/config'; import { HttpClient } from '@angular/common/http'; import 'rxjs/add/operator/map'; import swal from 'sweetalert'; import { Clase } from '../../models/clase.model'; @Injectable({ providedIn: 'root' }) export class ClaseService { token: string; constructor(public http: HttpClient) { this.cargarStorage(); } cargarStorage(){ if(localStorage.getItem('token')){ this.token = localStorage.getItem('token'); }else{ this.token = ''; } } cargarClases(fechaIni: string, fechaFin: string) { let url = URL_SERVICIOS + '/busqueda/clase/' + fechaIni + '/' + fechaFin; return this.http.get(url); } cargarClasePorFecha(fechaIni: string, hora: string){ let url = URL_SERVICIOS + '/busqueda/clase/dia/' + new Date(fechaIni).toISOString() + '/' + hora; return this.http.get(url); } crearClase(clase: Clase){ this.cargarStorage(); let url = URL_SERVICIOS + '/clase' + '?token=' + this.token; return this.http.post(url, clase) .map((resp: any) =>{ swal('Clase creada correctamente', '', 'success'); return resp.clase; }); } actualizarClase(clase: Clase){ this.cargarStorage(); let url = URL_SERVICIOS + '/clase/' + clase._id + '?token=' + this.token; return this.http.put(url, clase).map((resp: any) =>{ return resp; }); } borrarClase(clase: Clase){ this.cargarStorage(); let url = URL_SERVICIOS + '/clase/' + clase._id + '?token=' + this.token; return this.http.delete(url).map((resp: any) =>{ swal('Clase eliminada', '', 'success'); return true; }); } } <file_sep>/src/app/services/reserva/reserva.service.ts import { Injectable } from '@angular/core'; import { URL_SERVICIOS } from 'src/app/config/config'; import { HttpClient } from '@angular/common/http'; import 'rxjs/add/operator/map'; import swal from 'sweetalert'; import { Reserva } from 'src/app/models/reserva.model'; @Injectable({ providedIn: 'root' }) export class ReservaService { token: string; constructor(public http: HttpClient) { this.cargarStorage(); } cargarReservasPorFecha(fecha: string) { let url = URL_SERVICIOS + '/busqueda/reserva/' + fecha; console.log(url); return this.http.get(url); } crearReserva(reserva: Reserva){ this.cargarStorage(); let url = URL_SERVICIOS + '/reserva' + '?token=' + this.token; return this.http.post(url, reserva) .map((resp: any) =>{ swal('Reserva creada correctamente', '', 'success'); return resp; }); } borrarReserva(reserva: Reserva){ this.cargarStorage(); let url = URL_SERVICIOS + '/reserva/' + reserva._id + '?token=' + this.token; return this.http.delete(url).map((resp: any) =>{ swal('Reserva cancelada', '', 'success'); return resp; }); } cargarStorage(){ if(localStorage.getItem('token')){ this.token = localStorage.getItem('token'); }else{ this.token = ''; } } consultarReservaPorIds(idClase: string, idUsuario: string){ let url = URL_SERVICIOS + '/busqueda/reserva/ids/' + idClase + '/' + idUsuario; return this.http.get(url) .map((resp: any) =>{ return resp.reserva; }); } consultarReservasPorUsuario(idUsuario: string){ let url = URL_SERVICIOS + '/busqueda/reserva/usuario/' + idUsuario; console.log(url); return this.http.get(url) .map((resp: any) =>{ return resp; }); } } <file_sep>/src/app/components/modals/modalClaseUsuario/modalClaseUsuario.component.ts import { Component, OnInit } from '@angular/core'; import { ModalClaseUsuarioService } from './modalClaseUsuario.service'; @Component({ selector: 'app-modal-clase-usuario', templateUrl: './modalClaseUsuario.component.html', styles: [] }) export class ModalClaseUsuarioComponent implements OnInit { constructor(public _modalService: ModalClaseUsuarioService) { } ngOnInit() { } } <file_sep>/src/app/pages/reservas/reservas.component.ts import { Component, OnInit } from '@angular/core'; import { ReservaService } from '../../services/reserva/reserva.service'; import { Reserva } from '../../models/reserva.model'; import { Hora } from 'src/app/models/hora.model'; import { HoraService } from 'src/app/services/hora/hora.service'; import { ModalReservaAdmService } from '../../components/modals/modalReservaAdm/modalReservaAdm.service'; import { ModalReservaAdmCrearService } from '../../components/modals/modalReservaAdm/modalReservaAdmCrear.service'; import { ClaseService } from '../../services/clase/clase.service'; import { Clase } from 'src/app/models/clase.model'; import { UsuarioService } from '../../services/usuario/usuario.service'; declare function init_plugins(); @Component({ selector: 'app-reservas', templateUrl: './reservas.component.html', styles: [] }) export class ReservasComponent implements OnInit { DIAS = [ {id: 1, name: 'Lunes', fecha: ''}, {id: 2, name: 'Martes', fecha: ''}, {id: 3, name: 'Miercoles', fecha: ''}, {id: 4, name: 'Jueves', fecha: ''}, {id: 5, name: 'Viernes', fecha: ''}, {id: 6, name: 'Sabado', fecha: ''} ]; id: number = 1; fecha = new Date(); clase: Clase; clases: Clase[]; diaActual: number; reservas: Reserva[] = new Array(); reservas6: Reserva[] = new Array(); reservas7: Reserva[] = new Array(); reservas8: Reserva[] = new Array(); reservas9: Reserva[] = new Array(); reservas10: Reserva[] = new Array(); reservas16: Reserva[] = new Array(); reservas17: Reserva[] = new Array(); reservas18: Reserva[] = new Array(); reservas19: Reserva[] = new Array(); reservas20: Reserva[] = new Array(); reservas830: Reserva[] = new Array(); reservas930: Reserva[] = new Array(); reservas1030: Reserva[] = new Array(); fechaInicial: number; fechaFinal: number; horas: Hora[] = []; constructor(public _reservaService: ReservaService, public _horaService: HoraService, public _modalService: ModalReservaAdmService, public _modalCrearService: ModalReservaAdmCrearService, public _claseService: ClaseService, public _usuarioService: UsuarioService) { } ngOnInit() { init_plugins(); this._usuarioService.paginaActual = 'Administrar Reservas'; let fechaTmp =this.obtenerFechaActual(); this.calcularFechas(); this.cargarHoras(); this.cargarClases(); for (const dia of this.DIAS) { if(dia.fecha === fechaTmp){ console.log(dia.id); this.obtenerReservasPorFecha(dia.id, fechaTmp); this.diaActual = dia.id; break; } } this._modalCrearService.notificacion.subscribe( (resp: any) => { this.calcularFechas(); this.cargarHoras(); this.cargarClases(); let fecha = resp.fechaReserva; for (const dia of this.DIAS) { if(new Date(dia.fecha).toISOString() === fecha){ this.obtenerReservasPorFecha(dia.id, fecha); this.diaActual = dia.id; break; } } }); this._modalService.notificacion.subscribe((resp: any) => { this.calcularFechas(); this.cargarHoras(); this.cargarClases(); let fecha = resp.reserva.fechaReserva; for (const dia of this.DIAS) { if(new Date(dia.fecha).toISOString() === fecha){ this.obtenerReservasPorFecha(dia.id, fecha); this.diaActual = dia.id; break; } } }); } obtenerReservasPorFecha(id: number, fecha: string){ this._reservaService.cargarReservasPorFecha(fecha) .subscribe((resp: any) =>{ this.reservas = resp.reservas; this.agruparReservasPorHora(this.reservas); }); } monstrarTab(id){ if(this.id === id){ return true; } return false; } calcularFechas(){ let lunes = new Date(); let martes = new Date(); let miercoles = new Date(); let jueves = new Date(); let viernes = new Date(); let sabado = new Date(); if(new Date().getDay() === 1){ console.log('LUNES'); let fechaTempFin = new Date(); this.fechaInicial = new Date().getDate(); fechaTempFin.setDate(new Date().getDate() + 5); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear()); martes.setDate(new Date().getDate() + 1); miercoles.setDate(new Date().getDate() + 2); jueves.setDate(new Date().getDate() + 3); viernes.setDate(new Date().getDate() + 4); sabado.setDate(new Date().getDate() + 5); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 2){ console.log('MARTES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 1); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 4); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 1); miercoles.setDate(new Date().getDate() + 1); jueves.setDate(new Date().getDate() + 2); viernes.setDate(new Date().getDate() + 3); sabado.setDate(new Date().getDate() + 4); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 3){ console.log('MIERCOLES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(fechaTempIni.getDate() - 2); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(fechaTempIni.getDate() + 5); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 2); martes.setDate(new Date().getDate() - 1); jueves.setDate(new Date().getDate() + 1); viernes.setDate(new Date().getDate() + 2); sabado.setDate(new Date().getDate() + 3); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 4){ console.log('JUEVES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 3); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 2); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 3); martes.setDate(new Date().getDate() - 2); miercoles.setDate(new Date().getDate() - 1); viernes.setDate(new Date().getDate() + 1); sabado.setDate(new Date().getDate() + 2); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 5){ console.log('VIERNES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 4); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 1); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 4); martes.setDate(new Date().getDate() - 3); miercoles.setDate(new Date().getDate() - 2); jueves.setDate(new Date().getDate() - 1); sabado.setDate(new Date().getDate() + 1); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 6){ console.log('SABADO'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 5); this.fechaInicial = fechaTempIni.getDate(); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 5); martes.setDate(new Date().getDate() - 4); miercoles.setDate(new Date().getDate() - 3); jueves.setDate(new Date().getDate() - 2); viernes.setDate(new Date().getDate() - 1); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 0){ console.log('DOMINGO'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() + 1); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 6); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() + 1); martes.setDate(new Date().getDate() + 2); miercoles.setDate(new Date().getDate() + 3); jueves.setDate(new Date().getDate() + 4); viernes.setDate(new Date().getDate() + 5); sabado.setDate(new Date().getDate() + 6); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } } cargarHoras(){ this._horaService.cargarHoras() .subscribe((resp: any) =>{ this.horas = resp.horas; }); } cargarFechaEnDia(fechas: any[]){ for (let i = 0; i < this.DIAS.length; i++) { if(fechas[i].mes <= 9){ if(fechas[i].dia <= 9){ this.DIAS[i].fecha = fechas[i].anio + '-' + 0+fechas[i].mes + '-' + 0+fechas[i].dia; }else{ this.DIAS[i].fecha = fechas[i].anio + '-' + 0+fechas[i].mes + '-' + fechas[i].dia; } }else{ if(fechas[i].dia <= 9){ this.DIAS[i].fecha = fechas[i].anio + '-' + fechas[i].mes + '-' + 0+fechas[i].dia; }else{ this.DIAS[i].fecha = fechas[i].anio + '-' + fechas[i].mes + '-' + fechas[i].dia; } } } } agruparReservasPorHora(reservas: Reserva[], horaInicio?: string){ let numeroReserva: number = 0; this.reservas6 = new Array(); this.reservas7 = new Array(); this.reservas8 = new Array(); this.reservas9 = new Array(); this.reservas10 = new Array(); this.reservas16 = new Array(); this.reservas17 = new Array(); this.reservas18 = new Array(); this.reservas19 = new Array(); this.reservas20 = new Array(); this.reservas830 = new Array(); this.reservas930 = new Array(); this.reservas1030 = new Array(); //console.log(reservas); for (const reserva of reservas) { if (reserva.clase.horaInicio === horaInicio) { this.reservas6.push(reserva); numeroReserva = this.reservas6.length; } else if (reserva.clase.horaInicio === horaInicio){ this.reservas7.push(reserva); numeroReserva = this.reservas7.length; } else if (reserva.clase.horaInicio === horaInicio){ this.reservas8.push(reserva); numeroReserva = this.reservas8.length; } else if (reserva.clase.horaInicio === horaInicio){ this.reservas9.push(reserva); numeroReserva = this.reservas9.length; } else { numeroReserva = 0; } } return numeroReserva; } enviarReservas(reservas: Reserva[], horaInicio?: string){ let reservaFinal = new Array(); for (const reserva of reservas) { if (reserva.clase.horaInicio === horaInicio) { reservaFinal.push(reserva); } } return reservaFinal; } cargarClases() { this._claseService.cargarClases(this.DIAS[0].fecha, this.DIAS[5].fecha) .subscribe((resp: any) =>{ console.log(this.DIAS[0].fecha, this.DIAS[5].fecha); this.clases = resp.clases; }); } buscarClase(horaInicio: string, fecha: string){ let fechaTmp = new Date(fecha).toISOString(); for (const clase of this.clases) { if(clase.horaInicio === horaInicio && clase.fecha === fechaTmp){ this.clase = clase; break; }else{ this.clase = new Clase(null, null, null, null, null, null); } } return this.clase; } obtenerFechaActual(){ let fecha; if(this.fecha.getMonth() < 10){ if(this.fecha.getDate() < 10){ fecha = this.fecha.getFullYear() + '-' + 0 + (this.fecha.getMonth() + 1) + '-' + 0 + this.fecha.getDate(); return fecha; }else{ fecha = this.fecha.getFullYear() + '-' + 0 + (this.fecha.getMonth() + 1) + '-' + this.fecha.getDate(); return fecha; } }else{ if(this.fecha.getDate() < 10){ fecha = this.fecha.getFullYear() + '-' + (this.fecha.getMonth() + 1) + '-' + 0 + this.fecha.getDate(); return fecha; }else{ fecha = this.fecha.getFullYear() + '-' + (this.fecha.getMonth() + 1) + '-' + this.fecha.getDate(); return fecha; } } } } <file_sep>/src/app/pages/pages.routes.ts import { RouterModule, Routes } from '@angular/router'; import { PagesComponent } from './pages.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { ProgressComponent } from './progress/progress.component'; import { Graficas1Component } from './graficas1/graficas1.component'; import { RegisterComponent } from './register/register.component'; import { LoginGuardGuard } from '../services/guards/login-guard.guard'; import { ProfileComponent } from './profile/profile.component'; import { PlanesComponent } from './planes/planes.component'; import { ClasesComponent } from './clases/clases.component'; import { ReservasComponent } from './reservas/reservas.component'; import { ReservasUsuarioComponent } from './reservasUsuario/reservasUsuario.component'; import { ReservasCoachComponent } from './reservasCoach/reservasCoach.component'; import { PlanUsuarioComponent } from './planUsuario/planUsuario.component'; const pagesRoutes: Routes = [ { path: '', component: PagesComponent, canActivate: [ LoginGuardGuard ], children: [ { path: 'dashboard', component: DashboardComponent }, { path: 'progress', component: ProgressComponent }, { path: 'graficas1', component: Graficas1Component }, { path: 'perfil', component: ProfileComponent, data: {titulo: 'Perfil de usuario'}}, { path: 'administrarUsuarios', component: RegisterComponent, data: {titulo: 'Administacion de usuarios'} }, { path: 'administrarPlanes', component: PlanesComponent, data: {titulo: 'Administracion de planes'}}, { path: 'administrarClases', component: ClasesComponent, data: {titulo: 'Administracion de clases'}}, { path: 'administrarReservas', component: ReservasComponent, data: {titulo: 'Administracion de reservas'}}, { path: 'reservasUsuarios', component: ReservasUsuarioComponent, data: {titulo: 'Clases'}}, { path: 'reservasCoach', component: ReservasCoachComponent, data: {titulo: 'Reservas'}}, { path: 'planUsuario', component: PlanUsuarioComponent, data: {titulo: 'Plan'}}, { path: '', redirectTo: '/dashboard', pathMatch: 'full'} ] }, ]; export const PAGES_ROUTES = RouterModule.forChild( pagesRoutes ); <file_sep>/src/app/components/modals/modalPlan/modalPlan.component.ts import { Component, OnInit, EventEmitter } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { PlanService } from '../../../services/plan/plan.service'; import { ModalPlanService } from './modalPlan.service'; import { Plan } from 'src/app/models/plan.model'; @Component({ selector: 'app-modal-plan', templateUrl: './modalPlan.component.html', styles: [] }) export class ModalPlanComponent implements OnInit { formaC: FormGroup; constructor( public _planService: PlanService, public _modalService: ModalPlanService ) { } ngOnInit() { this.formaC = new FormGroup({ nombre: new FormControl(null, Validators.required), valor: new FormControl(null, Validators.required), descripcion: new FormControl(null, null) }); } actualizarPlan(){ let nuevoNombre: string; let nuevoValor: number; let nuevaDescripcion: string; if (this.formaC.value.nombre){ nuevoNombre = this.formaC.value.nombre; }else{ nuevoNombre = this._modalService.plan.nombre; } if (this.formaC.value.valor){ nuevoValor = this.formaC.value.valor; }else{ nuevoValor = this._modalService.plan.valor; } if(this.formaC.value.descripcion){ nuevaDescripcion = this.formaC.value.descripcion; }else{ nuevaDescripcion = this._modalService.plan.descripcion; } let plan = new Plan(nuevoNombre, nuevoValor, nuevaDescripcion); plan._id = this._modalService.plan._id; this._planService.actualizarPlan(plan).subscribe(resp =>{ this._modalService.notificacion.emit(resp); }); this._modalService.ocultarModal(); } } <file_sep>/src/app/services/hora/hora.service.ts import { Injectable, OnInit } from '@angular/core'; import { Hora } from '../../models/hora.model'; import { HttpClient } from '@angular/common/http'; import { URL_SERVICIOS } from '../../config/config'; import 'rxjs/add/operator/map'; import swal from 'sweetalert'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class HoraService { constructor(public http: HttpClient, public ruter: Router) { } cargarHoras() { let url = URL_SERVICIOS + '/hora/'; return this.http.get(url); } } <file_sep>/src/app/components/modals/modalReservaAdm/modalReservaAdmCrear.component.ts import { Component, OnInit } from '@angular/core'; import { ModalReservaAdmCrearService } from './modalReservaAdmCrear.service'; import { ReservaService } from '../../../services/reserva/reserva.service'; import { ClaseService } from '../../../services/clase/clase.service'; import { Clase } from 'src/app/models/clase.model'; import swal from 'sweetalert'; import { Usuario } from 'src/app/models/usuario.model'; import { UsuarioService } from 'src/app/services/service.index'; import { Reserva } from 'src/app/models/reserva.model'; @Component({ selector: 'app-modal-reserva-adm-crear', templateUrl: './modalReservaAdmCrear.component.html', styles: [] }) export class ModalReservaAdmCrearComponent implements OnInit { clase: Clase; usuarios: Usuario[] = []; cargando: boolean = true; desde: number = 0; totalRegistros: number = 0; constructor(public _modalService: ModalReservaAdmCrearService, public _reservaService: ReservaService, public _claseService: ClaseService, public _usuarioService: UsuarioService) { } ngOnInit() { this.cargarUsuarios(); } buscarClasePorFechaYHora(horaInicio: string, fecha: string){ this._claseService.cargarClasePorFecha(fecha, horaInicio).subscribe((resp: any) =>{ this.cargarClase(resp.clases); }); } cargarClase(clase: any){ this.clase = clase; } crearReserva(usuario: Usuario){ if(this._modalService.clase.cupo >= 1){ let reserva = new Reserva(usuario,this._modalService.clase, this._modalService.clase.fecha); this._reservaService.crearReserva(reserva) .subscribe( resp => { this._modalService.notificacion.emit(resp); }); } else { swal('No se puede realizar la reserva', 'No existe clase para este horario o no hay cupo.', 'error'); } this._modalService.ocultarModal(); } cargarUsuarios(){ this.cargando = true; this._usuarioService.cargarUsuarios(this.desde) .subscribe((resp: any) =>{ this.totalRegistros = resp.total; this.usuarios = resp.usuarios; this.cargando = false; }); } cambiarDesde(valor: number){ let nuevoDesde = this.desde + valor; if(nuevoDesde >= this.totalRegistros){ return; } if(nuevoDesde < 0){ return; } this.desde = this.desde + valor; this.cargarUsuarios(); } buscarUsuario(termino: string){ if(termino.length <= 0){ this.cargarUsuarios(); return; } this.cargando = true; this._usuarioService.buscarUsuarios(termino) .subscribe((resp: any) =>{ this.usuarios = resp.usuarios; this.cargando = false; }); } } <file_sep>/src/app/components/modals/modalReservaAdm/modalReservaAdm.component.ts import { Component, OnInit } from '@angular/core'; import { ModalReservaAdmService } from './modalReservaAdm.service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { ReservaService } from '../../../services/reserva/reserva.service'; import { Reserva } from 'src/app/models/reserva.model'; @Component({ selector: 'app-modal-reserva-adm', templateUrl: './modalReservaAdm.component.html' }) export class ModalReservaAdmComponent implements OnInit { role: string; constructor(public _modalService: ModalReservaAdmService, public _reservaService: ReservaService) { } ngOnInit() { this.role = localStorage.getItem('role'); } borrarReserva(reserva: Reserva){ this._reservaService.borrarReserva(reserva).subscribe(resp =>{ this._modalService.notificacion.emit(resp); }); this._modalService.ocultarModal(); } } <file_sep>/src/app/models/hora.model.ts export class Hora { constructor( public horaInicio: string, public horaFin: string, public _id?: string ) { } }<file_sep>/src/app/components/modals/modalClase/modalClaseActualizar.component.ts import { Component, OnInit } from '@angular/core'; import { ModalClaseActualizarService } from './modalClaseActualizar.service'; import { FormGroup, Validators, FormControl } from '@angular/forms'; import swal from 'sweetalert'; import { Clase } from 'src/app/models/clase.model'; import { ClaseService } from '../../../services/clase/clase.service'; @Component({ selector: 'app-modal-clase-actualizar', templateUrl: './modalClaseActualizar.component.html', styles: [] }) export class ModalClaseActualizarComponent implements OnInit { formaC: FormGroup; constructor(public _modalService: ModalClaseActualizarService, public _claseService: ClaseService) { this.formaC = new FormGroup({ descripcion: new FormControl(null, Validators.required), coach: new FormControl(null, Validators.required), cupo: new FormControl(null, Validators.required), wod: new FormControl(null, null) }); } ngOnInit() { } actualizarClase() { let nuevaDescripcion; let nuevoCoach; let nuevoCupo; let nuevoWod; if (this.formaC.value.descripcion){ nuevaDescripcion = this.formaC.value.descripcion; }else{ nuevaDescripcion = this._modalService.clase.descripcion; } if (this.formaC.value.coach){ nuevoCoach = this.formaC.value.coach; }else{ nuevoCoach = this._modalService.clase.coach; } if (this.formaC.value.wod){ nuevoWod = this.formaC.value.wod; }else{ nuevoWod = this._modalService.clase.wod; } if (this.formaC.value.cupo){ if(this.formaC.value.cupo >= 16){ let diferencia = 16 - this._modalService.clase.cupo; nuevoCupo = this.formaC.value.cupo - diferencia; }else{ swal('Cupo incorrecto', 'El cupo no puede ser inferior a 16', 'error'); } }else{ nuevoCupo = this._modalService.clase.cupo; } let clase = new Clase(this._modalService.clase.horaInicio, this._modalService.clase.horaFinal, this._modalService.clase.fecha, nuevaDescripcion, nuevoCoach, nuevoWod, nuevoCupo ); clase._id = this._modalService.clase._id; this._claseService.actualizarClase(clase).subscribe(resp =>{ if(resp.ok){ swal('Clase actualizada', '', 'success'); this._modalService.notificacion.emit(resp); } }); this._modalService.ocultarModal(); }; } <file_sep>/src/app/components/modals/modalUsuario/modalUsuario.service.ts import { Injectable, EventEmitter } from '@angular/core'; import { Usuario } from '../../../models/usuario.model'; import { Plan } from 'src/app/models/plan.model'; import swal from 'sweetalert'; @Injectable({ providedIn: 'root' }) export class ModalUsuarioService { usuario: Usuario; oculto: string = 'oculto'; notificacion = new EventEmitter<any>(); constructor( ) { this.usuario = new Usuario(null,null,null,new Plan(null,null),null,null, null, null, null, null, null, null); } ocultarModal(){ this.oculto = 'oculto'; this.usuario = new Usuario(null,null,null,new Plan(null,null),null,null, null, null, null, null, null, null); } mostrarModal(usuario: Usuario){ if (localStorage.getItem('id') === usuario._id){ swal('No puede Editar este usuario', 'No se puede editar a su mismo usuario.', 'error'); } else { this.oculto = ''; this.usuario = usuario; } } } <file_sep>/src/app/models/usuario.model.ts import { Plan } from './plan.model'; export class Usuario { constructor( public nombre: string, public email: string, public password: string, public plan: Plan, public cedula: string, public fechaNacimiento: string, public telefono: string, public direccion: string, public rh: string, public nombreContacto: string, public telefonoContacto: string, public descuento: boolean, public porcentajeDescuento?: number, public totalValorPlan?: number, public img?: string, public fechaInscripcion?: string, public fechaInicioPlan?: string, public fechaFinPlan?: string, public estado?: string, public role?: string, public _id?: string ) { } }<file_sep>/src/app/components/modals/modalUsuario/modalUsuario.component.ts import { Component, OnInit } from '@angular/core'; import { ModalUsuarioService } from './modalUsuario.service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { Plan } from 'src/app/models/plan.model'; import { PlanService } from 'src/app/services/plan/plan.service'; import swal from 'sweetalert'; import { SubirArchivoService } from '../../../services/subirArchivo/subir-archivo.service'; import { Usuario } from 'src/app/models/usuario.model'; import { UsuarioService } from 'src/app/services/service.index'; @Component({ selector: 'app-modal-usuario', templateUrl: './modalUsuario.component.html', styles: [] }) export class ModalUsuarioComponent implements OnInit { formaC: FormGroup; planes: Plan[] = []; imagenSubir: File; imagenTemp: any; constructor( public _modalService: ModalUsuarioService, public _subirArchivoService: SubirArchivoService, public _planService: PlanService, public _usuarioService: UsuarioService ) { } ngOnInit( ) { this.formaC = new FormGroup({ nombre: new FormControl(null, Validators.required), email: new FormControl(null, [Validators.required, Validators.email]), password: new FormControl(null, Validators.required), planC: new FormControl(null, Validators.required), cedula: new FormControl(null, Validators.required), fechaNacimiento: new FormControl(null, Validators.required), telefono: new FormControl(null, Validators.required), direccion: new FormControl(null, Validators.required), rh: new FormControl(null,Validators.required), nombreContacto: new FormControl(null, Validators.required), telefonoContacto: new FormControl(null, Validators.required), descuento: new FormControl(null, Validators.required), porcentajeDescuento: new FormControl(null, Validators.maxLength(3)) }); this.cargarPlanes(); } cargarPlanes() { this._planService.cargarPlanes(0) .subscribe((resp: any) =>{ this.planes = resp.planes; }); } seleccionImagen( archivo: File ){ if(!archivo){ this.imagenSubir = null; return; } if(archivo.type.indexOf('image') < 0){ swal('Solo imagenes', 'El archivo seleccionado no es una imagen', 'error'); this.imagenSubir = null; return; } this.imagenSubir = archivo; let reader = new FileReader(); let urlImagenTemp = reader.readAsDataURL(archivo); reader.onloadend = () => this.imagenTemp = reader.result; } actualizarUsuario(){ let nuevoNombre: string; let nuevaCedula: string; let nuevoEmail: string; let nuevoTelefono: string; let nuevaDireccion: string; let nuevaFechaNaciemiento: string; let nuevoRH: string; let nuevoPlan: any; let nuevoNombreContacto: string; let nuevoTelefonoContacto: string; let nuevoDescuento: boolean; let nuevoPorcentajeDescuento: number; let nuevoTotalValorPlan: number; if(this.formaC.value.nombre){ nuevoNombre = this.formaC.value.nombre; }else{ nuevoNombre = this._modalService.usuario.nombre; } if(this.formaC.value.email){ nuevoEmail = this.formaC.value.email; }else{ nuevoEmail = this._modalService.usuario.email; } if(this.formaC.value.planC){ nuevoPlan = this.formaC.value.planC; }else{ nuevoPlan = this._modalService.usuario.plan; } if(this.formaC.value.cedula){ nuevaCedula = this.formaC.value.cedula; }else{ nuevaCedula = this._modalService.usuario.cedula; } if(this.formaC.value.fechaNacimiento){ nuevaFechaNaciemiento = this.formaC.value.fechaNacimiento; }else{ nuevaFechaNaciemiento = this._modalService.usuario.fechaNacimiento; } if(this.formaC.value.telefono){ nuevoTelefono = this.formaC.value.telefono; }else{ nuevoTelefono = this._usuarioService.usuario.telefono; } if(this.formaC.value.direccion){ nuevaDireccion = this.formaC.value.direccion; }else{ nuevaDireccion = this._modalService.usuario.direccion; } if(this.formaC.value.rh){ nuevoRH = this.formaC.value.rh; }else{ nuevoRH = this._modalService.usuario.rh; } if(this.formaC.value.nombreContacto){ nuevoNombreContacto = this.formaC.value.nombreContacto; }else{ nuevoNombreContacto = this._modalService.usuario.nombreContacto; } if(this.formaC.value.telefonoContacto){ nuevoTelefonoContacto = this.formaC.value.telefonoContacto; }else{ nuevoTelefonoContacto = this._modalService.usuario.telefonoContacto; } if(this.formaC.value.descuento){ nuevoDescuento = this.formaC.value.descuento; }else{ nuevoDescuento = this._modalService.usuario.descuento; } if(nuevoDescuento){ if(this.formaC.value.porcentajeDescuento){ nuevoPorcentajeDescuento = this.formaC.value.porcentajeDescuento; nuevoTotalValorPlan = this._modalService.usuario.plan.valor - ((nuevoPorcentajeDescuento/100) * this._modalService.usuario.plan.valor); }else{ nuevoPorcentajeDescuento = this._modalService.usuario.porcentajeDescuento; nuevoTotalValorPlan = this._modalService.usuario.plan.valor - ((nuevoPorcentajeDescuento/100) * this._modalService.usuario.plan.valor); } }else{ nuevoPorcentajeDescuento = 0; nuevoTotalValorPlan = this._modalService.usuario.plan.valor; } console.log(nuevoTelefono); let usuario = new Usuario(nuevoNombre, nuevoEmail, null, nuevoPlan, nuevaCedula, nuevaFechaNaciemiento, nuevoTelefono, nuevaDireccion, nuevoRH, nuevoNombreContacto, nuevoTelefonoContacto, nuevoDescuento, nuevoPorcentajeDescuento, nuevoTotalValorPlan); usuario._id = this._modalService.usuario._id; this._usuarioService.actualizarUsuario(usuario).subscribe(resp =>{ this._modalService.notificacion.emit(resp); }); if(this.imagenSubir) { this._subirArchivoService.subirArchivo(this.imagenSubir, this._modalService.usuario._id) .then((resp: any) =>{ this._modalService.notificacion.emit(resp); }) .catch(resp =>{ console.log(resp); }); } this._modalService.ocultarModal(); } actualizarDescuento(evento: any){ this._modalService.usuario.descuento = evento; } } <file_sep>/src/app/pages/profile/profile.component.ts import { Component, OnInit } from '@angular/core'; import { UsuarioService } from '../../services/service.index'; import { Usuario } from '../../models/usuario.model'; import swal from 'sweetalert'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styles: [] }) export class ProfileComponent implements OnInit { usuario: Usuario; imagenSubir: File; imagenTemp: any; formaC: FormGroup; constructor( public _usuarioService: UsuarioService) { this.usuario = this._usuarioService.usuario; } ngOnInit() { this._usuarioService.paginaActual = 'Perfil'; this.formaC = new FormGroup({ nombre: new FormControl(null, Validators.required), email: new FormControl(null, [Validators.required, Validators.email]), password: new FormControl(null, null), planC: new FormControl(null, Validators.required), cedula: new FormControl(null, Validators.required), fechaNacimiento: new FormControl(null, Validators.required), telefono: new FormControl(null, Validators.required), direccion: new FormControl(null, Validators.required), rh: new FormControl(null,Validators.required), nombreContacto: new FormControl(null, Validators.required), telefonoContacto: new FormControl(null, Validators.required) }); } guardarPerfil(usuario: Usuario){ if(this.formaC.value.nombre){ usuario.nombre = this.formaC.value.nombre; }else{ usuario.nombre = this.usuario.nombre; } if(this.formaC.value.email){ usuario.email = this.formaC.value.email; }else{ usuario.email = this.usuario.email; } if(this.formaC.value.cedula){ usuario.cedula = this.formaC.value.cedula; }else{ usuario.cedula = this.usuario.cedula; } if(this.formaC.value.fechaNacimiento){ usuario.fechaNacimiento = this.formaC.value.fechaNacimiento; }else{ usuario.fechaNacimiento = this.usuario.fechaNacimiento; } if(this.formaC.value.telefono){ usuario.telefono = this.formaC.value.telefono; }else{ usuario.telefono = this.usuario.telefono; } if(this.formaC.value.direccion){ usuario.direccion = this.formaC.value.direccion; }else{ usuario.direccion = this.usuario.direccion; } if(this.formaC.value.rh){ usuario.rh = this.formaC.value.rh; }else{ usuario.rh = this.usuario.rh; } if(this.formaC.value.nombreContacto){ usuario.nombreContacto = this.formaC.value.nombreContacto; }else{ usuario.nombreContacto = this.usuario.nombreContacto; } if(this.formaC.value.telefonoContacto){ usuario.telefonoContacto = this.formaC.value.telefonoContacto; }else{ usuario.telefonoContacto = this.usuario.telefonoContacto; } this._usuarioService.actualizarUsuario(this.usuario) .subscribe(resp =>{ console.log(resp); }); } } <file_sep>/src/app/pages/pages.module.ts import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ChartsModule } from 'ng2-charts'; import { ProgressComponent } from './progress/progress.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { Graficas1Component } from './graficas1/graficas1.component'; import { PagesComponent } from './pages.component'; import { SharedModule } from '../shared/shared.module'; import { PAGES_ROUTES } from './pages.routes'; import { IncrementadorComponent } from '../components/incrementador/incrementador.component'; import { GraficoDonaComponent } from '../components/grafico-dona/grafico-dona.component'; import { RegisterComponent } from './register/register.component'; import { PipesModule } from '../pipes/pipes.module'; import { ProfileComponent } from './profile/profile.component'; import { CommonModule } from '@angular/common'; import { PlanesComponent } from './planes/planes.component'; import { ClasesComponent } from './clases/clases.component'; import { ModalPlanComponent } from '../components/modals/modalPlan/modalPlan.component'; import { ModalUsuarioComponent } from '../components/modals/modalUsuario/modalUsuario.component'; import { ModalClaseComponent } from '../components/modals/modalClase/modalClase.component'; import { ModalClaseActualizarComponent } from '../components/modals/modalClase/modalClaseActualizar.component'; import { ReservasComponent } from './reservas/reservas.component'; import { ModalReservaAdmComponent } from '../components/modals/modalReservaAdm/modalReservaAdm.component'; import { ModalReservaAdmCrearComponent } from '../components/modals/modalReservaAdm/modalReservaAdmCrear.component'; import { ReservasUsuarioComponent } from './reservasUsuario/reservasUsuario.component'; import { ModalClaseUsuarioComponent } from '../components/modals/modalClaseUsuario/modalClaseUsuario.component'; import { ReservasCoachComponent } from './reservasCoach/reservasCoach.component'; import { PlanUsuarioComponent } from './planUsuario/planUsuario.component'; @NgModule({ declarations: [ PagesComponent, DashboardComponent, ProgressComponent, Graficas1Component, IncrementadorComponent, GraficoDonaComponent, RegisterComponent, ProfileComponent, PlanesComponent, ClasesComponent, ModalPlanComponent, ModalUsuarioComponent, ModalClaseComponent, ModalClaseActualizarComponent, ReservasComponent, ModalReservaAdmComponent, ModalReservaAdmCrearComponent, ReservasUsuarioComponent, ModalClaseUsuarioComponent, ReservasCoachComponent, PlanUsuarioComponent ], exports: [ PagesComponent, DashboardComponent, ProgressComponent, Graficas1Component ], imports: [ SharedModule, PAGES_ROUTES, FormsModule, ReactiveFormsModule, ChartsModule, PipesModule, CommonModule ] }) export class PagesModule {}<file_sep>/src/app/pipes/imagen.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { URL_SERVICIOS } from '../config/config'; @Pipe({ name: 'imagen' }) export class ImagenPipe implements PipeTransform { transform(img: string): any { let url = URL_SERVICIOS + '/imagenes/usuarios/'; if(!img){ return url + 'no-img.jpg'; }else{ return url + img; } } } <file_sep>/src/app/pages/planUsuario/planUsuario.component.ts import { Component, OnInit } from '@angular/core'; import { UsuarioService } from '../../services/usuario/usuario.service'; @Component({ selector: 'app-plan-usuario', templateUrl: './planUsuario.component.html', styles: [] }) export class PlanUsuarioComponent implements OnInit { constructor(public _usuarioService: UsuarioService) { } ngOnInit() { this._usuarioService.paginaActual = 'Plan'; } } <file_sep>/src/app/models/reserva.model.ts import { Usuario } from './usuario.model'; import { Clase } from './clase.model'; export class Reserva { constructor( public usuario: Usuario, public clase: Clase, public fechaReserva: string, public _id?: string ) { } }<file_sep>/src/app/components/modals/modalPlan/modalPlan.service.ts import { Injectable, EventEmitter } from '@angular/core'; import { Plan } from '../../../models/plan.model'; @Injectable({ providedIn: 'root' }) export class ModalPlanService { plan: Plan; oculto: string = 'oculto'; notificacion = new EventEmitter<any>(); constructor() { this.plan = new Plan(null, null, null); } ocultarModal(){ this.oculto = 'oculto'; this.plan = new Plan(null, null, null); } mostrarModal(plan: Plan){ this.oculto = ''; this.plan = plan; } } <file_sep>/src/app/components/modals/modalClase/modalClase.component.ts import { Component, OnInit } from '@angular/core'; import { ModalClaseService } from './modalClase.service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { Clase } from 'src/app/models/clase.model'; import { ClaseService } from '../../../services/clase/clase.service'; @Component({ selector: 'app-modal-clase', templateUrl: './modalClase.component.html', styles: [] }) export class ModalClaseComponent implements OnInit { formaC: FormGroup; constructor(public _modalService: ModalClaseService, public _claseService: ClaseService) { } ngOnInit() { this.formaC = new FormGroup({ descripcion: new FormControl(null, Validators.required), coach: new FormControl(null, Validators.required), wod: new FormControl(null, null) }); } crearClase(){ let clase = new Clase(this._modalService.hora.horaInicio, this._modalService.hora.horaFin, new Date(this._modalService.fecha).toISOString(), this.formaC.value.descripcion, this.formaC.value.coach, this.formaC.value.wod); this._claseService.crearClase(clase).subscribe(resp =>{ this._modalService.notificacion.emit(resp); this.formaC.reset(); }); this._modalService.oculto = 'oculto'; } } <file_sep>/src/app/components/modals/modalClaseUsuario/modalClaseUsuario.service.ts import { Injectable, EventEmitter } from '@angular/core'; import { Clase } from 'src/app/models/clase.model'; @Injectable({ providedIn: 'root' }) export class ModalClaseUsuarioService { oculto: string = 'oculto'; clase: Clase; notificacion = new EventEmitter<any>(); constructor() { this.clase = new Clase(null, null, null, null, null, null); } ocultarModal(){ this.clase = new Clase(null, null, null, null, null, null); this.oculto = 'oculto'; } mostrarModal(clase: Clase){ this.clase = clase; this.oculto = ''; } } <file_sep>/src/app/pages/clases/clases.component.ts import { Component, OnInit } from '@angular/core'; import { HoraService } from '../../services/hora/hora.service'; import { Hora } from 'src/app/models/hora.model'; import { Clase } from 'src/app/models/clase.model'; import { ModalClaseService } from '../../components/modals/modalClase/modalClase.service'; import { ClaseService } from '../../services/clase/clase.service'; import { ModalClaseActualizarService } from '../../components/modals/modalClase/modalClaseActualizar.service'; import { UsuarioService } from '../../services/usuario/usuario.service'; @Component({ selector: 'app-clases', templateUrl: './clases.component.html' }) export class ClasesComponent implements OnInit { DIAS = [ {id: 1, name: 'Lunes', fecha: ''}, {id: 2, name: 'Martes', fecha: ''}, {id: 3, name: 'Miercoles', fecha: ''}, {id: 4, name: 'Jueves', fecha: ''}, {id: 5, name: 'Viernes', fecha: ''}, {id: 6, name: 'Sabado', fecha: ''} ]; fechaInicial: number; fechaFinal: number; horas: Hora[] = []; clases: Clase[] = []; constructor(public _horaService: HoraService, public _modalService: ModalClaseService, public _modalActualizarService: ModalClaseActualizarService, public _claseService: ClaseService, public _usuarioService: UsuarioService){ } ngOnInit(): void { this._usuarioService.paginaActual = 'Administrar Clases'; this.calcularFechas(); this.cargarHoras(); this.cargarClases(); this._modalService.notificacion.subscribe( (resp: any) => { this.cargarClases(); }); this._modalActualizarService.notificacion.subscribe( (resp: any) => { this.cargarClases(); }); } calcularFechas(){ let lunes = new Date(); let martes = new Date(); let miercoles = new Date(); let jueves = new Date(); let viernes = new Date(); let sabado = new Date(); if(new Date().getDay() === 1){ console.log('LUNES'); let fechaTempFin = new Date(); this.fechaInicial = new Date().getDate(); fechaTempFin.setDate(new Date().getDate() + 5); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth()+1 + '/' + new Date().getFullYear()); martes.setDate(new Date().getDate() + 1); miercoles.setDate(new Date().getDate() + 2); jueves.setDate(new Date().getDate() + 3); viernes.setDate(new Date().getDate() + 4); sabado.setDate(new Date().getDate() + 5); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 2){ console.log('MARTES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 1); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 4); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 1); miercoles.setDate(new Date().getDate() + 1); jueves.setDate(new Date().getDate() + 2); viernes.setDate(new Date().getDate() + 3); sabado.setDate(new Date().getDate() + 4); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 3){ console.log('MIERCOLES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(fechaTempIni.getDate() - 2); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(fechaTempIni.getDate() + 5); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 2); martes.setDate(new Date().getDate() - 1); jueves.setDate(new Date().getDate() + 1); viernes.setDate(new Date().getDate() + 2); sabado.setDate(new Date().getDate() + 3); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 4){ console.log('JUEVES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 3); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 2); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 3); martes.setDate(new Date().getDate() - 2); miercoles.setDate(new Date().getDate() - 1); viernes.setDate(new Date().getDate() + 1); sabado.setDate(new Date().getDate() + 2); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 5){ console.log('VIERNES'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 4); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 1); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 4); martes.setDate(new Date().getDate() - 3); miercoles.setDate(new Date().getDate() - 2); jueves.setDate(new Date().getDate() - 1); sabado.setDate(new Date().getDate() + 1); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 6){ console.log('SABADO'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() - 5); this.fechaInicial = fechaTempIni.getDate(); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() - 5); martes.setDate(new Date().getDate() - 4); miercoles.setDate(new Date().getDate() - 3); jueves.setDate(new Date().getDate() - 2); viernes.setDate(new Date().getDate() - 1); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } if(new Date().getDay() === 0){ console.log('DOMINGO'); let fechaTempIni = new Date(); let fechaTempFin = new Date(); fechaTempIni.setDate(new Date().getDate() + 1); this.fechaInicial = fechaTempIni.getDate(); fechaTempFin.setDate(new Date().getDate() + 6); this.fechaFinal = fechaTempFin.getDate(); //CarcgarFechasADias console.log('FECHA ACTUAL: ', new Date().getDate() + '/' + new Date().getMonth() + '/' + new Date().getFullYear()); lunes.setDate(new Date().getDate() + 1); martes.setDate(new Date().getDate() + 2); miercoles.setDate(new Date().getDate() + 3); jueves.setDate(new Date().getDate() + 4); viernes.setDate(new Date().getDate() + 5); sabado.setDate(new Date().getDate() + 6); let fechas = [ {dia: lunes.getDate(), mes: lunes.getMonth() + 1, anio: lunes.getFullYear()}, {dia: martes.getDate(), mes: martes.getMonth() + 1, anio: martes.getFullYear()}, {dia: miercoles.getDate(), mes: miercoles.getMonth() + 1, anio: miercoles.getFullYear()}, {dia: jueves.getDate(), mes: jueves.getMonth() + 1, anio: jueves.getFullYear()}, {dia: viernes.getDate(), mes: viernes.getMonth() + 1, anio: viernes.getFullYear()}, {dia: sabado.getDate(), mes: sabado.getMonth() + 1, anio: sabado.getFullYear()} ]; this.cargarFechaEnDia(fechas); } } cargarHoras(){ this._horaService.cargarHoras() .subscribe((resp: any) =>{ this.horas = resp.horas; }); } validarHoras(hora: Hora, dia: string){ if (dia === 'sabado') { if (hora.horaInicio === '8:30'){ return true; } else if (hora.horaInicio === '9:30') { return true; } else if (hora.horaInicio === '10:30') { return true; } else { return false; } } else { if (hora.horaInicio === '8:30') { return false; } else if (hora.horaInicio === '9:30') { return false; } else if (hora.horaInicio === '10:30') { return false; } else { return true; } } } cargarClases() { this._claseService.cargarClases(this.DIAS[0].fecha, this.DIAS[5].fecha) .subscribe((resp: any) =>{ console.log(this.DIAS[0].fecha, this.DIAS[5].fecha); this.clases = resp.clases; }); } cargarFechaEnDia(fechas: any[]){ for (let i = 0; i < this.DIAS.length; i++) { //console.log(fechas[i]); if(fechas[i].mes <= 9){ if(fechas[i].dia <= 9){ this.DIAS[i].fecha = fechas[i].anio + '-' + 0+fechas[i].mes + '-' + 0+fechas[i].dia; }else{ this.DIAS[i].fecha = fechas[i].anio + '-' + 0+fechas[i].mes + '-' + fechas[i].dia; } }else{ if(fechas[i].dia <= 9){ this.DIAS[i].fecha = fechas[i].anio + '-' + fechas[i].mes + '-' + 0+fechas[i].dia; }else{ this.DIAS[i].fecha = fechas[i].anio + '-' + fechas[i].mes + '-' + fechas[i].dia; } } } } buscarFecha(dia: number){ for (let i = 0; i < this.DIAS.length; i++) { if(this.DIAS[i].id === dia){ return this.DIAS[i].fecha; } } } validarClase(hora: Hora, dia: any, boton: string){ //console.log(this.existeClase(hora, dia) + '-----' + boton) if(this.existeClase(hora, dia) && boton === 'crear'){ return 'oculto'; } if(!this.existeClase(hora, dia) && boton === 'crear'){ return ''; } if(this.existeClase(hora, dia) && boton === 'ver'){ return ''; } if(!this.existeClase(hora, dia) && boton === 'ver'){ return 'oculto'; } } existeClase(hora: Hora, dia: any){ for (const clase of this.clases) { if(clase.fecha.substring(0, 10) === dia.fecha && clase.horaInicio === hora.horaInicio && clase.horaFinal === hora.horaFin) { return true; } } return false; } buscarClase(hora: Hora, dia: any){ for (const clase of this.clases) { if(clase.fecha.substring(0, 10) === dia.fecha && clase.horaInicio === hora.horaInicio && clase.horaFinal === hora.horaFin) { return clase; } } return new Clase(null, null, null, null, null, null, null); } eliminarClase(clase: Clase){ this._claseService.borrarClase(clase).subscribe( resp => { this.cargarClases(); }); } } <file_sep>/src/app/components/modals/modalClase/modalClase.service.ts import { Injectable, EventEmitter } from '@angular/core'; import { Clase } from 'src/app/models/clase.model'; import { Hora } from 'src/app/models/hora.model'; @Injectable({ providedIn: 'root' }) export class ModalClaseService { oculto: string = 'oculto'; hora: Hora; dia: number; fecha: string; clases: Clase[]; notificacion = new EventEmitter<any>(); constructor() { this.hora = new Hora(null, null); } ocultarModal(){ this.hora = new Hora(null, null); this.oculto = 'oculto'; } mostrarModal(hora: Hora, fecha: string){ this.hora = hora; this.fecha = fecha; this.oculto = ''; } } <file_sep>/src/app/models/plan.model.ts export class Plan { constructor( public nombre: string, public valor: number, public descripcion?: string, public _id?: string ) { } }<file_sep>/src/app/pages/planes/planes.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { UsuarioService } from '../../services/service.index'; import { Usuario } from 'src/app/models/usuario.model'; import { Plan } from '../../models/plan.model'; import { PlanService } from '../../services/plan/plan.service'; import swal from 'sweetalert'; import { ModalPlanService } from '../../components/modals/modalPlan/modalPlan.service'; declare function init_plugins(); @Component({ selector: 'app-planes', templateUrl: './planes.component.html', styles: [] }) export class PlanesComponent implements OnInit { formaC: FormGroup; planes: Plan[] = []; desde: number = 0; totalRegistros: number = 0; cargando: boolean = true; constructor(public _planService: PlanService, public _modalService: ModalPlanService, public _usuarioService: UsuarioService) { } ngOnInit() { init_plugins(); this._usuarioService.paginaActual = 'Administrar Planes'; this.formaC = new FormGroup({ nombre: new FormControl(null, Validators.required), valor: new FormControl(null, Validators.required), descripcion: new FormControl(null, null), }); this._modalService.notificacion.subscribe( (resp: any) => { this.cargarPlanes(); }); this.cargarPlanes(); } crearPlan(){ if(this.formaC.invalid){ return; } let plan = new Plan(this.formaC.value.nombre, this.formaC.value.valor, this.formaC.value.descripcion); this._planService.crearPlan(plan) .subscribe( resp => { this.formaC.reset(); this.cargarPlanes(); }); } cargarPlanes(){ this.cargando = true; this._planService.cargarPlanes(this.desde) .subscribe((resp: any) =>{ this.totalRegistros = resp.total; this.planes = resp.planes; this.cargando = false; }); } cambiarDesde(valor: number){ let nuevoDesde = this.desde + valor; if(nuevoDesde >= this.totalRegistros){ return; } if(nuevoDesde < 0){ return; } this.desde = this.desde + valor; this.cargarPlanes(); } eliminarPlan(plan: Plan){ this._planService.borrarPlan(plan).subscribe( resp => { this.cargarPlanes(); }); } buscarPlan(termino: string){ if(termino.length <= 0){ this.cargarPlanes(); return; } this.cargando = true; this._planService.buscarPlanes(termino) .subscribe((resp: any) =>{ this.planes = resp.planes; this.cargando = false; }); } } <file_sep>/src/app/pages/register/register.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { UsuarioService } from '../../services/service.index'; import { Usuario } from 'src/app/models/usuario.model'; import { Plan } from '../../models/plan.model'; import { PlanService } from '../../services/plan/plan.service'; import swal from 'sweetalert'; import { ModalUsuarioService } from '../../components/modals/modalUsuario/modalUsuario.service'; declare function init_plugins(); @Component({ selector: 'app-register', templateUrl: './register.component.html' //styleUrls: ['./register.component.css'] }) export class RegisterComponent implements OnInit { formaC: FormGroup; usuarios: Usuario[] = []; planes: Plan[] = []; desde: number = 0; totalRegistros: number = 0; cargando: boolean = true; imagenSubir: File; imagenTemp: any; totalValorPlan: number; porcentajeDescuento: number = 0; constructor( public _usuarioService: UsuarioService, public _planService: PlanService, public _modalService: ModalUsuarioService ) { } ngOnInit() { init_plugins(); this._usuarioService.paginaActual = 'Administrar Usuarios'; this.formaC = new FormGroup({ nombre: new FormControl(null, Validators.required), email: new FormControl(null, [Validators.required, Validators.email]), password: new FormControl(null, Validators.required), planC: new FormControl(null, Validators.required), cedula: new FormControl(null, Validators.required), fechaNacimiento: new FormControl(null, Validators.required), telefono: new FormControl(null, Validators.required), direccion: new FormControl(null, Validators.required), rh: new FormControl(null,Validators.required), nombreContacto: new FormControl(null, Validators.required), telefonoContacto: new FormControl(null, Validators.required), descuento: new FormControl(null, Validators.required), porcentajeDescuento: new FormControl(null, Validators.maxLength(3)), otroValor: new FormControl(null, Validators.required), nuevoValorPlan: new FormControl(null, Validators.required) }); this._modalService.notificacion.subscribe( (resp: any) => { this.cargarUsuarios(); }); this.cargarPlanes(); this.cargarUsuarios(); } cargarStorage(){ if (localStorage.getItem('token')) { this._usuarioService.usuario = JSON.parse(localStorage.getItem('usuario')); } else { this._usuarioService.usuario = null; } } crearUsuario(){ if(this.formaC.invalid){ return; } let fecha: Date; let valor: number; fecha = new Date(); const fechaFinPlan = fecha.setDate(fecha.getDate() + 30); for ( let i= 0; i < this.planes.length; i++ ) { if (this.planes[i]._id === this.formaC.value.planC){ valor = this.planes[i].valor; break; } } if (this.formaC.value.descuento) { this.porcentajeDescuento = this.formaC.value.porcentajeDescuento; this.totalValorPlan = valor - ((this.porcentajeDescuento / 100) * valor); } else { this.totalValorPlan = valor; } if (this.formaC.value.otroValor) { this.totalValorPlan = this.formaC.value.nuevoValorPlan; } else { this.totalValorPlan = valor; } const usuario = new Usuario(this.formaC.value.nombre, this.formaC.value.email, this.formaC.value.password, this.formaC.value.planC, this.formaC.value.cedula, this.formaC.value.fechaNacimiento, this.formaC.value.telefono, this.formaC.value.direccion, this.formaC.value.rh, this.formaC.value.nombreContacto, this.formaC.value.telefonoContacto, this.formaC.value.descuento, this.porcentajeDescuento, this.totalValorPlan, ); this._usuarioService.crearUsuario(usuario) .subscribe( resp => { this.formaC.reset(); this.cargarUsuarios(); }); console.log(this.formaC.value); } cargarUsuarios(){ this.cargando = true; this._usuarioService.cargarUsuarios(this.desde) .subscribe((resp: any) =>{ this.totalRegistros = resp.total; this.usuarios = resp.usuarios; this.cargando = false; }); } cambiarDesde(valor: number){ let nuevoDesde = this.desde + valor; if(nuevoDesde >= this.totalRegistros){ return; } if(nuevoDesde < 0){ return; } this.desde = this.desde + valor; this.cargarUsuarios(); } cargarPlanes() { this._planService.cargarPlanes(0) .subscribe((resp: any) =>{ this.planes = resp.planes; console.log(resp); }); } buscarUsuario(termino: string){ if(termino.length <= 0){ this.cargarUsuarios(); return; } this.cargando = true; this._usuarioService.buscarUsuarios(termino) .subscribe((resp: any) =>{ this.usuarios = resp.usuarios; this.cargando = false; }); } cambiarEstadoUsuario(usuario: Usuario, btn: string){ if(btn === 'Activar'){ if(usuario._id === this._usuarioService.usuario._id){ swal('No puede Activar este usuario', 'No se puede activar a su mismo usuario.', 'error'); return; } else { if (usuario.estado === 'INACTIVO'){ usuario.estado = 'ACTIVO'; this._usuarioService.actualizarUsuario(usuario) .subscribe((resp: any) => { this.cargarUsuarios(); }); } else { swal('No puede Activar este usuario', 'Este usuario ya se encuentra activo.', 'warning'); return; } } } else { if(usuario._id === this._usuarioService.usuario._id){ swal('No puede Inactivar este usuario', 'No se puede inactivar a su mismo usuario.', 'error'); return; } else { if (usuario.estado === 'ACTIVO'){ usuario.estado = 'INACTIVO'; this._usuarioService.actualizarUsuario(usuario) .subscribe((resp: any) => { this.cargarUsuarios(); }); } else { swal('No puede Inactivar este usuario', 'Este usuario ya se encuentra inactivo.', 'warning'); return; } } } } } <file_sep>/src/app/services/plan/plan.service.ts import { Injectable, OnInit } from '@angular/core'; import { Plan } from '../../models/plan.model'; import { HttpClient } from '@angular/common/http'; import { URL_SERVICIOS } from '../../config/config'; import 'rxjs/add/operator/map'; import swal from 'sweetalert'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class PlanService { token: string; constructor(public http: HttpClient, public ruter: Router) { this.cargarStorage(); } cargarPlanes(desde: number = 0) { let url = URL_SERVICIOS + '/plan/?desde=' + desde; return this.http.get(url); } cargarStorage(){ if(localStorage.getItem('token')){ this.token = localStorage.getItem('token'); }else{ this.token = ''; } } crearPlan(plan: Plan){ let url = URL_SERVICIOS + '/plan' + '?token=' + this.token; return this.http.post(url, plan) .map((resp: any) =>{ swal('Plan creado correctamente', '', 'success'); return resp.plan; }); } buscarPlanes(termino: string){ let url = URL_SERVICIOS + '/busqueda/plan/' + termino; console.log("URL: " + url); return this.http.get(url); } actualizarPlan(plan: Plan){ this.cargarStorage(); let url = URL_SERVICIOS + '/plan/' + plan._id + '?token=' + this.token; return this.http.put(url, plan).map((resp: any) =>{ swal('Plan actulizado', '', 'success'); return true; }); } borrarPlan(plan: Plan){ this.cargarStorage(); let url = URL_SERVICIOS + '/plan/' + plan._id + '?token=' + this.token; return this.http.delete(url).map((resp: any) =>{ swal('Plan eliminado', '', 'success'); return true; }); } } <file_sep>/src/app/components/modals/modalReservaAdm/modalReservaAdm.service.ts import { Injectable, EventEmitter } from '@angular/core'; import { Reserva } from '../../../models/reserva.model'; @Injectable({ providedIn: 'root' }) export class ModalReservaAdmService { reservas: Reserva[]; oculto: string = 'oculto'; notificacion = new EventEmitter<any>(); constructor() { this.reservas = new Array(); } ocultarModal(){ this.oculto = 'oculto'; this.reservas = new Array(); } mostrarModal(reservas: Reserva[]){ this.oculto = ''; this.reservas = reservas; } }
b336cc15456c02d7518349263602250e16d1c934
[ "TypeScript" ]
30
TypeScript
Crateral/invincibleprogram
a2c548d0c9a824d43f4fe9792a46a796adc14846
9fb4a8496a15d8e7baebdf35a5b561d03b5c4bd5
refs/heads/master
<file_sep>import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; // import { Accounts } from 'accounts-phone'; import './main.html'; // Template.body.onCreated(function helloOnCreated() { // var options = {phone:'+972545999999'}; // // You can also create user with password // options.password = '<PASSWORD>'; // Accounts.createUserWithPhone(options, function (){}); // // Debug: Verify the user phone isn't confirmed it. // console.log('Phone verification status is :', Accounts.isPhoneVerified()); // }); // // Template.body.helpers({ // tasks: [ // { text: 'This is task 1' }, // { text: 'This is task 2' }, // { text: 'This is task 3' }, // ], // });
3234aa52381b7425c001bc4dd83ff5eeb4751868
[ "JavaScript" ]
1
JavaScript
balibou/meteorPhoneConnection
7819a51316a8bbba50db381287e0b09586c6d807
df68b412981cdad162dda3309aa8b69c879725bb
refs/heads/master
<repo_name>samuelCupertino/fila-ED<file_sep>/README.md # Fila - Estrutura De Dados Exercício realizado durante disciplina de estrutura de dados na faculdade para compreensão da estrutura de fila. Através da alusão a um aeroporto, onde os aviões se encontram em uma fila, aguardando liberação da pista e decolando com gráficos animados feitos com matriz de caracteres. Obs: O programa se encontra com seu código original, não foi realizado refatoração. Sendo seu código-fonte datado de ‎19‎/08/‎2019, período onde estava aprendendo programação com C, no segundo semestre da faculdade. Fila de aviões na pista de decolagem: <img src="print-screen/run.gif"> <file_sep>/main.c #include "fila.h" int main (void){ setlocale(LC_ALL, "portuguese"); fila *Fila_Pista=Alocar_Fila(); char op, sub_op; int aviao_pista; do{ system("CLS"); op='0'; printf("1 - Número de aviões aguardando decolagem\n2 - Autorizar decolagem do primeiro avião\n3 - Adicionar um avião na fila da pista\n4 - Listar os aviões em espera\n"); scanf("%c", &op); switch(op){ case '1': system("CLS"); printf("0 - Voltar\n\n"); printf("Aviões aguardando decolagem: %d\n\n", Fila_Pista->tam); printf("`-> "); scanf("%s", &sub_op); break; case '2': do{ system("CLS"); if(Fila_Pista->tam > 0){ printf("0 - Voltar | 1 - Autorizar Decolagem\n\n\n"); Printar_Fila(Fila_Pista); printf("\n`-> "); scanf("%s", &sub_op); if (sub_op == '1') Decolagem_Aviao(Fila_Pista); } else{ system("CLS"); printf("0 - Voltar | 1 - Autorizar Decolagem\n\n"); Printar_Fila(Fila_Pista); printf("`-> "); scanf("%s", &sub_op); sub_op='0'; } }while(sub_op == '1'); break; case '3': do{ system("CLS"); printf("0 - Voltar | 1 - Inserir Aeronave\n\n"); Inserir_Aviao(Fila_Pista); printf("`-> "); scanf("%s", &sub_op); }while(sub_op == '1'); break; case '4': system("CLS"); printf("0 - Voltar\n\n"); Printar_Fila(Fila_Pista); printf("`-> "); scanf("%s", &sub_op); break; } }while(1); } <file_sep>/fila.c #include "fila.h" fila *Alocar_Fila(){ fila *fila_alocada=(fila*)malloc(sizeof(fila)); // Alocar espaco para fila if(fila_alocada == NULL){ // Se Alocacao falhou finaliza execucao printf("Erro de Memória :("); exit(1); } fila_alocada->ini=NULL; // Se deu certo a alocacao, iniciaiza as variaveis da fila fila_alocada->fim=NULL; fila_alocada->tam=0; return fila_alocada; } void Inserir_Aviao(fila *Fila){ no *n_aviao=(no*)malloc(sizeof(no)); // Alocar espaco para um nó de elemento aviao if(n_aviao == NULL){ // Se Alocacao falhou finaliza execucao printf("Erro de Memória :("); exit(1); } printf("Informe o ID do avião: "); // Preenchimento dos dados do aviao scanf("%d", &n_aviao->aeronave.id); printf("Informe o Nome do avião: "); fflush(stdin); gets(n_aviao->aeronave.nome); n_aviao->prox=NULL; if(Fila->ini == NULL){ // Se nao ha aviao na fila, o novo aviao será o 1º Fila->ini=n_aviao; Fila->fim=n_aviao; Fila->tam=1; } else{ // Se ha aviao na fila, o novo aviao será o ultimo Fila->fim->prox=n_aviao; Fila->fim=n_aviao; Fila->tam++; } printf("Inserido com Sucesso!\n\n"); } void Printar_Design_Aviao(int i){ // Funcao dedicada a printar desenho do aviao antes das informacoes do aviao que ele representa char design_aviao[3][8]={" /\\ ", "/-||-\\", " /\\ "}; printf("%s", design_aviao[i]); // Printa uma linha especifica do desenho do aviao referente a variavel 'i' } void Printar_Fila(fila *Fila){ // Funcao dedicada a printar a fila de avioes com o desenho e as informacoes de cada aviao int i=0; no *aux=Fila->ini; // aux recebe o que ha no inicio da fila if (aux != NULL){ // Se ha um aviao no inicio da fila, printa os dados dele e dos demais da fila a partir dele while(Fila->tam > i){ i++; Printar_Design_Aviao(0); // Manda para funcao printar a 1º linha do desenho do aviao printf(" .- %dº Aeronave\n", i); Printar_Design_Aviao(1); // Manda para funcao printar a 2º linha do desenho do aviao printf(" <-: ID: %d\n", aux->aeronave.id); Printar_Design_Aviao(2); // Manda para funcao printar a 3º linha do desenho do aviao printf(" `- Nome: %s\n\n", aux->aeronave.nome); aux=aux->prox; //passa para o proximo aviao a ser printado } } else{ // Se nao ha um aviao no inicio da fila, printa que a Pista esta vazia printf("Pista Vazia\n\n"); } } void Animacao_Decolagem(fila *Fila){ char design_aviao[6][7]={" ", " ", " ", " /\\ ", "/-||-\\", "` /\\ ´"}; char voo[7]={"| |"}; char limp[7]={" "}; int f=0; // f - Quantidade de frames int a; // a - Aux para printar aviao (string: design_aviao) int p; // p - Aux para mudar a posicao do aviao while(f <= 8){ // Printar os 6 frame que compoe o movimento do aviao system ("CLS"); a=0; while(a < 6){ // Printar o aviao na posicao que ele esta dentro da string (em cada frame a posicao muda, simulando movimento) printf("%s\n", design_aviao[a]); a++; } printf("\n"); Printar_Fila(Fila); // Printar a fila de avioes atras do aviao que "se movimenta" if (f == 0) // delay de ligando turbinas Sleep(400); Sleep(150); // Delay na atualizacao do proximo frame (para simular o movimento) p=0; while(p < a){ // Mudar a posicao do aviao dentro da string (atualizando o frame) if(p < a-1) strcpy(design_aviao[p], design_aviao[p+1]); // Mudar a posicao do aviao dentro da string else if(f < 2) strcpy(design_aviao[p], voo); // Adicionar efeito de voo na asa do aviao dentro da string else strcpy(design_aviao[p], limp); // Limpar a ultima coluna da string para a cauda do aviao nao se repetir p++; } f++; } while(f > 4){ // Printar a fila de avioes avancando para posicao de partida system ("CLS"); a=f; while(a > 3){ // Printar a distancia da fila de avioes diminuindo em relacao a posicao de partida printf("%s\n", limp); a--; } printf("\n"); Printar_Fila(Fila); // A cada distancia diminuida a lista se atualiza (para da o efeito de locomocao) Sleep(500); // Delay na atualizacao do proximo frame (para simular o movimento) f--; } } void Decolagem_Aviao(fila *Fila_Pista){ no *aux=Fila_Pista->ini; // aux recebe o aviao inicial da fila Fila_Pista->ini=Fila_Pista->ini->prox; // o aviao inicial da fila pista = passa a ser = o proximo Fila_Pista->tam--; free(aux); // O ex aviao inicial, é liberado Animacao_Decolagem(Fila_Pista); // iniciar animacao de aviao decolando } <file_sep>/fila.h #ifndef FILA_H #define FILA_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> #include <locale.h> typedef struct Dado{ // <--. Dado int id; // : ' char nome[15]; // : ' }aviao; // <--' aviao }-------. // (FORMA) typedef struct Elemento{ // <--. Elemento <----' aviao aeronave; // : ' struct Elemento *prox; // : ' }no; // <--' no }-------. // (FORMA) typedef struct Lista{ // <--. Lista <------' no *ini; // : ' no *fim; // : ' int tam; // : ' }fila; // <--' fila fila *Alocar_Fila(); void Inserir_Aviao(fila *Fila); void Printar_Design_Aviao(int i); void Printar_Fila(fila *Fila); void Animacao_Decolagem(fila *Fila); void Decolagem_Aviao(fila *Fila_Pista); #endif
2e4802cabe643103460a5422deeaf80b48a829f4
[ "Markdown", "C" ]
4
Markdown
samuelCupertino/fila-ED
1511b936112dce2416c36aa81cc27260eed40747
517f78798cb1434dacabfd1734f3d5d3bb24e1f6
refs/heads/master
<repo_name>weswalker125/JautoJams<file_sep>/src/main/java/wes/auto/jams/Main.java package wes.auto.jams; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.CommandLineRunner; import wes.auto.jams.models.SimpleSong; import wes.auto.jams.utils.JamminUtils; @SpringBootApplication public class Main implements CommandLineRunner { //private static Logger log = Logger.getLogger(ConsoleMain.class); private static String _root = "/Users/wes/Music/"; //private static String _root = "C:\\Users\\WesWa\\Music\\"; private static boolean PRINT = !true; public static void main(String[] args) { System.out.println("JautoJams console has started"); SpringApplication.run(Main.class, args); System.out.println("JautoJams console has finished"); } @Override public void run(String... args) { /* TODO: build menu using Spring tool */ System.out.println("Scan directory set to: " + _root); System.out.print("Enter scan directory (ENTER for default):"); try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { String scanDir = br.readLine(); if(scanDir != null && !scanDir.isEmpty()) { _root = scanDir; } System.out.println("1. Correct song files"); System.out.println("2. Find empty directories"); System.out.print("Enter choice: "); String choice = br.readLine(); switch (choice) { case "1": correctSongFiles(); break; case "2": findEmptyDirs(_root); break; default: break; } } catch(Exception ex) { System.out.println("Err: " + ex.getMessage()); } } private static void correctSongFiles() { List<SimpleSong> songs = getAllSongs(_root); for(Iterator<SimpleSong> it = songs.iterator(); it.hasNext();) { SimpleSong song = it.next(); if(!song.filepath.equalsIgnoreCase(song.getFormattedFilePath())) { System.out.println(String.format("current: %s\r\nproposed:%s\r\n", song.filepath, song.getFormattedFilePath())); if(!JamminUtils.moveFile(song.filepath, song.getFormattedFilePath())) { System.out.println(String.format("Failed to move file.\r\n\tcurrent: %s\r\n\tproposed:%s\r\n", song.filepath, song.getFormattedFilePath())); } } } } private static List<String> getFiles(String scanDirectory) { List<String> all = new ArrayList<String>(); Queue<String> scanQueue = new PriorityQueue<String>(); scanQueue.add(scanDirectory); while(!scanQueue.isEmpty()) { //Pop directory from queue File dir = new File(scanQueue.remove()); File[] files = dir.listFiles(); //Iterate through all items under directory for(int i=0; i<files.length; ++i) { String fullPath = files[i].getPath(); //Add unseen directory to queue if(files[i].isDirectory()) { if(!scanQueue.contains(fullPath)) { scanQueue.add(fullPath); } } else { all.add(fullPath); } } } return all; } private static List<SimpleSong> getAllSongs(String scanDirectory) { List<SimpleSong> all = new ArrayList<SimpleSong>(); List<String> allFiles = getFiles(scanDirectory); for(Iterator<String> it = allFiles.iterator(); it.hasNext();) { String filePath = it.next(); if(filePath.contains(".git")) { continue; } else if(filePath.endsWith(".mp3")) { //Otherwise process the file all.add(new SimpleSong(filePath)); } else { System.out.println("Ignored file: " + filePath); } } if(PRINT) { JamminUtils.Print(all); } return all; } private static List<String> findEmptyDirs(String scanDirectory) { List<String> all = new ArrayList<String>(); Queue<String> scanQueue = new PriorityQueue<String>(); scanQueue.add(scanDirectory); while(!scanQueue.isEmpty()) { //Pop directory from queue File dir = new File(scanQueue.remove()); File[] files = dir.listFiles(); // if(files.length == 1) { // System.out.println("empty dir: " + dir.getPath()); // } boolean hasMusic = false; //Iterate through all items under directory for(int i=0; i<files.length; ++i) { String fullPath = files[i].getPath(); //Add unseen directory to queue if(files[i].isDirectory()) { if(!scanQueue.contains(fullPath)) { scanQueue.add(fullPath); hasMusic = true; } } else { if(fullPath.endsWith(".mp3")) { hasMusic = true; } all.add(fullPath); } } if(!hasMusic) { System.out.println("HEY - doesn't have music: " + dir.getPath()); } } return all; } } <file_sep>/build.gradle plugins { id 'org.springframework.boot' version '2.4.3' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } sourceCompatibility = 11 version = '1.0' repositories { mavenCentral() mavenLocal() } dependencies { compile 'org.springframework.boot:spring-boot-starter' compile 'com.google.code.gson:gson' compile 'commons-collections:commons-collections:3.2' compile 'org.apache.commons:commons-io:1.3.2' } bootJar { mainClassName = 'wes.auto.jams.Main' }<file_sep>/src/main/java/wes/auto/jams/models/SimpleSong.java package wes.auto.jams.models; import java.io.File; import java.util.regex.Pattern; public class SimpleSong { private final static String[] uglyPhrases = {"[Explicit]", "[+Digital Booklet]", "[+digital booklet]", "(Album Version)", "(Amazon MP3 Exclusive Version)"}; public String title; public String artist; public String album; public String filepath; private boolean certainValidity; public boolean getCertainValidity() { return certainValidity; } /** * Retrieve file extension from file path (excluding the "." (dot)) * @return */ public String getFileExt() { return filepath.substring(filepath.lastIndexOf(".") + 1).trim(); } public int trackNumber; /** * Stringify track number with padded 0 for single-digit numbers * @return */ public String getFormattedTrackNumber() { return trackNumber < 10 ? "0" + trackNumber : "" + trackNumber; } public String getFormattedFilePath() { String[] tokens = this.filepath.split(Pattern.quote(File.separator)); tokens[tokens.length - 1] = String.format("%s %s.%s", getFormattedTrackNumber(), this.title, getFileExt()); tokens[tokens.length - 2] = this.album; tokens[tokens.length - 3] = this.artist; return String.join(File.separator, tokens); } public SimpleSong() { } public SimpleSong(String fullFilePath) { String[] tokens = fullFilePath.split(Pattern.quote(File.separator)); this.album = cleanPhrase(tokens[tokens.length - 2]); this.artist = cleanPhrase(tokens[tokens.length - 3]); this.filepath = fullFilePath.trim(); //determine title and track number String filename = tokens[tokens.length - 1].trim(); //remove extension filename = filename.substring(0, filename.lastIndexOf(".")); //separate disc/track information from filename int firstSpace = filename.indexOf(" "); try { if(firstSpace < 0) { //no track info?! this.title = cleanPhrase(filename); this.trackNumber = 0; certainValidity = false; } else { this.title = cleanPhrase(filename.substring(firstSpace + 1)); String trackInfo = filename.substring(0, firstSpace).trim(); if(trackInfo.contains("-")) { String[] indexNumbers = trackInfo.split("-"); this.trackNumber = Integer.parseInt(indexNumbers[indexNumbers.length - 1]); } else if(trackInfo.contains(" ")){ String[] indexNumbers = trackInfo.split(" "); this.trackNumber = Integer.parseInt(indexNumbers[indexNumbers.length - 1]); } else { this.trackNumber = Integer.parseInt(trackInfo); } certainValidity = true; } } catch(NumberFormatException ex) { //System.out.println("Error with file: " + this.filepath + ".\r\n\tError: " + ex.getMessage()); //no track info?! this.title = cleanPhrase(filename); this.trackNumber = 0; certainValidity = false; } } private static String cleanPhrase(String phrase) { for(int i=0; i<uglyPhrases.length; ++i) { phrase = phrase.replace(uglyPhrases[i], ""); } //replace multi-spaces phrase = phrase.replace(" ", " ").replace(" ", " ").replace("- ", ""); return phrase.trim(); } } <file_sep>/src/main/java/wes/auto/jams/utils/JamminUtils.java package wes.auto.jams.utils; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import com.google.gson.Gson; import wes.auto.jams.models.SimpleSong; public class JamminUtils { private static Gson gson = new Gson(); public static void Print(List<SimpleSong> songs) { System.out.println(gson.toJson(songs)); } public static boolean moveFile(String sourceStr, String destinationStr) { boolean ret = false; File source, destination; source = new File(sourceStr); destination = new File(destinationStr); try { FileUtils.copyFile(source, destination, true); try { FileUtils.forceDelete(source); } catch (IOException ex) { System.out.println("Failed to delete file.\r\n\tError: " + ex.getMessage()); } ret = true; } catch (IOException ex) { System.out.println("Failed to copy file.\r\n\tError: " + ex.getMessage()); } return ret; } }
ed6d6fcf4736d7d4ffcf1bd7e53ae2f747d95da3
[ "Java", "Gradle" ]
4
Java
weswalker125/JautoJams
83752cf4fe82b67a857c1e8b20307559d9791ed3
e98ce8574fda5e7dc77aeb928ff968b1b43afd74
refs/heads/master
<file_sep>version: '3' services: workspace: build: . command: sls offline -o 0.0.0.0 --printOutput volumes: - .:/code tty: true ports: - "3000:3000" environment: TEST_ENV: ${TEST_ENV} AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID} AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY} <file_sep>import os import json def run(event, context): test_env = os.getenv('TEST_ENV') body = {'envValue': test_env} response = { 'statusCode': '200', 'headers': 'application/json', 'body': json.dumps(body) } return response <file_sep>## Python Install packages <file_sep>FROM lambci/lambda:build-python3.7 ADD . /code WORKDIR /code RUN yum install -y gcc-c++ make RUN curl -sL https://rpm.nodesource.com/setup_10.x | bash - RUN yum install -y nodejs RUN npm install -g serverless RUN npm install RUN pip install -r requirements.txt CMD /bin/bash <file_sep># api-gateway-lambda-dev-env ## Description - Example of a local development using AWS-ApiGateway and Lambda ## Requirement - Docker & Docker-Compose - Serverless ## Quick Start ```bash $ git clone <EMAIL>:myoshioka/api-gateway-lambda-dev-env.git $ cd api-gateway-lambda-dev-env $ docker-compose up -d ``` ## Usage - Access `http://localhost:3000/` ## Author [<NAME>](https://github.com/myoshioka)
1759e9ffc017e6a1e090a10cff9475d23c269deb
[ "YAML", "Markdown", "Python", "Text", "Dockerfile" ]
5
YAML
myoshioka/api-gateway-lambda-dev-env
9de8eab2e25c8ab5b6c9f5de4a727ea74617f7d3
e6c137f30a8241f75745a17ba6d8aff29a87bf0f
refs/heads/master
<repo_name>BSUIR-4-course-7-semester/SDH-Lab-2<file_sep>/main.py from math import sin, pi, ceil, sqrt, cos import matplotlib.pyplot as plt INITIAL_PHASE = pi / 8 def harmonic_signal_function(n, N, phase=0.0): return sin(2 * pi * n / N + phase) def calc_M_vector(N): K = 3 * N / 4 K = 0 MAX_M = N * 5 M_vector = [N - 1] step = (MAX_M - K) / (4 * 8) m = N - 1 - step while m > K: M_vector.insert(0, round(m)) m -= step m = N - 1 + step while m < MAX_M: M_vector.append(round(m)) m += step return M_vector def calc_mean_square_value(vector): return sqrt(sum([v * v for v in vector]) / len(vector)) NORMAL_MSV = 0.707 def calc_mean_square_value_error(mean_square_value): return NORMAL_MSV - mean_square_value NORMAL_AMPLITUDE = 1 def calc_amplitude_error(amplitude): return NORMAL_AMPLITUDE - amplitude def calc_mean_square_deviation(vector, mathematical_expectation): return sqrt(sum([v * v - pow(mathematical_expectation, 2) for v in vector]) / len(vector)) def calc_math_expectation(vector): return sum(vector) / len(vector) def calc_amplitude(signal, M): pack = zip(signal, [i for i in range(len(signal))]) Asin = (2 / M) * sum(map(lambda a: a[0] * sin(2 * pi * a[1] / M), pack)) Acos = (2 / M) * sum(map(lambda a: a[0] * cos(2 * pi * a[1] / M), pack)) return sqrt(Asin * Asin + Acos * Acos) def calc_amplitude_vector(signals, M_vector): pack = zip(signals, M_vector) return [calc_amplitude(signal, m) for signal, m in pack] def main(): N = 128 M_vector = calc_M_vector(N) # without initial phase signals = [[harmonic_signal_function(n, N) for n in range(0, m + 1)] for m in M_vector] # with initial phase signals_with_phase = [[harmonic_signal_function(n, N, INITIAL_PHASE) for n in range(0, m + 1)] for m in M_vector] # mean_square_value_vector_with_phase = [calc_mean_square_value(signal) for signal in signals] mean_square_value_vector = [calc_mean_square_value(signal) for signal in signals_with_phase] math_exp_vector = [calc_math_expectation(signal) for signal in signals] pack = zip(signals, math_exp_vector) mean_square_deviation_vector = [calc_mean_square_deviation(a[0], a[1]) for a in pack] # mean_square_value_error_vector_with_phase = [calc_mean_square_value_error(msv) for msv in mean_square_value_vector_with_phase] mean_square_value_error_vector = [calc_mean_square_value_error(msv) for msv in mean_square_value_vector] mean_square_deviation_error_vector = [calc_mean_square_value_error(msd) for msd in mean_square_deviation_vector] # plt.plot(M_vector, mean_square_value_error_vector) # plt.show() # plt.plot(M_vector, calc_amplitude_vector(signals, M_vector)) # plt.plot(M_vector, list(map(lambda a: calc_amplitude_error(a), calc_amplitude_vector(signals, M_vector)))) # plt.show() plt.figure(1) plt.subplot(211) plt.title('Ошибка СКЗ') plt.plot(M_vector, mean_square_value_error_vector) plt.plot(M_vector, mean_square_deviation_error_vector) # plt.plot(M_vector, mean_square_value_error_vector_with_phase) plt.subplot(212) plt.title('Ошибка амплитуды') # plt.plot(M_vector, calc_amplitude_vector(signals_with_phase, M_vector)) # plt.plot(M_vector, calc_amplitude_vector(signals, M_vector)) # plt.plot(M_vector, list(map(lambda a: calc_amplitude_error(a), calc_amplitude_vector(signals_with_phase, M_vector)))) plt.plot(M_vector, list(map(lambda a: calc_amplitude_error(a), calc_amplitude_vector(signals, M_vector)))) plt.show() if __name__ == "__main__": main()<file_sep>/README.md # SDH-Lab-2 # Цифровая обработка сигнала Цель работы – исследовать влияние длительности временного интервала анализа на точность определения параметров периодического сигнала.
6dadb43a60b34769b794aa75565b2cfcd6fbc460
[ "Markdown", "Python" ]
2
Python
BSUIR-4-course-7-semester/SDH-Lab-2
e4c36e13cc247d611eb0bf221448808fd6fca436
5515ad0c90b9b15c864e5d316af91997c42fffed
refs/heads/master
<repo_name>cburleso/CS228<file_sep>/Deliverable.py import os, sys import shutil sys.path.insert(0, '..') from pygameWindow import PYGAME_WINDOW from pygameWindow_Del03 import PYGAME_WINDOW import Leap import constants import numpy as np import pickle class DELIVERABLE: def __init__(self): self.controller = Leap.Controller() self.pygameWindow = PYGAME_WINDOW() self.x = 400 self.y = 400 self.xMin = 1000.0 self.xMax = -1000.0 self.yMin = 1000.0 self.yMax = -1000.0 self.previousNumberOfHands = 0 self.currentNumberOfHands = 0 self.gestureData = np.zeros((5, 4, 6), dtype='f') self.gestureCount = 0 self.Create_Directory() def Handle_Frame(self, frame): global x, y, xMin, xMax, yMin, yMax hand = frame.hands[0] fingers = hand.fingers i = 0 for finger in fingers: self.Handle_Finger(finger, i) i += 1 if self.Recording_Is_Ending(): print(self.gestureData) self.Save_Gesture() def Handle_Finger(self, finger, i): for j in range(4): bone = finger.bone(j) fingerWidth = 4 - j self.Handle_Bone(bone, fingerWidth, i, j) def Handle_Bone(self, bone, fingerWidth, i, j): tip = bone.next_joint base = bone.prev_joint # For gesture recording if self.Recording_Is_Ending(): self.gestureData[i,j,0] = base[0] self.gestureData[i,j,1] = base[1] self.gestureData[i,j,2] = base[2] self.gestureData[i,j,3] = tip[0] self.gestureData[i,j,4] = tip[1] self.gestureData[i,j,5] = tip[2] xBase, yBase = self.Handle_Vector_From_Leap(base) xTip, yTip = self.Handle_Vector_From_Leap(tip) if self.currentNumberOfHands == 1: handColor = (102, 255, 102) # Green else: handColor = (255, 0, 0) # Red self.pygameWindow.Draw_Line(xBase, yBase, xTip, yTip, fingerWidth, handColor) def Handle_Vector_From_Leap(self, v): global xMax, xMin, yMax, yMin xVal = v[0] yVal = v[2] if (xVal < self.xMin): self.xMin = xVal if (xVal > self.xMax): self.xMax = xVal if (yVal < self.yMin): self.yMin = yVal if (yVal > self.yMax): self.yMax = yVal # Scale x and y coordinates xVal = self.Scale(xVal, self.xMin, self.xMax, 0, constants.pygameWindowWidth) yVal = self.Scale(yVal, self.yMin, self.yMax, 0, constants.pygameWindowDepth) return xVal, yVal def Scale(self, val, minOldRange, maxOldRange, minNewRange, maxNewRange): diff = val - minOldRange oldRange = maxOldRange - minOldRange newRange = maxNewRange - minNewRange if (oldRange == 0): return val oldFraction = diff / oldRange newVal = oldFraction * newRange return newVal def Save_Gesture(self): gestureF = open('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/userData/gesture%s.p' % self.gestureCount, 'wb') pickle.dump(self.gestureData, gestureF) gestureF.close() self.gestureCount += 1 def Create_Directory(self): shutil.rmtree('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/userData') # Delete previous os.mkdir('userData') # Create new def Recording_Is_Ending(self): if (self.previousNumberOfHands == 2): if (self.currentNumberOfHands == 1): return True def Run_Forever(self): while True: # Run until the user shuts down the program self.Run_Once() def Run_Once(self): self.pygameWindow.Prepare() # Create user window frame = self.controller.frame() # Capture a frame object for hand detection self.currentNumberOfHands = len(frame.hands) if (len(frame.hands) > 0): self.Handle_Frame(frame) self.pygameWindow.Reveal() # Update window frame self.previousNumberOfHands = self.currentNumberOfHands <file_sep>/pygameWindow_Del03.py import pygame import constants class PYGAME_WINDOW: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((constants.pygameWindowWidth, constants.pygameWindowDepth)) def Prepare(self): self.screen.fill((255, 255, 255)) def Reveal(self): pygame.display.update() def Draw_Black_Circle(self, x, y): pygame.draw.circle(self.screen, (0,0,0), (x, y), 20) def Draw_Line(self, xBase, yBase, xTip, yTip, fingerWidth, color): pygame.draw.line(self.screen, color, (xBase, yBase), (xTip, yTip), fingerWidth) <file_sep>/Del8/ASLCoinCollector.py import sys sys.path.insert(0, '../..') import Leap import constants import pickle from pygameWindow import PYGAME_WINDOW import random import numpy as np import threading import time import Tkinter as tk from Tkinter import * from PIL import Image, ImageTk database = pickle.load(open('userData/database.p', 'rb')) # Calculating top 3 users mostCoins = 0 numUsers = 0 for name in database: numUsers += 1 if (database[name]['numCoins'] > mostCoins): mostCoins = database[name]['numCoins'] firstPlace = name + " (" + str(mostCoins) + ")" # Calculate second place user mostCoins2 = 0 for name in database: if ((database[name]['numCoins'] > mostCoins2) & (database[name]['numCoins'] < mostCoins)): mostCoins2 = database[name]['numCoins'] secondPlace = name + " (" + str(mostCoins2) + ")" # Calculate third place user mostCoins3 = 0 for name in database: if ((database[name]['numCoins'] > mostCoins3) & (database[name]['numCoins'] < mostCoins2)): mostCoins3 = database[name]['numCoins'] thirdPlace = name + " (" + str(mostCoins3) + ")" if (numUsers == 0): firstPlace = "N/A" secondPlace = "N/A" thirdPlace = "N/A" # -------------------TKINTER WINDOW START-------------------- userName = "" root = tk.Tk() canvas1 = tk.Canvas(root, width = 400, height = 300) canvas1.pack() entry1 = tk.Entry (root) canvas1.create_window(180, 220, window=entry1) def getUsername(): global userName, database userName = entry1.get() if userName in database: print('Welcome back, ' + userName + '.') database[userName]['logins'] += 1 else: database[userName] = {'logins' : 1} userProgress = database[userName] userProgress['currDigitDict'] = [0, 1, 2] userProgress['numCoins'] = 0 print('Welcome, ' + userName + '.') print(database) pickle.dump(database, open('userData/database.p', 'wb')) root.destroy() def showHighscores(): load = Image.open("smallMedals.jpg") render = ImageTk.PhotoImage(load) img = Label(image=render) img.image = render img.place(x=-55, y=0) text = Label(text=firstPlace) text.place(x=40, y=110) text2 = Label(text=secondPlace) text2.place(x=160, y=110) text3 = Label(text=thirdPlace) text3.place(x=296, y=110) loginButton = tk.Button(text='Login', command=getUsername) highscoreButton = tk.Button(text='Highscores', command=showHighscores) canvas1.create_window(270, 220, window=loginButton) canvas1.create_window(200, 260, window=highscoreButton) root.mainloop() clf = pickle.load(open('userData/classifier.p', 'rb')) testData = np.zeros((1, 30), dtype = 'f') controller = Leap.Controller() pygameWindow = PYGAME_WINDOW() # Create user display window print(pygameWindow) x = 400 y = 400 xMin = 1000.0 xMax = -1000.0 yMin = 1000.0 yMax = -1000.0 prevNumCoins = database[userName]['numCoins'] # Get prev number of coins from user's last session handCenteredTimer = 0 # Timer for how long hand is centered before entering handleState1 greenCheckTimer = 0 # Timer for how long green check is presented to user digitTimer = 0 # Timer for how long user is presented with digit signCorrect = 0 # Number of times KNN recognizes digit successfully signed signTimer = 0 # Timer to maintain total duration of sign being presented numHearts = 3 # Number of "lives" user has (1 missed digit = 1 less life) numCoins = 0 # Reset bag of coins to zero for each session numIndex = 0 # Index value which iterates over current digit dictionary for the user coinStreak = 0 currDigitList = database[userName]['currDigitDict'] digitToSign = currDigitList[numIndex] # Initial digit to sign globalCoinChange = 0 missTimer = 0 miss = False programState = 0 beatPrev = 0 def Handle_Frame(frame): global x, y, xMin, xMax, yMin, yMax hand = frame.hands[0] fingers = hand.fingers for finger in fingers: Handle_Finger(finger) def Handle_Finger(finger): for i in range(4): bone = finger.bone(i) fingerWidth = 4 - i Handle_Bone(bone, fingerWidth) def Handle_Bone(bone, fingerWidth): tip = bone.next_joint base = bone.prev_joint xBase, yBase = Handle_Vector_From_Leap(base) xTip, yTip = Handle_Vector_From_Leap(tip) pygameWindow.Draw_Black_Line(xBase, yBase, xTip, yTip, fingerWidth) def Handle_Vector_From_Leap(v): global xMax, xMin, yMax, yMin xVal = v[0] yVal = v[2] if (xVal < xMin): xMin = xVal if (xVal > xMax): xMax = xVal if (yVal < yMin): yMin = yVal if (yVal > yMax): yMax = yVal # Scale x and y coordinates xVal = Scale(xVal, xMin, xMax, 0, constants.pygameWindowWidth) yVal = Scale(yVal, yMin, yMax, 0, constants.pygameWindowDepth) return xVal, yVal def Scale(val, minOldRange, maxOldRange, minNewRange, maxNewRange): maxNewRange = maxNewRange / 2 diff = val - minOldRange oldRange = maxOldRange - minOldRange newRange = maxNewRange - minNewRange if (oldRange == 0): return val oldFraction = diff / oldRange newVal = oldFraction * newRange return newVal def CenterData(X): allXCoordinates = X[0,::3] XmeanValue = allXCoordinates.mean() X[0,::3] = allXCoordinates - XmeanValue allYCoordinates = X[0,1::3] YmeanValue = allYCoordinates.mean() X[0,1::3] = allYCoordinates - YmeanValue allZCoordinates = X[0,2::3] ZmeanValue = allZCoordinates.mean() X[0,2::3] = allZCoordinates - ZmeanValue return X def HandCentered(): frame = controller.frame() centered = True hand = frame.hands[0] fingers = hand.fingers targetFinger = fingers[2] targetBone = targetFinger.bone(0) targetJoint = targetBone.prev_joint xBaseJoint, yBaseJoint = Handle_Vector_From_Leap(targetJoint) if (xBaseJoint <= 110): centered = False if (xBaseJoint >= 225): centered = False if (yBaseJoint <= 250): centered = False if (yBaseJoint >= 350): centered = False return centered def DrawImageToHelpUserPutTheirHandOverTheDevice(): pygameWindow.Prepare() pygameWindow.drawHandImage() pygameWindow.Reveal() def HandOverDevice(): frame = controller.frame() if (len(frame.hands) > 0): return True else: return False def HandleState0(): global programState DrawImageToHelpUserPutTheirHandOverTheDevice() if HandOverDevice(): programState = 1 def HandleState1(): global programState, handCenteredTimer pygameWindow.Prepare() frame = controller.frame() if (handCenteredTimer > 100): programState = 2 hand = frame.hands[0] Handle_Frame(frame) fingers = hand.fingers targetFinger = fingers[2] targetBone = targetFinger.bone(0) # Middle Metacarpal targetJoint = targetBone.prev_joint xBaseJoint, yBaseJoint = Handle_Vector_From_Leap(targetJoint) if (xBaseJoint <= 110): pygameWindow.promptHandRight() handCenteredTimer = 0 if (xBaseJoint >= 225): pygameWindow.promptHandLeft() handCenteredTimer = 0 if (yBaseJoint <= 250): pygameWindow.promptHandDown() handCenteredTimer = 0 if (yBaseJoint >= 350): pygameWindow.promptHandUp() handCenteredTimer = 0 if (xBaseJoint > 110): # If hand is centered if (xBaseJoint < 225): if (yBaseJoint > 250): if (yBaseJoint < 350): pygameWindow.promptThumbsUp() handCenteredTimer += 1 if HandOverDevice() == False: programState = 0 handCenteredTimer = 0 pygameWindow.Reveal() def HandleState2(): global programState, digitToSign, testData, clf, signCorrect, digitTimer, handCenteredTimer, currDigitList, numIndex, signTimer, numCoins, prevNumCoins, numHearts, coinStreak, globalCoinChange, miss, missTimer, coinMiss, beatPrev digitTimer += 1 # Time viewing random digit signTimer += 1 # Time viewing ASL sign #database = pickle.load(open('userData/database.p', 'rb')) pygameWindow.Prepare() if HandOverDevice(): frame = controller.frame() hand = frame.hands[0] Handle_Frame(frame) if (HandCentered() == False): handCenteredTimer = 0 programState = 1 attemptsDict = 'digit' + str(digitToSign) + 'attempts' successesDict = 'digit' + str(digitToSign) + 'successes' if (miss): if (missTimer < 5): missTimer += 1 pygameWindow.promptMiss(coinMiss) else: miss = False missTimer = 0 # Determine how much coins user earns for each success try: numSuccess = database[userName][successesDict] except: numSuccess = 0 if (numSuccess == 0): coinChange = 1 if (numSuccess == 1): coinChange = 1 if (numSuccess == 2): coinChange = 2 if (numSuccess > 2): coinChange = 3 globalCoinChange = coinChange # Determine how long ASL gesture should be presented to user (depending on number of successes # with the current digit to sign) & length of time they have to sign the gesture try: if (database[userName][successesDict] == 1): signTimerLimit = 25 digitTimerLimit = 15 elif (database[userName][successesDict] == 2): signTimerLimit = 10 digitTimerLimit = 15 elif (database[userName][successesDict] > 2): signTimerLimit = 0 digitTimerLimit = 10 # Decrease time user has to sign digit elif (database[userName][successesDict] > 3): digitTimerLimit = 10 else: signTimerLimit = 20 # Show ASL gesture the entire time digitTimerLimit = 15 except: signTimerLimit = 25 digitTimerLimit = 15 if (signTimer < signTimerLimit): pygameWindow.promptASLsign(digitToSign) pygameWindow.promptASLnum(digitToSign) # Get number of times user has been presented with digit userRecord = database[userName] try: numSeen = database[userName][attemptsDict] except: userRecord[attemptsDict] = 1 numSeen = 1 pygameWindow.promptNumSeen(numSeen) try: pygameWindow.promptNumSuccess(database[userName][successesDict]) except: pygameWindow.promptNumSuccess(0) pygameWindow.promptCurrCoinBag(numCoins) pygameWindow.promptPrevCoins(prevNumCoins) pygameWindow.promptStreak(coinStreak) pygameWindow.promptClock(((digitTimer - digitTimerLimit) * -1)) if (numHearts != 0): pygameWindow.promptNumHearts(numHearts) #pygameWindow.promptLeaderboard(firstPlace, secondPlace, thirdPlace) # KNN k = 0 for finger in range(5): finger = hand.fingers[finger] for b in range(4): if b == 0: bone = finger.bone(Leap.Bone.TYPE_METACARPAL) elif b == 1: bone = finger.bone(Leap.Bone.TYPE_PROXIMAL) elif b == 2: bone = finger.bone(Leap.Bone.TYPE_INTERMEDIATE) elif b == 3: bone = finger.bone(Leap.Bone.TYPE_DISTAL) boneBase = bone.prev_joint boneTip = bone.next_joint xBase = boneBase[0] yBase = boneBase[1] zBase = boneBase[2] xTip = boneTip[0] yTip = boneTip[1] zTip = boneTip[2] if ((b == 0)or(b == 3)): testData[0, k] = xTip testData[0, k+1] = yTip testData[0, k+2] = zTip k = k+3 testData = CenterData(testData) predictedClass = clf.Predict(testData) #print(predictedClass) if (predictedClass == digitToSign): pygameWindow.promptHoldHand() signCorrect += 1 else: pygameWindow.promptIce() signCorrect = 0 if (digitTimer > digitTimerLimit): # Change digit and increment attempt if not signed correctly coinMiss = coinChange miss = True database[userName][attemptsDict] += 1 # Increment user attempt at digit if (numCoins != 0): numCoins -= coinChange if (numHearts != 0): numHearts -= 1 if (numHearts == 0): numCoins = 0 database[userName]['numCoins'] = numCoins pickle.dump(database, open('userData/database.p', 'wb')) # Change digit if (numIndex == len(database[userName]['currDigitDict']) - 1): numIndex = 0 else: numIndex += 1 digitToSign = database[userName]['currDigitDict'][numIndex] digitTimer = 0 coinStreak = 0 # Set coin streak back to zero signTimer = 0 if (signCorrect == 7): # User successfully signed digit (recognized by KNN 7 times) try: database[userName][successesDict] += 1 except: userRecord[successesDict] = 1 database[userName][attemptsDict] += 1 # Increment user attempt at digit digitTimer = 0 coinStreak += 1 # Increment coin streak if (coinStreak == 5): numCoins += 5 elif (coinStreak == 10): numCoins += 15 else: numCoins += coinChange # Increment number of gold coins depending on user success with digit (calculated for coinChange) if (prevNumCoins > 2): if (numCoins > prevNumCoins): beatPrev += 1 if (beatPrev == 1): numCoins += 10 database[userName]['numCoins'] = numCoins # Update database info # Check if user passed 'level one' (digits 0 through 2) levelOnePass = True for digit in range(3): try: digitDict = 'digit' + str(digit) + 'successes' if (database[userName][digitDict] < 1): levelOnePass = False break except: levelOnePass = False break if (levelOnePass): # Change subset of digits shown to three new (3 through 5) database[userName]['currDigitDict'] = [0, 1, 2, 3, 4, 5] # Check if user passed 'level two' (digits 3 through 5) levelTwoPass = True for digit in range(3, 6): try: digitDict = 'digit' + str(digit) + 'successes' if (database[userName][digitDict] < 1): levelTwoPass = False break except: levelTwoPass = False break if (levelTwoPass): # Change subset of digits shown to four new (6 through 9) * all digits database[userName]['currDigitDict'] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Increment to next digit in the list if (numIndex == len(database[userName]['currDigitDict']) - 1): numIndex = 0 else: numIndex += 1 digitToSign = database[userName]['currDigitDict'][numIndex] pickle.dump(database, open('userData/database.p', 'wb')) signTimer = 0 programState = 3 else: programState = 0 digitTimer = 0 signTimer = 0 pygameWindow.Reveal() def HandleState3(): # To show 'success' check mark when user correctly signs digit global programState, randNum, greenCheckTimer, numIndex, levelOneNums, numHearts, coinStreak, globalCoinChange, beatPrev if (coinStreak == 5): checkTimerLimit = 300 elif (coinStreak == 10): checkTimerLimit = 300 else: checkTimerLimit = 5 if (beatPrev == 1): checkTimerLimit = 300 greenCheckTimer += 1 pygameWindow.Prepare() frame = controller.frame() Handle_Frame(frame) pygameWindow.promptSuccess(numHearts, coinStreak, globalCoinChange, beatPrev) if HandOverDevice(): if HandCentered(): if (greenCheckTimer > checkTimerLimit): if (numHearts != 3): numHearts += 1 programState = 2 greenCheckTimer = 0 else: programState = 1 greenCheckTimer = 0 else: programState = 0 greenCheckTimer = 0 pygameWindow.Reveal() # Main program loop while True: if programState == 0: HandleState0() elif programState == 1: HandleState1() elif programState == 2: HandleState2() elif programState == 3: HandleState3() <file_sep>/Del8/pygameWindow.py import pygame import constants class PYGAME_WINDOW: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((constants.pygameWindowWidth, constants.pygameWindowDepth)) def Prepare(self): self.screen.fill((255, 255, 255)) def Reveal(self): pygame.display.update() def Draw_Black_Circle(self, x, y): pygame.draw.circle(self.screen, (0,0,0), (x, y), 20) def Draw_Black_Line(self, xBase, yBase, xTip, yTip, fingerWidth): pygame.draw.line(self.screen, (0, 0, 0), (xBase, yBase), (xTip, yTip), fingerWidth) def drawHandImage(self): handImg = pygame.image.load('handOverDevice.jpg') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandLeft(self): handImg = pygame.image.load('moveLeft.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandRight(self): handImg = pygame.image.load('moveRight.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandUp(self): handImg = pygame.image.load('moveUp.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandDown(self): handImg = pygame.image.load('moveDown.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptSuccess(self, numHearts, coinStreak, coinChange, beatPrev): if (coinStreak == 5): # Show 5 coin streak visual streakImg = pygame.image.load('5xstreak.JPG') self.screen.blit(streakImg, (constants.pygameWindowWidth - 480, 50)) elif (coinStreak == 10): # Show 10 coin streak visual streakImg = pygame.image.load('10xstreak.JPG') self.screen.blit(streakImg, (constants.pygameWindowWidth - 500, 50)) elif (beatPrev == 1): beatPrevImg = pygame.image.load('beatPrev.JPG') self.screen.blit(beatPrevImg, (constants.pygameWindowWidth - 480, 50)) else: # Otherwise show simple green check (and heart if applicable) # Coin visual coinImg = pygame.image.load('goldCoin.png') coinImg = pygame.transform.scale(coinImg, (50, 50)) self.screen.blit(coinImg, (545, 140)) checkImg = pygame.image.load('greenCheck.png') self.screen.blit(checkImg, (constants.pygameWindowWidth - 460, 0)) font = pygame.font.Font('freesansbold.ttf', 32) text = font.render(('+ ' + str(coinChange)), True, (0, 128, 0)) self.screen.blit(text, (525, 150)) # Heart Visual (if numHearts < 3) if (numHearts < 3): text = font.render('+', True, (255, 0, 0)) self.screen.blit(text, (520, 340)) heartImg = pygame.image.load('1lives.jpg') self.screen.blit(heartImg, (540, 340)) def promptThumbsUp(self): handImg = pygame.image.load('thumbsUp.png') handImg = pygame.transform.scale(handImg, (325,325)) self.screen.blit(handImg, (constants.pygameWindowWidth - 350, 0)) def promptASLnum(self, mode): if mode == 0: pic = pygame.image.load('0.png') elif mode == 1: pic = pygame.image.load('1.png') elif mode == 2: pic = pygame.image.load('2.png') elif mode == 3: pic = pygame.image.load('3.png') elif mode == 4: pic = pygame.image.load('4.png') elif mode == 5: pic = pygame.image.load('5.png') elif mode == 6: pic = pygame.image.load('6.png') elif mode == 7: pic = pygame.image.load('7.png') elif mode == 8: pic = pygame.image.load('8.png') else: pic = pygame.image.load('9.png') pic = pygame.transform.scale(pic, (375, 375)) self.screen.blit(pic, (375, 0)) def promptASLsign(self, mode): if mode == 0: pic = pygame.image.load('asl0.png') elif mode == 1: pic = pygame.image.load('asl1.png') elif mode == 2: pic = pygame.image.load('asl2.png') elif mode == 3: pic = pygame.image.load('asl3.png') elif mode == 4: pic = pygame.image.load('asl4.png') elif mode == 5: pic = pygame.image.load('asl5.png') elif mode == 6: pic = pygame.image.load('asl6.png') elif mode == 7: pic = pygame.image.load('asl7.png') elif mode == 8: pic = pygame.image.load('asl8.png') else: pic = pygame.image.load('asl9.png') pic = pygame.transform.scale(pic, (375, 375)) self.screen.blit(pic, (375, 375)) def promptNumSeen(self, numSeen): # Eye visual eyeImg = pygame.image.load('eye.jpg') eyeImg = pygame.transform.scale(eyeImg, (130, 130)) self.screen.blit(eyeImg, (0, 470)) # Digit (# seen) visual font = pygame.font.Font('freesansbold.ttf', 32) text = font.render('x' + str(numSeen), True, (0, 0, 0)) self.screen.blit(text, (120, 538)) def promptNumSuccess(self, numSuccess): # Green check visual checkImg = pygame.image.load('greenCheck.png') checkImg = pygame.transform.scale(checkImg, (160, 160)) self.screen.blit(checkImg, (140, 470)) # Digit (# successes) visual font = pygame.font.Font('freesansbold.ttf', 32) text = font.render('x' + str(numSuccess), True, (0, 0, 0)) self.screen.blit(text, (250, 538)) def promptCurrCoinBag(self, numCoins): # Money bag check visual bagImg = pygame.image.load('moneyBag.jpg') bagImg = pygame.transform.scale(bagImg, (90, 70)) self.screen.blit(bagImg, (0, 600)) # Coin visual coinImg = pygame.image.load('goldCoin.png') coinImg = pygame.transform.scale(coinImg, (50, 50)) self.screen.blit(coinImg, (120, 610)) # Digit (# coins) visual font = pygame.font.Font('freesansbold.ttf', 32) text = font.render('x' + str(numCoins), True, (0, 0, 0)) self.screen.blit(text, (175, 630)) # Colon between coin pic and number font2 = pygame.font.Font('freesansbold.ttf', 32) text2 = font2.render(':', True, (0, 0, 0)) self.screen.blit(text2, (95, 618)) def promptPrevCoins(self, prevNumCoins): prevSeshImg = pygame.image.load('lastSesh.JPG') self.screen.blit(prevSeshImg, (250, 590)) font2 = pygame.font.Font('freesansbold.ttf', 32) text2 = font2.render(str(prevNumCoins), True, (255, 0, 0)) self.screen.blit(text2, (285, 635)) def promptHoldHand(self): handImg = pygame.image.load('holdHand.png') handImg = pygame.transform.scale(handImg, (100, 100)) self.screen.blit(handImg, (150, 695)) def promptIce(self): iceImg = pygame.image.load('ice.png') iceImg = pygame.transform.scale(iceImg, (140, 120)) self.screen.blit(iceImg, (150, 690)) def promptLeaderboard(self, first, second, third): medalsImg = pygame.image.load('medals.jpg') medalsImg = pygame.transform.scale(medalsImg, (268, 80)) self.screen.blit(medalsImg, (115, 690)) font = pygame.font.Font('freesansbold.ttf', 16) text = font.render("1. " + first + " 2. " + second + " 3. " + third, True, (0, 0, 0)) self.screen.blit(text, (95, 765)) def promptNumHearts(self, numHearts): fileString = str(numHearts) + 'lives.jpg' heartsImg = pygame.image.load(fileString) self.screen.blit(heartsImg, (500, 750)) def promptStreak(self, coinStreak): streakImg = pygame.image.load('streakPic.JPG') self.screen.blit(streakImg, (540, 700)) font = pygame.font.Font('freesansbold.ttf', 32) text = font.render(str(coinStreak), True, (255, 165, 0)) self.screen.blit(text, (605, 712)) def promptMiss(self, coinMiss): font = pygame.font.Font('freesansbold.ttf', 32) text = font.render(('-' + str(coinMiss)), True, (255, 0, 0)) self.screen.blit(text, (180, 660)) def promptClock(self, timeLeft): clockImg = pygame.image.load('clock.jpg') clockImg = pygame.transform.scale(clockImg, (80, 80)) self.screen.blit(clockImg, (0, 690)) font = pygame.font.Font('freesansbold.ttf', 32) text = font.render((str(timeLeft)), True, (0, 0, 0)) if (timeLeft >= 0): self.screen.blit(text, (95, 735)) <file_sep>/Classify.py import pickle import numpy as np from knn import KNN openTrain7File = open('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/train7.p', 'rb') openTrain8File = open('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/train8.p', 'rb') openTest7File = open('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/test7.p', 'rb') openTest8File = open('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/test8.p', 'rb') def ReduceData(X): X = np.delete(X,1,1) X = np.delete(X,1,1) return X def CenterData(X): allXCoordinates = X[:,:,0,:] meanValue = allXCoordinates.mean() X[:,:,0,:] = allXCoordinates - meanValue allYCoordinates = X[:,:,1,:] meanValue = allYCoordinates.mean() X[:,:,1,:] = allYCoordinates - meanValue allZCoordinates = X[:,:,2,:] meanValue = allZCoordinates.mean() X[:,:,2,:] = allZCoordinates - meanValue return X train7 = pickle.load(openTrain7File) train7 = ReduceData(train7) train7 = CenterData(train7) train8 = pickle.load(openTrain8File) train8 = ReduceData(train8) train8 = CenterData(train8) test7 = pickle.load(openTest7File) test7 = ReduceData(test7) test7 = CenterData(test7) test8 = pickle.load(openTest8File) test8 = ReduceData(test8) test8 = CenterData(test8) ##print(train5.shape) ##print(train6.shape) ##print(test5.shape) ##print(test6.shape) def ReshapeData(set1,set2): X = np.zeros((2000,5*2*3),dtype='f') y = np.zeros(2000,dtype='f') for row in range(0,1000): col = 0 for j in range(0,5): for k in range(0,2): for m in range(0,3): y[row] = 5 y[row+1000] = 6 X[row,col] = set1[j,k,m,row] X[row+1000,col] = set2[j,k,m,row] col = col + 1 return X,y trainX, trainy = ReshapeData(train7, train8) testX, testy = ReshapeData(test7,test8) ##print(trainX) ##print(trainX.shape) ##print(trainy) ##print(trainy.shape) ##print(testX) ##print(testX.shape) ##print(testy) ##print(testy.shape) knn = KNN() knn.Use_K_Of(15) knn.Fit(trainX,trainy) predictCorrect = 0 for row in range(0,2000): prediction = int(knn.Predict(testX[row,:])) actualClass = int(testy[row]) #print(row,prediction,actualClass) if (prediction == actualClass): predictCorrect += 1 percentage = float(predictCorrect) percentage = percentage/2000 percentage = percentage * 100 print("Accuracy: " + str(percentage)) <file_sep>/Del05.py import numpy from Recorder import RECORDER Deliverable = RECORDER() Deliverable.Run_Forever() <file_sep>/Del7/Del7.py import sys sys.path.insert(0, '../..') import Leap import constants import pickle from pygameWindow import PYGAME_WINDOW import random import numpy as np import threading import time clf = pickle.load(open('userData/classifier.p', 'rb')) testData = np.zeros((1, 30), dtype = 'f') controller = Leap.Controller() pygameWindow = PYGAME_WINDOW() # Create user display window print(pygameWindow) x = 400 y = 400 xMin = 1000.0 xMax = -1000.0 yMin = 1000.0 yMax = -1000.0 timer = 0 timer2 = 0 randNum = random.randrange(0, 9) signCorrect = 0 timer2 = 0 programState = 0 def Handle_Frame(frame): global x, y, xMin, xMax, yMin, yMax hand = frame.hands[0] fingers = hand.fingers for finger in fingers: Handle_Finger(finger) def Handle_Finger(finger): for i in range(4): bone = finger.bone(i) fingerWidth = 4 - i Handle_Bone(bone, fingerWidth) def Handle_Bone(bone, fingerWidth): tip = bone.next_joint base = bone.prev_joint xBase, yBase = Handle_Vector_From_Leap(base) xTip, yTip = Handle_Vector_From_Leap(tip) pygameWindow.Draw_Black_Line(xBase, yBase, xTip, yTip, fingerWidth) def Handle_Vector_From_Leap(v): global xMax, xMin, yMax, yMin xVal = v[0] yVal = v[2] if (xVal < xMin): xMin = xVal if (xVal > xMax): xMax = xVal if (yVal < yMin): yMin = yVal if (yVal > yMax): yMax = yVal # Scale x and y coordinates xVal = Scale(xVal, xMin, xMax, 0, constants.pygameWindowWidth) yVal = Scale(yVal, yMin, yMax, 0, constants.pygameWindowDepth) return xVal, yVal def Scale(val, minOldRange, maxOldRange, minNewRange, maxNewRange): maxNewRange = maxNewRange / 2 diff = val - minOldRange oldRange = maxOldRange - minOldRange newRange = maxNewRange - minNewRange if (oldRange == 0): return val oldFraction = diff / oldRange newVal = oldFraction * newRange return newVal def CenterData(X): allXCoordinates = X[0,::3] XmeanValue = allXCoordinates.mean() X[0,::3] = allXCoordinates - XmeanValue allYCoordinates = X[0,1::3] YmeanValue = allYCoordinates.mean() X[0,1::3] = allYCoordinates - YmeanValue allZCoordinates = X[0,2::3] ZmeanValue = allZCoordinates.mean() X[0,2::3] = allZCoordinates - ZmeanValue return X def HandCentered(): frame = controller.frame() centered = True hand = frame.hands[0] fingers = hand.fingers targetFinger = fingers[2] targetBone = targetFinger.bone(0) targetJoint = targetBone.prev_joint xBaseJoint, yBaseJoint = Handle_Vector_From_Leap(targetJoint) if (xBaseJoint <= 110): centered = False if (xBaseJoint >= 225): centered = False if (yBaseJoint <= 250): centered = False if (yBaseJoint >= 350): centered = False return centered def DrawImageToHelpUserPutTheirHandOverTheDevice(): pygameWindow.Prepare() pygameWindow.drawHandImage() pygameWindow.Reveal() def HandOverDevice(): frame = controller.frame() if (len(frame.hands) > 0): return True else: return False def HandleState0(): global programState DrawImageToHelpUserPutTheirHandOverTheDevice() if HandOverDevice(): programState = 1 def HandleState1(): global programState, timer, centered pygameWindow.Prepare() frame = controller.frame() if (timer > 100): programState = 2 hand = frame.hands[0] Handle_Frame(frame) fingers = hand.fingers targetFinger = fingers[2] targetBone = targetFinger.bone(0) # Middle Metacarpal targetJoint = targetBone.prev_joint xBaseJoint, yBaseJoint = Handle_Vector_From_Leap(targetJoint) if (xBaseJoint <= 110): pygameWindow.promptHandRight() timer = 0 if (xBaseJoint >= 225): pygameWindow.promptHandLeft() timer = 0 if (yBaseJoint <= 250): pygameWindow.promptHandDown() timer = 0 if (yBaseJoint >= 350): pygameWindow.promptHandUp() timer = 0 if (xBaseJoint > 110): # If hand is centered if (xBaseJoint < 225): if (yBaseJoint > 250): if (yBaseJoint < 350): pygameWindow.promptThumbsUp() timer += 1 if HandOverDevice() == False: programState = 0 timer = 0 pygameWindow.Reveal() def HandleState2(): global programState, randNum, testData, clf, signCorrect pygameWindow.Prepare() if HandOverDevice(): frame = controller.frame() hand = frame.hands[0] Handle_Frame(frame) if (HandCentered() == False): programState = 1 pygameWindow.promptASLnum(randNum) pygameWindow.promptASLsign(randNum) # KNN k = 0 for finger in range(5): finger = hand.fingers[finger] for b in range(4): if b == 0: bone = finger.bone(Leap.Bone.TYPE_METACARPAL) elif b == 1: bone = finger.bone(Leap.Bone.TYPE_PROXIMAL) elif b == 2: bone = finger.bone(Leap.Bone.TYPE_INTERMEDIATE) elif b == 3: bone = finger.bone(Leap.Bone.TYPE_DISTAL) boneBase = bone.prev_joint boneTip = bone.next_joint xBase = boneBase[0] yBase = boneBase[1] zBase = boneBase[2] xTip = boneTip[0] yTip = boneTip[1] zTip = boneTip[2] if ((b == 0)or(b == 3)): testData[0, k] = xTip testData[0, k+1] = yTip testData[0, k+2] = zTip k = k+3 testData = CenterData(testData) predictedClass = clf.Predict(testData) print(predictedClass) if (predictedClass == randNum): signCorrect += 1 else: signCorrect = 0 if (signCorrect == 10): programState = 3 else: programState = 0 pygameWindow.Reveal() def HandleState3(): global programState, randNum, timer2 randNum = random.randrange(0, 9) # Choose new random digit timer2 += 1 pygameWindow.Prepare() frame = controller.frame() Handle_Frame(frame) pygameWindow.promptGreenCheck() if HandOverDevice(): if HandCentered(): if (timer2 > 100): programState = 2 timer2 = 0 else: programState = 1 timer2 = 0 else: programState = 0 timer2 = 0 pygameWindow.Reveal() while True: if programState == 0: HandleState0() elif programState == 1: HandleState1() elif programState == 2: HandleState2() elif programState == 3: HandleState3() <file_sep>/Del01.py import sys sys.path.insert(0, '..') # Used to allow program to find necessary packages import Leap # Module used to interact with Leap Motion device import constants controller = Leap.Controller() # Create an instance of a controller object from pygameWindow import PYGAME_WINDOW # Import class containing visual program # functions import random # Random module used to generate random (x,y) coordinates for the # black dot x = 400 # Initial x position for dot y = 400 # Initial y position for dot # Boundaries for dot movement within window xMin = 1000.0 xMax = -1000.0 yMin = 1000.0 yMax = -1000.0 # This function will randomly "roll" a four sided die, generating a random # change in the x or y coordinate position of the dot within the window ##def Perturb_Circle_Position(): ## global x, y ## fourSidedDieRoll = random.randint(1,4) ## if fourSidedDieRoll == 1: ## x -= 1 ## elif fourSidedDieRoll == 2: ## x += 1 ## elif fourSidedDieRoll == 3: ## y -= 1 ## else: ## y += 1 def Handle_Frame(frame): global x, y, xMin, xMax, yMin, yMax hand = frame.hands[0] fingers = hand.fingers indexFingerList = fingers.finger_type(Leap.Finger.TYPE_INDEX) indexFinger = indexFingerList[0] distalPhalanx = indexFinger.bone(Leap.Bone.TYPE_DISTAL) tip = distalPhalanx.next_joint x = int(tip[0]) y = int(tip[1]) if (x < xMin): xMin = x if (x > xMax): xMax = x if (y < yMin): yMin = y if (y > yMax): yMax = y def Scale(val, minVal, maxVal, lowVal, upVal): rangeOne = maxVal - minVal rangeTwo = upVal - lowVal if (val in range(int(minVal), int(maxVal))): val = abs(val)*3 return val # Initialize an instance of the PYGAME_WINDOW class to create function calls pygameWindow = PYGAME_WINDOW() print(pygameWindow) while True: # Run until the user shuts down the program pygameWindow.Prepare() # Creates user window frame = controller.frame() # Create a frame object for hand detection if (len(frame.hands) > 0): Handle_Frame(frame) pygameX = Scale(x, xMin, xMax, 0, constants.pygameWindowWidth) pygameY = Scale(y, yMin, yMax, 0, constants.pygameWindowDepth) pygameWindow.Draw_Black_Circle(int(pygameX), int(pygameY)) # Draw the black dot to the screen #Perturb_Circle_Position() # Randomly change dot position pygameWindow.Reveal() # Update window frame <file_sep>/Predict.py import matplotlib.pyplot as plt import numpy as np from knn import KNN knn = KNN() knn.Load_Dataset('iris.csv') x = knn.data[0:, 0] # col one / first iris feature y = knn.data[0:, 1] # col two / second iris feature # training set trainX = knn.data[::2, 1:3] # col two and three , 'even' rows trainy = knn.target[::2] # test set testX = knn.data[1::2, 1:3] # col two and three, 'odd' rows testy = knn.target[1::2] # applying kNN to Iris data set knn.Use_K_Of(15) knn.Fit(trainX, trainy) for i in range(75): actualClass = testy[i] prediction = knn.Predict(testX[i, :]) # print(actualClass, prediction) # colors matrix colors = np.zeros((3, 3), dtype='f') colors[0, :] = [1, 0.5, 0.5] colors[1, :] = [0.5, 1, 0.5] colors[2, :] = [0.5, 0.5, 1] # visualization lines # training points loop plt.figure() [numItems, numFeatures] = knn.data.shape for i in range(0, numItems / 2): itemClass = int(trainy[i]) currColor = colors[itemClass, :] plt.scatter(trainX[i, 0], trainX[i, 1], facecolor=currColor, edgecolor = 'black', s = 50, lw = 2) numCorrect = 0 # testing points loop [numItems, numFeatures] = knn.data.shape for i in range(0, numItems / 2): prediction = int(knn.Predict(testX[i, :])) edgeColor = colors[prediction, :] itemClass = int(testy[i]) currColor = colors[itemClass, :] if (prediction == itemClass): numCorrect += 1 plt.scatter(testX[i, 0], testX[i, 1], facecolor=currColor, s = 50, lw = 2, edgecolor = edgeColor) percentCorrect = float((numCorrect / 75.) * 100.) print(percentCorrect) #plt.scatter(trainX[:,0], trainX[:,1], c = trainy) # plot training set #plt.scatter(testX[:,0], testX[:,1], c = testy) # plot test set plt.show() <file_sep>/Del02.py import sys sys.path.insert(0, '..') # Used to allow program to find necessary packages import Leap # Module used to interact with Leap Motion device import constants controller = Leap.Controller() # Create an instance of a controller object from pygameWindow import PYGAME_WINDOW # Import class containing visual program # functions import random x = 400 # Initial x position for dot y = 400 # Initial y position for dot timer = 0 # Boundaries for dot movement within window xMin = 1000.0 xMax = -1000.0 yMin = 1000.0 yMax = -1000.0 def Handle_Frame(frame): global x, y, xMin, xMax, yMin, yMax hand = frame.hands[0] fingers = hand.fingers for finger in fingers: Handle_Finger(finger) def Handle_Finger(finger): for i in range(4): bone = finger.bone(i) fingerWidth = 4 - i Handle_Bone(bone, fingerWidth) def Handle_Bone(bone, fingerWidth): tip = bone.next_joint base = bone.prev_joint xBase, yBase = Handle_Vector_From_Leap(base) xTip, yTip = Handle_Vector_From_Leap(tip) pygameWindow.Draw_Black_Line(xBase, yBase, xTip, yTip, fingerWidth) def Handle_Vector_From_Leap(v): global xMax, xMin, yMax, yMin xVal = v[0] yVal = v[2] if (xVal < xMin): xMin = xVal if (xVal > xMax): xMax = xVal if (yVal < yMin): yMin = yVal if (yVal > yMax): yMax = yVal # Scale x and y coordinates xVal = Scale(xVal, xMin, xMax, 0, constants.pygameWindowWidth) yVal = Scale(yVal, yMin, yMax, 0, constants.pygameWindowDepth) return xVal, yVal def Scale(val, minOldRange, maxOldRange, minNewRange, maxNewRange): diff = val - minOldRange oldRange = maxOldRange - minOldRange newRange = maxNewRange - minNewRange if (oldRange == 0): return val oldFraction = diff / oldRange newVal = oldFraction * newRange return newVal # Initialize an instance of the PYGAME_WINDOW class to create function calls pygameWindow = PYGAME_WINDOW() print(pygameWindow) while True: # Run until the user shuts down the program pygameWindow.Prepare() # Create user window frame = controller.frame() # Create a frame object for hand detection if (len(frame.hands) > 0): Handle_Frame(frame) pygameWindow.Reveal() # Update window frame <file_sep>/Playback.py import numpy import pickle from Reader import READER Reader = READER() Reader.Draw_Gestures() <file_sep>/Del6/Del2.py import sys sys.path.insert(0, '../..') import Leap import constants import pickle from pygameWindow import PYGAME_WINDOW import random import numpy as np clf = pickle.load(open('userData/classifier.p', 'rb')) testData = np.zeros((1, 30), dtype = 'f') controller = Leap.Controller() x = 400 y = 400 xMin = 1000.0 xMax = -1000.0 yMin = 1000.0 yMax = -1000.0 def Handle_Frame(frame): global x, y, xMin, xMax, yMin, yMax hand = frame.hands[0] fingers = hand.fingers for finger in fingers: Handle_Finger(finger) def Handle_Finger(finger): for i in range(4): bone = finger.bone(i) fingerWidth = 4 - i Handle_Bone(bone, fingerWidth) def Handle_Bone(bone, fingerWidth): tip = bone.next_joint base = bone.prev_joint xBase, yBase = Handle_Vector_From_Leap(base) xTip, yTip = Handle_Vector_From_Leap(tip) pygameWindow.Draw_Black_Line(xBase, yBase, xTip, yTip, fingerWidth) def Handle_Vector_From_Leap(v): global xMax, xMin, yMax, yMin xVal = v[0] yVal = v[2] if (xVal < xMin): xMin = xVal if (xVal > xMax): xMax = xVal if (yVal < yMin): yMin = yVal if (yVal > yMax): yMax = yVal # Scale x and y coordinates xVal = Scale(xVal, xMin, xMax, 0, constants.pygameWindowWidth) yVal = Scale(yVal, yMin, yMax, 0, constants.pygameWindowDepth) return xVal, yVal def Scale(val, minOldRange, maxOldRange, minNewRange, maxNewRange): diff = val - minOldRange oldRange = maxOldRange - minOldRange newRange = maxNewRange - minNewRange if (oldRange == 0): return val oldFraction = diff / oldRange newVal = oldFraction * newRange return newVal def CenterData(X): allXCoordinates = X[0,::3] XmeanValue = allXCoordinates.mean() X[0,::3] = allXCoordinates - XmeanValue allYCoordinates = X[0,1::3] YmeanValue = allYCoordinates.mean() X[0,1::3] = allYCoordinates - YmeanValue allZCoordinates = X[0,2::3] ZmeanValue = allZCoordinates.mean() X[0,2::3] = allZCoordinates - ZmeanValue return X pygameWindow = PYGAME_WINDOW() print(pygameWindow) while True: pygameWindow.Prepare() frame = controller.frame() if (len(frame.hands) > 0): hand = frame.hands[0] Handle_Frame(frame) k = 0 for finger in range(5): finger = hand.fingers[finger] for b in range(4): if b == 0: bone = finger.bone(Leap.Bone.TYPE_METACARPAL) elif b == 1: bone = finger.bone(Leap.Bone.TYPE_PROXIMAL) elif b == 2: bone = finger.bone(Leap.Bone.TYPE_INTERMEDIATE) elif b == 3: bone = finger.bone(Leap.Bone.TYPE_DISTAL) boneBase = bone.prev_joint boneTip = bone.next_joint xBase = boneBase[0] yBase = boneBase[1] zBase = boneBase[2] xTip = boneTip[0] yTip = boneTip[1] zTip = boneTip[2] if ((b == 0)or(b == 3)): testData[0, k] = xTip testData[0, k+1] = yTip testData[0, k+2] = zTip k = k+3 #print(testData) testData = CenterData(testData) predictedClass = clf.Predict(testData) print(predictedClass) pygameWindow.Reveal() <file_sep>/Del8/Del8.py import sys sys.path.insert(0, '../..') import Leap import constants import pickle from pygameWindow import PYGAME_WINDOW import random import numpy as np import threading import time # User login database = pickle.load(open('userData/database.p', 'rb')) userName = raw_input('Please enter your name: ') if userName in database: print('Welcome back, ' + userName + '.') database[userName]['logins'] += 1 else: database[userName] = {'logins' : 1} userProgress = database[userName] userProgress['currDigitDict'] = [0, 1, 2] #database[userName] = {'currDigitDict' : [0, 1, 2]} print('Welcome, ' + userName + '.') print(database) pickle.dump(database, open('userData/database.p', 'wb')) clf = pickle.load(open('userData/classifier.p', 'rb')) testData = np.zeros((1, 30), dtype = 'f') controller = Leap.Controller() pygameWindow = PYGAME_WINDOW() # Create user display window print(pygameWindow) x = 400 y = 400 xMin = 1000.0 xMax = -1000.0 yMin = 1000.0 yMax = -1000.0 handCenteredTimer = 0 greenCheckTimer = 0 digitTimer = 0 signCorrect = 0 signTimer = 0 numIndex = 0 currDigitList = database[userName]['currDigitDict'] digitToSign = currDigitList[numIndex] # Initial digit to sign programState = 0 def Handle_Frame(frame): global x, y, xMin, xMax, yMin, yMax hand = frame.hands[0] fingers = hand.fingers for finger in fingers: Handle_Finger(finger) def Handle_Finger(finger): for i in range(4): bone = finger.bone(i) fingerWidth = 4 - i Handle_Bone(bone, fingerWidth) def Handle_Bone(bone, fingerWidth): tip = bone.next_joint base = bone.prev_joint xBase, yBase = Handle_Vector_From_Leap(base) xTip, yTip = Handle_Vector_From_Leap(tip) pygameWindow.Draw_Black_Line(xBase, yBase, xTip, yTip, fingerWidth) def Handle_Vector_From_Leap(v): global xMax, xMin, yMax, yMin xVal = v[0] yVal = v[2] if (xVal < xMin): xMin = xVal if (xVal > xMax): xMax = xVal if (yVal < yMin): yMin = yVal if (yVal > yMax): yMax = yVal # Scale x and y coordinates xVal = Scale(xVal, xMin, xMax, 0, constants.pygameWindowWidth) yVal = Scale(yVal, yMin, yMax, 0, constants.pygameWindowDepth) return xVal, yVal def Scale(val, minOldRange, maxOldRange, minNewRange, maxNewRange): maxNewRange = maxNewRange / 2 diff = val - minOldRange oldRange = maxOldRange - minOldRange newRange = maxNewRange - minNewRange if (oldRange == 0): return val oldFraction = diff / oldRange newVal = oldFraction * newRange return newVal def CenterData(X): allXCoordinates = X[0,::3] XmeanValue = allXCoordinates.mean() X[0,::3] = allXCoordinates - XmeanValue allYCoordinates = X[0,1::3] YmeanValue = allYCoordinates.mean() X[0,1::3] = allYCoordinates - YmeanValue allZCoordinates = X[0,2::3] ZmeanValue = allZCoordinates.mean() X[0,2::3] = allZCoordinates - ZmeanValue return X def HandCentered(): frame = controller.frame() centered = True hand = frame.hands[0] fingers = hand.fingers targetFinger = fingers[2] targetBone = targetFinger.bone(0) targetJoint = targetBone.prev_joint xBaseJoint, yBaseJoint = Handle_Vector_From_Leap(targetJoint) if (xBaseJoint <= 110): centered = False if (xBaseJoint >= 225): centered = False if (yBaseJoint <= 250): centered = False if (yBaseJoint >= 350): centered = False return centered def DrawImageToHelpUserPutTheirHandOverTheDevice(): pygameWindow.Prepare() pygameWindow.drawHandImage() pygameWindow.Reveal() def HandOverDevice(): frame = controller.frame() if (len(frame.hands) > 0): return True else: return False def HandleState0(): global programState DrawImageToHelpUserPutTheirHandOverTheDevice() if HandOverDevice(): programState = 1 def HandleState1(): global programState, handCenteredTimer pygameWindow.Prepare() frame = controller.frame() if (handCenteredTimer > 100): programState = 2 hand = frame.hands[0] Handle_Frame(frame) fingers = hand.fingers targetFinger = fingers[2] targetBone = targetFinger.bone(0) # Middle Metacarpal targetJoint = targetBone.prev_joint xBaseJoint, yBaseJoint = Handle_Vector_From_Leap(targetJoint) if (xBaseJoint <= 110): pygameWindow.promptHandRight() handCenteredTimer = 0 if (xBaseJoint >= 225): pygameWindow.promptHandLeft() handCenteredTimer = 0 if (yBaseJoint <= 250): pygameWindow.promptHandDown() handCenteredTimer = 0 if (yBaseJoint >= 350): pygameWindow.promptHandUp() handCenteredTimer = 0 if (xBaseJoint > 110): # If hand is centered if (xBaseJoint < 225): if (yBaseJoint > 250): if (yBaseJoint < 350): pygameWindow.promptThumbsUp() handCenteredTimer += 1 if HandOverDevice() == False: programState = 0 handCenteredTimer = 0 pygameWindow.Reveal() def HandleState2(): global programState, digitToSign, testData, clf, signCorrect, digitTimer, handCenteredTimer, currDigitList, numIndex, signTimer digitTimer += 1 # Time viewing random digit signTimer += 1 # Time viewing ASL sign #database = pickle.load(open('userData/database.p', 'rb')) pygameWindow.Prepare() if HandOverDevice(): frame = controller.frame() hand = frame.hands[0] Handle_Frame(frame) if (HandCentered() == False): handCenteredTimer = 0 programState = 1 attemptsDict = 'digit' + str(digitToSign) + 'attempts' successesDict = 'digit' + str(digitToSign) + 'successes' # Determine how long ASL gesture should be presented to user (depending on number of successes # with the current digit to sign) & length of time they have to sign the gesture try: if (database[userName][successesDict] < 1): digitTimerLimit = 30 elif (database[userName][successesDict] == 1): signTimerLimit = 15 digitTimerLimit = 30 elif (database[userName][successesDict] == 2): signTimerLimit = 8 digitTimerLimit = 30 elif (database[userName][successesDict] > 2): signTimerLimit = 0 digitTimerLimit = 15 # Decrease time user has to sign digit elif (database[userName][successesDict] > 3): digitTimerLimit = 10 else: signTimerLimit = 100 # Show ASL gesture the entire time digitTimerLimit = 30 except: signTimerLimit = 100 digitTimerLimit = 30 if (signTimer < signTimerLimit): pygameWindow.promptASLsign(digitToSign) pygameWindow.promptASLnum(digitToSign) # Get number of times user has been presented with digit userRecord = database[userName] try: numSeen = database[userName][attemptsDict] except: userRecord[attemptsDict] = 1 numSeen = 1 pygameWindow.promptNumSeen(numSeen) # KNN k = 0 for finger in range(5): finger = hand.fingers[finger] for b in range(4): if b == 0: bone = finger.bone(Leap.Bone.TYPE_METACARPAL) elif b == 1: bone = finger.bone(Leap.Bone.TYPE_PROXIMAL) elif b == 2: bone = finger.bone(Leap.Bone.TYPE_INTERMEDIATE) elif b == 3: bone = finger.bone(Leap.Bone.TYPE_DISTAL) boneBase = bone.prev_joint boneTip = bone.next_joint xBase = boneBase[0] yBase = boneBase[1] zBase = boneBase[2] xTip = boneTip[0] yTip = boneTip[1] zTip = boneTip[2] if ((b == 0)or(b == 3)): testData[0, k] = xTip testData[0, k+1] = yTip testData[0, k+2] = zTip k = k+3 testData = CenterData(testData) predictedClass = clf.Predict(testData) print(predictedClass) if (predictedClass == digitToSign): signCorrect += 1 else: signCorrect = 0 if (digitTimer > digitTimerLimit): # Change digit and increment attempt if not signed correctly database[userName][attemptsDict] += 1 # Increment user attempt at digit pickle.dump(database, open('userData/database.p', 'wb')) # Change digit if (numIndex == len(database[userName]['currDigitDict']) - 1): numIndex = 0 else: numIndex += 1 digitToSign = database[userName]['currDigitDict'][numIndex] digitTimer = 0 signTimer = 0 if (signCorrect == 10): # User successfully signed digit (recognized by KNN 10 times) try: database[userName][successesDict] += 1 except: userRecord[successesDict] = 1 database[userName][attemptsDict] += 1 # Increment user attempt at digit digitTimer = 0 # Check if user passed 'level one' (digits 0 through 2) levelOnePass = True for digit in range(3): try: digitDict = 'digit' + str(digit) + 'successes' if (database[userName][digitDict] < 1): levelOnePass = False break except: levelOnePass = False break if (levelOnePass): # Change subset of digits shown to three new (3 through 5) database[userName]['currDigitDict'] = [0, 1, 2, 3, 4, 5] # Check if user passed 'level two' (digits 3 through 5) levelTwoPass = True for digit in range(3, 6): try: digitDict = 'digit' + str(digit) + 'successes' if (database[userName][digitDict] < 1): levelTwoPass = False break except: levelTwoPass = False break if (levelTwoPass): # Change subset of digits shown to four new (6 through 9) * all digits database[userName]['currDigitDict'] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Increment to next digit in the list if (numIndex == len(database[userName]['currDigitDict']) - 1): numIndex = 0 else: numIndex += 1 digitToSign = database[userName]['currDigitDict'][numIndex] pickle.dump(database, open('userData/database.p', 'wb')) signTimer = 0 programState = 3 else: programState = 0 digitTimer = 0 signTimer = 0 pygameWindow.Reveal() def HandleState3(): # To show 'success' check mark when user correctly signs digit global programState, randNum, greenCheckTimer, numIndex, levelOneNums greenCheckTimer += 1 pygameWindow.Prepare() frame = controller.frame() Handle_Frame(frame) pygameWindow.promptGreenCheck() if HandOverDevice(): if HandCentered(): if (greenCheckTimer > 100): programState = 2 greenCheckTimer = 0 else: programState = 1 greenCheckTimer = 0 else: programState = 0 greenCheckTimer = 0 pygameWindow.Reveal() # Main program loop while True: if programState == 0: HandleState0() elif programState == 1: HandleState1() elif programState == 2: HandleState2() elif programState == 3: HandleState3() <file_sep>/Del8/Classify.py import pickle import numpy as np from knn import KNN openTrain0File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_train0.p", 'rb') openTest0File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_test0.p", 'rb') openTrain0File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Clark_train0.p", 'rb') openTest0File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Clark_test0.p", 'rb') openTrain1File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Genovese_train1.p", 'rb') openTest1File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Genovese_test1.p", 'rb') openTrain1File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Newton_train1.p", 'rb') openTest1File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Newton_test1.p", 'rb') openTrain2File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Gordon_train2.p", 'rb') openTest2File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Gordon_test2.p", 'rb') openTrain2File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Gordon_train2.p", 'rb') openTest2File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Gordon_test2.p", 'rb') openTrain3File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Liu_train3.p", 'rb') openTest3File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Liu_test3.p", 'rb') openTrain3File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Trinity_train3.p", 'rb') openTest3File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Trinity_test3.p", 'rb') openTrain4File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Warren_train4.p", 'rb') openTest4File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Warren_test4.p", 'rb') openTrain4File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Ortigara_train4.p", 'rb') openTest4File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Ortigara_test4.p", 'rb') openTrain5File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_train5.p", 'rb') openTrain6File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_train6.p", 'rb') openTest5File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_test5.p", 'rb') openTest6File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_test6.p", 'rb') openTrain5File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_train5.p", 'rb') openTrain6File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_train6.p", 'rb') openTest5File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_test5.p", 'rb') openTest6File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_test6.p", 'rb') openTrain7File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_train7.p", 'rb') openTest7File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_test7.p", 'rb') openTrain7File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Yeung_train7.p", 'rb') openTest7File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Yeung_test7.p", 'rb') openTrain8File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Rubin_train8.p", 'rb') openTest8File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Rubin_test8.p", 'rb') openTrain8File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Mardis_train8.p", 'rb') openTest8File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Mardis_test8.p", 'rb') openTrain9File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_train9.p", 'rb') openTest9File = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Burleson_test9.p", 'rb') openTrain9File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Lee_train9.p", 'rb') openTest9File_ = open(r"C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/Del7/userData/Lee_test9.p", 'rb') def ReduceData(X): X = np.delete(X,1,1) X = np.delete(X,1,1) return X def CenterData(X): allXCoordinates = X[:,:,0,:] meanValue = allXCoordinates.mean() X[:,:,0,:] = allXCoordinates - meanValue allYCoordinates = X[:,:,1,:] meanValue = allYCoordinates.mean() X[:,:,1,:] = allYCoordinates - meanValue allZCoordinates = X[:,:,2,:] meanValue = allZCoordinates.mean() X[:,:,2,:] = allZCoordinates - meanValue return X train0 = pickle.load(openTrain0File) train0 = ReduceData(train0) train0 = CenterData(train0) test0 = pickle.load(openTest0File) test0 = ReduceData(test0) test0 = CenterData(test0) train0_ = pickle.load(openTrain0File_) train0_ = ReduceData(train0_) train0_ = CenterData(train0_) test0_ = pickle.load(openTest0File_) test0_ = ReduceData(test0_) test0_ = CenterData(test0_) train1 = pickle.load(openTrain1File) train1 = ReduceData(train1) train1 = CenterData(train1) test1 = pickle.load(openTest1File) test1 = ReduceData(test1) test1 = CenterData(test1) train1_ = pickle.load(openTrain1File_) train1_ = ReduceData(train1_) train1_ = CenterData(train1_) test1_ = pickle.load(openTest1File_) test1_ = ReduceData(test1_) test1_ = CenterData(test1_) train2 = pickle.load(openTrain2File) train2 = ReduceData(train2) train2 = CenterData(train2) test2 = pickle.load(openTest2File) test2 = ReduceData(test2) test2 = CenterData(test2) train2_ = pickle.load(openTrain2File_) train2_ = ReduceData(train2_) train2_ = CenterData(train2_) test2_ = pickle.load(openTest2File_) test2_ = ReduceData(test2_) test2_ = CenterData(test2_) train3 = pickle.load(openTrain3File) train3 = ReduceData(train3) train3 = CenterData(train3) test3 = pickle.load(openTest3File) test3 = ReduceData(test3) test3 = CenterData(test3) train3_ = pickle.load(openTrain3File_) train3_ = ReduceData(train3_) train3_ = CenterData(train3_) test3_ = pickle.load(openTest3File_) test3_ = ReduceData(test3_) test3_ = CenterData(test3_) train4 = pickle.load(openTrain4File) train4 = ReduceData(train4) train4 = CenterData(train4) test4 = pickle.load(openTest4File) test4 = ReduceData(test4) test4 = CenterData(test4) train4_ = pickle.load(openTrain4File_) train4_ = ReduceData(train4_) train4_ = CenterData(train4_) test4_ = pickle.load(openTest4File_) test4_ = ReduceData(test4_) test4_ = CenterData(test4_) #######MEEEE##### train5 = pickle.load(openTrain5File) train5 = ReduceData(train5) train5 = CenterData(train5) train5_ = pickle.load(openTrain5File_) train5_ = ReduceData(train5_) train5_ = CenterData(train5_) train6 = pickle.load(openTrain6File) train6 = ReduceData(train6) train6 = CenterData(train6) train6_ = pickle.load(openTrain6File_) train6_ = ReduceData(train6_) train6_ = CenterData(train6_) test5 = pickle.load(openTest5File) test5 = ReduceData(test5) test5 = CenterData(test5) test5_ = pickle.load(openTest5File_) test5_ = ReduceData(test5_) test5_ = CenterData(test5_) test6 = pickle.load(openTest6File) test6 = ReduceData(test6) test6 = CenterData(test6) test6_ = pickle.load(openTest6File_) test6_ = ReduceData(test6_) test6_ = CenterData(test6_) train7 = pickle.load(openTrain7File) train7 = ReduceData(train7) train7 = CenterData(train7) test7 = pickle.load(openTest7File) test7 = ReduceData(test7) test7 = CenterData(test7) train7_ = pickle.load(openTrain7File_) train7_ = ReduceData(train7_) train7_ = CenterData(train7_) test7_ = pickle.load(openTest7File_) test7_ = ReduceData(test7_) test7_ = CenterData(test7_) train8 = pickle.load(openTrain8File) train8 = ReduceData(train8) train8 = CenterData(train8) test8 = pickle.load(openTest8File) test8 = ReduceData(test8) test8 = CenterData(test8) train8_ = pickle.load(openTrain8File_) train8_ = ReduceData(train8_) train8_ = CenterData(train8_) test8_ = pickle.load(openTest8File_) test8_ = ReduceData(test8_) test8_ = CenterData(test8_) train9 = pickle.load(openTrain9File) train9 = ReduceData(train9) train9 = CenterData(train9) test9 = pickle.load(openTest9File) test9 = ReduceData(test9) test9 = CenterData(test9) train9_ = pickle.load(openTrain9File_) train9_ = ReduceData(train9_) train9_ = CenterData(train9_) test9_ = pickle.load(openTest9File_) test9_ = ReduceData(test9_) test9_ = CenterData(test9_) def ReshapeData(set0,set1,set2,set3,set4,set5,set6,set7,set8,set9,set10,set11,set12,set13,set14,set15,set16,set17,set18,set19): X = np.zeros((20000,5*2*3),dtype='f') y = np.zeros(20000,dtype='f') for row in range(0,1000): col = 0 for j in range(0,5): for k in range(0,2): for m in range(0,3): X[row,col] = set0[j,k,m,row] y[row] = 0 X[row+1000,col] = set1[j,k,m,row] y[row+1000] = 1 X[row+2000,col] = set2[j,k,m,row] y[row+2000] = 2 X[row+3000,col] = set3[j,k,m,row] y[row+3000] = 3 X[row+4000,col] = set4[j,k,m,row] y[row+4000] = 4 X[row+5000,col] = set5[j,k,m,row] y[row+5000] = 5 X[row+6000,col] = set6[j,k,m,row] y[row+6000] = 6 X[row+7000,col] = set7[j,k,m,row] y[row+7000] = 7 X[row+8000,col] = set8[j,k,m,row] y[row+8000] = 8 X[row+9000,col] = set9[j,k,m,row] y[row+9000] = 9 X[row+10000,col] = set10[j,k,m,row] y[row+10000] = 0 X[row+11000,col] = set11[j,k,m,row] y[row+11000] = 1 X[row+12000,col] = set12[j,k,m,row] y[row+12000] = 2 X[row+13000,col] = set13[j,k,m,row] y[row+13000] = 3 X[row+14000,col] = set14[j,k,m,row] y[row+14000] = 4 X[row+15000,col] = set15[j,k,m,row] y[row+15000] = 5 X[row+16000,col] = set16[j,k,m,row] y[row+16000] = 6 X[row+17000,col] = set17[j,k,m,row] y[row+17000] = 7 X[row+18000,col] = set18[j,k,m,row] y[row+18000] = 8 X[row+19000,col] = set19[j,k,m,row] y[row+19000] = 9 col += 1 return X,y trainX, trainy = ReshapeData(train0,train1,train2,train3,train4,train5,train6,train7,train8,train9,train0_,train1_,train2_,train3_,train4_,train5_,train6_,train7_,train8_,train9_) testX, testy = ReshapeData(test0,test1,test2,test3,test4,test5,test6,test7,test8,test9,test0_,test1_,test2_,test3_,test4_,test5_,test6_,test7_,test8_,test9_) ##print(trainX) ##print(trainX.shape) ##print(trainy) ##print(trainy.shape) ##print(testX) ##print(testX.shape) ##print(testy) ##print(testy.shape) knn = KNN() knn.Use_K_Of(15) knn.Fit(trainX,trainy) predictCorrect = 0 ##for row in range(0,10000): ## prediction = int(knn.Predict(testX[row,:])) ## actualClass = int(testy[row]) ## print(row,prediction,actualClass) ## if (prediction == actualClass): ## predictCorrect += 1 ##percentage = float(predictCorrect) ##percentage = percentage/2000 ##percentage = percentage * 100 ##print("Accuracy: " + str(percentage)) # START DEL6 pickle.dump(knn,open('userData/classifier.p','wb')) <file_sep>/Record.py import numpy from Deliverable import DELIVERABLE Deliverable = DELIVERABLE() Deliverable.Run_Forever() <file_sep>/RealTimeDraw.py from pygameWindow import PYGAME_WINDOW # Import class containing visual program # functions import random # Random module used to generate random (x,y) coordinates for the # black dot x = 400 # Initial x position for dot y = 400 # Initial y position for dot # This function will randomly "roll" a four sided die, generating a random # change in the x or y coordinate position of the dot within the window def Perturb_Circle_Position(): global x, y fourSidedDieRoll = random.randint(1,4) if fourSidedDieRoll == 1: x -= 1 elif fourSidedDieRoll == 2: x += 1 elif fourSidedDieRoll == 3: y -= 1 else: y += 1 # Initialize an instance of the PYGAME_WINDOW class to create function calls pygameWindow = PYGAME_WINDOW() # Print the window to the users screen print(pygameWindow) while True: # Run until the user shuts down the program pygameWindow.Prepare() # Creates user window pygameWindow.Draw_Black_Circle(x, y) # Draw the black dot to the screen Perturb_Circle_Position() # Randomly change dot position pygameWindow.Reveal() # Update window frame <file_sep>/Reader.py import pickle import os import constants import time from pygameWindow_Del03 import PYGAME_WINDOW class READER: def __init__(self): self.numGestures = 0 self.Count_Gestures() self.pygameWindow = PYGAME_WINDOW() def Count_Gestures(self): path, dirs, files = next(os.walk('userData')) self.numGestures = len(files) def Print_Gestures(self): for i in range(self.numGestures): pickleIn = open('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/userData/gesture%s.p' % i, 'rb') gestureData = pickle.load(pickleIn) print(gestureData) def Draw_Gestures(self): while True: self.Draw_Each_Gesture_Once() def Draw_Each_Gesture_Once(self): for i in range(self.numGestures): self.Draw_Gesture(i) def Scale_Coordinates(self, x, y): xVal = (constants.pygameWindowWidth / 300) * x + .5 * constants.pygameWindowWidth yVal = (500 - y) * constants.pygameWindowDepth / 400 return xVal, yVal def Draw_Gesture(self, i): self.pygameWindow.Prepare() pickleIn = open('C:/Users/CHBADMIN/Desktop/LeapDeveloperKit_2.3.1+31549_win/LeapSDK/lib/x86/CS228/userData/gesture%s.p' % i, 'rb') gestureData = pickle.load(pickleIn) print(gestureData) for i in range(5): for j in range(4): # base xBaseNotYetScaled = gestureData[i,j,0] yBaseNotYetScaled = gestureData[i,j,1] # tip xTipNotYetScaled = gestureData[i,j,3] yTipNotYetScaled = gestureData[i,j,4] xBase, yBase = self.Scale_Coordinates(xBaseNotYetScaled, yBaseNotYetScaled) xTip, yTip = self.Scale_Coordinates(xTipNotYetScaled, yTipNotYetScaled) self.pygameWindow.Draw_Line(xBase, yBase, xTip, yTip, 1, (0, 0, 255)) self.pygameWindow.Reveal() time.sleep(0.1) <file_sep>/Del6/pygameWindow.py import pygame import constants class PYGAME_WINDOW: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((constants.pygameWindowWidth, constants.pygameWindowDepth)) def Prepare(self): self.screen.fill((255, 255, 255)) def Reveal(self): pygame.display.update() def Draw_Black_Circle(self, x, y): pygame.draw.circle(self.screen, (0,0,0), (x, y), 20) def Draw_Black_Line(self, xBase, yBase, xTip, yTip, fingerWidth): pygame.draw.line(self.screen, (0, 0, 0), (xBase, yBase), (xTip, yTip), fingerWidth) def drawHandImage(self): handImg = pygame.image.load('handOverDevice.jpg') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandLeft(self): handImg = pygame.image.load('moveLeft.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandRight(self): handImg = pygame.image.load('moveRight.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandUp(self): handImg = pygame.image.load('moveUp.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptHandDown(self): handImg = pygame.image.load('moveDown.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 400, 0)) def promptGreenCheck(self): handImg = pygame.image.load('greenCheck.png') self.screen.blit(handImg, (constants.pygameWindowWidth - 460, 0)) def promptThumbsUp(self): handImg = pygame.image.load('thumbsUp.png') handImg = pygame.transform.scale(handImg, (325,325)) self.screen.blit(handImg, (constants.pygameWindowWidth - 350, 0)) def promptASLnum(self, mode): if mode == 0: pic = pygame.image.load('0.png') elif mode == 1: pic = pygame.image.load('1.png') elif mode == 2: pic = pygame.image.load('2.png') elif mode == 3: pic = pygame.image.load('3.png') elif mode == 4: pic = pygame.image.load('4.png') elif mode == 5: pic = pygame.image.load('5.png') elif mode == 6: pic = pygame.image.load('6.png') elif mode == 7: pic = pygame.image.load('7.png') elif mode == 8: pic = pygame.image.load('8.png') else: pic = pygame.image.load('9.png') pic = pygame.transform.scale(pic, (375,375)) self.screen.blit(pic, (375,375)) def promptASLsign(self, mode): if mode == 0: pic = pygame.image.load('asl0.png') elif mode == 1: pic = pygame.image.load('asl1.png') elif mode == 2: pic = pygame.image.load('asl2.png') elif mode == 3: pic = pygame.image.load('asl3.png') elif mode == 4: pic = pygame.image.load('asl4.png') elif mode == 5: pic = pygame.image.load('asl5.png') elif mode == 6: pic = pygame.image.load('asl6.png') elif mode == 7: pic = pygame.image.load('asl7.png') elif mode == 8: pic = pygame.image.load('asl8.png') else: pic = pygame.image.load('asl9.png') pic = pygame.transform.scale(pic, (375,375)) self.screen.blit(pic, (375,0)) <file_sep>/pygameWindow.py import pygame # pygame module import constants # Contains all constant variables within the program class PYGAME_WINDOW: # Function to initialize the window screen to a specific width/depth # for the UI window def __init__(self): pygame.init() self.screen = pygame.display.set_mode((constants.pygameWindowWidth, constants.pygameWindowDepth)) # Function to fill the window with a white background def Prepare(self): self.screen.fill((255, 255, 255)) # Function that consistently updates the current window frame def Reveal(self): pygame.display.update() # Function to draw a black circle given a specific (x,y) coordinate # within the users window def Draw_Black_Circle(self, x, y): pygame.draw.circle(self.screen, (0,0,0), (x, y), 20) def Draw_Black_Line(self, xBase, yBase, xTip, yTip, fingerWidth): pygame.draw.line(self.screen, (0, 0, 0), (xBase, yBase), (xTip, yTip), fingerWidth)
0ee3e859fc3ec4a5d3599024ea3b9eeb86ead4df
[ "Python" ]
19
Python
cburleso/CS228
a59470079adc5eb91f3157f37e348af3c87e3055
9eb435b97d6b2f4798ed673b332f05d89d20d2f4
refs/heads/master
<file_sep>## Työnhallintasovellus Ideana yksinkertainen työnhallintasovellus, jolla yritys pystyy hallinnoimaan työntekijöidensä työkeikkoja. Työnantaja voi luoda työntekijöitä, asiakkaita ja määrittää työntekijöilleen keikkoja. Huom. Ohjelman source githubissa on Java 8 versio. Erillinen Java 11:lla pyörivä .jar release löytyy alta. Erona vain pom.xml:ssä määritellyt dependencyt, ja sit erillinen NewMain-luokka, joka avaa Main-luokan. Java 11 release toimi, kun kokeilin etätyöpöytäyhteydellä. Java 8 toimii omalla Windowsillani. ## Työn dokumentaatio: [Vaatimusmäärittely](https://github.com/RoniNiklas/ot-harjoitustyo/blob/master/dokumentaatio/vaatimusmaarittely.MD) [Arkkitehtuuri](https://github.com/RoniNiklas/ot-harjoitustyo/blob/master/dokumentaatio/arkkitehtuuri.md) [Käyttöohjeet](https://github.com/RoniNiklas/ot-harjoitustyo/blob/master/dokumentaatio/k%C3%A4ytt%C3%B6ohjeet.MD) [Testausdokumentti](https://github.com/RoniNiklas/ot-harjoitustyo/blob/master/dokumentaatio/Testausdokumentti.MD) [Työaikakirjanpito](https://github.com/RoniNiklas/ot-harjoitustyo/blob/master/dokumentaatio/tyoaikakirjanpito.MD) ## Releaset [Viikko5-6](https://github.com/RoniNiklas/ot-harjoitustyo/releases/tag/Viikko5) [Final( Java 8 )](https://github.com/RoniNiklas/ot-harjoitustyo/releases/tag/1.0.0) [Final( Java 11 )](https://github.com/RoniNiklas/ot-harjoitustyo/releases/tag/1.0.1) ## Komentorivi Testit suoritetaan komennolla mvn test Testikattavuusraportti luodaan komennolla mvn jacoco:report Checkstyleraportti luodaan komennolla mvn checkstyle:checkstyle .Jar tiedosto luodaan komennolla mvn package <file_sep>package harjoitustyo.dao; //Roni import harjoitustyo.domain.Assignment; import harjoitustyo.domain.Client; import harjoitustyo.domain.Employee; import java.time.LocalDate; import java.time.LocalDateTime; import javafx.collections.ObservableList; public interface AssignmentManagerDao { public boolean contains(Long id); public ObservableList getObservableAssignments(String filter); public Assignment add(Assignment assignment); public void update(Long id, String field, String newValue); public void remove(Assignment assignment); public Assignment get(Long id); public boolean validateAssignment(Client client, Employee employee, LocalDate value, String text, String text0, LocalDate value0, String text1, String text2, String text3, String text4, String text5, String string, String assigned); } <file_sep>/* * */ package harjoitustyo.repoTests; import harjoitustyo.domain.Client; import harjoitustyo.repositories.ClientRepository; import javax.transaction.Transactional; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest() @TestPropertySource( locations = "classpath:application-test.properties") @Transactional public class ClientRepoTest { @Autowired ClientRepository clientrepo; @Test public void clientCanBeSavedAndRetrieved() { Client client = new Client(); client.setAddress("osoite"); client.setEmail("email"); client.setFirstname("etunimi"); client.setLastname("lastname"); client.setIdNumber("112233-1234"); client.setNumber("555666777"); Client savedClient = clientrepo.save(client); savedClient = clientrepo.getOne(savedClient.getId()); assertEquals(savedClient.getAddress(), client.getAddress()); assertEquals(savedClient.getEmail(), client.getEmail()); assertEquals(savedClient.getFullname(), client.getFullname()); assertEquals(savedClient.getNumber(), client.getNumber()); assertEquals(savedClient.getIdNumber(), client.getIdNumber()); } } <file_sep>## Sovelluksen rakenne Sovelluksen datan muodostavat harjoitustyo.domain pakkauksen luokat User, Employee, Client ja Assignment, jotka kuvaavat käyttäjiä, työntekijöitä, asiakkaita ja työtehtäviä. Luokkien suhteet näkyvät alla olevassa luokkakaaviossa. [Luokkakaavio](https://github.com/RoniNiklas/ot-harjoitustyo/blob/master/dokumentaatio/LuokkakaavioUusi.jpg) Käyttöliittymästä vastaa Main ja harjoitustyo.presentation pakkauksen oliot (tällä hetkellä Ui ja Ui.EmployeeView). Main olio toimii pohjana, jonka päälle luodaan erillisiä olioita ihan vain luokkien koodin selattavuutta helpottamaan. Nimentä tulee muuttumaan, sillä tällä hetkellä EmployeeView - luokan olio vastaa siitä työnantajan näkymästä, missä työntekijöitä voi selata, ja nimentä ei välttämättä kaikista selkein. Sovelluslogiikasta vastaa harjoitustyo.dao pakkauksen interfacet appUserManagerDao, employeeManagerDao ja ClientManagerDao sekä näitä toteuttavat luokat Tietokannasta vastaa harjoitustyo.repository luokan oliot AppUserRepository, ClientRepository, EmployeeRepository ja AssignmentRepository. Alla esimerkki ohjelman end-to-end toiminnasta. Kuvassa on sekvenssikaavio adminin kirjautumiselle sovellukseen sisään ja sovelluksesta ulos. [Sekvenssikaavio adminin sisään kirjautumiselle](https://github.com/RoniNiklas/ot-harjoitustyo/blob/master/dokumentaatio/sekvenssikaavioUusi.png) Käyttäjä täyttää kirjautumistiedot ja painaa login nappulaa (tai enteriä). Tällöin käyttöliittymä kutsuu AppUserManagerDB-luokan checkLogin-metodia, jolla varmistetaan kirjautumistietojen oikeus. CheckLogin-metodi hakee AppUserRepositorysta käyttäjänimellä käyttäjän, varmistaa tälläisen olevan olemassa, ja vertaa syötettyä salasanaa tallennetun käyttäjän salasanaan, ja palauttaa boolean arvon. Jos arvo on tosi, niin käyttöliittymä pyytää AppUserManagerDB-luokkaa hakemaan käyttäjän AppUserRepositorystä. Sen jälkeen käyttäjän authorization-tarkistetaan, ja "Admin"-tason käyttäjille avataan admin-näkymä kutsumalla UI-luokan createAdminView()-metodia. Samalla suljetaan sisäänkirjautumisnäkymä, ja avataan uloskirjautumisnäkymä. Uloskirjauduttaessa poistetaan admin-näkymän eri osat, ja luodaan sisäänkirjautumisnäkymä uudelleen. ## Ohjelman rakenteeseen jääneet heikkoudet Ohjelmassa on paljon toisteista koodia. Employee ja Client luokat (ja näitä käsittelevät dao, presentation ja repository-luokat) ovat lähes täysin toistensa kopioita. En kumminkaan saanut fiksattua niitä abstraktin super-luokan alle, sillä JPArepositoryn toiminnan mukauttaminen tälläiseen ei onnistunut halutulla aikataululla. Employee ja Client luokat kutsuvat Assignmentteja fetchtype.EAGER:illä, mikä aiheuttaa suhtkoht ison määrän tarpeettomia tietokantakutsuja. LAZY:n käyttäminen johti kumminkin ongelmiin tietyissä käyttötapauksissa, enkä löytänyt muuta ratkaisua. Käyttöliittymän näkymän voisi luoda FXML-tiedostoilla java-koodin sijaan, sillä nyt nämä käyttöliittymä-luokat ovat melko massiivisia ja vaikeaselkoisia parhaista yrityksistäni huolimatta. Näkymän siirtäminen FXML:ään ja sen controllerin pyörittäminen Javalla olisi hyvä idea. <file_sep>package harjoitustyo.unitTests; /* * 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. */ import harjoitustyo.domain.Assignment; import harjoitustyo.domain.Client; import java.util.ArrayList; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Roni */ public class ClientUnitTest { public ClientUnitTest() { } @Test public void ClientCanBeCreatedFullConstructor() { Client client = new Client("Make", "Makenen", "555-666-777", "<EMAIL>", "111", "kotitie 1A"); assertNotNull(client); assertEquals(client.getFirstname(), "Make"); assertEquals(client.getLastname(), "Makenen"); assertEquals(client.getNumber(), "555-666-777"); assertEquals(client.getEmail(), "<EMAIL>"); assertEquals(client.getIdNumber(), "111"); assertEquals(client.getAssignments().size(), 0); assertEquals(client.getAddress(), "kotitie 1A"); } @Test public void ClientAttributesCanBeSetAndGot() { Client client = new Client(); client.setFirstname("Make"); client.setLastname("Makenen"); client.setEmail("<EMAIL>"); client.setNumber("555-666-777"); client.setIdNumber("111"); client.setAddress("kotitie 1A"); assertEquals(client.getFirstname(), "Make"); assertEquals(client.getLastname(), "Makenen"); assertEquals(client.getNumber(), "555-666-777"); assertEquals(client.getEmail(), "<EMAIL>"); assertEquals(client.getIdNumber(), "111"); assertEquals(client.getAssignments().size(), 0); assertEquals(client.getFullname(), "<NAME>"); assertEquals(client.getAddress(), "kotitie 1A"); } } <file_sep># Vaatimusmäärittely ## Sovelluksen tarkoitus Ideana yksinkertainen työnhallintasovellus, jolla yritys pystyy hallinnoimaan työntekijöidensä työkeikkoja, koska satuin näkemään joskus yhden yrityksen pyynnön, että joku jonkun tälläisen heille tuottaisi. Tämä ei kumminkaan ole menossa oikean maailman käyttöön. Paljon vastaavia on jo olemassa, mutta en nyt keksi muutakaan tekemistä. Työnantaja voi luoda työntekijöitä, asiakkaita ja keikkoja. Työnantaja voi myös merkitä keikkoja tehdyksi. ## Perusversion tarjoama toiminnallisuus Työnantaja - Voi kirjautua sisään ja ulos. **TEHTY** - Voi lisätä työntekijöitä **TEHTY**, paitsi että ei tee työntekijälle käyttäjää - Attribuutteina id (pk), nimi (string), osoite (string), puh (string), sahkoposti (string), käyttäjätunnus(string), salasana(string) - Voi selailla työntekijöitä **TEHTY** - Voi muuttaa työntekijöiden tietoja **TEHTY** - Voi poistaa työntekijöitä **TEHTY** - Työntekijän poisto poistaa myös asiakkaaseen liittyvät keikat. - Voi lisätä asiakkaita **TEHTY** - Attribuutteina id (pk), nimi (string), osoite (string), puh (string), sahkoposti (string) - Voi poistaa asiakkaita **TEHTY** - Asiakkaan poisto poistaa myös asiakkaaseen liittyvät keikat. - Voi muuttaa asiakkaiden tietoja **TEHTY** - Voi lisätä keikkoja **TEHTY** - Attribuutteina id (pk), asiakas (fk), työntekijä (fk), keikan kuvaus (string), keikka tehty/eitehty (boolean), keikkaraportti (luodaan keikan jälkeen)(string), keikan alku (date), keikan loppu (date). - Voi liittää asiakkaita keikkoihin **TEHTY** - Voi liittää työntekijöitä keikkoihin **TEHTY** - Työntekijälle ei voi liittää päällekkäisiä keikkoja. **TEHTY** - Voi poistaa keikkoja **TEHTY** ## Jatkokehitysideoita Yksittäisen työntekijän kaikki keikat voisi nähdä erillisessä näkymässä (nyt löytyy filtteröimällä assignments listaa käyttäjän nimellä). Keikan tietojen muokkaaminen ja selaaminen erillisessä näkymässä. Nyt assignments näkymässä voi selata ja muokata joitain tietoja, mutta esim raporttia ei voi tehdä tai löytää, ja keikan kuvauksen kohta hyvin pieni oikean maailman tarpeisiin. Jokin palvelin systeemi, että ohjelmaa voisi käyttää useammasta paikasta ja useampi henkilö samaan aikaan. Työntekijöille pääsy systeemiin (voisivat itse merkitä keikkoja tehdyiksi, ja antaa raportteja niistä). Asiakkaalle mahdollisuus antaa kommentteja keikasta. <file_sep># Työaikakirjanpito | päivä | aika | mitä tein | | :----:|:-----| :-----| | 9.11 | 1 | Vaatimusmäärittelyn luonti | 15.11 | 4 | Tämänhetkinen versio githubissa (minimit mitä vaadittiin pisteisiin) + julkaisematon graafisen käyttöliittymän pohja. | 25.11 | 6 | Graafisen käyttöliittymän työstämistä, checkstyle, jacoco, lisää testejä, luokkakaavio, uusi pakkausrakenne. Työntekijään liittyvien toimintojen toteuttaminen käyttöliittymään. | 1.12 | 5 | Lisää unit testejä. Asiakkaseen liittyvien toimintojen lisäys käyttöliittymään. Sekvenssikaavio. Toimintojen siirtäminen muistista tietokantaan. | 9.12 | 6 | Paljon uusia testejä. Parannettu pakkausratkaisu (springapplicationin käyttö kömpelöä erillisen UI luokan kanssa, mutta nyt toimii). Tietojen muuttaminen näkymässä johtaa nyt tietokannan tilan muutokseen. Kaunistettu koodia joissain kohissa (etenkin tablenäkymän luomisessa). | 16.12| 6 | Keikkojen luominen ja selaaminen lisätty. | 22.12| 10 | Dokumentaation kasvattaminen. Koodin kaunistelu. Testien kasvattaminen. Loppupalautuksen hommat. Java 11 release. yhteensä: 38 <file_sep>package harjoitustyo.unitTests; /* * 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. */ import harjoitustyo.domain.AppUser; import harjoitustyo.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Roni */ public class AppUserUnitTest { public AppUserUnitTest() { } @Test public void AppUserCanBeCreatedFullConstructor() { AppUser user = new AppUser("name", "password", "authorization"); assertNotNull(user); assertEquals(user.getAuthorization(), "authorization"); assertEquals(user.getPassword(), "<PASSWORD>"); assertEquals(user.getUsername(), "name"); } @Test public void AppUserAttributesCanBeSetAndGot() { AppUser user = new AppUser(); user.setAuthorization("authorization"); user.setPassword("<PASSWORD>"); user.setUsername("name"); assertEquals(user.getAuthorization(), "authorization"); assertEquals(user.getPassword(), "<PASSWORD>"); assertEquals(user.getUsername(), "name"); } @Test public void toStringTest() { AppUser user = new AppUser(); user.setAuthorization("authorization"); user.setPassword("<PASSWORD>"); user.setUsername("name"); assertEquals(user.toString(), "User: name has authorization: authorization"); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package harjoitustyo.dao; import harjoitustyo.domain.Assignment; import harjoitustyo.domain.Employee; import harjoitustyo.repositories.EmployeeRepository; import java.lang.reflect.Method; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; @Controller public class EmployeeManagerDB implements EmployeeManagerDao { @Autowired private EmployeeRepository employeerepo; @Override public ObservableList<Employee> getObservableEmployees(String filter) { final String filterUp = filter.toUpperCase().trim(); ObservableList<Employee> returnable = FXCollections.observableArrayList(); employeerepo.findAll().parallelStream() .filter(employeeX -> employeeX.getFullname().toUpperCase().contains(filterUp) || employeeX.getIdNumber().toUpperCase().contains(filterUp) || employeeX.getEmail().toUpperCase().contains(filterUp) || employeeX.getNumber().toUpperCase().contains(filterUp) || employeeX.getAddress().toUpperCase().contains(filterUp)) .forEach(employee -> returnable.add(employee)); return returnable; } @Override @Transactional public Employee add(Employee employee) { if (!employeerepo.existsByIdNumber(employee.getIdNumber())) { employee = employeerepo.save(employee); } return employee; } @Override @Transactional public void remove(String idNumber) { employeerepo.deleteByIdNumber(idNumber); } @Override public Employee getEmployee(String idNumber) { return employeerepo.findByIdNumber(idNumber); } @Override public boolean contains(String idNumber) { return employeerepo.existsByIdNumber(idNumber); } @Override @Transactional public void update(Long id, String field, String value) { try { Employee employee = employeerepo.findById(id).get(); String methodName = "set" + Character.toUpperCase(field.charAt(0)) + field.substring(1, field.length()); Method method = employee.getClass().getMethod(methodName, String.class); method.invoke(employee, value); employeerepo.save(employee); } catch (Exception e) { System.out.println("update doesn't work with field " + field + " and value: " + value + " error: " + e); } } public void remove(Employee employee) { employeerepo.delete(employee); } } <file_sep>/* * */ package harjoitustyo.managerTests; import harjoitustyo.dao.AssignmentManagerDB; import harjoitustyo.dao.ClientManagerDB; import harjoitustyo.dao.EmployeeManagerDB; import harjoitustyo.domain.Assignment; import harjoitustyo.domain.Client; import harjoitustyo.domain.Employee; import java.time.LocalDateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.junit.jupiter.api.Assertions; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; //Roni @RunWith(SpringRunner.class) @SpringBootTest() @TestPropertySource( locations = "classpath:application-test.properties") @Transactional public class AssignmentManagerDBTest { @Autowired AssignmentManagerDB assignmentManager; @Autowired EmployeeManagerDB employeeManager; @Autowired ClientManagerDB clientManager; private Assignment assignment; @Before public void initRepo() { Employee employee = employeeManager.add(new Employee("Teemu", "Työntekijä", "0501234567", "<EMAIL>", "111133-5555", "Tyontekijankatu 1 a")); Client client = clientManager.add(new Client("Aatu", "Asiakas", "0507654321", "<EMAIL>", "121212-1234", "Asiakkaantie 7 B 22")); assignment = new Assignment(client, employee, LocalDateTime.of(2019, 12, 24, 21, 00), LocalDateTime.of(2019, 12, 24, 22, 00), "Vie lahjoja ja laula joululauluja", client.getAddress(), client.getNumber(), "", "Assigned"); assignment = assignmentManager.add(assignment); } @Test public void assignmentsCanBeAdded() { assertTrue(assignmentManager.getObservableAssignments("").size() > 0); } @Test public void assignmentsCanBeRemoved() { assertTrue(assignmentManager.getObservableAssignments("").size() > 0); assignmentManager.remove(assignment); assertTrue(assignmentManager.getObservableAssignments("").size() == 0); } @Test @Transactional public void assignmentsCanBeUpdated() { assertTrue(assignment.getStatus().equals("Assigned")); assignmentManager.update(assignment.getId(), "status", "Completed"); assignment = assignmentManager.get(assignment.getId()); assertEquals("Completed", assignment.getStatus()); } @Test @Transactional public void assignmentsCantBeUpdatedWithWrongField() { assertTrue(assignment.getStatus().equals("Assigned")); assignmentManager.update(assignment.getId(), "serratus", "Completed"); assignment = assignmentManager.get(assignment.getId()); assertEquals("Assigned", assignment.getStatus()); } @Test public void assignmentsCanBeValidated() { assertTrue(assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned")); } @Test public void assignmentsCanBeValidatedClient() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( null, assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedEmployee() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), null, assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedStartDate() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), null, String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedStartHour() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), "", String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), "24", String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), "-1", String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedStartMinute() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), "", assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), "60", assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), "-1", assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedEndDate() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), null, String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedEndHour() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), "", String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), "24", String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), "-1", String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedEndMinute() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), "", assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), "60", assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), "-1", assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedDescription() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), "", assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedAddress() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), "", assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedStartPhoneNumber() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() + 1), String.valueOf(assignment.getStartTime().getMinute() + 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), "", "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedEmployeeOverlap() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() - 1), String.valueOf(assignment.getStartTime().getMinute() - 1), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } @Test public void assignmentsCanBeValidatedStartDateAfterEndDate() { Assertions.assertThrows(IllegalArgumentException.class, () -> { assignmentManager.validateAssignment( assignment.getClient(), assignment.getEmployee(), assignment.getEndTime().toLocalDate(), String.valueOf(assignment.getEndTime().getHour() + 1), String.valueOf(assignment.getEndTime().getMinute() + 1), assignment.getStartTime().toLocalDate(), String.valueOf(assignment.getStartTime().getHour() +1), String.valueOf(assignment.getStartTime().getMinute() +1), assignment.getDescription(), assignment.getAddress(), assignment.getContact(), "", "Assigned"); }); } } <file_sep> ## ASENNUS Lataa tiedosto joko Java 8:lle [täältä](https://github.com/RoniNiklas/ot-harjoitustyo/releases/tag/1.0.0) tai Java 11 [täältä](https://github.com/RoniNiklas/ot-harjoitustyo/releases/tag/1.0.1). Ohjelma käsittelee database.mv.db nimistä tiedostoa, joten pyöritä ohjelmaa kansiossa, jossa vastaavaa ei ole. Ohjelma luo tiedoston itse, joten älä luo vastaavaa käsin. ## Aloita käskyllä Sovellus käynnistetään alla olevalla cmdline-komennolla siinä kansiossa, mihin .jar tiedoston latasit. Java 8: java -jar Harjoitustyo-0.jar Java 11: java -jar Tyonhallintasovellus-0.jar ## Kirjautuminen Täytä käyttäjätiedot Käyttäjä: Admin Salasana: <PASSWORD> ## Kirjautumisen jälkeen Uloskirjautuminen onnistuu painamalla logout nappulaa näkymän yläosassa. Vasemmassa reunassa näkyy nappulat Employees, Clients ja Assignments. Niitä painelemalla vaihtuu käyttöliittymän keskellä oleva osio. ## Employee-näkymä Employees-nappulalla saat näkyviin työntekijöiden muokkaamiseen tarkoitetun käyttöliittymän. Ylimpänä näkyy taulukko, jossa kaikki firman nykyiset työntekijät. Työntekijöiden National Identity Number (HeTu) on uniikki. Taulukon soluja tuplaklikkaamalla voit muokata työntekijän tietoja. Taulukon alla on työntekijöiden filtteröinti-toiminnallisuus, jossa voit syöttää tekstilaatikkoon tekstiä, ja Filter Employees-nappulalla rajoittaa taulukossa näkyviä työntekijöitä tekstilaatikon tekstin pohjalta. Clear Filter nappula tyhjentää tekstilaatikon ja palauttaa kaikki työntekijät näkyviin. Filtterin alla on uusien työntekijöiden-lisäämisboxi, johon voit täyttää tekstilaatikkoihin tietoja, ja sitten luoda uuden työntekijän painamalla Add Employee. Ohjelma tarkistaa, että uuden työntekijän HeTua ei ole jo olemassaolevalla työntekijällä. Työntekijänlisäämisboxin alla on työntekijän poistamisboxi. Täytä tekstilaatikkoon työntekijän HeTu, ja paina Remove Employee-nappulaa, ja työntekijä poistetaan tietokannasta, ja taulukko päivittyy. Työntekijän tai asiakkaan poistaminen poistaa tällä hetkellä myös heihin liittyvät työkeikat, mikä ei oikeastaan liene älykästä, joten ole varovainen poistamisien kanssa. ## Client-näkymä Sama kuin yllä, mutta asiakkaiden hallintaan tarkoitettu. ## Assignments-näkymä Assignments näkymässä näkyy kaikki työtehtävät samalla tavalla taulussa kuin työntekijätkin, ja niitä voi filtteröidä samalla tavalla kuin työntekijöitä. Taulukon tiedoista vain keikan kuvausta, statusta, osoitetta ja contact-puhelinnumeroa voi muuttaa. Muut keikan muuttujat eivät ole muutettavissa. Työtehtäviä voi myös poistaa taulukossa olevalla delete nappulalla. Uusia keikkoja voi luoda painamalla Create Assignment nappulaa, josta avautuu uusi ikkuna. Ensin valitaan uudessa ikkunassa keikkaan liittyvä asiakas listasta, jota voi myös filtteröidä vieressä olevalla filtteriboxilla samalla tavalla kuin muissakin näkymissä. Näkymässä voi myös suoraan luoda uuden asiakkaan, joskin pitää muistaa painaa Create Client nappulaa, jotta asiakas luodaan ja hän siirtyy valikoitavien asiakkaiden listaan. Sitten painetaan next, ja tehdään sama keikkaan liittyvän työntekijän suhteen. Sitten painetaan next, ja täytetään puuttuvat keikan yksityiskohdat. Näkymässä voi muuttaa keikan osoitetta (default: asiakkaan kotiosoite), contact-puhelinnumeroa (default:asiakkaan puhelinnumero), kuvausta, alkupäivää ja -aikaa sekä loppupäivää ja -aikaa. Sitten painetaan submit, ja uusi ikkuna sulkeutuu, ja uuden keikan pitäisi näkyä keikkaluettelossa. <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package harjoitustyo.presentation; import harjoitustyo.domain.Employee; import harjoitustyo.dao.EmployeeManagerDao; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import lombok.Getter; //Roni public class EmployeeView { private BorderPane root; private EmployeeManagerDao employeeManager; private ObservableList employees; private String filter = ""; private Text errorField = new Text(""); @Getter private VBox allComponentsBox = new VBox(); private VBox tableBox = new VBox(); private VBox filterBox = new VBox(); private VBox newEmployeeBox = new VBox(); private VBox removeEmployeeBox = new VBox(); public EmployeeView(BorderPane root, EmployeeManagerDao employeeManager) { this.root = root; this.employeeManager = employeeManager; allComponentsBox.setSpacing(10); employees = employeeManager.getObservableEmployees(filter); createTableBox(); createFilterBox(); createNewEmployeeBox(); createRemoveEmployeeBox(); allComponentsBox.getChildren().clear(); allComponentsBox.getChildren().addAll(tableBox, errorField, filterBox, newEmployeeBox, removeEmployeeBox); } public void createTableBox() { employees = employeeManager.getObservableEmployees(filter); tableBox.getChildren().clear(); TableView table = new TableView(); table.setEditable(true); TableColumn firstnameCol = createEditableColumn("First name", "firstname", 100); TableColumn lastnameCol = createEditableColumn("Last name", "lastname", 100); TableColumn emailCol = createEditableColumn("Email", "email", 200); TableColumn numberCol = createEditableColumn("Number", "number", 100); TableColumn addressCol = createEditableColumn("Address", "address", 200); TableColumn idNumberCol = createEditableColumn("ID number", "idNumber", 100); table.getColumns().addAll(firstnameCol, lastnameCol, emailCol, numberCol, addressCol, idNumberCol); table.setItems(employees); tableBox.getChildren().add(table); } private void createFilterBox() { filterBox.getChildren().clear(); HBox filterHBox = new HBox(); TextField filterField = new TextField(filter); Button filterBtn = new Button("Filter Employees"); Button removeFilterBtn = new Button("Clear Filter"); filterBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { filter = filterField.getText(); createTableBox(); } }); removeFilterBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { filter = ""; createTableBox(); createFilterBox(); } }); filterHBox.getChildren().addAll(filterField, filterBtn, removeFilterBtn); filterHBox.setSpacing(10); filterBox.getChildren().addAll(new Text("Filter Employees"), filterHBox); } private void createNewEmployeeBox() { newEmployeeBox.getChildren().clear(); HBox newEmployeeHBox = new HBox(); newEmployeeHBox.setSpacing(10); TextField fnameField = Utils.createTextField("First Name", 75); TextField lnameField = Utils.createTextField("Last name", 75); TextField emailField = Utils.createTextField("Email", 100); TextField numberField = Utils.createTextField("Phone number", 75); TextField addressField = Utils.createTextField("Address", 100); TextField idNumberField = Utils.createTextField("National id number", 125); Button submitButton = new Button("Add Employee"); newEmployeeHBox.getChildren().addAll(fnameField, lnameField, emailField, numberField, addressField, idNumberField, submitButton); submitButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (!employeeManager.contains(idNumberField.getText())) { Employee employee = new Employee(); employee.setEmail(emailField.getText()); employee.setFirstname(fnameField.getText()); employee.setLastname(lnameField.getText()); employee.setIdNumber(idNumberField.getText()); employee.setNumber(numberField.getText()); employee.setAddress(addressField.getText()); employeeManager.add(employee); createTableBox(); createNewEmployeeBox(); } else { errorField.setText("An employee with that ID already exists!"); } } }); newEmployeeBox.getChildren().addAll(new Text("Add a new employee"), newEmployeeHBox); } private void createRemoveEmployeeBox() { removeEmployeeBox.getChildren().clear(); HBox removeEmployeeHBox = new HBox(); TextField removeEmployeeTextField = Utils.createTextField("Employee's national id number", 200); removeEmployeeHBox.setSpacing(10); Button removeEmployeeButton = new Button("Remove Employee"); removeEmployeeHBox.getChildren().addAll(removeEmployeeTextField, removeEmployeeButton); removeEmployeeButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { String idNumber = removeEmployeeTextField.getText(); if (employeeManager.contains(idNumber)) { employeeManager.remove(idNumber); } else { errorField.setText("No employee with that ID exists."); } createTableBox(); } }); removeEmployeeBox.getChildren().addAll(new Text("Remove Employee"), removeEmployeeHBox); } private TableColumn createEditableColumn(String header, String field, int minWidth) { TableColumn returnCol = new TableColumn(header); returnCol.setMinWidth(minWidth); returnCol.setCellValueFactory(new PropertyValueFactory<Employee, String>(field)); returnCol.setCellFactory(TextFieldTableCell.forTableColumn()); if (field.equals("idNumber")) { returnCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Employee, String>>() { @Override public void handle(TableColumn.CellEditEvent<Employee, String> t) { if (!employeeManager.contains(t.getNewValue())) { Long id = t.getTableView().getItems().get( t.getTablePosition().getRow()).getId(); employeeManager.update(id, field, t.getNewValue()); } else { errorField.setText("An employee with that ID already exists!"); Utils.replaceTextAfterSleep(errorField, "", 5000); createTableBox(); } } }); } else { returnCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Employee, String>>() { @Override public void handle(TableColumn.CellEditEvent<Employee, String> t) { Long id = t.getTableView().getItems().get( t.getTablePosition().getRow()).getId(); employeeManager.update(id, field, t.getNewValue()); } }); } return returnCol; } } <file_sep>/* * */ package harjoitustyo.repoTests; import harjoitustyo.domain.AppUser; import harjoitustyo.repositories.AppUserRepository; import javax.transaction.Transactional; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest() @TestPropertySource( locations = "classpath:application-test.properties") @Transactional public class AppUserRepoTest { @Autowired AppUserRepository userrepo; @Test public void userCanBeSavedAndRetrieved() { AppUser user = new AppUser(); user.setAuthorization("authorization"); user.setPassword("<PASSWORD>"); user.setUsername("name"); AppUser savedUser = userrepo.save(user); savedUser = userrepo.getOne(savedUser.getId()); assertEquals(user.getAuthorization(), savedUser.getAuthorization()); assertEquals(user.getUsername(), savedUser.getUsername()); assertEquals(user.getPassword(), savedUser.getPassword()); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package harjoitustyo.dao; import harjoitustyo.domain.AppUser; import java.util.ArrayList; import org.springframework.stereotype.Service; /** * * @author Roni */ @Service public interface AppUserManagerDao { @Override String toString(); AppUser add(AppUser user); void remove(AppUser user); public ArrayList<AppUser> getUsers(); public AppUser getUser(String username); public boolean checkLogin(String username, String password); } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>harjoitustyo</groupId> <artifactId>Harjoitustyo</artifactId> <version>0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> </parent> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.17</version> <configuration> <configLocation>checkstyle.xml</configLocation> <excludes>harjoitustyo/presentation/*</excludes> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> <mainClass>harjoitustyo.Main</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-5</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>harjoitustyo.Main</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>assemble-all</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.3</version> <executions> <execution> <id>default-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> </executions> <configuration> <excludes> <exclude>harjoitustyo/presentation/**</exclude> <exclude>harjoitustyo/dao/ClientManagerMemory.class</exclude> <exclude>harjoitustyo/dao/EmployeeManagerMemory.class</exclude> <exclude>harjoitustyo/dao/AppUserManagerMemory.class</exclude> </excludes> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.2.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.2.2.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> </dependencies> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <start-class>harjoitustyo.Main</start-class> </properties> </project><file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Roni */ package harjoitustyo.repositories; import harjoitustyo.domain.Client; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ClientRepository extends JpaRepository<Client, Long> { Client findByIdNumber(String idNumber); boolean existsByIdNumber(String idNumber); void deleteByIdNumber(String idNumber); }<file_sep>package harjoitustyo.domain; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import lombok.Getter; import lombok.Setter; import org.springframework.data.jpa.domain.AbstractPersistable; @Entity @Getter @Setter public class Employee extends AbstractPersistable<Long> { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; private String firstname; private String fullname; private String lastname; private String number; private String email; private String idNumber; @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER, orphanRemoval = true) private Set<Assignment> assignments = new HashSet<Assignment>(); private String address; public Employee() { } public Employee(String firstname, String lastname, String number, String email, String idNumber, String address) { this.firstname = firstname; this.lastname = lastname; this.number = number; this.email = email; this.idNumber = idNumber; this.fullname = firstname + " " + lastname; this.address = address; } public void setLastname(String lastname) { this.lastname = lastname; this.fullname = this.firstname + " " + this.lastname; } public void setFirstname(String firstname) { this.firstname = firstname; this.fullname = this.firstname + " " + this.lastname; } public void addAssignment(Assignment assignment) { this.assignments.add(assignment); } public void removeAssignment(Assignment assignment) { this.assignments.remove(assignment); } public void clearAssignments() { this.assignments.stream().forEach(assignment -> assignment.getClient().removeAssignment(assignment)); this.assignments.clear(); } @Override public String toString() { return this.fullname + " " + this.idNumber; } } <file_sep>package harjoitustyo.presentation; //Roni import harjoitustyo.dao.AppUserManagerDao; import harjoitustyo.dao.AssignmentManagerDao; import harjoitustyo.dao.ClientManagerDao; import harjoitustyo.dao.EmployeeManagerDao; import harjoitustyo.domain.AppUser; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; public class Ui { private AppUserManagerDao userManager; private EmployeeManagerDao employeeManager; private ClientManagerDao clientManager; private AssignmentManagerDao assignmentManager; private Stage primaryStage; private Text errorField = new Text(""); private BorderPane root; private Scene scene; private AppUser user; public Ui(AppUserManagerDao userManager, EmployeeManagerDao employeeManager, ClientManagerDao clientManager, AssignmentManagerDao assignmentManager, Stage primaryStage) { this.userManager = userManager; this.employeeManager = employeeManager; this.clientManager = clientManager; this.assignmentManager = assignmentManager; this.primaryStage = primaryStage; } public void start() { // Graphics // Create the root root = new BorderPane(); root.setPadding(new Insets(10, 5, 5, 5)); // top, right, bottom, left //Top Box createLoginView(); // create the scene scene = new Scene(root, 1400, 1000); primaryStage.setTitle("Employee Management App"); primaryStage.setScene(scene); primaryStage.show(); } private void createLoginView() { HBox loginBox = new HBox(); loginBox.setSpacing(10); Button loginBtn = new Button("Login"); loginBtn.setDefaultButton(true); TextField nameField = new TextField(); PasswordField pwField = new PasswordField(); loginBox.getChildren().addAll(nameField, pwField, loginBtn, errorField); loginBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (userManager.checkLogin(nameField.getText(), pwField.getText())) { errorField.setText("Successful login"); removeLoginView(); createLogoutView(); user = userManager.getUser(nameField.getText()); if (user.getAuthorization().equals("Admin")) { createAdminView(); } } else { errorField.setText("Wrong username or password"); } } }); root.setTop(loginBox); Utils.replaceTextAfterSleep(errorField, "", 5000); } private void createLogoutView() { HBox hbox = new HBox(); hbox.setSpacing(10); hbox.setPadding(new Insets(10, 0, 10, 0)); // top, right, bottom, left Button logoutBtn = new Button("Logout"); hbox.getChildren().addAll(logoutBtn, errorField); logoutBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { errorField.setText("Successful logout"); user = null; removeAllViews(); createLoginView(); } }); root.setTop(hbox); Utils.replaceTextAfterSleep(errorField, "", 5000); } private void createAdminView() { // Creates the sidebar VBox sidebar = new VBox(); sidebar.setPadding(new Insets(10, 5, 5, 5)); // top, right, bottom, left sidebar.setSpacing(10); Button openEmployeeView = new Button("Employees"); Button openClientView = new Button("Client"); Button openAssignmentView = new Button("Assignments"); sidebar.getChildren().addAll(openEmployeeView, openClientView, openAssignmentView); root.setLeft(sidebar); //Creates the views in the center EmployeeView employeeView = new EmployeeView(root, employeeManager); ClientView clientView = new ClientView(root, clientManager); AssignmentView assignmentView = new AssignmentView(root, assignmentManager, clientManager, employeeManager); //Sets the buttons in the sidebar to manage the views in the center openEmployeeView.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { root.getChildren().remove(root.getCenter()); root.setCenter(employeeView.getAllComponentsBox()); } }); openClientView.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { root.getChildren().remove(root.getCenter()); root.setCenter(clientView.getAllComponentsBox()); } }); openAssignmentView.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { root.getChildren().remove(root.getCenter()); assignmentView.createTableBox(); root.setCenter(assignmentView.getAllComponentsBox()); } }); } private void removeLoginView() { root.getChildren().remove(root.getTop()); } private void removeAllViews() { root.getChildren().clear(); } } <file_sep>package harjoitustyo.dao; import harjoitustyo.domain.AppUser; import harjoitustyo.repositories.AppUserRepository; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @Controller public class AppUserManagerDB implements AppUserManagerDao { @Autowired private AppUserRepository userrepo; @Override public AppUser add(AppUser user) { if (!userrepo.existsByUsername(user.getUsername())) { user = userrepo.save(user); } return user; } @Override public void remove(AppUser user) { userrepo.delete(user); } @Override public ArrayList<AppUser> getUsers() { return (ArrayList) userrepo.findAll(); } @Override public AppUser getUser(String username) { return userrepo.findByUsername(username); } @Override public boolean checkLogin(String username, String password) { AppUser user = userrepo.findByUsername(username); if (user != null) { return user.getPassword().equals(password); } return false; } } <file_sep>## Testausdokumentti Ohjelmaa on testattu sekä kattavasti manuaalisesti että automatisoiduin testein JUnitilla. ## Yksikkö- ja integraatiotestaus ## Yksikkötestit Yksikkötestit keskittyvät lähinnä domain-pakkauksen luokkien toiminnan varmistamiseen, ja ovat suoritettu täysin automaattisesti JUnit-kirjastolla. Nämä löytyvät harjoitustyo.unitTests-pakkauksesta. ## Integraatiotestit Integraatiotestit keskittyvät dao-pakkauksen luokkien toiminnan varmistamiseen. Nämä löytyvät harjoitustyo.managerTests-pakkauksesta. Testit on konfiguroitu käyttämään erillistä muistissa olevaa SQL-databasea application-test.properties tiedostolla, jotta testien toimintaan ei vaikuta minkään käytetyn tietokannan tila. Testit käyttävät kumminkin ohjelman oikeita luokkia kyseisen databasen pyörittämiseen. Missään integraatiotestissä ei ole käytetty stub- tai mock-luokkia, sillä en nähnyt tarvetta testeille, joissa sellaisia käytettäisiin. Mahdollisesti, jos olisi pitänyt myös käyttöliittymää testata, niin database olisi silloin voitu luoda stubbina tai mockina, jotta testit nopeutuisivat. (sillä databaselle on jo omat testinsä). Ohjelmassa on myös repository-interface-luokille muutama testi, mutta nämä eivät kattavia, sillä managerDB-testit testaavat jo ne toiminnot, joita repositoryilta vaaditaan. ## Testauskattavuus Käyttöliittymäkerrosta lukuunottamatta sovelluksen testauksen rivikattavuus on 79% ja haarautumakattavuus 92%. Kattavuutta vähentää domain-pakkauksen luokkien osalta mm. lombok-kirjaston @Setter annotaation mukana tulevat setterit, joita ohjelma ei käytä mihinkään, ja joita en jaksa testata. En kumminkaan halunnut luopua annotaatioista, sillä ne vähentävät boilerplatea niiden attribuuttien kannalta, joille tarvitaan settereitä. Samaten assignmenttein poistamiseen clienteilta/employeelta liittyvät toiminnot ovat testaamatta, sillä niitä käytetään, kun poistetaan client/employee, jolla on assignmentteja, enkä tiennyt haluanko sallia sellaista tehtävän. Nykyisessä versiossa kumminkin näin voi tehdä, mutta toimintoa ei testata automaattisesti. ## Järjestelmätestaus Käyttöliittymätestaus on tehty manuaalisesti. ## Asennus ja konfigurointi Sovelluksen automaattisest testit on pyöritetty Windows 7-ympäristössä sekä Java 8 että Java 11 versioilla, ja testattu Java 11 versiota manuaalisesti etätyöpöydällä. Sovellusta on testattu sekä silloin kun se luo database-tiedoston itse, että kun se käyttää jo aiemmin luomaansa database-tiedostoa. ## Toiminnallisuudet Kaikki määrittelydokumentin ja käyttöohjeen listaamat toiminnallisuudet on käyty läpi. Kaikkien toiminnallisuuksien yhteydessä on syötekentät yritetty täyttää myös virheellisillä arvoilla kuten tyhjillä, joskin esimerkiksi asiakkaiden ja työntekijöiden luonnissa ei ole validointia, joka estäisi tyhjien nimien tai numeroiden käyttämisen arvoina. Ainoastaan se, että kahdella työntekijällä/asiakkaalla ei voi olla samaa HeTua tarkistetaan. Keikkojen luomisessa on vahvempi validointi tyhien osalta, ja päiväyksien osalta, joskin siinäkin voi täyttää hölmöjä arvoja, kuten kirjaimia puhelinnumeroiksi jne. Nämä laskettavissa ohjelman laatuongelmaksi.
a9e0f8fb3cb0953ad80ba252b7ea1b0159be4713
[ "Markdown", "Java", "Maven POM" ]
20
Markdown
RoniNiklas/ot-harjoitustyo
7be19b7f5cfbda07be2439bab127282762087b01
a3f7910ca16d927d6d14d7bcb2f54ca797ae6551
refs/heads/master
<repo_name>Artrigger/generator<file_sep>/src/Services/SwaggerService.php <?php namespace LaravelRocket\Generator\Services; use LaravelRocket\Generator\Objects\Swagger\Spec; use Symfony\Component\Yaml\Yaml; class SwaggerService { /** * @param string $path * * @return Spec */ public function parse($path) { $content = file_get_contents($path); if ($this->isJson($path)) { $data = json_decode($content); } else { $data = Yaml::parse($content, Yaml::PARSE_OBJECT_FOR_MAP); } return new Spec($data, $path); } protected function getPathExtension($path) { return strtolower(pathinfo($path, PATHINFO_EXTENSION)); } protected function isJson($path) { $extension = $this->getPathExtension($path); return strtolower($extension) === 'json'; } protected function isYaml($path) { $extension = $this->getPathExtension($path); return $extension === 'yml' || $extension === 'yaml'; } } <file_sep>/src/Generators/ServiceGenerator.php <?php namespace LaravelRocket\Generator\Generators; class ServiceGenerator extends Generator { public function generate($name, $overwrite = false, $baseDirectory = null) { $modelName = $this->getModelName($name); $this->generateService($modelName); $this->generateServiceInterface($modelName); $this->generateServiceUnitTest($modelName); $this->bindInterface($modelName); } /** * @param string $name * * @return string */ protected function getModelName($name) { $className = $this->getClassName($name); $modelName = str_replace('Service', '', $className); return $modelName; } /** * @param string $name * * @return string */ protected function getModelClass($name) { $modelName = $this->getModelName($name); return '\\App\\Models\\'.$modelName; } protected function getServiceClass($name) { $modelName = $this->getModelName($name); return '\\App\\Services\\Production\\'.$modelName.'Service'; } /** * @param string $modelName * * @return bool */ protected function generateService($modelName) { $className = $this->getServiceClass($modelName); $classPath = $this->convertClassToPath($className); $modelClass = $this->getModelClass($modelName); $stubFilePath = $this->getStubPath('/service/service.stub'); $classExists = class_exists($modelClass); if ($classExists) { $instance = new $modelClass(); if ($instance instanceof \LaravelRocket\Foundation\Models\AuthenticatableBase) { $stubFilePath = $this->getStubPath('/service/service_with_auth.stub'); } else { $stubFilePath = $this->getStubPath('/service/service_with_model.stub'); } } return $this->generateFile($modelName, $classPath, $stubFilePath); } /** * @param string $modelName * * @return bool */ protected function generateServiceInterface($modelName) { $className = '\\App\\Services\\'.$modelName.'ServiceInterface'; $classPath = $this->convertClassToPath($className); $modelClass = $this->getModelClass($modelName); $stubFilePath = $this->getStubPath('/service/service_interface.stub'); $classExists = class_exists($modelClass); if ($classExists) { $instance = new $modelClass(); if ($instance instanceof \LaravelRocket\Foundation\Models\AuthenticatableBase) { $stubFilePath = $this->getStubPath('/service/service_interface_with_auth.stub'); } } return $this->generateFile($modelName, $classPath, $stubFilePath); } /** * @param string $modelName * * @return bool */ protected function generateServiceUnitTest($modelName) { $classPath = base_path('/tests/Services/'.$modelName.'ServiceTest.php'); $modelClass = $this->getModelClass($modelName); $stubFilePath = $this->getStubPath('/service/service_unittest.stub'); $classExists = class_exists($modelClass); if ($classExists) { $instance = new $modelClass(); if ($instance instanceof \LaravelRocket\Foundation\Models\AuthenticatableBase) { $stubFilePath = $this->getStubPath('/service/service_unittest.stub'); } } return $this->generateFile($modelName, $classPath, $stubFilePath); } /** * @param string $name * * @return bool */ protected function bindInterface($name) { $bindingPath = base_path('/app/Providers/ServiceServiceProvider.php'); $key = '/* NEW BINDING */'; $bind = '$this->app->singleton('.PHP_EOL.' \\App\\Services\\'.$name.'ServiceInterface::class,'.PHP_EOL.' \\App\\Services\\Production\\'.$name.'Service::class'.PHP_EOL.' );'.PHP_EOL.PHP_EOL.' '; $this->replaceFile([ $key => $bind, ], $bindingPath); return true; } } <file_sep>/src/Console/Commands/APIGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\APIGenerator; class APIGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:api'; protected $description = 'Create APIs from Swagger file'; protected $generator = APIGenerator::class; /** * Execute the console command. * * @return bool|null */ public function handle() { $targetName = $this->getTargetName(); return $this->generate($targetName); } } <file_sep>/src/Console/Commands/AlterMigrationGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\AlterMigrationGenerator; class AlterMigrationGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:migration:alter'; protected $description = 'Create a migration for alter table'; protected $generator = AlterMigrationGenerator::class; } <file_sep>/src/Generators/APIGenerator.php <?php namespace LaravelRocket\Generator\Generators; use LaravelRocket\Generator\Objects\Swagger\Definition; use LaravelRocket\Generator\Objects\Swagger\Spec; use LaravelRocket\Generator\Services\SwaggerService; class APIGenerator extends Generator { /** @var Spec */ protected $swagger; protected $namespace; public function generate($swaggerPath, $overwrite = false, $baseDirectory = null) { $ret = $this->readSwaggerFile($swaggerPath); if (!$ret) { return; } $this->generateRoute(); $this->generateResponses(); } protected function generateRoute() { $routesPath = $this->getRoutesPath(); if (!$this->files->exists($routesPath)) { $route = $this->getStubPath('/api/route_file.stub'); $this->files->put($routesPath, $route); } } /** * @param string $name * * @return string */ protected function getResponseClass($name) { return '\\App\\Http\\Responses\\'.$this->namespace.'\\'.$name; } /** * @return string */ protected function getRoutesPath() { return base_path('/routes/api.php'); } protected function generateResponses() { $definitions = $this->swagger->getDefinitions(); foreach ($definitions as $definition) { $this->generateResponse($definition); } } /** * @param Definition $definition * * @return bool */ protected function generateResponse($definition) { $name = $definition->getName(); $class = $this->getResponseClass($name); $classPath = $this->convertClassToPath($class); $stubFilePath = $this->getStubForResponse(); $columns = ''; $columnsFromModel = ''; foreach ($definition->getProperties() as $property) { $default = 'null'; switch ($property->getType()) { case 'string': $default = '\'\''; break; case 'integer': case 'int': $default = '0'; break; case 'array': $default = '[]'; break; } if (!empty($columns)) { $columns .= PHP_EOL; $columnsFromModel .= PHP_EOL; } $columns .= ' \''.$property->getName().'\' => '.$default.','; $columnsFromModel .= ' \''.$property->getName().'\' => $model->'.$property->getName().','; } if ($this->files->exists($classPath)) { return false; } return $this->generateFile($class, $classPath, $stubFilePath, [ 'COLUMNS' => $columns, 'COLUMNS_FROM_MODEL' => $columnsFromModel, 'NAMESPACE' => $this->namespace, 'NAME' => $name, ]); } /** * @return string */ protected function getStubForResponse() { return $this->getStubPath('/api/response.stub'); } protected function readSwaggerFile($swaggerPath) { $service = new SwaggerService(); $this->swagger = $service->parse($swaggerPath); if (empty($this->swagger)) { $this->error('Fail to parse Swagger File'); } $this->namespace = $this->swagger->getNamespace(); return true; } } <file_sep>/tests/Objects/SwaggerTest.php <?php namespace LaravelRocket\Generator\Tests\Objects; use LaravelRocket\Generator\Objects\Swagger\Definition; use LaravelRocket\Generator\Tests\TestCase; use LaravelRocket\Generator\Services\SwaggerService; class SwaggerTest extends TestCase { public function testGetFromYaml() { $dataPath = realpath(__DIR__.'/../data/sample_swagger.yaml'); $service = new SwaggerService(); $spec = $service->parse($dataPath); $this->assertNotEmpty($spec); $this->assertEquals('/api/v1', $spec->getBasePath()); $definitions = $spec->getDefinitions(); /** * @var string $name * @var Definition $definition */ foreach($definitions as $definition) { print $definition->getName().PHP_EOL; $properties = $definition->getProperties(); foreach($properties as $property) { print $property->getName().PHP_EOL; print $property->getType().PHP_EOL; } } $this->assertEquals('Api\\V1', $spec->getNamespace()); } public function testGetFromJson() { $dataPath = realpath(__DIR__.'/../data/sample_swagger.json'); $service = new SwaggerService(); $swagger = $service->parse($dataPath); $this->assertNotEmpty($swagger); $this->assertEquals('/api/v1', $swagger->getBasePath()); } } <file_sep>/src/Generators/CreateMigrationGenerator.php <?php namespace LaravelRocket\Generator\Generators; use Symfony\Component\Console\Exception\InvalidArgumentException; use function ICanBoogie\pluralize; class CreateMigrationGenerator extends Generator { public function generate($name, $overwrite = false, $baseDirectory = null) { $this->generateMigration($name); } protected function generateMigration($name) { $name = $this->getTableName($name); if (class_exists($className = $this->getClassName($name))) { throw new InvalidArgumentException("A $className migration already exists."); } $path = $this->getPath($name); $stubFilePath = $this->getStubPath('/migration/create.stub'); return $this->generateFile($className, $path, $stubFilePath, [ 'CLASS' => $className, 'TABLE' => $name, ]); } protected function getTableName($name) { return pluralize(snake_case($name)); } protected function getClassName($name) { return 'Create'.ucfirst(camel_case($name)).'Table'; } protected function getPath($name) { $basePath = database_path('migrations'); return $basePath.'/'.date('Y_m_d_His').'_create_'.$name.'_table.php'; } } <file_sep>/src/Generators/AdminCRUDGenerator.php <?php namespace LaravelRocket\Generator\Generators; class AdminCRUDGenerator extends Generator { public function generate($name, $overwrite = false, $baseDirectory = null) { $modelName = $this->getModelName($name); $this->generateController($modelName); $this->generateRequest($modelName); $this->generateView($modelName, 'index'); $this->generateView($modelName, 'edit'); $this->generateView($modelName, '_nav'); $this->generateView($modelName, '_form'); $this->generateUnittest($modelName); $this->addItemToSubMenu($modelName); $this->addItemToLanguageFile($modelName); $this->addItemToRoute($modelName); } /** * @param string $name * * @return string */ protected function getModelName($name) { $className = $this->getClassName($name); $modelName = str_replace('Controller', '', $className); return $modelName; } /** * @param string $name * * @return string */ protected function getControllerClass($name) { $modelName = $this->getModelName($name); return '\\App\\Http\\Controllers\\Admin\\'.$modelName.'Controller'; } /** * @param string $name * * @return string */ protected function getRequestClass($name) { $modelName = $this->getModelName($name); return '\\App\\Http\\Requests\\Admin\\'.$modelName.'Request'; } /** * @param string $name * @param string $type * * @return string */ protected function getViewPath($name, $type) { $directoryName = \StringHelper::camel2Spinal(\StringHelper::pluralize($name)); return base_path('/resources/views/pages/admin/'.$directoryName.'/'.$type.'.blade.php'); } /** * @return string */ protected function getSideBarViewPath() { return base_path('/resources/views/layouts/admin/side_menu.blade.php'); } /** * @return string */ protected function getLanguageFilePath() { return base_path('/resources/lang/en/admin.php'); } /** * @return string */ protected function getRoutesPath() { return base_path('/routes/admin.php'); } /** * @param string * * @return string */ protected function getStubForView($type) { return $this->getStubPath('/admin-crud/view-'.$type.'.stub'); } /** * @param string $modelName * @param string $classPath * @param string $stubFilePath * * @return bool */ protected function saveFile($modelName, $classPath, $stubFilePath) { $list = $this->generateParams($modelName); $updates = $this->generateUpdate($modelName); $tableHeader = $this->generateListHeader($modelName); $tableContent = $this->generateListRow($modelName); $formContent = $this->generateEditForm($modelName); $testColumn = $this->generateTestColumn($modelName); return $this->generateFile($modelName, $classPath, $stubFilePath, [ 'models-spinal' => \StringHelper::camel2Spinal(\StringHelper::pluralize($modelName)), 'models' => lcfirst(\StringHelper::pluralize($modelName)), 'MODELS' => \StringHelper::pluralize($modelName), 'COLUMN_UPDATES' => $updates, 'COLUMNS' => $list, 'TABLE_HEADER' => $tableHeader, 'TABLE_CONTENT' => $tableContent, 'FORM' => $formContent, 'test_column' => $testColumn, ]); } /** * @param string $name * * @return bool */ protected function generateController($name) { $modelName = $this->getModelName($name); $className = $this->getControllerClass($modelName); $classPath = $this->convertClassToPath($className); $stubFilePath = $this->getStubPath('/admin-crud/controller.stub'); return $this->saveFile($modelName, $classPath, $stubFilePath); } /** * @param string $name * * @return bool */ protected function generateRequest($name) { $modelName = $this->getModelName($name); $className = $this->getRequestClass($modelName); $classPath = $this->convertClassToPath($className); $stubFilePath = $this->getStubPath('/admin-crud/request.stub'); return $this->saveFile($modelName, $classPath, $stubFilePath); } /** * @param string $name * * @return bool */ protected function generateView($name, $type) { $modelName = $this->getModelName($name); $path = $this->getViewPath($name, $type); $stubPath = $this->getStubForView($type); return $this->saveFile($modelName, $path, $stubPath); } /** * @param string $name * * @return bool */ protected function generateUnitTest($name) { $modelName = $this->getModelName($name); $classPath = base_path('/tests/Controllers/Admin/'.$modelName.'ControllerTest.php'); $stubFilePath = $this->getStubPath('/admin-crud/unittest.stub'); return $this->saveFile($modelName, $classPath, $stubFilePath); } /** * @param string $name * * @return bool */ protected function addItemToSubMenu($name) { $modelName = $this->getModelName($name); $sideMenuPath = $this->getSideBarViewPath(); $stubPath = $this->getStubPath('/admin-crud/view-side_menu.stub'); $result = $this->replace([ 'column' => $name, 'column-spinal' => \StringHelper::camel2Spinal(\StringHelper::snake2Camel($name)), 'models-spinal' => \StringHelper::camel2Spinal(\StringHelper::pluralize($modelName)), 'models' => \StringHelper::pluralize(lcfirst($modelName)), 'MODEL' => $modelName, 'model' => lcfirst($modelName), ], $stubPath).PHP_EOL.' '; $key = '<!-- %%SIDEMENU%% -->'; $bind = $result; return $this->replaceFile([ $key => $bind, ], $sideMenuPath); } /** * @param string $name * * @return bool */ protected function addItemToLanguageFile($name) { $modelName = $this->getModelName($name); $languageFilePath = $this->getLanguageFilePath(); $directoryName = \StringHelper::camel2Spinal(\StringHelper::pluralize($modelName)); $key = '/* NEW PAGE STRINGS */'; $columns = $this->getFillableColumns($modelName); $bind = "'".$directoryName."' => [".PHP_EOL." 'columns' => [".PHP_EOL; foreach ($columns as $column) { $name = $column->getName(); $bind .= " '".$name."' => '".ucfirst($name)."',".PHP_EOL; } $bind .= ' ],'.PHP_EOL.' ],'.PHP_EOL.' '; return $this->replaceFile([ $key => $bind, ], $languageFilePath); } /** * @param string $name * * @return bool */ protected function addItemToRoute($name) { $modelName = $this->getModelName($name); $routePath = $this->getRoutesPath(); $directoryName = \StringHelper::camel2Spinal(\StringHelper::pluralize($modelName)); $key = '/* NEW ADMIN RESOURCE ROUTE */'; $bind = 'Route::resource(\''.$directoryName.'\', \'Admin\\'.$modelName.'Controller\');'.PHP_EOL.' '; return $this->replaceFile([ $key => $bind, ], $routePath); } /** * @param string $name * * @return string */ protected function generateEditForm($name) { $modelName = $this->getModelName($name); $columns = $this->getFillableColumns($modelName); $result = ''; foreach ($columns as $column) { $name = $column->getName(); $type = $column->getType()->getName(); if ($name == 'id') { continue; } $stubPath = $this->getStubPath('/admin-crud/form/text.stub'); if (\StringHelper::endsWith($name, 'image_id')) { $stubPath = $this->getStubPath('/admin-crud/form/image.stub'); } else { if (\StringHelper::endsWith($name, '_id')) { continue; } else { switch ($type) { case 'boolean': $stubPath = $this->getStubPath('/admin-crud/form/checkbox.stub'); break; case 'datetime': $stubPath = $this->getStubPath('/admin-crud/form/datetime.stub'); break; case 'text': $stubPath = $this->getStubPath('/admin-crud/form/textarea.stub'); break; case 'date': $stubPath = $this->getStubPath('/admin-crud/form/date.stub'); break; case 'string': case 'integer': case 'bigint': case 'smallint': switch ($name) { case 'password': $stubPath = $this->getStubPath('/admin-crud/form/password.stub'); break; case 'email': $stubPath = $this->getStubPath('/admin-crud/form/email.stub'); break; default: $stubPath = $this->getStubPath('/admin-crud/form/text.stub'); } break; } } } $fieldName = strlen($name) > 3 ? substr($name, 0, strlen($name) - 3) : $name; $relationName = lcfirst(\StringHelper::snake2Camel($fieldName)); $result .= $this->replace([ 'column' => $name, 'column-spinal' => \StringHelper::camel2Spinal(\StringHelper::snake2Camel($name)), 'models-spinal' => \StringHelper::camel2Spinal(\StringHelper::pluralize($modelName)), 'models-snake' => \StringHelper::camel2Snake(\StringHelper::pluralize($modelName)), 'models' => \StringHelper::pluralize(lcfirst($modelName)), 'MODEL' => $modelName, 'model' => lcfirst($modelName), 'relation' => $relationName, ], $stubPath).PHP_EOL; } return $result; } /** * @param string $name * * @return string */ protected function generateListHeader($name) { $modelName = $this->getModelName($name); $spinalName = \StringHelper::camel2Spinal(\StringHelper::pluralize($modelName)); $columns = $this->getFillableColumns($modelName); $result = ''; foreach ($columns as $column) { $name = $column->getName(); $type = $column->getType()->getName(); if (\StringHelper::endsWith($name, 'image_id')) { continue; } elseif (\StringHelper::endsWith($name, '_id')) { continue; } else { switch ($type) { case 'text': break; case 'datetime': case 'string': case 'integer': case 'boolean': $result .= ' <th>@lang(\'admin.pages.'.$spinalName.'.columns.'.$name.'\')</th>'.PHP_EOL; break; } } } return $result; } /** * @param string $name * * @return string */ protected function generateListRow($name) { $modelName = $this->getModelName($name); $lcName = lcfirst($modelName); $columns = $this->getFillableColumns($modelName); $result = ''; foreach ($columns as $column) { $name = $column->getName(); $type = $column->getType()->getName(); if (\StringHelper::endsWith($name, 'image_id')) { continue; } else { if (\StringHelper::endsWith($name, '_id')) { continue; } else { switch ($type) { case 'text': break; case 'boolean': $result .= ' <td>{{ ($'.$lcName.'->'.$name.') ? \'ON\' : \'OFF\' }}</td>'.PHP_EOL; break; case 'datetime': case 'string': case 'integer': $result .= ' <td>{{ $'.$lcName.'->'.$name.' }}</td>'.PHP_EOL; break; } } } } return $result; } /** * @param string $name * * @return string */ protected function generateUpdate($name) { $modelName = $this->getModelName($name); $columns = $this->getFillableColumns($modelName); $result = ''; foreach ($columns as $column) { $name = $column->getName(); $type = $column->getType()->getName(); if (\StringHelper::endsWith($name, 'image_id')) { continue; } else { if (\StringHelper::endsWith($name, '_id')) { continue; } else { switch ($type) { case 'text': break; case 'boolean': $result .= ' $input[\''.$name.'\'] = $request->get(\''.$name.'\', false);'.PHP_EOL; break; case 'datetime': case 'string': case 'integer': break; } } } } return $result; } /** * @param string $name * * @return string */ protected function generateParams($name) { $modelName = $this->getModelName($name); $columns = $this->getFillableColumns($modelName); $params = []; foreach ($columns as $column) { $name = $column->getName(); $type = $column->getType()->getName(); if (\StringHelper::endsWith($name, 'image_id')) { continue; } else { if (\StringHelper::endsWith($name, '_id')) { continue; } else { switch ($type) { case 'boolean': break; case 'text': case 'datetime': case 'string': case 'integer': $params[] = $name; break; } } } } $result = implode(',', array_map(function ($name) { return "'".$name."'"; }, $params)); return $result; } /** * @param $name * * @return string */ protected function generateTestColumn($name) { $modelName = $this->getModelName($name); $columns = $this->getFillableColumns($modelName); $candidate = 'NONAME'; foreach ($columns as $column) { $name = $column->getName(); $type = $column->getType()->getName(); if ($type == 'string' || $type == 'text') { return $name; } if ($type == 'integer') { $candidate = $name; } } return $candidate; } } <file_sep>/src/Objects/Swagger/Spec.php <?php namespace LaravelRocket\Generator\Objects\Swagger; class Spec { /** * @var string */ protected $path; /** * @var \stdClass */ protected $object; /** * Swagger constructor. * * @param \stdClass $data * @param string $path */ public function __construct($data, $path) { $this->path = $path; $this->data = $data; } /** * @return array */ public function getOperations() { return $this->data->paths; } /** * @return string */ public function getBasePath() { return $this->data->basePath; } /** * @return array|\Swagger\Object\Reference */ public function getDefinitions() { /** @var \Swagger\Object\Definitions $definitions */ $definitions = $this->data->definitions; $ret = []; foreach ($definitions as $name => $definition) { $ret[] = new Definition($name, $definition); } return $ret; } /** * @return string */ public function getNamespace() { $basePath = $this->getBasePath(); $names = array_filter(explode('/', $basePath), function ($path) { return !empty($path); }); return implode('\\', array_map(function ($path) { return studly_case($path); }, $names)); } } <file_sep>/src/Console/Commands/AdminCRUDGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\AdminCRUDGenerator; class AdminCRUDGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:admin:crud'; protected $description = 'Create a admin crud for database table'; protected $generator = AdminCRUDGenerator::class; } <file_sep>/src/Console/Commands/ModelGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\ModelGenerator; class ModelGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:model'; protected $description = 'Create a new model class'; protected $generator = ModelGenerator::class; } <file_sep>/src/Objects/Swagger/Parameter.php <?php namespace LaravelRocket\Generator\Objects\Swagger; class Parameter { /** * @var \Swagger\Object\Schema */ protected $definition; /** @var string $name */ protected $name; /** @var array $properties */ protected $properties; public function __construct($name, $definition) { $this->definition = $definition; $this->name = $name; $this->properties = []; } public function getName() { return $this->name; } } <file_sep>/src/Generators/ModelGenerator.php <?php namespace LaravelRocket\Generator\Generators; class ModelGenerator extends Generator { public function generate($name, $overwrite = false, $baseDirectory = null) { $modelName = $this->getModelName($name); if (!$this->checkTableExists($name)) { return; } $this->generateModel($modelName); $this->generatePresenter($modelName); $this->generateModelUnitTest($modelName); $this->generateModelFactory($modelName); } /** * @param $name * * @return bool */ protected function checkTableExists($name) { $modelName = $this->getModelName($name); $tableName = $this->getTableName($modelName); $columns = $this->getTableColumns($tableName); if (empty($columns) || count($columns) == 0) { $this->error('table '.$tableName.' could not found in database.'); return false; } return true; } /** * @param string $name * * @return string */ protected function getModelName($name) { $className = $this->getClassName($name); return $className; } /** * @param string $name * * @return string */ protected function getModelClass($name) { $modelName = $this->getModelName($name); return '\\App\\Models\\'.$modelName; } /** * @param string $modelName * * @return string */ protected function getDateTimeColumns($modelName) { $tableName = $this->getTableName($modelName); $ret = []; $columns = $this->getTableColumns($tableName); if ($columns) { foreach ($columns as $column) { if (!in_array($column->getType()->getName(), ['datetime', 'date', 'time'])) { continue; } $columnName = $column->getName(); if (!in_array($columnName, ['created_at', 'updated_at'])) { $ret[] = $columnName; } } } $datetimes = count($ret) > 0 ? "'".implode("','", $ret)."'" : ''; return $datetimes; } /** * @param string $modelName * * @return bool */ protected function hasSoftDeleteColumn($modelName) { $tableName = $this->getTableName($modelName); $columns = $this->getTableColumns($tableName); if ($columns) { foreach ($columns as $column) { $columnName = $column->getName(); if ($columnName == 'deleted_at') { return true; } } } return false; } /** * @return string[] */ protected function getTableList() { $hasDoctrine = interface_exists('Doctrine\DBAL\Driver'); if (!$hasDoctrine) { return []; } $tables = \DB::getDoctrineSchemaManager()->listTables(); $ret = []; foreach ($tables as $table) { $ret[] = $table->getName(); } return $ret; } /** * @param string $modelName * * @return bool */ protected function generateModel($modelName) { $className = $this->getModelClass($modelName); $classPath = $this->convertClassToPath($className); $stubFilePath = $this->getStubPath('/model/model.stub'); $tableName = $this->getTableName($modelName); $columns = $this->getFillableColumns($modelName); $fillables = count($columns) > 0 ? "'".implode("',".PHP_EOL." '", $this->getColumnNames($columns))."'," : ''; $hasSoftDelete = $this->hasSoftDeleteColumn($tableName); return $this->generateFile($modelName, $classPath, $stubFilePath, [ 'TABLE' => $tableName, 'FILLABLES' => $fillables, 'SOFT_DELETE_CLASS_USE' => $hasSoftDelete ? 'use Illuminate\Database\Eloquent\SoftDeletes;'.PHP_EOL : '', 'SOFT_DELETE_USE' => $hasSoftDelete ? 'use SoftDeletes;'.PHP_EOL : '', 'DATETIMES' => $this->getDateTimeColumns($modelName), 'RELATIONS' => $this->generateModelRelation($modelName), ]); } protected function getPath($name) { $className = $this->getClassName($name); return app_path('/Models/'.$className.'.php'); } protected function generateModelRelation($modelName) { $relations = ''; $tables = $this->getTableList(); $tableName = $this->getTableName($modelName); $columns = $this->getFillableColumns($tableName); foreach ($columns as $column) { $columnName = $column->getName(); if (preg_match('/^(.*_image)_id$/', $columnName, $matches)) { $relationName = \StringHelper::snake2Camel($matches[1]); $relations .= ' public function '.$relationName.'()'.PHP_EOL.' {'.PHP_EOL.' return $this->hasOne(\App\Models\File::class, \'id\', \''.$columnName.'\');'.PHP_EOL.' }'.PHP_EOL.PHP_EOL; } elseif (preg_match('/^(.*)_id$/', $columnName, $matches)) { $relationName = \StringHelper::snake2Camel($matches[1]); $className = ucfirst($relationName); if (!$this->getPath($className)) { continue; } $relations .= ' public function '.$relationName.'()'.PHP_EOL.' {'.PHP_EOL.' return $this->belongsTo(\App\Models\\'.$className.'::class, \''.$columnName.'\', \'id\');'.PHP_EOL.' }'.PHP_EOL.PHP_EOL; } } return $relations; } /** * @param string $modelName * * @return bool */ protected function generatePresenter($modelName) { $className = '\\App\\Presenters\\'.$modelName.'Presenter'; $classPath = $this->convertClassToPath($className); $stubFilePath = __DIR__.'/../../stubs/model/presenter.stub'; $tableName = $this->getTableName($modelName); $columns = $this->getFillableColumns($tableName); $multilingualKeys = []; foreach ($columns as $column) { if (preg_match('/^(.*)_en$/', $column->getName(), $matches)) { $multilingualKeys[] = $matches[1]; } } $multilingualKeyString = count($multilingualKeys) > 0 ? "'".implode("','", array_unique($multilingualKeys))."'" : ''; $imageFields = []; foreach ($columns as $column) { if (preg_match('/^(.*_image)_id$/', $column->getName(), $matches)) { $imageFields[] = $matches[1]; } } $imageFieldString = count($imageFields) > 0 ? "'".implode("','", array_unique($imageFields))."'" : ''; return $this->generateFile($modelName, $classPath, $stubFilePath, [ 'MULTILINGUAL_COLUMNS' => $multilingualKeyString, 'IMAGE_COLUMNS' => $imageFieldString, ]); } /** * @param string $modelName * * @return bool */ protected function generateModelUnitTest($modelName) { $classPath = base_path('/tests/Models/'.$modelName.'Test.php'); $stubFilePath = $this->getStubPath('/model/model_unittest.stub'); return $this->generateFile($modelName, $classPath, $stubFilePath); } /** * @param string $modelName * * @return bool */ protected function generateModelFactory($modelName) { $className = $this->getModelClass($modelName); $tableName = $this->getTableName($modelName); $columns = $this->getFillableColumns($tableName); $factoryPath = base_path('/database/factories/ModelFactory.php'); $key = '/* NEW MODEL FACTORY */'; $data = '$factory->define('.$className.'::class, function (Faker\Generator $faker) {'.PHP_EOL.' return ['.PHP_EOL; foreach ($columns as $column) { $defaultValue = "''"; switch ($column->getType()->getName()) { case 'bigint': case 'integer': case 'smallint': $defaultValue = '0'; break; case 'decimal': case 'float': $defaultValue = '0.0'; break; case 'string': case 'text': case 'binary': $defaultValue = "''"; break; case 'datetime': $defaultValue = '$faker->dateTime'; break; case 'boolean': $defaultValue = '$faker->boolean'; break; } switch ($column->getName()) { case 'name': $defaultValue = '$faker->name'; break; case 'email': $defaultValue = '$faker->unique()->safeEmail'; break; case 'password': $defaultValue = '<PASSWORD>(\'<PASSWORD>\')'; break; } $data .= " '".$column->getName()."' => ".$defaultValue.','.PHP_EOL; } $data .= ' ];'.PHP_EOL.'});'.PHP_EOL.PHP_EOL; $this->replaceFile([ $key => $data, ], $factoryPath); return true; } } <file_sep>/src/Utilities/APIValidator.php <?php namespace LaravelRocket\Generator\Utilities; class APIValidator { protected $swagger; public function __construct($swagger) { $this->swagger = $swagger; } public function validate() { } protected function validateBasePath() { } } <file_sep>/src/Generators/Generator.php <?php namespace LaravelRocket\Generator\Generators; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Filesystem\Filesystem; use Illuminate\View\Factory as ViewFactory; abstract class Generator { /** @var \Illuminate\Config\Repository */ protected $config; /** @var \Illuminate\Filesystem\Filesystem */ protected $files; /** @var \Illuminate\View\Factory */ protected $view; /** @var string */ protected $errorString; /** @var bool */ protected $overwrite; /** * @param \Illuminate\Config\Repository $config * @param \Illuminate\Filesystem\Filesystem $files * @param \Illuminate\View\Factory $view */ public function __construct( ConfigRepository $config, Filesystem $files, ViewFactory $view ) { $this->config = $config; $this->files = $files; $this->view = $view; } /** * @param string $name * @param bool $overwrite * @param string|null $baseDirectory */ abstract public function generate($name, $overwrite = false, $baseDirectory = null); /** * @param bool $overwrite */ public function setOverwrite($overwrite) { $this->overwrite = $overwrite; } public function shouldOverwrite() { return $this->overwrite; } /** * @param array $data * @param string $stubPath * * @return string */ protected function replace($data, $stubPath) { $stub = $this->files->get($stubPath); foreach ($data as $key => $value) { $templateKey = '%%'.$key.'%%'; $stub = str_replace($templateKey, $value, $stub); } return $stub; } /** * @param array $data * @param string $filePath * * @return bool */ protected function replaceFile($data, $filePath) { if (!$this->files->exists($filePath)) { return false; } $content = $this->files->get($filePath); foreach ($data as $key => $value) { $content = str_replace($key, $value.$key, $content); } $this->files->put($filePath, $content); return true; } /** * Get the default namespace for the class. * * @param string $rootNamespace * * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace; } protected function getClassName($name) { $names = array_slice(explode('\\', $name), -1, 1); $className = count($names) ? $names[0] : $name; return ucfirst($className); } /** * @param string $modelName * * @return \Doctrine\DBAL\Schema\Column[] */ protected function getFillableColumns($modelName) { $ret = []; $tableName = $this->getTableName($modelName); $fillableNames = []; $modelFullName = '\\App\\Models\\'.$modelName; $classExists = class_exists($modelFullName); $columns = $this->getTableColumns($tableName); if ($classExists) { /** @var \LaravelRocket\Foundation\Models\Base $modelObject */ $modelObject = new $modelFullName(); if (!empty($modelObject)) { $fillableNames = $modelObject->getFillableColumns(); } } else { if ($columns) { foreach ($columns as $column) { $columnName = $column->getName(); if (!in_array($columnName, ['id', 'created_at', 'updated_at', 'deleted_at'])) { $fillableNames[] = $columnName; } } } } if ($columns) { foreach ($columns as $column) { if ($column->getAutoincrement()) { continue; } $columnName = $column->getName(); if (in_array($columnName, $fillableNames)) { $ret[] = $column; } } } return $ret; } /** * @param string $modelName * * @return string */ protected function getTableName($modelName) { $modelName = $this->getModelName($modelName); $modelFullName = '\\App\\Models\\'.$modelName; $classExists = class_exists($modelFullName); if ($classExists) { return $modelFullName::getTableName(); } else { $name = \StringHelper::pluralize(\StringHelper::camel2Snake($modelName)); $columns = $this->getTableColumns($name); if (count($columns)) { return $name; } $name = \StringHelper::singularize(\StringHelper::camel2Snake($modelName)); $columns = $this->getTableColumns($name); if (count($columns)) { return $name; } return \StringHelper::pluralize(\StringHelper::camel2Snake($modelName)); } } /** * @param string $tableName * * @return \Doctrine\DBAL\Schema\Column[] */ protected function getTableColumns($tableName) { $hasDoctrine = interface_exists('Doctrine\DBAL\Driver'); if (!$hasDoctrine) { return []; } $platform = \DB::getDoctrineConnection()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('json', 'string'); $schema = \DB::getDoctrineSchemaManager(); $columns = $schema->listTableColumns($tableName); return $columns; } /** * @param \Doctrine\DBAL\Schema\Column[] $columns * * @return string[] */ protected function getColumnNames($columns) { $result = []; foreach ($columns as $column) { $result[] = $column->getName(); } return $result; } /** * @param string $path * * @return bool */ protected function alreadyExists($path) { return $this->files->exists($path); } /** * Build the directory for the class if necessary. * * @param string $path * * @return string */ protected function makeDirectory($path) { if (!$this->files->isDirectory(dirname($path))) { $this->files->makeDirectory(dirname($path), 0777, true, true); } return $path; } /** * @param string $class * * @return string */ protected function convertClassToPath($class) { return base_path(str_replace('\\', '/', str_replace('App', 'app', $class)).'.php'); } /** * @param string $string */ protected function error($string) { $this->errorString = $string; } /** * @param string $modelName * @param string $classPath * @param string $stubFilePath * @param array $additionalData * * @return bool */ protected function generateFile($modelName, $classPath, $stubFilePath, $additionalData = []) { if ($this->alreadyExists($classPath)) { if ($this->shouldOverwrite()) { $this->files->delete($classPath); } else { $this->error($classPath.' already exists.'); return false; } } $pathInfo = pathinfo($classPath); $className = $pathInfo['filename']; $this->makeDirectory($classPath); $defaultData = [ 'MODEL' => $modelName, 'model' => lcfirst($modelName), 'CLASS' => $className, 'class' => lcfirst($className), ]; $data = $additionalData; foreach ($defaultData as $key => $value) { if (!array_key_exists($key, $data)) { $data[$key] = $value; } } $content = $this->replace($data, $stubFilePath); if (empty($content)) { return false; } $this->files->put($classPath, $content); return true; } protected function getStubPath($path) { $stubFilePath = resource_path('stubs'.$path); if ($this->files->exists($stubFilePath)) { return $stubFilePath; } $stubFilePath = __DIR__.'/../../stubs'.$path; return $stubFilePath; } } <file_sep>/src/Generators/RepositoryGenerator.php <?php namespace LaravelRocket\Generator\Generators; class RepositoryGenerator extends Generator { public function generate($name, $overwrite = false, $baseDirectory = null) { $modelName = $this->getModelName($name); $this->generateRepository($modelName); $this->generateRepositoryInterface($modelName); $this->generateRepositoryUnitTest($modelName); $this->bindInterface($modelName); } /** * @param string $name * * @return string */ protected function getModelName($name) { $className = $this->getClassName($name); $modelName = str_replace('Repository', '', $className); return $modelName; } /** * @param string $name * * @return string */ protected function getModelClass($name) { $modelName = $this->getModelName($name); return '\\App\\Models\\'.$modelName; } protected function getRepositoryClass($name) { $modelName = $this->getModelName($name); return '\\App\\Repositories\\Eloquent\\'.$modelName.'Repository'; } /** * @param string $modelName * * @return bool */ protected function generateRepository($modelName) { $className = $this->getRepositoryClass($modelName); $classPath = $this->convertClassToPath($className); $modelClass = $this->getModelClass($modelName); $instance = new $modelClass(); $stubFilePath = $this->getStubPath('/repository/repository.stub'); if ($instance instanceof \LaravelRocket\Foundation\Models\AuthenticatableBase) { $stubFilePath = $this->getStubPath('/repository/repository.stub'); } return $this->generateFile($modelName, $classPath, $stubFilePath); } /** * @param string $modelName * * @return bool */ protected function generateRepositoryInterface($modelName) { $className = '\\App\\Repositories\\'.$modelName.'RepositoryInterface'; $classPath = $this->convertClassToPath($className); $modelClass = $this->getModelClass($modelName); $instance = new $modelClass(); $stubFilePath = $this->getStubPath('/repository/repository_interface.stub'); if ($instance instanceof \LaravelRocket\Foundation\Models\AuthenticatableBase) { $stubFilePath = $this->getStubPath('/repository/repository_interface.stub'); } return $this->generateFile($modelName, $classPath, $stubFilePath); } /** * @param string $modelName * * @return bool */ protected function generateRepositoryUnitTest($modelName) { $classPath = base_path('/tests/Repositories/'.$modelName.'RepositoryTest.php'); $modelClass = $this->getModelClass($modelName); $instance = new $modelClass(); $stubFilePath = $this->getStubPath('/repository/repository_unittest.stub'); if ($instance instanceof \LaravelRocket\Foundation\Models\AuthenticatableBase) { $stubFilePath = $this->getStubPath('/repository/repository_unittest.stub'); } return $this->generateFile($modelName, $classPath, $stubFilePath); } /** * @param string $name * * @return bool */ protected function bindInterface($name) { $bindingPath = base_path('/app/Providers/RepositoryServiceProvider.php'); $key = '/* NEW BINDING */'; $bind = '$this->app->singleton('.PHP_EOL.' \\App\\Repositories\\'.$name.'RepositoryInterface::class,' .PHP_EOL.' \\App\\Repositories\\Eloquent\\'.$name.'Repository::class'.PHP_EOL.' );' .PHP_EOL.PHP_EOL.' '; $this->replaceFile([ $key => $bind, ], $bindingPath); return true; } } <file_sep>/src/Generators/HelperGenerator.php <?php namespace LaravelRocket\Generator\Generators; class HelperGenerator extends Generator { public function generate($name, $overwrite = false, $baseDirectory = null) { $helperName = $this->getName($name); $this->generateHelper($helperName); $this->generateHelperInterface($helperName); $this->generateFacade($helperName); $this->generateHelperUnitTest($helperName); $this->bindInterface($helperName); $this->addFacadeToConfig($helperName); } /** * @param string $name * * @return string */ protected function getName($name) { $className = $this->getClassName($name); $rootName = str_replace('Helper', '', $className); return $rootName.'Helper'; } protected function getHelperClass($name) { $helperName = $this->getName($name); return '\\App\\Helpers\\Production\\'.$helperName; } /** * @param string $helperName * * @return bool */ protected function generateHelper($helperName) { $className = $this->getHelperClass($helperName); $classPath = $this->convertClassToPath($className); $stubFilePath = $this->getStubPath('/helper/helper.stub'); return $this->generateFile($className, $classPath, $stubFilePath); } /** * @param string $helperName * * @return bool */ protected function generateHelperInterface($helperName) { $className = '\\App\\Helpers\\'.$helperName.'Interface'; $classPath = $this->convertClassToPath($className); $stubFilePath = $this->getStubPath('/helper/helper_interface.stub'); return $this->generateFile($className, $classPath, $stubFilePath); } /** * @param string $helperName * * @return bool */ protected function generateFacade($helperName) { $className = '\\App\\Facades\\'.$helperName; $classPath = $this->convertClassToPath($className); $stubFilePath = $this->getStubPath('/helper/facade.stub'); return $this->generateFile($className, $classPath, $stubFilePath); } /** * @param string $helperName * * @return bool */ protected function generateHelperUnitTest($helperName) { $classPath = base_path('/tests/Helpers/'.$helperName.'Test.php'); $stubFilePath = $this->getStubPath('/helper/helper_unittest.stub'); return $this->generateFile($helperName, $classPath, $stubFilePath); } /** * @param string $helperName * * @return bool */ protected function bindInterface($helperName) { $bindingPath = base_path('/app/Providers/HelperServiceProvider.php'); $key = '/* NEW BINDING */'; $bind = '$this->app->singleton('.PHP_EOL.' \\App\\Helpers\\'.$helperName.'Interface::class,'.PHP_EOL.' \\App\\Helpers\\Production\\'.$helperName.'::class'.PHP_EOL.' );'.PHP_EOL.PHP_EOL.' '; $this->replaceFile([ $key => $bind, ], $bindingPath); return true; } protected function addFacadeToConfig($helperName) { $appConfigPath = base_path('/config/app.php'); $key = '/* NEW FACADE */'; $facade = "'".$helperName."' => \\App\\Facades\\".$helperName.'::class,'.PHP_EOL.' '; $this->replaceFile([ $key => $facade, ], $appConfigPath); return true; } } <file_sep>/src/Console/Commands/ServiceGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\ServiceGenerator; class ServiceGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:service'; protected $description = 'Create a new service class'; protected $generator = ServiceGenerator::class; } <file_sep>/src/Providers/ServiceProvider.php <?php namespace LaravelRocket\Generator\Providers; use Illuminate\Support\ServiceProvider as BaseServiceProvider; use LaravelRocket\Generator\Console\Commands\AdminCRUDGeneratorCommand; use LaravelRocket\Generator\Console\Commands\AlterMigrationGeneratorCommand; use LaravelRocket\Generator\Console\Commands\APIGeneratorCommand; use LaravelRocket\Generator\Console\Commands\CreateMigrationGeneratorCommand; use LaravelRocket\Generator\Console\Commands\HelperGeneratorCommand; use LaravelRocket\Generator\Console\Commands\ModelGeneratorCommand; use LaravelRocket\Generator\Console\Commands\RepositoryGeneratorCommand; use LaravelRocket\Generator\Console\Commands\ServiceGeneratorCommand; class ServiceProvider extends BaseServiceProvider { /** * Bootstrap any application services. */ public function boot() { } /** * Register any application services. */ public function register() { $this->app->singleton('command.rocket.make.repository', function ($app) { return new RepositoryGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->app->singleton('command.rocket.make.service', function ($app) { return new ServiceGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->app->singleton('command.rocket.model.make', function ($app) { return new ModelGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->app->singleton('command.rocket.make.helper', function ($app) { return new HelperGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->app->singleton('command.rocket.make.migration.create', function ($app) { return new CreateMigrationGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->app->singleton('command.rocket.make.migration.alter', function ($app) { return new AlterMigrationGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->app->singleton('command.rocket.make.admin.crud', function ($app) { return new AdminCRUDGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->app->singleton('command.rocket.make.api', function ($app) { return new APIGeneratorCommand($app['config'], $app['files'], $app['view']); }); $this->commands('command.rocket.make.repository', 'command.rocket.make.service', 'command.rocket.model.make', 'command.rocket.make.helper', 'command.rocket.make.migration.create', 'command.rocket.make.migration.alter', 'command.rocket.make.admin.crud', 'command.rocket.make.api'); } } <file_sep>/src/Console/Commands/HelperGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\HelperGenerator; class HelperGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:helper'; protected $description = 'Create a new helper class'; protected $generator = HelperGenerator::class; } <file_sep>/src/Console/Commands/CreateMigrationGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\CreateMigrationGenerator; class CreateMigrationGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:migration:create'; protected $description = 'Create a migration for create table'; protected $generator = CreateMigrationGenerator::class; } <file_sep>/src/Console/Commands/RepositoryGeneratorCommand.php <?php namespace LaravelRocket\Generator\Console\Commands; use LaravelRocket\Generator\Generators\RepositoryGenerator; class RepositoryGeneratorCommand extends GeneratorCommand { protected $name = 'rocket:make:repository'; protected $description = 'Create a new repository class'; protected $generator = RepositoryGenerator::class; } <file_sep>/src/Objects/Swagger/Definition.php <?php namespace LaravelRocket\Generator\Objects\Swagger; class Definition { /** * @var \Swagger\Object\Schema */ protected $definition; /** @var string $name */ protected $name; /** @var string $parent */ protected $parent; /** @var Property[] $properties */ protected $properties; public function __construct($name, $definition) { $this->data = $definition; $this->name = $name; $this->inherit = null; $this->properties = []; if (property_exists($this->data, 'allOf')) { foreach ($this->data->allOf as $value) { if (property_exists($value, '$ref')) { $parent = $value->{'$ref'}; if (preg_match('/\/(.+$)/', $parent, $matches)) { $this->parent = $matches[1]; } } } } } public function getName() { return $this->name; } /** * @return array */ public function getProperties() { if (count($this->properties)) { return $this->properties; } if (property_exists($this->data, 'allOf')) { foreach ($this->data->allOf as $value) { if (property_exists($value, 'properties')) { foreach ($value->properties as $name => $property) { $this->properties[] = new Property($name, $property); } } } } elseif (property_exists($this->data, 'properties')) { foreach ($this->data->properties as $name => $property) { $this->properties[] = new Property($name, $property); } } return $this->properties; } }
e7391c51a1a624349ae57cf6a4ce131446d568d9
[ "PHP" ]
23
PHP
Artrigger/generator
7b082014b5a0392546da370c84545a28d66bf192
db13c85aaf41863d693cd52395b27623ad268ab8
refs/heads/master
<repo_name>SaraPerezSoler/JavaCheck<file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/type/TypeFunction.java package es.uam.sara.tfg.properties.type; public interface TypeFunction extends Type{ } <file_sep>/Code/es.uam.sara.tfg.ast/src/es/uam/sara/tfg/ast/Visitors.java package es.uam.sara.tfg.ast; import java.util.ArrayList; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.TypeDeclaration; public class Visitors { private ArrayList<UnitVisitor> visitors=new ArrayList<UnitVisitor>(); public void addVisitor(UnitVisitor v){ visitors.add(v); } public ArrayList <TypeDeclaration> getClasses(){ ArrayList<TypeDeclaration> result=new ArrayList<TypeDeclaration>(); for (UnitVisitor u: visitors){ result.addAll(u.getClasses()); } return result; } public ArrayList<PackageDeclaration> getPackages() { ArrayList<PackageDeclaration> result=new ArrayList<PackageDeclaration>(); for (UnitVisitor u: visitors){ result.add(u.getPackages()); } return result; } public ArrayList<TypeDeclaration> getInterfaces() { ArrayList<TypeDeclaration> result=new ArrayList<TypeDeclaration>(); for (UnitVisitor u: visitors){ result.addAll(u.getInterfaces()); } return result; } public ArrayList<EnumDeclaration> getEnumerations() { ArrayList<EnumDeclaration> result=new ArrayList<EnumDeclaration>(); for (UnitVisitor u: visitors){ result.addAll(u.getEnumerations()); } return result; } public ArrayList<MethodDeclaration> getMethods() { ArrayList<MethodDeclaration> result=new ArrayList<MethodDeclaration>(); for (UnitVisitor u: visitors){ result.addAll(u.getMethods()); } return result; } public ArrayList<FieldDeclaration> getAttributes() { ArrayList<FieldDeclaration> result=new ArrayList<FieldDeclaration>(); for (UnitVisitor u: visitors){ result.addAll(u.getAttributes()); } return result; } public ArrayList<TypeDeclaration> classForPackage (String packageName){ ArrayList<TypeDeclaration> result=new ArrayList<TypeDeclaration>(); for (UnitVisitor u: visitors){ if (packageName.compareTo(u.getPackages().getName().toString())==0){ result.addAll(u.getClasses()); } } return result; } public ArrayList<TypeDeclaration> interfacesForPackage (String packageName){ ArrayList<TypeDeclaration> result=new ArrayList<TypeDeclaration>(); for (UnitVisitor u: visitors){ if (packageName.compareTo(u.getPackages().getName().toString())==0){ result.addAll(u.getInterfaces()); } } return result; } public ArrayList<EnumDeclaration> enumForPackage (String packageName){ ArrayList<EnumDeclaration> result=new ArrayList<EnumDeclaration>(); for (UnitVisitor u: visitors){ if (packageName.compareTo(u.getPackages().getName().toString())==0){ result.addAll(u.getEnumerations()); } } return result; } public ArrayList<MethodDeclaration> methodForClass (TypeDeclaration clas){ ArrayList<MethodDeclaration> result=new ArrayList<MethodDeclaration>(); for (MethodDeclaration m: clas.getMethods()){ result.add(m); } return result; } public ArrayList<FieldDeclaration> attributesForClass (TypeDeclaration clas){ ArrayList<FieldDeclaration> result=new ArrayList<FieldDeclaration>(); for (FieldDeclaration a: clas.getFields()){ result.add(a); } return result; } public ArrayList<MethodDeclaration> methodForInterface (TypeDeclaration inter){ ArrayList<MethodDeclaration> result=new ArrayList<MethodDeclaration>(); for (MethodDeclaration m: inter.getMethods()){ result.add(m); } return result; } public ArrayList<FieldDeclaration> attributesForInterface (TypeDeclaration inter){ ArrayList<FieldDeclaration> result=new ArrayList<FieldDeclaration>(); for (FieldDeclaration a: inter.getFields()){ result.add(a); } return result; } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/File.java /** */ package javaRule; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>File</b></em>'. * <!-- end-user-doc --> * * * @see javaRule.JavaRulePackage#getFile() * @model abstract="true" * @generated */ public interface File extends Property { } // File <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/InitializeImpl.java /** */ package javaRule.impl; import javaRule.Initialize; import javaRule.JavaRulePackage; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Initialize</b></em>'. * <!-- end-user-doc --> * * @generated */ public class InitializeImpl extends AttributeImpl implements Initialize { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected InitializeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.INITIALIZE; } } //InitializeImpl <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/Checkeable.java package es.uam.sara.tfg.properties; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import es.uam.sara.tfg.elements.IElements; import es.uam.sara.tfg.sentence.RuleSave; public abstract class Checkeable<T extends IElements> { private List<T> right; private List<T> wrong; protected boolean no; protected Map<String, IElements> using; public Checkeable(boolean no) { this.no = no; this.right = new ArrayList<T>(); this.wrong = new ArrayList<T>(); } public List<T> getRight() { return right; } public List<T> getWrong() { return wrong; } public void addRight(T t) { if (!this.right.contains(t)) { this.right.add(t); } if (this.wrong.contains(t)) { this.wrong.remove(t); } } public void addWrong(T t) { if (!this.wrong.contains(t) && !this.right.contains(t)) { this.wrong.add(t); } } public void reset() { this.right.clear(); this.wrong.clear(); } public void removeAllRight(Collection<T> c) { for (T c1 : c) { this.right.remove(c1); } } public void addAllRight(Collection<T> c) { for (T c1 : c) { if (!this.right.contains(c1)) { this.right.add(c1); } } } public void addLastWrong(T a) { if( right.contains(a)){ right.remove(a); } if (!wrong.contains(a)){ wrong.add(a); } } public void removeAllWrong(Collection<T> c) { for (T c1 : c) { this.wrong.remove(c1); } } public void addAllWrong(Collection<T> c) { for (T c1 : c) { if (!right.contains(c1) && !wrong.contains(c1)) { wrong.add(c1); } } } public boolean isNoProperty() { return false; } public void check(List<T> analyze) { for (T t : analyze) { if (no) { if (!checkElement(t)) { addRight(t); } else { addWrong(t); } } else { if (checkElement(t)) { addRight(t); } else { addWrong(t); } } } } public abstract boolean checkElement(T analyze); public String print(boolean right) { List<T> print; String cad; if (right) { cad = "\nThis elements satisfy " + this.toString() + ":\n\n"; print = this.getRight(); } else { cad = "\nThis elements not satisfy " + this.toString() + ":\n\n"; print = this.getWrong(); } for (T t : print) { cad += print(t); } return cad; } public String print(T t) { return t.toString(); } public boolean needVariables() { return false; } public void setUsing(Map<String, IElements> using) { this.using = using; } public abstract String toString(); public boolean isChangeForContains() { return false; } @SuppressWarnings("unchecked") public void reset(RuleSave<T> rs, int i){ this.right=(List<T>) ((ArrayList<T>)rs.getRight(i)).clone(); this.wrong=(List<T>) ((ArrayList<T>)rs.getWrong(i)).clone(); } public int getChildren(){ return 1; } public void save(RuleSave<T> rs, int i){ rs.save(i, getRight(), getWrong()); } }<file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/all/IsSuper.java /** * */ package es.uam.sara.tfg.properties.all; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import es.uam.sara.tfg.elements.ClassInterface; import es.uam.sara.tfg.elements.JavaTypes; import es.uam.sara.tfg.properties.StringProperty; import es.uam.sara.tfg.properties.type.TypeString; /** * @author Sara * */ public abstract class IsSuper<T extends ClassInterface> extends StringProperty<T> { private Map<ClassInterface, List<JavaTypes>> classesExtended; private int intMin; private int intMax; private List<TypeString> nameSubContantes = null; private List<TypeString> nameSubVariable = null; /* * a -> b :a toma el valor analyze, b toma el valor all * class->class :a is superClass of b * inter->class/enum :a is implemented for b inter->inter :a is * superInterface of b class->enum :XXXXXXX no es posible */ private boolean aIsInterface; private boolean bIsInterface; public IsSuper(boolean no,int min, int max, List<TypeString> subClass) { super(no); this.intMax = min; this.intMax = max; nameSubContantes = new ArrayList<TypeString>(); nameSubVariable = new ArrayList<TypeString>(); for (TypeString t: subClass){ if (t.isVariable()){ nameSubVariable.add(t); }else{ nameSubContantes.add(t); } } classesExtended = new HashMap<ClassInterface, List<JavaTypes>>(); } /* * (non-Javadoc) * * @see es.uam.sara.tfg.properties.Properties#check() */ @Override public boolean checkElement(T td) { List<JavaTypes> sub = getSub(td); List<String> names=JavaTypes.getNames(sub); List<TypeString> nameSub= new ArrayList<TypeString>(); nameSub.addAll(nameSubContantes); nameSub.addAll(nameSubVariable); classesExtended.put(td, sub); if (sub.size() >= this.intMin && sub.size() <= this.intMax) { for (TypeString s : nameSub) { if (!s.isTypeIn(names)) { return false; } } return true; } return false; } public String print(T t) { List<JavaTypes> subClass=classesExtended.get(t); String cad= "is super of:\n"; if (subClass.isEmpty()){ cad=""; } for (JavaTypes jt: subClass){ cad+="\t"+jt.toString()+"\n"; } return t.toString()+ cad; } public void setString(String string, int i){ nameSubVariable.get(i).setString(string); } public void deleteString(String string, int i){ nameSubVariable.get(i).deleteString(string); } public abstract List<JavaTypes> getSub(T td); @Override public String toString() { String cad; if (no){ cad="is not "; }else{ cad="is "; } if (aIsInterface == false && bIsInterface == false) { cad += "superclass "; } else if (aIsInterface && bIsInterface == false) { cad += "implemented "; } else { cad += "superinterface "; } if (this.intMin != -1) { if (this.intMax == Integer.MAX_VALUE) { cad += "[" + intMin + "..*]"; } else { cad += "[" + intMin + ".." + intMax + "]"; } } List<TypeString> nameSub= new ArrayList<TypeString>(); nameSub.addAll(nameSubContantes); nameSub.addAll(nameSubVariable); if (!nameSub.isEmpty()) { cad += "{"; for (TypeString s : nameSub) { cad += s + " "; } cad += "}"; } return cad; } public void setaIsInterface(boolean aIsInterface) { this.aIsInterface = aIsInterface; } public void setbIsInterface(boolean bIsInterface) { this.bIsInterface = bIsInterface; } } <file_sep>/Code/es.uam.sara.tfg.dsl.ide/src-gen/es/uam/sara/tfg/dsl/ide/contentassist/antlr/JRulesParser.java /* * generated by Xtext 2.10.0 */ package es.uam.sara.tfg.dsl.ide.contentassist.antlr; import com.google.inject.Inject; import es.uam.sara.tfg.dsl.ide.contentassist.antlr.internal.InternalJRulesParser; import es.uam.sara.tfg.dsl.services.JRulesGrammarAccess; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.antlr.runtime.RecognitionException; import org.eclipse.xtext.AbstractElement; import org.eclipse.xtext.ide.editor.contentassist.antlr.AbstractContentAssistParser; import org.eclipse.xtext.ide.editor.contentassist.antlr.FollowElement; import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser; public class JRulesParser extends AbstractContentAssistParser { @Inject private JRulesGrammarAccess grammarAccess; private Map<AbstractElement, String> nameMappings; @Override protected InternalJRulesParser createParser() { InternalJRulesParser result = new InternalJRulesParser(null); result.setGrammarAccess(grammarAccess); return result; } @Override protected String getRuleName(AbstractElement element) { if (nameMappings == null) { nameMappings = new HashMap<AbstractElement, String>() { private static final long serialVersionUID = 1L; { put(grammarAccess.getRuleSetAccess().getAlternatives_2(), "rule__RuleSet__Alternatives_2"); put(grammarAccess.getSentenceAccess().getAlternatives_0(), "rule__Sentence__Alternatives_0"); put(grammarAccess.getPrimaryOpAccess().getAlternatives(), "rule__PrimaryOp__Alternatives"); put(grammarAccess.getPropertyAccess().getAlternatives(), "rule__Property__Alternatives"); put(grammarAccess.getIsImplementedAccess().getAlternatives_0(), "rule__IsImplemented__Alternatives_0"); put(grammarAccess.getIsSuperInterfaceAccess().getAlternatives_0(), "rule__IsSuperInterface__Alternatives_0"); put(grammarAccess.getIsSuperClassAccess().getAlternatives_0(), "rule__IsSuperClass__Alternatives_0"); put(grammarAccess.getIsSubClassAccess().getAlternatives_1(), "rule__IsSubClass__Alternatives_1"); put(grammarAccess.getImplementsAccess().getAlternatives_0(), "rule__Implements__Alternatives_0"); put(grammarAccess.getExtendsAccess().getAlternatives_0(), "rule__Extends__Alternatives_0"); put(grammarAccess.getTamanioAccess().getAlternatives_1(), "rule__Tamanio__Alternatives_1"); put(grammarAccess.getTamanioAccess().getAlternatives_1_0_0(), "rule__Tamanio__Alternatives_1_0_0"); put(grammarAccess.getTamanioAccess().getAlternatives_1_1_3(), "rule__Tamanio__Alternatives_1_1_3"); put(grammarAccess.getParameterAccess().getAlternatives_2(), "rule__Parameter__Alternatives_2"); put(grammarAccess.getParameterAccess().getAlternatives_2_0_1_0(), "rule__Parameter__Alternatives_2_0_1_0"); put(grammarAccess.getParameterAccess().getAlternatives_2_1_3(), "rule__Parameter__Alternatives_2_1_3"); put(grammarAccess.getConstructorAccess().getAlternatives_1(), "rule__Constructor__Alternatives_1"); put(grammarAccess.getReturnAccess().getAlternatives_2(), "rule__Return__Alternatives_2"); put(grammarAccess.getAttributeTypeAccess().getAlternatives_1(), "rule__AttributeType__Alternatives_1"); put(grammarAccess.getInitializeAccess().getAlternatives_1(), "rule__Initialize__Alternatives_1"); put(grammarAccess.getEmptyAccess().getAlternatives_1(), "rule__Empty__Alternatives_1"); put(grammarAccess.getIsGenericAccess().getAlternatives_1(), "rule__IsGeneric__Alternatives_1"); put(grammarAccess.getNameOperationAccess().getAlternatives_1(), "rule__NameOperation__Alternatives_1"); put(grammarAccess.getNameOperationAccess().getAlternatives_1_1(), "rule__NameOperation__Alternatives_1_1"); put(grammarAccess.getNameTypeAccess().getAlternatives_2(), "rule__NameType__Alternatives_2"); put(grammarAccess.getContainsAccess().getAlternatives_1(), "rule__Contains__Alternatives_1"); put(grammarAccess.getContainsAccess().getAlternatives_1_0_0(), "rule__Contains__Alternatives_1_0_0"); put(grammarAccess.getModifiersAccess().getAlternatives_0(), "rule__Modifiers__Alternatives_0"); put(grammarAccess.getEBooleanAccess().getAlternatives(), "rule__EBoolean__Alternatives"); put(grammarAccess.getRangoNamesAccess().getAlternatives_1_3(), "rule__RangoNames__Alternatives_1_3"); put(grammarAccess.getStringPropertyAccess().getAlternatives(), "rule__StringProperty__Alternatives"); put(grammarAccess.getTypePropertyAccess().getAlternatives(), "rule__TypeProperty__Alternatives"); put(grammarAccess.getIsCollectionTypeAccess().getAlternatives_2(), "rule__IsCollectionType__Alternatives_2"); put(grammarAccess.getBlendModifiersAccess().getAlternatives(), "rule__BlendModifiers__Alternatives"); put(grammarAccess.getEStringAccess().getAlternatives(), "rule__EString__Alternatives"); put(grammarAccess.getElementAccess().getAlternatives(), "rule__Element__Alternatives"); put(grammarAccess.getPrimitiveAccess().getAlternatives(), "rule__Primitive__Alternatives"); put(grammarAccess.getNameOperatorAccess().getAlternatives(), "rule__NameOperator__Alternatives"); put(grammarAccess.getElementStringAccess().getAlternatives(), "rule__ElementString__Alternatives"); put(grammarAccess.getLanguageAccess().getAlternatives(), "rule__Language__Alternatives"); put(grammarAccess.getNameCheckAccess().getAlternatives(), "rule__NameCheck__Alternatives"); put(grammarAccess.getAccessModifierAccess().getAlternatives(), "rule__AccessModifier__Alternatives"); put(grammarAccess.getQuantifierAccess().getAlternatives(), "rule__Quantifier__Alternatives"); put(grammarAccess.getRuleSetAccess().getGroup(), "rule__RuleSet__Group__0"); put(grammarAccess.getRuleSetAccess().getGroup_2_0(), "rule__RuleSet__Group_2_0__0"); put(grammarAccess.getRuleSetAccess().getGroup_2_0_1(), "rule__RuleSet__Group_2_0_1__0"); put(grammarAccess.getSentenceAccess().getGroup(), "rule__Sentence__Group__0"); put(grammarAccess.getVariableAccess().getGroup(), "rule__Variable__Group__0"); put(grammarAccess.getVariableAccess().getGroup_3(), "rule__Variable__Group_3__0"); put(grammarAccess.getVariableAccess().getGroup_4(), "rule__Variable__Group_4__0"); put(grammarAccess.getVariableAccess().getGroup_4_2(), "rule__Variable__Group_4_2__0"); put(grammarAccess.getVariableAccess().getGroup_5(), "rule__Variable__Group_5__0"); put(grammarAccess.getVariableAccess().getGroup_5_2(), "rule__Variable__Group_5_2__0"); put(grammarAccess.getVariableAccess().getGroup_6(), "rule__Variable__Group_6__0"); put(grammarAccess.getRuleAccess().getGroup(), "rule__Rule__Group__0"); put(grammarAccess.getRuleAccess().getGroup_3(), "rule__Rule__Group_3__0"); put(grammarAccess.getRuleAccess().getGroup_4(), "rule__Rule__Group_4__0"); put(grammarAccess.getRuleAccess().getGroup_4_2(), "rule__Rule__Group_4_2__0"); put(grammarAccess.getRuleAccess().getGroup_5(), "rule__Rule__Group_5__0"); put(grammarAccess.getRuleAccess().getGroup_5_2(), "rule__Rule__Group_5_2__0"); put(grammarAccess.getRuleAccess().getGroup_6(), "rule__Rule__Group_6__0"); put(grammarAccess.getRuleAccess().getGroup_7(), "rule__Rule__Group_7__0"); put(grammarAccess.getOrAccess().getGroup(), "rule__Or__Group__0"); put(grammarAccess.getOrAccess().getGroup_1(), "rule__Or__Group_1__0"); put(grammarAccess.getAndAccess().getGroup(), "rule__And__Group__0"); put(grammarAccess.getAndAccess().getGroup_1(), "rule__And__Group_1__0"); put(grammarAccess.getPrimaryOpAccess().getGroup_0(), "rule__PrimaryOp__Group_0__0"); put(grammarAccess.getIsImplementedAccess().getGroup(), "rule__IsImplemented__Group__0"); put(grammarAccess.getIsSuperInterfaceAccess().getGroup(), "rule__IsSuperInterface__Group__0"); put(grammarAccess.getIsSuperClassAccess().getGroup(), "rule__IsSuperClass__Group__0"); put(grammarAccess.getIsSubClassAccess().getGroup(), "rule__IsSubClass__Group__0"); put(grammarAccess.getIsSubClassAccess().getGroup_4(), "rule__IsSubClass__Group_4__0"); put(grammarAccess.getImplementsAccess().getGroup(), "rule__Implements__Group__0"); put(grammarAccess.getImplementsAccess().getGroup_0_0(), "rule__Implements__Group_0_0__0"); put(grammarAccess.getImplementsAccess().getGroup_0_2(), "rule__Implements__Group_0_2__0"); put(grammarAccess.getExtendsAccess().getGroup(), "rule__Extends__Group__0"); put(grammarAccess.getExtendsAccess().getGroup_0_0(), "rule__Extends__Group_0_0__0"); put(grammarAccess.getExtendsAccess().getGroup_0_2(), "rule__Extends__Group_0_2__0"); put(grammarAccess.getTamanioAccess().getGroup(), "rule__Tamanio__Group__0"); put(grammarAccess.getTamanioAccess().getGroup_1_0(), "rule__Tamanio__Group_1_0__0"); put(grammarAccess.getTamanioAccess().getGroup_1_1(), "rule__Tamanio__Group_1_1__0"); put(grammarAccess.getParameterAccess().getGroup(), "rule__Parameter__Group__0"); put(grammarAccess.getParameterAccess().getGroup_2_0(), "rule__Parameter__Group_2_0__0"); put(grammarAccess.getParameterAccess().getGroup_2_0_1(), "rule__Parameter__Group_2_0_1__0"); put(grammarAccess.getParameterAccess().getGroup_2_1(), "rule__Parameter__Group_2_1__0"); put(grammarAccess.getParameterAccess().getGroup_3(), "rule__Parameter__Group_3__0"); put(grammarAccess.getParameterAccess().getGroup_3_4(), "rule__Parameter__Group_3_4__0"); put(grammarAccess.getConstructorAccess().getGroup(), "rule__Constructor__Group__0"); put(grammarAccess.getReturnAccess().getGroup(), "rule__Return__Group__0"); put(grammarAccess.getAttributeTypeAccess().getGroup(), "rule__AttributeType__Group__0"); put(grammarAccess.getInitializeAccess().getGroup(), "rule__Initialize__Group__0"); put(grammarAccess.getEmptyAccess().getGroup(), "rule__Empty__Group__0"); put(grammarAccess.getIsGenericAccess().getGroup(), "rule__IsGeneric__Group__0"); put(grammarAccess.getNameOperationAccess().getGroup(), "rule__NameOperation__Group__0"); put(grammarAccess.getNameOperationAccess().getGroup_1_0(), "rule__NameOperation__Group_1_0__0"); put(grammarAccess.getNameOperationAccess().getGroup_1_0_0(), "rule__NameOperation__Group_1_0_0__0"); put(grammarAccess.getNameOperationAccess().getGroup_3(), "rule__NameOperation__Group_3__0"); put(grammarAccess.getNameTypeAccess().getGroup(), "rule__NameType__Group__0"); put(grammarAccess.getJavaDocAccess().getGroup(), "rule__JavaDoc__Group__0"); put(grammarAccess.getContainsAccess().getGroup(), "rule__Contains__Group__0"); put(grammarAccess.getContainsAccess().getGroup_1_0(), "rule__Contains__Group_1_0__0"); put(grammarAccess.getContainsAccess().getGroup_1_0_0_0(), "rule__Contains__Group_1_0_0_0__0"); put(grammarAccess.getContainsAccess().getGroup_1_0_0_2(), "rule__Contains__Group_1_0_0_2__0"); put(grammarAccess.getModifiersAccess().getGroup(), "rule__Modifiers__Group__0"); put(grammarAccess.getModifiersAccess().getGroup_6(), "rule__Modifiers__Group_6__0"); put(grammarAccess.getRangoNamesAccess().getGroup(), "rule__RangoNames__Group__0"); put(grammarAccess.getRangoNamesAccess().getGroup_1(), "rule__RangoNames__Group_1__0"); put(grammarAccess.getRangoNamesAccess().getGroup_2(), "rule__RangoNames__Group_2__0"); put(grammarAccess.getRangoNamesAccess().getGroup_2_3(), "rule__RangoNames__Group_2_3__0"); put(grammarAccess.getStringVariableAccess().getGroup(), "rule__StringVariable__Group__0"); put(grammarAccess.getVariableSubtypeAccess().getGroup(), "rule__VariableSubtype__Group__0"); put(grammarAccess.getVariableSubtypeAccess().getGroup_1(), "rule__VariableSubtype__Group_1__0"); put(grammarAccess.getTypePrimitiveAccess().getGroup(), "rule__TypePrimitive__Group__0"); put(grammarAccess.getIsPrimitiveFunctionAccess().getGroup(), "rule__IsPrimitiveFunction__Group__0"); put(grammarAccess.getIsCollectionTypeAccess().getGroup(), "rule__IsCollectionType__Group__0"); put(grammarAccess.getIsCollectionTypeAccess().getGroup_2_1(), "rule__IsCollectionType__Group_2_1__0"); put(grammarAccess.getEIntAccess().getGroup(), "rule__EInt__Group__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_0(), "rule__BlendModifiers__Group_0__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_0_1(), "rule__BlendModifiers__Group_0_1__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_0_2(), "rule__BlendModifiers__Group_0_2__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_0_3(), "rule__BlendModifiers__Group_0_3__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_0_4(), "rule__BlendModifiers__Group_0_4__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_0_5(), "rule__BlendModifiers__Group_0_5__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_1(), "rule__BlendModifiers__Group_1__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_1_1(), "rule__BlendModifiers__Group_1_1__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_1_2(), "rule__BlendModifiers__Group_1_2__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_1_3(), "rule__BlendModifiers__Group_1_3__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_1_4(), "rule__BlendModifiers__Group_1_4__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_2(), "rule__BlendModifiers__Group_2__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_2_1(), "rule__BlendModifiers__Group_2_1__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_2_2(), "rule__BlendModifiers__Group_2_2__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_2_3(), "rule__BlendModifiers__Group_2_3__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_3(), "rule__BlendModifiers__Group_3__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_3_1(), "rule__BlendModifiers__Group_3_1__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_3_2(), "rule__BlendModifiers__Group_3_2__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_4(), "rule__BlendModifiers__Group_4__0"); put(grammarAccess.getBlendModifiersAccess().getGroup_4_1(), "rule__BlendModifiers__Group_4_1__0"); put(grammarAccess.getRuleSetAccess().getProjectNameAssignment_2_0_0(), "rule__RuleSet__ProjectNameAssignment_2_0_0"); put(grammarAccess.getRuleSetAccess().getProjectNameAssignment_2_0_1_1(), "rule__RuleSet__ProjectNameAssignment_2_0_1_1"); put(grammarAccess.getRuleSetAccess().getSentencesAssignment_3(), "rule__RuleSet__SentencesAssignment_3"); put(grammarAccess.getRuleSetAccess().getSentencesAssignment_4(), "rule__RuleSet__SentencesAssignment_4"); put(grammarAccess.getVariableAccess().getNameAssignment_0(), "rule__Variable__NameAssignment_0"); put(grammarAccess.getVariableAccess().getElementAssignment_2(), "rule__Variable__ElementAssignment_2"); put(grammarAccess.getVariableAccess().getFromAssignment_3_1(), "rule__Variable__FromAssignment_3_1"); put(grammarAccess.getVariableAccess().getInAssignment_4_1(), "rule__Variable__InAssignment_4_1"); put(grammarAccess.getVariableAccess().getInAssignment_4_2_1(), "rule__Variable__InAssignment_4_2_1"); put(grammarAccess.getVariableAccess().getUsingAssignment_5_1(), "rule__Variable__UsingAssignment_5_1"); put(grammarAccess.getVariableAccess().getUsingAssignment_5_2_1(), "rule__Variable__UsingAssignment_5_2_1"); put(grammarAccess.getVariableAccess().getSatisfyAssignment_6_1(), "rule__Variable__SatisfyAssignment_6_1"); put(grammarAccess.getRuleAccess().getNoAssignment_0(), "rule__Rule__NoAssignment_0"); put(grammarAccess.getRuleAccess().getQuantifierAssignment_1(), "rule__Rule__QuantifierAssignment_1"); put(grammarAccess.getRuleAccess().getElementAssignment_2(), "rule__Rule__ElementAssignment_2"); put(grammarAccess.getRuleAccess().getFromAssignment_3_1(), "rule__Rule__FromAssignment_3_1"); put(grammarAccess.getRuleAccess().getInAssignment_4_1(), "rule__Rule__InAssignment_4_1"); put(grammarAccess.getRuleAccess().getInAssignment_4_2_1(), "rule__Rule__InAssignment_4_2_1"); put(grammarAccess.getRuleAccess().getUsingAssignment_5_1(), "rule__Rule__UsingAssignment_5_1"); put(grammarAccess.getRuleAccess().getUsingAssignment_5_2_1(), "rule__Rule__UsingAssignment_5_2_1"); put(grammarAccess.getRuleAccess().getFilterAssignment_6_1(), "rule__Rule__FilterAssignment_6_1"); put(grammarAccess.getRuleAccess().getSatisfyAssignment_7_1(), "rule__Rule__SatisfyAssignment_7_1"); put(grammarAccess.getOrAccess().getOpAssignment_0(), "rule__Or__OpAssignment_0"); put(grammarAccess.getOrAccess().getOpAssignment_1_1(), "rule__Or__OpAssignment_1_1"); put(grammarAccess.getAndAccess().getOpAssignment_0(), "rule__And__OpAssignment_0"); put(grammarAccess.getAndAccess().getOpAssignment_1_1(), "rule__And__OpAssignment_1_1"); put(grammarAccess.getPropertyLiteralAccess().getPropertyAssignment(), "rule__PropertyLiteral__PropertyAssignment"); put(grammarAccess.getIsImplementedAccess().getNoAssignment_1(), "rule__IsImplemented__NoAssignment_1"); put(grammarAccess.getIsImplementedAccess().getValoresAssignment_3(), "rule__IsImplemented__ValoresAssignment_3"); put(grammarAccess.getIsSuperInterfaceAccess().getNoAssignment_1(), "rule__IsSuperInterface__NoAssignment_1"); put(grammarAccess.getIsSuperInterfaceAccess().getValoresAssignment_3(), "rule__IsSuperInterface__ValoresAssignment_3"); put(grammarAccess.getIsSuperClassAccess().getNoAssignment_1(), "rule__IsSuperClass__NoAssignment_1"); put(grammarAccess.getIsSuperClassAccess().getValoresAssignment_3(), "rule__IsSuperClass__ValoresAssignment_3"); put(grammarAccess.getIsSubClassAccess().getNoAssignment_2(), "rule__IsSubClass__NoAssignment_2"); put(grammarAccess.getIsSubClassAccess().getOfAssignment_4_1(), "rule__IsSubClass__OfAssignment_4_1"); put(grammarAccess.getImplementsAccess().getNoAssignment_0_0_0(), "rule__Implements__NoAssignment_0_0_0"); put(grammarAccess.getImplementsAccess().getNoAssignment_0_1(), "rule__Implements__NoAssignment_0_1"); put(grammarAccess.getImplementsAccess().getNoAssignment_0_2_0(), "rule__Implements__NoAssignment_0_2_0"); put(grammarAccess.getImplementsAccess().getNoAssignment_0_3(), "rule__Implements__NoAssignment_0_3"); put(grammarAccess.getImplementsAccess().getValoresAssignment_2(), "rule__Implements__ValoresAssignment_2"); put(grammarAccess.getExtendsAccess().getNoAssignment_0_0_0(), "rule__Extends__NoAssignment_0_0_0"); put(grammarAccess.getExtendsAccess().getNoAssignment_0_1(), "rule__Extends__NoAssignment_0_1"); put(grammarAccess.getExtendsAccess().getNoAssignment_0_2_0(), "rule__Extends__NoAssignment_0_2_0"); put(grammarAccess.getExtendsAccess().getNoAssignment_0_3(), "rule__Extends__NoAssignment_0_3"); put(grammarAccess.getExtendsAccess().getValoresAssignment_2(), "rule__Extends__ValoresAssignment_2"); put(grammarAccess.getTamanioAccess().getNoAssignment_1_0_0_1(), "rule__Tamanio__NoAssignment_1_0_0_1"); put(grammarAccess.getTamanioAccess().getExactAssignment_1_0_1(), "rule__Tamanio__ExactAssignment_1_0_1"); put(grammarAccess.getTamanioAccess().getMinAssignment_1_1_1(), "rule__Tamanio__MinAssignment_1_1_1"); put(grammarAccess.getTamanioAccess().getMaxAssignment_1_1_3_0(), "rule__Tamanio__MaxAssignment_1_1_3_0"); put(grammarAccess.getParameterAccess().getNoAssignment_2_0_1_0_1(), "rule__Parameter__NoAssignment_2_0_1_0_1"); put(grammarAccess.getParameterAccess().getExactAssignment_2_0_1_1(), "rule__Parameter__ExactAssignment_2_0_1_1"); put(grammarAccess.getParameterAccess().getMinAssignment_2_1_1(), "rule__Parameter__MinAssignment_2_1_1"); put(grammarAccess.getParameterAccess().getMaxAssignment_2_1_3_0(), "rule__Parameter__MaxAssignment_2_1_3_0"); put(grammarAccess.getParameterAccess().getTypesAssignment_3_3(), "rule__Parameter__TypesAssignment_3_3"); put(grammarAccess.getParameterAccess().getTypesAssignment_3_4_1(), "rule__Parameter__TypesAssignment_3_4_1"); put(grammarAccess.getConstructorAccess().getNoAssignment_2(), "rule__Constructor__NoAssignment_2"); put(grammarAccess.getReturnAccess().getNoAssignment_2_1(), "rule__Return__NoAssignment_2_1"); put(grammarAccess.getReturnAccess().getTypeAssignment_3(), "rule__Return__TypeAssignment_3"); put(grammarAccess.getAttributeTypeAccess().getNoAssignment_1_1(), "rule__AttributeType__NoAssignment_1_1"); put(grammarAccess.getAttributeTypeAccess().getTypeAssignment_2(), "rule__AttributeType__TypeAssignment_2"); put(grammarAccess.getInitializeAccess().getNoAssignment_2(), "rule__Initialize__NoAssignment_2"); put(grammarAccess.getEmptyAccess().getNoAssignment_2(), "rule__Empty__NoAssignment_2"); put(grammarAccess.getIsGenericAccess().getNoAssignment_2(), "rule__IsGeneric__NoAssignment_2"); put(grammarAccess.getNameOperationAccess().getNoAssignment_1_0_0_0(), "rule__NameOperation__NoAssignment_1_0_0_0"); put(grammarAccess.getNameOperationAccess().getOperatorAssignment_1_0_1(), "rule__NameOperation__OperatorAssignment_1_0_1"); put(grammarAccess.getNameOperationAccess().getNoAssignment_1_1_1(), "rule__NameOperation__NoAssignment_1_1_1"); put(grammarAccess.getNameOperationAccess().getNameAssignment_2(), "rule__NameOperation__NameAssignment_2"); put(grammarAccess.getNameOperationAccess().getLanguageAssignment_3_1(), "rule__NameOperation__LanguageAssignment_3_1"); put(grammarAccess.getNameTypeAccess().getNoAssignment_2_1(), "rule__NameType__NoAssignment_2_1"); put(grammarAccess.getNameTypeAccess().getTypeAssignment_3(), "rule__NameType__TypeAssignment_3"); put(grammarAccess.getJavaDocAccess().getNoAssignment_1(), "rule__JavaDoc__NoAssignment_1"); put(grammarAccess.getJavaDocAccess().getAuthorAssignment_3(), "rule__JavaDoc__AuthorAssignment_3"); put(grammarAccess.getJavaDocAccess().getParameterAssignment_4(), "rule__JavaDoc__ParameterAssignment_4"); put(grammarAccess.getJavaDocAccess().getReturnAssignment_5(), "rule__JavaDoc__ReturnAssignment_5"); put(grammarAccess.getJavaDocAccess().getVersionAssignment_6(), "rule__JavaDoc__VersionAssignment_6"); put(grammarAccess.getJavaDocAccess().getThrowsAssignment_7(), "rule__JavaDoc__ThrowsAssignment_7"); put(grammarAccess.getJavaDocAccess().getSeeAssignment_8(), "rule__JavaDoc__SeeAssignment_8"); put(grammarAccess.getContainsAccess().getNoAssignment_1_0_0_0_0(), "rule__Contains__NoAssignment_1_0_0_0_0"); put(grammarAccess.getContainsAccess().getNoAssignment_1_0_0_1(), "rule__Contains__NoAssignment_1_0_0_1"); put(grammarAccess.getContainsAccess().getNoAssignment_1_0_0_2_0(), "rule__Contains__NoAssignment_1_0_0_2_0"); put(grammarAccess.getContainsAccess().getNoAssignment_1_0_0_3(), "rule__Contains__NoAssignment_1_0_0_3"); put(grammarAccess.getContainsAccess().getNoAssignment_1_1(), "rule__Contains__NoAssignment_1_1"); put(grammarAccess.getContainsAccess().getRuleAssignment_3(), "rule__Contains__RuleAssignment_3"); put(grammarAccess.getModifiersAccess().getNoAssignment_1(), "rule__Modifiers__NoAssignment_1"); put(grammarAccess.getModifiersAccess().getBlendAssignment_5(), "rule__Modifiers__BlendAssignment_5"); put(grammarAccess.getModifiersAccess().getBlendAssignment_6_1(), "rule__Modifiers__BlendAssignment_6_1"); put(grammarAccess.getRangoNamesAccess().getMinAssignment_1_1(), "rule__RangoNames__MinAssignment_1_1"); put(grammarAccess.getRangoNamesAccess().getMaxAssignment_1_3_0(), "rule__RangoNames__MaxAssignment_1_3_0"); put(grammarAccess.getRangoNamesAccess().getTypesAssignment_2_2(), "rule__RangoNames__TypesAssignment_2_2"); put(grammarAccess.getRangoNamesAccess().getTypesAssignment_2_3_1(), "rule__RangoNames__TypesAssignment_2_3_1"); put(grammarAccess.getStringValueAccess().getValueAssignment(), "rule__StringValue__ValueAssignment"); put(grammarAccess.getStringVariableAccess().getVariableAssignment_0(), "rule__StringVariable__VariableAssignment_0"); put(grammarAccess.getStringVariableAccess().getStringsAssignment_2(), "rule__StringVariable__StringsAssignment_2"); put(grammarAccess.getVariableSubtypeAccess().getVariableAssignment_0(), "rule__VariableSubtype__VariableAssignment_0"); put(grammarAccess.getVariableSubtypeAccess().getSubtypeAssignment_1_1(), "rule__VariableSubtype__SubtypeAssignment_1_1"); put(grammarAccess.getTypePrimitiveAccess().getTypePrimitiveAssignment_1(), "rule__TypePrimitive__TypePrimitiveAssignment_1"); put(grammarAccess.getIsCollectionTypeAccess().getOfAssignment_2_1_1(), "rule__IsCollectionType__OfAssignment_2_1_1"); put(grammarAccess.getBlendModifiersAccess().getAccessAssignment_0_0(), "rule__BlendModifiers__AccessAssignment_0_0"); put(grammarAccess.getBlendModifiersAccess().getStaticAssignment_0_1_1(), "rule__BlendModifiers__StaticAssignment_0_1_1"); put(grammarAccess.getBlendModifiersAccess().getFinalAssignment_0_2_1(), "rule__BlendModifiers__FinalAssignment_0_2_1"); put(grammarAccess.getBlendModifiersAccess().getAbstractAssignment_0_3_1(), "rule__BlendModifiers__AbstractAssignment_0_3_1"); put(grammarAccess.getBlendModifiersAccess().getDefaultAssignment_0_4_1(), "rule__BlendModifiers__DefaultAssignment_0_4_1"); put(grammarAccess.getBlendModifiersAccess().getSynchronizedAssignment_0_5_1(), "rule__BlendModifiers__SynchronizedAssignment_0_5_1"); put(grammarAccess.getBlendModifiersAccess().getStaticAssignment_1_0(), "rule__BlendModifiers__StaticAssignment_1_0"); put(grammarAccess.getBlendModifiersAccess().getFinalAssignment_1_1_1(), "rule__BlendModifiers__FinalAssignment_1_1_1"); put(grammarAccess.getBlendModifiersAccess().getAbstractAssignment_1_2_1(), "rule__BlendModifiers__AbstractAssignment_1_2_1"); put(grammarAccess.getBlendModifiersAccess().getDefaultAssignment_1_3_1(), "rule__BlendModifiers__DefaultAssignment_1_3_1"); put(grammarAccess.getBlendModifiersAccess().getSynchronizedAssignment_1_4_1(), "rule__BlendModifiers__SynchronizedAssignment_1_4_1"); put(grammarAccess.getBlendModifiersAccess().getFinalAssignment_2_0(), "rule__BlendModifiers__FinalAssignment_2_0"); put(grammarAccess.getBlendModifiersAccess().getAbstractAssignment_2_1_1(), "rule__BlendModifiers__AbstractAssignment_2_1_1"); put(grammarAccess.getBlendModifiersAccess().getDefaultAssignment_2_2_1(), "rule__BlendModifiers__DefaultAssignment_2_2_1"); put(grammarAccess.getBlendModifiersAccess().getSynchronizedAssignment_2_3_1(), "rule__BlendModifiers__SynchronizedAssignment_2_3_1"); put(grammarAccess.getBlendModifiersAccess().getAbstractAssignment_3_0(), "rule__BlendModifiers__AbstractAssignment_3_0"); put(grammarAccess.getBlendModifiersAccess().getDefaultAssignment_3_1_1(), "rule__BlendModifiers__DefaultAssignment_3_1_1"); put(grammarAccess.getBlendModifiersAccess().getSynchronizedAssignment_3_2_1(), "rule__BlendModifiers__SynchronizedAssignment_3_2_1"); put(grammarAccess.getBlendModifiersAccess().getDefaultAssignment_4_0(), "rule__BlendModifiers__DefaultAssignment_4_0"); put(grammarAccess.getBlendModifiersAccess().getSynchronizedAssignment_4_1_1(), "rule__BlendModifiers__SynchronizedAssignment_4_1_1"); put(grammarAccess.getBlendModifiersAccess().getSynchronizedAssignment_5(), "rule__BlendModifiers__SynchronizedAssignment_5"); } }; } return nameMappings.get(element); } @Override protected Collection<FollowElement> getFollowElements(AbstractInternalContentAssistParser parser) { try { InternalJRulesParser typedParser = (InternalJRulesParser) parser; typedParser.entryRuleRuleSet(); return typedParser.getFollowElements(); } catch(RecognitionException ex) { throw new RuntimeException(ex); } } @Override protected String[] getInitialHiddenTokens() { return new String[] { "RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT" }; } public JRulesGrammarAccess getGrammarAccess() { return this.grammarAccess; } public void setGrammarAccess(JRulesGrammarAccess grammarAccess) { this.grammarAccess = grammarAccess; } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/VariableSubtypeImpl.java /** */ package javaRule.impl; import javaRule.Element; import javaRule.JavaRulePackage; import javaRule.Variable; import javaRule.VariableSubtype; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Variable Subtype</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link javaRule.impl.VariableSubtypeImpl#getVariable <em>Variable</em>}</li> * <li>{@link javaRule.impl.VariableSubtypeImpl#getSubtype <em>Subtype</em>}</li> * </ul> * * @generated */ public class VariableSubtypeImpl extends MinimalEObjectImpl.Container implements VariableSubtype { /** * The cached value of the '{@link #getVariable() <em>Variable</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVariable() * @generated * @ordered */ protected Variable variable; /** * The default value of the '{@link #getSubtype() <em>Subtype</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSubtype() * @generated * @ordered */ protected static final Element SUBTYPE_EDEFAULT = Element.NULL; /** * The cached value of the '{@link #getSubtype() <em>Subtype</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSubtype() * @generated * @ordered */ protected Element subtype = SUBTYPE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected VariableSubtypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.VARIABLE_SUBTYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Variable getVariable() { if (variable != null && variable.eIsProxy()) { InternalEObject oldVariable = (InternalEObject)variable; variable = (Variable)eResolveProxy(oldVariable); if (variable != oldVariable) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, JavaRulePackage.VARIABLE_SUBTYPE__VARIABLE, oldVariable, variable)); } } return variable; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Variable basicGetVariable() { return variable; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setVariable(Variable newVariable) { Variable oldVariable = variable; variable = newVariable; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.VARIABLE_SUBTYPE__VARIABLE, oldVariable, variable)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Element getSubtype() { return subtype; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSubtype(Element newSubtype) { Element oldSubtype = subtype; subtype = newSubtype == null ? SUBTYPE_EDEFAULT : newSubtype; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.VARIABLE_SUBTYPE__SUBTYPE, oldSubtype, subtype)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case JavaRulePackage.VARIABLE_SUBTYPE__VARIABLE: if (resolve) return getVariable(); return basicGetVariable(); case JavaRulePackage.VARIABLE_SUBTYPE__SUBTYPE: return getSubtype(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case JavaRulePackage.VARIABLE_SUBTYPE__VARIABLE: setVariable((Variable)newValue); return; case JavaRulePackage.VARIABLE_SUBTYPE__SUBTYPE: setSubtype((Element)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case JavaRulePackage.VARIABLE_SUBTYPE__VARIABLE: setVariable((Variable)null); return; case JavaRulePackage.VARIABLE_SUBTYPE__SUBTYPE: setSubtype(SUBTYPE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case JavaRulePackage.VARIABLE_SUBTYPE__VARIABLE: return variable != null; case JavaRulePackage.VARIABLE_SUBTYPE__SUBTYPE: return subtype != SUBTYPE_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (subtype: "); result.append(subtype); result.append(')'); return result.toString(); } } //VariableSubtypeImpl <file_sep>/Code/es.uam.sara.tfg.dsl/src-gen/es/uam/sara/tfg/dsl/parser/antlr/JRulesParser.java /* * generated by Xtext 2.10.0 */ package es.uam.sara.tfg.dsl.parser.antlr; import com.google.inject.Inject; import es.uam.sara.tfg.dsl.parser.antlr.internal.InternalJRulesParser; import es.uam.sara.tfg.dsl.services.JRulesGrammarAccess; import org.eclipse.xtext.parser.antlr.AbstractAntlrParser; import org.eclipse.xtext.parser.antlr.XtextTokenStream; public class JRulesParser extends AbstractAntlrParser { @Inject private JRulesGrammarAccess grammarAccess; @Override protected void setInitialHiddenTokens(XtextTokenStream tokenStream) { tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT"); } @Override protected InternalJRulesParser createParser(XtextTokenStream stream) { return new InternalJRulesParser(stream, getGrammarAccess()); } @Override protected String getDefaultRuleName() { return "RuleSet"; } public JRulesGrammarAccess getGrammarAccess() { return this.grammarAccess; } public void setGrammarAccess(JRulesGrammarAccess grammarAccess) { this.grammarAccess = grammarAccess; } } <file_sep>/Code/es.uam.sara.tfg.ast/src/es/uam/sara/tfg/ast/properties/Methods.java package es.uam.sara.tfg.ast.properties; import java.util.ArrayList; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import es.uam.sara.tfg.ast.properties.Name.Idioma; import es.uam.sara.tfg.ast.properties.Name.Type; public class Methods { private ArrayList<MethodDeclaration> methods; public Methods(ArrayList<MethodDeclaration> methods){ this.methods=methods; } public Result<MethodDeclaration> isConstructor(ArrayList<MethodDeclaration> methods){ if (methods==null){ methods=this.methods; } Result<MethodDeclaration> result=new Result<MethodDeclaration>("is constructor"); for (MethodDeclaration m: methods){ if (m.isConstructor()){ result.addRight(m); }else{ result.addWrong(m); } } return result; } public Result<MethodDeclaration> parametres (ArrayList<MethodDeclaration> methods,int number, ArrayList<String> type){ if (methods==null){ methods=this.methods; } Result<MethodDeclaration> result=new Result<MethodDeclaration>("number of parameters is" +number); for (MethodDeclaration m: methods){ if (m.parameters().size()!=number){ result.addWrong(m); }else{ if (type!=null){ result.addPropertie("and types are "+type); int i=0; boolean flag=true; for (Object p:m.parameters()){ if (p instanceof SingleVariableDeclaration){ if(!(((SingleVariableDeclaration) p).getType().toString().equals(type.get(i)))){ flag=false; } } i++; } if (flag){ result.addRight(m); }else{ result.addWrong(m); } }else{ result.addRight(m); } } } return result; } public Result<MethodDeclaration> returns (ArrayList<MethodDeclaration> methods, String returnType){ if (methods==null){ methods=this.methods; } Result<MethodDeclaration> result=new Result<MethodDeclaration>("return type is " +returnType); for (MethodDeclaration m: methods){ if (m.getReturnType2().toString().equals(returnType)){ result.addRight(m); }else{ result.addWrong(m); } } return result; } public Result<MethodDeclaration> nameType(ArrayList<MethodDeclaration> list, Type type) { if (list==null){ list=this.methods; } Result<MethodDeclaration> result= new Result<MethodDeclaration>("name type is "+type); for (MethodDeclaration m:list){ if (Name.nameType(m.getName().toString(), type)){ result.addRight(m); }else{ result.addRight(m); } } return result; } public Result<MethodDeclaration> nameLike(ArrayList<MethodDeclaration> list, String name, Idioma idioma) { if (list==null){ list=this.methods; } Result<MethodDeclaration> result= new Result<MethodDeclaration>("name like"+name+" language "+idioma); for (MethodDeclaration m:list){ if (Name.nameLike(m.getName().toString(), name, idioma)){ result.addRight(m); }else{ result.addRight(m); } } return result; } public Result<MethodDeclaration> nameEqual(ArrayList<MethodDeclaration> list, String name) { if (list==null){ list=this.methods; } Result<MethodDeclaration> result= new Result<MethodDeclaration>("name equals"+name); for (MethodDeclaration m:list){ if (Name.nameEqual(m.getName().toString(), name)){ result.addRight(m); }else{ result.addRight(m); } } return result; } public Result<MethodDeclaration> noEmpty(ArrayList<MethodDeclaration> list){ if (list==null){ list=this.methods; } Result<MethodDeclaration> result= new Result<MethodDeclaration>("no empty"); for (MethodDeclaration m: list){ if (m.getBody().statements().isEmpty()){ result.addWrong(m); }else{ result.addRight(m); } } return result; } public Result<MethodDeclaration> JavaDoc (ArrayList<MethodDeclaration> list, JavaDocPropertie jdp){ if (list==null){ list=this.methods; } Result<MethodDeclaration> result= new Result<MethodDeclaration>(jdp.generateStringPropertie()); for (MethodDeclaration m:list){ if (jdp.javaDoc(m.getJavadoc())){ result.addRight(m); }else{ result.addRight(m); } } return result; } public Result<MethodDeclaration> Modifiers(ArrayList<MethodDeclaration> list, Modifiers m){ if (list==null){ list=this.methods; } Result<MethodDeclaration> result= new Result<MethodDeclaration>(""); for (MethodDeclaration e:list){ ArrayList<Modifier> mList=new ArrayList<Modifier>(); for (Object o:e.modifiers()){ if (o instanceof Modifier){ mList.add((Modifier) o); } } if (m.modifiers(mList)){ result.addRight(e); }else{ result.addWrong(e); } } return result; } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/ModifiersImpl.java /** */ package javaRule.impl; import java.util.Collection; import javaRule.BlendModifiers; import javaRule.JavaRulePackage; import javaRule.Modifiers; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Modifiers</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link javaRule.impl.ModifiersImpl#getBlend <em>Blend</em>}</li> * </ul> * * @generated */ public class ModifiersImpl extends AttributeImpl implements Modifiers { /** * The cached value of the '{@link #getBlend() <em>Blend</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBlend() * @generated * @ordered */ protected EList<BlendModifiers> blend; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ModifiersImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.MODIFIERS; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<BlendModifiers> getBlend() { if (blend == null) { blend = new EObjectContainmentEList<BlendModifiers>(BlendModifiers.class, this, JavaRulePackage.MODIFIERS__BLEND); } return blend; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case JavaRulePackage.MODIFIERS__BLEND: return ((InternalEList<?>)getBlend()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case JavaRulePackage.MODIFIERS__BLEND: return getBlend(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case JavaRulePackage.MODIFIERS__BLEND: getBlend().clear(); getBlend().addAll((Collection<? extends BlendModifiers>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case JavaRulePackage.MODIFIERS__BLEND: getBlend().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case JavaRulePackage.MODIFIERS__BLEND: return blend != null && !blend.isEmpty(); } return super.eIsSet(featureID); } } //ModifiersImpl <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/all/ContainInterface.java package es.uam.sara.tfg.properties.all; import java.util.List; import es.uam.sara.tfg.elements.Container; import es.uam.sara.tfg.elements.type.MInterface; import es.uam.sara.tfg.sentence.Rule; public class ContainInterface<T extends Container> extends Contain<T,MInterface> { public ContainInterface(boolean no, Rule<MInterface> r) { super(no, r); } @Override public List<MInterface> getSubType(Container t) { return t.getInterfaces(); } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/StringPropertyImpl.java /** */ package javaRule.impl; import javaRule.JavaRulePackage; import javaRule.StringProperty; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>String Property</b></em>'. * <!-- end-user-doc --> * * @generated */ public abstract class StringPropertyImpl extends TypePropertyImpl implements StringProperty { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected StringPropertyImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.STRING_PROPERTY; } } //StringPropertyImpl <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/RangoNamesImpl.java /** */ package javaRule.impl; import java.util.Collection; import javaRule.JavaRulePackage; import javaRule.RangoNames; import javaRule.StringProperty; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Rango Names</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link javaRule.impl.RangoNamesImpl#getMin <em>Min</em>}</li> * <li>{@link javaRule.impl.RangoNamesImpl#getMax <em>Max</em>}</li> * <li>{@link javaRule.impl.RangoNamesImpl#getTypes <em>Types</em>}</li> * </ul> * * @generated */ public class RangoNamesImpl extends MinimalEObjectImpl.Container implements RangoNames { /** * The default value of the '{@link #getMin() <em>Min</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMin() * @generated * @ordered */ protected static final int MIN_EDEFAULT = 1; /** * The cached value of the '{@link #getMin() <em>Min</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMin() * @generated * @ordered */ protected int min = MIN_EDEFAULT; /** * The default value of the '{@link #getMax() <em>Max</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMax() * @generated * @ordered */ protected static final int MAX_EDEFAULT = 2147483647; /** * The cached value of the '{@link #getMax() <em>Max</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMax() * @generated * @ordered */ protected int max = MAX_EDEFAULT; /** * The cached value of the '{@link #getTypes() <em>Types</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypes() * @generated * @ordered */ protected EList<StringProperty> types; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected RangoNamesImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.RANGO_NAMES; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getMin() { return min; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMin(int newMin) { int oldMin = min; min = newMin; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.RANGO_NAMES__MIN, oldMin, min)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getMax() { return max; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMax(int newMax) { int oldMax = max; max = newMax; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.RANGO_NAMES__MAX, oldMax, max)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<StringProperty> getTypes() { if (types == null) { types = new EObjectContainmentEList<StringProperty>(StringProperty.class, this, JavaRulePackage.RANGO_NAMES__TYPES); } return types; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case JavaRulePackage.RANGO_NAMES__TYPES: return ((InternalEList<?>)getTypes()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case JavaRulePackage.RANGO_NAMES__MIN: return getMin(); case JavaRulePackage.RANGO_NAMES__MAX: return getMax(); case JavaRulePackage.RANGO_NAMES__TYPES: return getTypes(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case JavaRulePackage.RANGO_NAMES__MIN: setMin((Integer)newValue); return; case JavaRulePackage.RANGO_NAMES__MAX: setMax((Integer)newValue); return; case JavaRulePackage.RANGO_NAMES__TYPES: getTypes().clear(); getTypes().addAll((Collection<? extends StringProperty>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case JavaRulePackage.RANGO_NAMES__MIN: setMin(MIN_EDEFAULT); return; case JavaRulePackage.RANGO_NAMES__MAX: setMax(MAX_EDEFAULT); return; case JavaRulePackage.RANGO_NAMES__TYPES: getTypes().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case JavaRulePackage.RANGO_NAMES__MIN: return min != MIN_EDEFAULT; case JavaRulePackage.RANGO_NAMES__MAX: return max != MAX_EDEFAULT; case JavaRulePackage.RANGO_NAMES__TYPES: return types != null && !types.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (min: "); result.append(min); result.append(", max: "); result.append(max); result.append(')'); return result.toString(); } } //RangoNamesImpl <file_sep>/Code/es.uam.sara.tfg.astPlugin/src/es/uam/sara/tfg/elements/type/MAttribute.java package es.uam.sara.tfg.elements.type; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import es.uam.sara.tfg.ast.UnitVisitor; import es.uam.sara.tfg.elements.ICanGeneric; import es.uam.sara.tfg.elements.JavaElement; public class MAttribute extends JavaElement implements ICanGeneric{ private FieldDeclaration fd; public MAttribute(FieldDeclaration fd, UnitVisitor uv) { super(fd, uv); this.fd=fd; } public String getName (){ if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { VariableDeclarationFragment declaration = (VariableDeclarationFragment) fd.fragments().get(0); return declaration.getName().toString(); } return ""; } public Type getType(){ return fd.getType(); } @Override public FieldDeclaration getBodyDeclaration() { return fd; } @Override public String toString() { UnitVisitor uv=getVisitor(); return "In file "+uv.getNameFile()+" the attribute "+getName() +" (line: " +uv.getLineNumber(fd.getStartPosition())+")\n"; } public boolean isInitialize(){ if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { VariableDeclarationFragment declaration = (VariableDeclarationFragment) fd.fragments().get(0); if (declaration.getInitializer() != null) { return true; } } return false; } @Override public boolean isGeneric() { if (fd.getParent() instanceof TypeDeclaration) { TypeDeclaration t = (TypeDeclaration) fd.getParent(); if (t.isInterface()){ return false; } MClass c= new MClass(t, getVisitor()); if (c.isGeneric()) { if (comparaParam(getTypes(fd.getType()), getGenericTypes(t.typeParameters()))) { return true; } } } return false; } @Override public boolean equals(Object object) { boolean sameSame = false; if (object != null && object instanceof MAttribute) { sameSame = this.fd.equals(((MAttribute)object).fd); } return sameSame; } @Override public String getStringType() { return fd.getType().toString(); } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/JavaRuleFactory.java /** */ package javaRule; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see javaRule.JavaRulePackage * @generated */ public interface JavaRuleFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ JavaRuleFactory eINSTANCE = javaRule.impl.JavaRuleFactoryImpl.init(); /** * Returns a new object of class '<em>Rule Set</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Rule Set</em>'. * @generated */ RuleSet createRuleSet(); /** * Returns a new object of class '<em>Variable</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Variable</em>'. * @generated */ Variable createVariable(); /** * Returns a new object of class '<em>Rule</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Rule</em>'. * @generated */ Rule createRule(); /** * Returns a new object of class '<em>Or</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Or</em>'. * @generated */ Or createOr(); /** * Returns a new object of class '<em>And</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>And</em>'. * @generated */ And createAnd(); /** * Returns a new object of class '<em>Property Literal</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Property Literal</em>'. * @generated */ PropertyLiteral createPropertyLiteral(); /** * Returns a new object of class '<em>Is Implemented</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Is Implemented</em>'. * @generated */ IsImplemented createIsImplemented(); /** * Returns a new object of class '<em>Is Super Interface</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Is Super Interface</em>'. * @generated */ IsSuperInterface createIsSuperInterface(); /** * Returns a new object of class '<em>Is Super Class</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Is Super Class</em>'. * @generated */ IsSuperClass createIsSuperClass(); /** * Returns a new object of class '<em>Is Sub Class</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Is Sub Class</em>'. * @generated */ IsSubClass createIsSubClass(); /** * Returns a new object of class '<em>Implements</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Implements</em>'. * @generated */ Implements createImplements(); /** * Returns a new object of class '<em>Extends</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Extends</em>'. * @generated */ Extends createExtends(); /** * Returns a new object of class '<em>Rango Names</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Rango Names</em>'. * @generated */ RangoNames createRangoNames(); /** * Returns a new object of class '<em>Tamanio</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Tamanio</em>'. * @generated */ Tamanio createTamanio(); /** * Returns a new object of class '<em>Parameter</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Parameter</em>'. * @generated */ Parameter createParameter(); /** * Returns a new object of class '<em>Constructor</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Constructor</em>'. * @generated */ Constructor createConstructor(); /** * Returns a new object of class '<em>Return</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Return</em>'. * @generated */ Return createReturn(); /** * Returns a new object of class '<em>Attribute Type</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Attribute Type</em>'. * @generated */ AttributeType createAttributeType(); /** * Returns a new object of class '<em>Initialize</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Initialize</em>'. * @generated */ Initialize createInitialize(); /** * Returns a new object of class '<em>Empty</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Empty</em>'. * @generated */ Empty createEmpty(); /** * Returns a new object of class '<em>Is Generic</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Is Generic</em>'. * @generated */ IsGeneric createIsGeneric(); /** * Returns a new object of class '<em>Name Operation</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Name Operation</em>'. * @generated */ NameOperation createNameOperation(); /** * Returns a new object of class '<em>String Variable</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>String Variable</em>'. * @generated */ StringVariable createStringVariable(); /** * Returns a new object of class '<em>Variable Subtype</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Variable Subtype</em>'. * @generated */ VariableSubtype createVariableSubtype(); /** * Returns a new object of class '<em>String Value</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>String Value</em>'. * @generated */ StringValue createStringValue(); /** * Returns a new object of class '<em>Name Type</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Name Type</em>'. * @generated */ NameType createNameType(); /** * Returns a new object of class '<em>Contains</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Contains</em>'. * @generated */ Contains createContains(); /** * Returns a new object of class '<em>Java Doc</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Java Doc</em>'. * @generated */ JavaDoc createJavaDoc(); /** * Returns a new object of class '<em>Modifiers</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Modifiers</em>'. * @generated */ Modifiers createModifiers(); /** * Returns a new object of class '<em>Blend Modifiers</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Blend Modifiers</em>'. * @generated */ BlendModifiers createBlendModifiers(); /** * Returns a new object of class '<em>Type Primitive</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Type Primitive</em>'. * @generated */ TypePrimitive createTypePrimitive(); /** * Returns a new object of class '<em>Is Primitive Funtion</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Is Primitive Funtion</em>'. * @generated */ IsPrimitiveFuntion createIsPrimitiveFuntion(); /** * Returns a new object of class '<em>Is Collection Type</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Is Collection Type</em>'. * @generated */ IsCollectionType createIsCollectionType(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ JavaRulePackage getJavaRulePackage(); } //JavaRuleFactory <file_sep>/Code/es.uam.sara.tfg.ast/src/es/uam/sara/tfg/ast/properties/Enumerations.java package es.uam.sara.tfg.ast.properties; import java.util.ArrayList; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.Modifier; import es.uam.sara.tfg.ast.properties.Name.Idioma; import es.uam.sara.tfg.ast.properties.Name.Type; public class Enumerations { private ArrayList<EnumDeclaration> enumerations; public Enumerations(ArrayList<EnumDeclaration> enums){ this.enumerations=enums; } public Result<EnumDeclaration> nameType(ArrayList<EnumDeclaration> list, Type type) { if (list==null){ list=this.enumerations; } Result<EnumDeclaration> result= new Result<EnumDeclaration>("name type is "+type); for (EnumDeclaration e:list){ if (Name.nameType(e.getName().toString(), type)){ result.addRight(e); }else{ result.addRight(e); } } return result; } public Result<EnumDeclaration> nameLike(ArrayList<EnumDeclaration> list, String name, Idioma idioma) { if (list==null){ list=this.enumerations; } Result<EnumDeclaration> result= new Result<EnumDeclaration>("name like"+name+" language "+idioma); for (EnumDeclaration e:list){ if (Name.nameLike(e.getName().toString(), name, idioma)){ result.addRight(e); }else{ result.addRight(e); } } return result; } public Result<EnumDeclaration> nameEqual(ArrayList<EnumDeclaration> list, String name) { if (list==null){ list=this.enumerations; } Result<EnumDeclaration> result= new Result<EnumDeclaration>("name equals"+name); for (EnumDeclaration e:list){ if (Name.nameEqual(e.getName().toString(), name)){ result.addRight(e); }else{ result.addRight(e); } } return result; } public Result<EnumDeclaration> noEmpty(ArrayList<EnumDeclaration> list){ if (list==null){ list=this.enumerations; } Result<EnumDeclaration> result= new Result<EnumDeclaration>("no empty"); for (EnumDeclaration e: list){ if (e.bodyDeclarations().isEmpty() && e.enumConstants().isEmpty()){ result.addWrong(e); }else{ result.addRight(e); } } return result; } public Result<EnumDeclaration> JavaDoc (ArrayList<EnumDeclaration> list, JavaDocPropertie jdp){ if (list==null){ list=this.enumerations; } Result<EnumDeclaration> result= new Result<EnumDeclaration>(jdp.generateStringPropertie()); for (EnumDeclaration e:list){ if (jdp.javaDoc(e.getJavadoc())){ result.addRight(e); }else{ result.addRight(e); } } return result; } public Result<EnumDeclaration> Modifiers(ArrayList<EnumDeclaration> list, Modifiers m){ if (list==null){ list=this.enumerations; } Result<EnumDeclaration> result= new Result<EnumDeclaration>(""); for (EnumDeclaration e:list){ ArrayList<Modifier> mList=new ArrayList<Modifier>(); for (Object o:e.modifiers()){ if (o instanceof Modifier){ mList.add((Modifier) o); } } if (m.modifiers(mList)){ result.addRight(e); }else{ result.addWrong(e); } } return result; } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/ParameterImpl.java /** */ package javaRule.impl; import java.util.Collection; import javaRule.JavaRulePackage; import javaRule.Parameter; import javaRule.TypeProperty; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Parameter</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link javaRule.impl.ParameterImpl#getMin <em>Min</em>}</li> * <li>{@link javaRule.impl.ParameterImpl#getMax <em>Max</em>}</li> * <li>{@link javaRule.impl.ParameterImpl#getExact <em>Exact</em>}</li> * <li>{@link javaRule.impl.ParameterImpl#getTypes <em>Types</em>}</li> * </ul> * * @generated */ public class ParameterImpl extends MethodImpl implements Parameter { /** * The default value of the '{@link #getMin() <em>Min</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMin() * @generated * @ordered */ protected static final int MIN_EDEFAULT = 1; /** * The cached value of the '{@link #getMin() <em>Min</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMin() * @generated * @ordered */ protected int min = MIN_EDEFAULT; /** * The default value of the '{@link #getMax() <em>Max</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMax() * @generated * @ordered */ protected static final int MAX_EDEFAULT = 2147483647; /** * The cached value of the '{@link #getMax() <em>Max</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMax() * @generated * @ordered */ protected int max = MAX_EDEFAULT; /** * The default value of the '{@link #getExact() <em>Exact</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExact() * @generated * @ordered */ protected static final int EXACT_EDEFAULT = -2147483647; /** * The cached value of the '{@link #getExact() <em>Exact</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExact() * @generated * @ordered */ protected int exact = EXACT_EDEFAULT; /** * The cached value of the '{@link #getTypes() <em>Types</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypes() * @generated * @ordered */ protected EList<TypeProperty> types; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ParameterImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.PARAMETER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getMin() { return min; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMin(int newMin) { int oldMin = min; min = newMin; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.PARAMETER__MIN, oldMin, min)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getMax() { return max; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMax(int newMax) { int oldMax = max; max = newMax; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.PARAMETER__MAX, oldMax, max)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getExact() { return exact; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExact(int newExact) { int oldExact = exact; exact = newExact; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.PARAMETER__EXACT, oldExact, exact)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<TypeProperty> getTypes() { if (types == null) { types = new EObjectContainmentEList<TypeProperty>(TypeProperty.class, this, JavaRulePackage.PARAMETER__TYPES); } return types; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case JavaRulePackage.PARAMETER__TYPES: return ((InternalEList<?>)getTypes()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case JavaRulePackage.PARAMETER__MIN: return getMin(); case JavaRulePackage.PARAMETER__MAX: return getMax(); case JavaRulePackage.PARAMETER__EXACT: return getExact(); case JavaRulePackage.PARAMETER__TYPES: return getTypes(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case JavaRulePackage.PARAMETER__MIN: setMin((Integer)newValue); return; case JavaRulePackage.PARAMETER__MAX: setMax((Integer)newValue); return; case JavaRulePackage.PARAMETER__EXACT: setExact((Integer)newValue); return; case JavaRulePackage.PARAMETER__TYPES: getTypes().clear(); getTypes().addAll((Collection<? extends TypeProperty>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case JavaRulePackage.PARAMETER__MIN: setMin(MIN_EDEFAULT); return; case JavaRulePackage.PARAMETER__MAX: setMax(MAX_EDEFAULT); return; case JavaRulePackage.PARAMETER__EXACT: setExact(EXACT_EDEFAULT); return; case JavaRulePackage.PARAMETER__TYPES: getTypes().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case JavaRulePackage.PARAMETER__MIN: return min != MIN_EDEFAULT; case JavaRulePackage.PARAMETER__MAX: return max != MAX_EDEFAULT; case JavaRulePackage.PARAMETER__EXACT: return exact != EXACT_EDEFAULT; case JavaRulePackage.PARAMETER__TYPES: return types != null && !types.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (min: "); result.append(min); result.append(", max: "); result.append(max); result.append(", exact: "); result.append(exact); result.append(')'); return result.toString(); } } //ParameterImpl <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/elements/IPosicionable.java package es.uam.sara.tfg.elements; public interface IPosicionable extends IElements{ public int getStartLine(); public int getEndLine(); } <file_sep>/Code/es.uam.sara.tfg.dsl/src-gen/es/uam/sara/tfg/dsl/serializer/JRulesSemanticSequencer.java /* * generated by Xtext 2.10.0 */ package es.uam.sara.tfg.dsl.serializer; import com.google.inject.Inject; import es.uam.sara.tfg.dsl.services.JRulesGrammarAccess; import java.util.Set; import javaRule.And; import javaRule.AttributeType; import javaRule.BlendModifiers; import javaRule.Constructor; import javaRule.Contains; import javaRule.Empty; import javaRule.Extends; import javaRule.Implements; import javaRule.Initialize; import javaRule.IsCollectionType; import javaRule.IsGeneric; import javaRule.IsImplemented; import javaRule.IsPrimitiveFuntion; import javaRule.IsSubClass; import javaRule.IsSuperClass; import javaRule.IsSuperInterface; import javaRule.JavaDoc; import javaRule.JavaRulePackage; import javaRule.Modifiers; import javaRule.NameOperation; import javaRule.NameType; import javaRule.Or; import javaRule.PropertyLiteral; import javaRule.RangoNames; import javaRule.Return; import javaRule.Rule; import javaRule.RuleSet; import javaRule.StringValue; import javaRule.StringVariable; import javaRule.Tamanio; import javaRule.TypePrimitive; import javaRule.Variable; import javaRule.VariableSubtype; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.xtext.Action; import org.eclipse.xtext.Parameter; import org.eclipse.xtext.ParserRule; import org.eclipse.xtext.serializer.ISerializationContext; import org.eclipse.xtext.serializer.acceptor.SequenceFeeder; import org.eclipse.xtext.serializer.sequencer.AbstractDelegatingSemanticSequencer; import org.eclipse.xtext.serializer.sequencer.ITransientValueService.ValueTransient; @SuppressWarnings("all") public class JRulesSemanticSequencer extends AbstractDelegatingSemanticSequencer { @Inject private JRulesGrammarAccess grammarAccess; @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set<Parameter> parameters = context.getEnabledBooleanParameters(); if (epackage == JavaRulePackage.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case JavaRulePackage.AND: sequence_And(context, (And) semanticObject); return; case JavaRulePackage.ATTRIBUTE_TYPE: sequence_AttributeType(context, (AttributeType) semanticObject); return; case JavaRulePackage.BLEND_MODIFIERS: sequence_BlendModifiers(context, (BlendModifiers) semanticObject); return; case JavaRulePackage.CONSTRUCTOR: sequence_Constructor(context, (Constructor) semanticObject); return; case JavaRulePackage.CONTAINS: sequence_Contains(context, (Contains) semanticObject); return; case JavaRulePackage.EMPTY: sequence_Empty(context, (Empty) semanticObject); return; case JavaRulePackage.EXTENDS: sequence_Extends(context, (Extends) semanticObject); return; case JavaRulePackage.IMPLEMENTS: sequence_Implements(context, (Implements) semanticObject); return; case JavaRulePackage.INITIALIZE: sequence_Initialize(context, (Initialize) semanticObject); return; case JavaRulePackage.IS_COLLECTION_TYPE: sequence_IsCollectionType(context, (IsCollectionType) semanticObject); return; case JavaRulePackage.IS_GENERIC: sequence_IsGeneric(context, (IsGeneric) semanticObject); return; case JavaRulePackage.IS_IMPLEMENTED: sequence_IsImplemented(context, (IsImplemented) semanticObject); return; case JavaRulePackage.IS_PRIMITIVE_FUNTION: sequence_isPrimitiveFunction(context, (IsPrimitiveFuntion) semanticObject); return; case JavaRulePackage.IS_SUB_CLASS: sequence_IsSubClass(context, (IsSubClass) semanticObject); return; case JavaRulePackage.IS_SUPER_CLASS: sequence_IsSuperClass(context, (IsSuperClass) semanticObject); return; case JavaRulePackage.IS_SUPER_INTERFACE: sequence_IsSuperInterface(context, (IsSuperInterface) semanticObject); return; case JavaRulePackage.JAVA_DOC: sequence_JavaDoc(context, (JavaDoc) semanticObject); return; case JavaRulePackage.MODIFIERS: sequence_Modifiers(context, (Modifiers) semanticObject); return; case JavaRulePackage.NAME_OPERATION: sequence_NameOperation(context, (NameOperation) semanticObject); return; case JavaRulePackage.NAME_TYPE: sequence_NameType(context, (NameType) semanticObject); return; case JavaRulePackage.OR: sequence_Or(context, (Or) semanticObject); return; case JavaRulePackage.PARAMETER: sequence_Parameter(context, (javaRule.Parameter) semanticObject); return; case JavaRulePackage.PROPERTY_LITERAL: sequence_PropertyLiteral(context, (PropertyLiteral) semanticObject); return; case JavaRulePackage.RANGO_NAMES: sequence_RangoNames(context, (RangoNames) semanticObject); return; case JavaRulePackage.RETURN: sequence_Return(context, (Return) semanticObject); return; case JavaRulePackage.RULE: sequence_Rule(context, (Rule) semanticObject); return; case JavaRulePackage.RULE_SET: sequence_RuleSet(context, (RuleSet) semanticObject); return; case JavaRulePackage.STRING_VALUE: sequence_StringValue(context, (StringValue) semanticObject); return; case JavaRulePackage.STRING_VARIABLE: sequence_StringVariable(context, (StringVariable) semanticObject); return; case JavaRulePackage.TAMANIO: sequence_Tamanio(context, (Tamanio) semanticObject); return; case JavaRulePackage.TYPE_PRIMITIVE: sequence_TypePrimitive(context, (TypePrimitive) semanticObject); return; case JavaRulePackage.VARIABLE: sequence_Variable(context, (Variable) semanticObject); return; case JavaRulePackage.VARIABLE_SUBTYPE: sequence_VariableSubtype(context, (VariableSubtype) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } /** * Contexts: * And returns And * * Constraint: * (op+=PrimaryOp op+=PrimaryOp*) */ protected void sequence_And(ISerializationContext context, And semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns AttributeType * AttributeType returns AttributeType * * Constraint: * (no?='<>'? type=TypeProperty) */ protected void sequence_AttributeType(ISerializationContext context, AttributeType semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * BlendModifiers returns BlendModifiers * * Constraint: * ( * ( * access=AccessModifier * static?='static'? * final?='final'? * abstract?='abstract'? * default?='default'? * synchronized?='synchronized'? * ) | * (static?='static' final?='final'? abstract?='abstract'? default?='default'? synchronized?='synchronized'?) | * (final?='final' abstract?='abstract'? default?='default'? synchronized?='synchronized'?) | * (abstract?='abstract' default?='default'? synchronized?='synchronized'?) | * (default?='default' synchronized?='synchronized'?) | * synchronized?='synchronized' * ) */ protected void sequence_BlendModifiers(ISerializationContext context, BlendModifiers semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Constructor * Constructor returns Constructor * * Constraint: * no?='not'? */ protected void sequence_Constructor(ISerializationContext context, Constructor semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Contains * Contains returns Contains * * Constraint: * ((no?='do' | no?='don't' | no?='does' | no?='doesn't' | no?='haven't')? rule=Rule) */ protected void sequence_Contains(ISerializationContext context, Contains semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Empty * Empty returns Empty * * Constraint: * no?='not'? */ protected void sequence_Empty(ISerializationContext context, Empty semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Extends * Extends returns Extends * * Constraint: * ((no?='do' | no?='don't' | no?='does' | no?='doesn't')? valores=RangoNames) */ protected void sequence_Extends(ISerializationContext context, Extends semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Implements * Implements returns Implements * * Constraint: * ((no?='do' | no?='don't' | no?='does' | no?='doesn't')? valores=RangoNames) */ protected void sequence_Implements(ISerializationContext context, Implements semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Initialize * Initialize returns Initialize * * Constraint: * no?='not'? */ protected void sequence_Initialize(ISerializationContext context, Initialize semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * TypeProperty returns IsCollectionType * IsCollectionType returns IsCollectionType * * Constraint: * of=TypeProperty? */ protected void sequence_IsCollectionType(ISerializationContext context, IsCollectionType semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns IsGeneric * IsGeneric returns IsGeneric * * Constraint: * no?='not'? */ protected void sequence_IsGeneric(ISerializationContext context, IsGeneric semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns IsImplemented * IsImplemented returns IsImplemented * * Constraint: * (no?='not'? valores=RangoNames) */ protected void sequence_IsImplemented(ISerializationContext context, IsImplemented semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns IsSubClass * IsSubClass returns IsSubClass * * Constraint: * (no?='not'? of=StringProperty?) */ protected void sequence_IsSubClass(ISerializationContext context, IsSubClass semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns IsSuperClass * IsSuperClass returns IsSuperClass * * Constraint: * (no?='not'? valores=RangoNames) */ protected void sequence_IsSuperClass(ISerializationContext context, IsSuperClass semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns IsSuperInterface * IsSuperInterface returns IsSuperInterface * * Constraint: * (no?='not'? valores=RangoNames) */ protected void sequence_IsSuperInterface(ISerializationContext context, IsSuperInterface semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns JavaDoc * JavaDoc returns JavaDoc * * Constraint: * ( * no?='no'? * author?='@author'? * parameter?='@parameter'? * return?='@return'? * version?='@version'? * throws?='@throws'? * see?='@see'? * ) */ protected void sequence_JavaDoc(ISerializationContext context, JavaDoc semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Modifiers * Modifiers returns Modifiers * * Constraint: * (no?='not'? blend+=BlendModifiers blend+=BlendModifiers*) */ protected void sequence_Modifiers(ISerializationContext context, Modifiers semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns NameOperation * NameOperation returns NameOperation * * Constraint: * (((no?='does'? operator=NameOperator) | no?='<>')? name=StringProperty Language=Language?) */ protected void sequence_NameOperation(ISerializationContext context, NameOperation semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns NameType * NameType returns NameType * * Constraint: * (no?='<>'? type=NameCheck) */ protected void sequence_NameType(ISerializationContext context, NameType semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Or returns Or * PrimaryOp returns Or * * Constraint: * (op+=And op+=And*) */ protected void sequence_Or(ISerializationContext context, Or semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Parameter * Parameter returns Parameter * * Constraint: * (((no?='<>'? exact=EInt) | (min=EInt max=EInt?))? (types+=TypeProperty types+=TypeProperty*)?) */ protected void sequence_Parameter(ISerializationContext context, javaRule.Parameter semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * PrimaryOp returns PropertyLiteral * PropertyLiteral returns PropertyLiteral * * Constraint: * property=Property */ protected void sequence_PropertyLiteral(ISerializationContext context, PropertyLiteral semanticObject) { if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject, JavaRulePackage.Literals.PROPERTY_LITERAL__PROPERTY) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, JavaRulePackage.Literals.PROPERTY_LITERAL__PROPERTY)); } SequenceFeeder feeder = createSequencerFeeder(context, semanticObject); feeder.accept(grammarAccess.getPropertyLiteralAccess().getPropertyPropertyParserRuleCall_0(), semanticObject.getProperty()); feeder.finish(); } /** * Contexts: * RangoNames returns RangoNames * * Constraint: * ((min=EInt max=EInt?)? (types+=StringProperty types+=StringProperty*)?) */ protected void sequence_RangoNames(ISerializationContext context, RangoNames semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Property returns Return * Return returns Return * * Constraint: * (no?='<>'? type=TypeProperty) */ protected void sequence_Return(ISerializationContext context, Return semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * RuleSet returns RuleSet * * Constraint: * ((ProjectName+=EString ProjectName+=EString*)? sentences+=Sentence sentences+=Sentence*) */ protected void sequence_RuleSet(ISerializationContext context, RuleSet semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Sentence returns Rule * Rule returns Rule * * Constraint: * ( * no?='no'? * quantifier=Quantifier * element=Element * from=[Variable|EString]? * (in+=[Variable|EString] in+=[Variable|EString]*)? * (using+=VariableSubtype using+=VariableSubtype*)? * filter=Or? * satisfy=Or? * ) */ protected void sequence_Rule(ISerializationContext context, Rule semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * StringProperty returns StringValue * StringValue returns StringValue * TypeProperty returns StringValue * * Constraint: * value=EString */ protected void sequence_StringValue(ISerializationContext context, StringValue semanticObject) { if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject, JavaRulePackage.Literals.STRING_VALUE__VALUE) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, JavaRulePackage.Literals.STRING_VALUE__VALUE)); } SequenceFeeder feeder = createSequencerFeeder(context, semanticObject); feeder.accept(grammarAccess.getStringValueAccess().getValueEStringParserRuleCall_0(), semanticObject.getValue()); feeder.finish(); } /** * Contexts: * StringProperty returns StringVariable * StringVariable returns StringVariable * TypeProperty returns StringVariable * * Constraint: * (variable=VariableSubtype strings=ElementString) */ protected void sequence_StringVariable(ISerializationContext context, StringVariable semanticObject) { if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject, JavaRulePackage.Literals.STRING_VARIABLE__VARIABLE) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, JavaRulePackage.Literals.STRING_VARIABLE__VARIABLE)); if (transientValues.isValueTransient(semanticObject, JavaRulePackage.Literals.STRING_VARIABLE__STRINGS) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, JavaRulePackage.Literals.STRING_VARIABLE__STRINGS)); } SequenceFeeder feeder = createSequencerFeeder(context, semanticObject); feeder.accept(grammarAccess.getStringVariableAccess().getVariableVariableSubtypeParserRuleCall_0_0(), semanticObject.getVariable()); feeder.accept(grammarAccess.getStringVariableAccess().getStringsElementStringEnumRuleCall_2_0(), semanticObject.getStrings()); feeder.finish(); } /** * Contexts: * Property returns Tamanio * Tamanio returns Tamanio * * Constraint: * ((no?='<>'? exact=EInt) | (min=EInt max=EInt?)) */ protected void sequence_Tamanio(ISerializationContext context, Tamanio semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * TypeProperty returns TypePrimitive * TypePrimitive returns TypePrimitive * * Constraint: * typePrimitive=Primitive */ protected void sequence_TypePrimitive(ISerializationContext context, TypePrimitive semanticObject) { if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject, JavaRulePackage.Literals.TYPE_PRIMITIVE__TYPE_PRIMITIVE) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, JavaRulePackage.Literals.TYPE_PRIMITIVE__TYPE_PRIMITIVE)); } SequenceFeeder feeder = createSequencerFeeder(context, semanticObject); feeder.accept(grammarAccess.getTypePrimitiveAccess().getTypePrimitivePrimitiveEnumRuleCall_1_0(), semanticObject.getTypePrimitive()); feeder.finish(); } /** * Contexts: * VariableSubtype returns VariableSubtype * * Constraint: * (variable=[Variable|EString] subtype=Element?) */ protected void sequence_VariableSubtype(ISerializationContext context, VariableSubtype semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * Sentence returns Variable * Variable returns Variable * * Constraint: * ( * name=EString * element=Element * from=[Variable|EString]? * (in+=[Variable|EString] in+=[Variable|EString]*)? * (using+=VariableSubtype using+=VariableSubtype*)? * satisfy=Or? * ) */ protected void sequence_Variable(ISerializationContext context, Variable semanticObject) { genericSequencer.createSequence(context, semanticObject); } /** * Contexts: * TypeProperty returns IsPrimitiveFuntion * isPrimitiveFunction returns IsPrimitiveFuntion * * Constraint: * {IsPrimitiveFuntion} */ protected void sequence_isPrimitiveFunction(ISerializationContext context, IsPrimitiveFuntion semanticObject) { genericSequencer.createSequence(context, semanticObject); } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/elements/IElements.java package es.uam.sara.tfg.elements; import es.uam.sara.tfg.ast.UnitVisitor; public interface IElements { public abstract String getName(); public abstract String toString(); public UnitVisitor getVisitor(); public boolean equals(Object object); public abstract String getStringType(); } <file_sep>/Code/es.uam.sara.tfg.ast/src/es/uam/sara/tfg/ast/properties/JavaDocPropertie.java package es.uam.sara.tfg.ast.properties; import java.util.ArrayList; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.TagElement; public class JavaDocPropertie { private boolean author; private boolean parameter; private boolean returns; private boolean version; private boolean throwss; private boolean see; public JavaDocPropertie (boolean author, boolean parameter, boolean returns, boolean version, boolean throwss, boolean see){ this.author=author; this.parameter=parameter; this.returns=returns; this.version=version; this.throwss=throwss; this.see=see; } public String generateStringPropertie(){ String res="javaDoc "; if (author){res=res+ "@author ";} if (parameter){res=res+ "@parameter ";} if (returns){res=res+ "@returns ";} if (version){res=res+ "@version ";} if (throwss){res=res+ "@throws ";} if (see){res=res+ "@see ";} return res; } public boolean javaDoc(Javadoc j){ if (j==null) return false; else { ArrayList<TagElement> tags=new ArrayList<TagElement>(); for (Object t: j.tags()){ if (t instanceof TagElement){ tags.add((TagElement) t); } } if (author){ if (buscar("@author", tags)==false) return false; } if (parameter){ if (buscar("@parameter", tags)==false) return false; } if (returns){ if (buscar("@returns", tags)==false) return false; } if (version){ if (buscar("@version", tags)==false) return false; } if (throwss){ if (buscar("@throws", tags)==false) return false; } if (see){ if (buscar("@see", tags)==false) return false; } } return true; } private boolean buscar(String tag, ArrayList<TagElement> list){ for (TagElement t: list){ if (t.getTagName().compareTo(tag)==0){ return true; } } return false; } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/Rule.java /** */ package javaRule; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Rule</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link javaRule.Rule#isNo <em>No</em>}</li> * <li>{@link javaRule.Rule#getQuantifier <em>Quantifier</em>}</li> * <li>{@link javaRule.Rule#getFilter <em>Filter</em>}</li> * </ul> * * @see javaRule.JavaRulePackage#getRule() * @model * @generated */ public interface Rule extends Sentence { /** * Returns the value of the '<em><b>No</b></em>' attribute. * The default value is <code>"false"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>No</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>No</em>' attribute. * @see #setNo(boolean) * @see javaRule.JavaRulePackage#getRule_No() * @model default="false" required="true" * @generated */ boolean isNo(); /** * Sets the value of the '{@link javaRule.Rule#isNo <em>No</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>No</em>' attribute. * @see #isNo() * @generated */ void setNo(boolean value); /** * Returns the value of the '<em><b>Quantifier</b></em>' attribute. * The literals are from the enumeration {@link javaRule.Quantifier}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Quantifier</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Quantifier</em>' attribute. * @see javaRule.Quantifier * @see #setQuantifier(Quantifier) * @see javaRule.JavaRulePackage#getRule_Quantifier() * @model required="true" * @generated */ Quantifier getQuantifier(); /** * Sets the value of the '{@link javaRule.Rule#getQuantifier <em>Quantifier</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Quantifier</em>' attribute. * @see javaRule.Quantifier * @see #getQuantifier() * @generated */ void setQuantifier(Quantifier value); /** * Returns the value of the '<em><b>Filter</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Filter</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Filter</em>' containment reference. * @see #setFilter(Or) * @see javaRule.JavaRulePackage#getRule_Filter() * @model containment="true" * @generated */ Or getFilter(); /** * Sets the value of the '{@link javaRule.Rule#getFilter <em>Filter</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Filter</em>' containment reference. * @see #getFilter() * @generated */ void setFilter(Or value); } // Rule <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/JavaRulePackageImpl.java /** */ package javaRule.impl; import javaRule.AccessModifier; import javaRule.And; import javaRule.Attribute; import javaRule.AttributeType; import javaRule.BlendModifiers; import javaRule.Constructor; import javaRule.Contains; import javaRule.Element; import javaRule.ElementString; import javaRule.Empty; import javaRule.Enumeration; import javaRule.Extends; import javaRule.File; import javaRule.Implements; import javaRule.Initialize; import javaRule.Interface; import javaRule.IsCollectionType; import javaRule.IsGeneric; import javaRule.IsImplemented; import javaRule.IsPrimitiveFuntion; import javaRule.IsSubClass; import javaRule.IsSuperClass; import javaRule.IsSuperInterface; import javaRule.JavaDoc; import javaRule.JavaRuleFactory; import javaRule.JavaRulePackage; import javaRule.Language; import javaRule.Method; import javaRule.Modifiers; import javaRule.NameCheck; import javaRule.NameOperation; import javaRule.NameOperator; import javaRule.NameType; import javaRule.Or; import javaRule.Parameter; import javaRule.PrimaryOp; import javaRule.Primitive; import javaRule.Property; import javaRule.PropertyLiteral; import javaRule.Quantifier; import javaRule.RangoNames; import javaRule.Return; import javaRule.Rule; import javaRule.RuleSet; import javaRule.Sentence; import javaRule.StringProperty; import javaRule.StringValue; import javaRule.StringVariable; import javaRule.Tamanio; import javaRule.TypePrimitive; import javaRule.TypeProperty; import javaRule.Variable; import javaRule.VariableSubtype; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.impl.EPackageImpl; /** * <!-- begin-user-doc --> * An implementation of the model <b>Package</b>. * <!-- end-user-doc --> * @generated */ public class JavaRulePackageImpl extends EPackageImpl implements JavaRulePackage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass ruleSetEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass sentenceEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass variableEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass ruleEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass orEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass andEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass primaryOpEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass propertyLiteralEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass propertyEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass fileEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass packageEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass interfaceEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass classEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass enumerationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass methodEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass attributeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass isImplementedEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass isSuperInterfaceEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass isSuperClassEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass isSubClassEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass implementsEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass extendsEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass rangoNamesEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass tamanioEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass parameterEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass constructorEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass returnEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass attributeTypeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass initializeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass emptyEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass isGenericEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass nameOperationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass stringPropertyEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass stringVariableEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass variableSubtypeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass stringValueEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass nameTypeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass containsEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass javaDocEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass modifiersEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass blendModifiersEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass typePropertyEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass typePrimitiveEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass isPrimitiveFuntionEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass isCollectionTypeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum quantifierEEnum = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum elementEEnum = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum elementStringEEnum = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum languageEEnum = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum nameCheckEEnum = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum nameOperatorEEnum = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum accessModifierEEnum = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum primitiveEEnum = null; /** * Creates an instance of the model <b>Package</b>, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * <p>Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.emf.ecore.EPackage.Registry * @see javaRule.JavaRulePackage#eNS_URI * @see #init() * @generated */ private JavaRulePackageImpl() { super(eNS_URI, JavaRuleFactory.eINSTANCE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. * * <p>This method is used to initialize {@link JavaRulePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static JavaRulePackage init() { if (isInited) return (JavaRulePackage)EPackage.Registry.INSTANCE.getEPackage(JavaRulePackage.eNS_URI); // Obtain or create and register package JavaRulePackageImpl theJavaRulePackage = (JavaRulePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof JavaRulePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new JavaRulePackageImpl()); isInited = true; // Create package meta-data objects theJavaRulePackage.createPackageContents(); // Initialize created meta-data theJavaRulePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theJavaRulePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(JavaRulePackage.eNS_URI, theJavaRulePackage); return theJavaRulePackage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getRuleSet() { return ruleSetEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getRuleSet_ProjectName() { return (EAttribute)ruleSetEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getRuleSet_Sentences() { return (EReference)ruleSetEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getSentence() { return sentenceEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getSentence_Element() { return (EAttribute)sentenceEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getSentence_From() { return (EReference)sentenceEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getSentence_In() { return (EReference)sentenceEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getSentence_Satisfy() { return (EReference)sentenceEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getSentence_Using() { return (EReference)sentenceEClass.getEStructuralFeatures().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getSentence_Name() { return (EAttribute)sentenceEClass.getEStructuralFeatures().get(5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getVariable() { return variableEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getRule() { return ruleEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getRule_No() { return (EAttribute)ruleEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getRule_Quantifier() { return (EAttribute)ruleEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getRule_Filter() { return (EReference)ruleEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getOr() { return orEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getOr_Op() { return (EReference)orEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getAnd() { return andEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getAnd_Op() { return (EReference)andEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getPrimaryOp() { return primaryOpEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getPropertyLiteral() { return propertyLiteralEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getPropertyLiteral_Property() { return (EReference)propertyLiteralEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getProperty() { return propertyEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getProperty_No() { return (EAttribute)propertyEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getFile() { return fileEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getPackage() { return packageEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getInterface() { return interfaceEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getClass_() { return classEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getEnumeration() { return enumerationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getMethod() { return methodEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getAttribute() { return attributeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getIsImplemented() { return isImplementedEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getIsImplemented_Valores() { return (EReference)isImplementedEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getIsSuperInterface() { return isSuperInterfaceEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getIsSuperInterface_Valores() { return (EReference)isSuperInterfaceEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getIsSuperClass() { return isSuperClassEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getIsSuperClass_Valores() { return (EReference)isSuperClassEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getIsSubClass() { return isSubClassEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getIsSubClass_Of() { return (EReference)isSubClassEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getImplements() { return implementsEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getImplements_Valores() { return (EReference)implementsEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getExtends() { return extendsEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getExtends_Valores() { return (EReference)extendsEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getRangoNames() { return rangoNamesEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getRangoNames_Min() { return (EAttribute)rangoNamesEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getRangoNames_Max() { return (EAttribute)rangoNamesEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getRangoNames_Types() { return (EReference)rangoNamesEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getTamanio() { return tamanioEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getTamanio_Min() { return (EAttribute)tamanioEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getTamanio_Max() { return (EAttribute)tamanioEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getTamanio_Exact() { return (EAttribute)tamanioEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getParameter() { return parameterEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getParameter_Min() { return (EAttribute)parameterEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getParameter_Max() { return (EAttribute)parameterEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getParameter_Exact() { return (EAttribute)parameterEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getParameter_Types() { return (EReference)parameterEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getConstructor() { return constructorEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getReturn() { return returnEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getReturn_Type() { return (EReference)returnEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getAttributeType() { return attributeTypeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getAttributeType_Type() { return (EReference)attributeTypeEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getInitialize() { return initializeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getEmpty() { return emptyEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getIsGeneric() { return isGenericEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getNameOperation() { return nameOperationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getNameOperation_Operator() { return (EAttribute)nameOperationEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getNameOperation_Language() { return (EAttribute)nameOperationEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getNameOperation_Name() { return (EReference)nameOperationEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getStringProperty() { return stringPropertyEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getStringVariable() { return stringVariableEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getStringVariable_Variable() { return (EReference)stringVariableEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getStringVariable_Strings() { return (EAttribute)stringVariableEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getVariableSubtype() { return variableSubtypeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getVariableSubtype_Variable() { return (EReference)variableSubtypeEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getVariableSubtype_Subtype() { return (EAttribute)variableSubtypeEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getStringValue() { return stringValueEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getStringValue_Value() { return (EAttribute)stringValueEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getNameType() { return nameTypeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getNameType_Type() { return (EAttribute)nameTypeEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getContains() { return containsEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getContains_Rule() { return (EReference)containsEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getJavaDoc() { return javaDocEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getJavaDoc_Author() { return (EAttribute)javaDocEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getJavaDoc_Parameter() { return (EAttribute)javaDocEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getJavaDoc_Return() { return (EAttribute)javaDocEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getJavaDoc_Version() { return (EAttribute)javaDocEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getJavaDoc_Throws() { return (EAttribute)javaDocEClass.getEStructuralFeatures().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getJavaDoc_See() { return (EAttribute)javaDocEClass.getEStructuralFeatures().get(5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getModifiers() { return modifiersEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getModifiers_Blend() { return (EReference)modifiersEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getBlendModifiers() { return blendModifiersEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getBlendModifiers_Access() { return (EAttribute)blendModifiersEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getBlendModifiers_Static() { return (EAttribute)blendModifiersEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getBlendModifiers_Final() { return (EAttribute)blendModifiersEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getBlendModifiers_Abstract() { return (EAttribute)blendModifiersEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getBlendModifiers_Default() { return (EAttribute)blendModifiersEClass.getEStructuralFeatures().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getBlendModifiers_Synchronized() { return (EAttribute)blendModifiersEClass.getEStructuralFeatures().get(5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getTypeProperty() { return typePropertyEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getTypePrimitive() { return typePrimitiveEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EAttribute getTypePrimitive_TypePrimitive() { return (EAttribute)typePrimitiveEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getIsPrimitiveFuntion() { return isPrimitiveFuntionEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getIsCollectionType() { return isCollectionTypeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getIsCollectionType_Of() { return (EReference)isCollectionTypeEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getQuantifier() { return quantifierEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getElement() { return elementEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getElementString() { return elementStringEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getLanguage() { return languageEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getNameCheck() { return nameCheckEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getNameOperator() { return nameOperatorEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getAccessModifier() { return accessModifierEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EEnum getPrimitive() { return primitiveEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public JavaRuleFactory getJavaRuleFactory() { return (JavaRuleFactory)getEFactoryInstance(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features ruleSetEClass = createEClass(RULE_SET); createEAttribute(ruleSetEClass, RULE_SET__PROJECT_NAME); createEReference(ruleSetEClass, RULE_SET__SENTENCES); sentenceEClass = createEClass(SENTENCE); createEAttribute(sentenceEClass, SENTENCE__ELEMENT); createEReference(sentenceEClass, SENTENCE__FROM); createEReference(sentenceEClass, SENTENCE__IN); createEReference(sentenceEClass, SENTENCE__SATISFY); createEReference(sentenceEClass, SENTENCE__USING); createEAttribute(sentenceEClass, SENTENCE__NAME); variableEClass = createEClass(VARIABLE); ruleEClass = createEClass(RULE); createEAttribute(ruleEClass, RULE__NO); createEAttribute(ruleEClass, RULE__QUANTIFIER); createEReference(ruleEClass, RULE__FILTER); orEClass = createEClass(OR); createEReference(orEClass, OR__OP); andEClass = createEClass(AND); createEReference(andEClass, AND__OP); primaryOpEClass = createEClass(PRIMARY_OP); propertyLiteralEClass = createEClass(PROPERTY_LITERAL); createEReference(propertyLiteralEClass, PROPERTY_LITERAL__PROPERTY); propertyEClass = createEClass(PROPERTY); createEAttribute(propertyEClass, PROPERTY__NO); fileEClass = createEClass(FILE); packageEClass = createEClass(PACKAGE); interfaceEClass = createEClass(INTERFACE); classEClass = createEClass(CLASS); enumerationEClass = createEClass(ENUMERATION); methodEClass = createEClass(METHOD); attributeEClass = createEClass(ATTRIBUTE); isImplementedEClass = createEClass(IS_IMPLEMENTED); createEReference(isImplementedEClass, IS_IMPLEMENTED__VALORES); isSuperInterfaceEClass = createEClass(IS_SUPER_INTERFACE); createEReference(isSuperInterfaceEClass, IS_SUPER_INTERFACE__VALORES); isSuperClassEClass = createEClass(IS_SUPER_CLASS); createEReference(isSuperClassEClass, IS_SUPER_CLASS__VALORES); isSubClassEClass = createEClass(IS_SUB_CLASS); createEReference(isSubClassEClass, IS_SUB_CLASS__OF); implementsEClass = createEClass(IMPLEMENTS); createEReference(implementsEClass, IMPLEMENTS__VALORES); extendsEClass = createEClass(EXTENDS); createEReference(extendsEClass, EXTENDS__VALORES); rangoNamesEClass = createEClass(RANGO_NAMES); createEAttribute(rangoNamesEClass, RANGO_NAMES__MIN); createEAttribute(rangoNamesEClass, RANGO_NAMES__MAX); createEReference(rangoNamesEClass, RANGO_NAMES__TYPES); tamanioEClass = createEClass(TAMANIO); createEAttribute(tamanioEClass, TAMANIO__MIN); createEAttribute(tamanioEClass, TAMANIO__MAX); createEAttribute(tamanioEClass, TAMANIO__EXACT); parameterEClass = createEClass(PARAMETER); createEAttribute(parameterEClass, PARAMETER__MIN); createEAttribute(parameterEClass, PARAMETER__MAX); createEAttribute(parameterEClass, PARAMETER__EXACT); createEReference(parameterEClass, PARAMETER__TYPES); constructorEClass = createEClass(CONSTRUCTOR); returnEClass = createEClass(RETURN); createEReference(returnEClass, RETURN__TYPE); attributeTypeEClass = createEClass(ATTRIBUTE_TYPE); createEReference(attributeTypeEClass, ATTRIBUTE_TYPE__TYPE); initializeEClass = createEClass(INITIALIZE); emptyEClass = createEClass(EMPTY); isGenericEClass = createEClass(IS_GENERIC); nameOperationEClass = createEClass(NAME_OPERATION); createEAttribute(nameOperationEClass, NAME_OPERATION__OPERATOR); createEAttribute(nameOperationEClass, NAME_OPERATION__LANGUAGE); createEReference(nameOperationEClass, NAME_OPERATION__NAME); stringPropertyEClass = createEClass(STRING_PROPERTY); stringVariableEClass = createEClass(STRING_VARIABLE); createEReference(stringVariableEClass, STRING_VARIABLE__VARIABLE); createEAttribute(stringVariableEClass, STRING_VARIABLE__STRINGS); variableSubtypeEClass = createEClass(VARIABLE_SUBTYPE); createEReference(variableSubtypeEClass, VARIABLE_SUBTYPE__VARIABLE); createEAttribute(variableSubtypeEClass, VARIABLE_SUBTYPE__SUBTYPE); stringValueEClass = createEClass(STRING_VALUE); createEAttribute(stringValueEClass, STRING_VALUE__VALUE); nameTypeEClass = createEClass(NAME_TYPE); createEAttribute(nameTypeEClass, NAME_TYPE__TYPE); containsEClass = createEClass(CONTAINS); createEReference(containsEClass, CONTAINS__RULE); javaDocEClass = createEClass(JAVA_DOC); createEAttribute(javaDocEClass, JAVA_DOC__AUTHOR); createEAttribute(javaDocEClass, JAVA_DOC__PARAMETER); createEAttribute(javaDocEClass, JAVA_DOC__RETURN); createEAttribute(javaDocEClass, JAVA_DOC__VERSION); createEAttribute(javaDocEClass, JAVA_DOC__THROWS); createEAttribute(javaDocEClass, JAVA_DOC__SEE); modifiersEClass = createEClass(MODIFIERS); createEReference(modifiersEClass, MODIFIERS__BLEND); blendModifiersEClass = createEClass(BLEND_MODIFIERS); createEAttribute(blendModifiersEClass, BLEND_MODIFIERS__ACCESS); createEAttribute(blendModifiersEClass, BLEND_MODIFIERS__STATIC); createEAttribute(blendModifiersEClass, BLEND_MODIFIERS__FINAL); createEAttribute(blendModifiersEClass, BLEND_MODIFIERS__ABSTRACT); createEAttribute(blendModifiersEClass, BLEND_MODIFIERS__DEFAULT); createEAttribute(blendModifiersEClass, BLEND_MODIFIERS__SYNCHRONIZED); typePropertyEClass = createEClass(TYPE_PROPERTY); typePrimitiveEClass = createEClass(TYPE_PRIMITIVE); createEAttribute(typePrimitiveEClass, TYPE_PRIMITIVE__TYPE_PRIMITIVE); isPrimitiveFuntionEClass = createEClass(IS_PRIMITIVE_FUNTION); isCollectionTypeEClass = createEClass(IS_COLLECTION_TYPE); createEReference(isCollectionTypeEClass, IS_COLLECTION_TYPE__OF); // Create enums quantifierEEnum = createEEnum(QUANTIFIER); elementEEnum = createEEnum(ELEMENT); elementStringEEnum = createEEnum(ELEMENT_STRING); languageEEnum = createEEnum(LANGUAGE); nameCheckEEnum = createEEnum(NAME_CHECK); nameOperatorEEnum = createEEnum(NAME_OPERATOR); accessModifierEEnum = createEEnum(ACCESS_MODIFIER); primitiveEEnum = createEEnum(PRIMITIVE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes variableEClass.getESuperTypes().add(this.getSentence()); ruleEClass.getESuperTypes().add(this.getSentence()); orEClass.getESuperTypes().add(this.getPrimaryOp()); propertyLiteralEClass.getESuperTypes().add(this.getPrimaryOp()); fileEClass.getESuperTypes().add(this.getProperty()); packageEClass.getESuperTypes().add(this.getProperty()); interfaceEClass.getESuperTypes().add(this.getProperty()); classEClass.getESuperTypes().add(this.getProperty()); enumerationEClass.getESuperTypes().add(this.getProperty()); methodEClass.getESuperTypes().add(this.getProperty()); attributeEClass.getESuperTypes().add(this.getProperty()); isImplementedEClass.getESuperTypes().add(this.getInterface()); isSuperInterfaceEClass.getESuperTypes().add(this.getInterface()); isSuperClassEClass.getESuperTypes().add(this.getClass_()); isSubClassEClass.getESuperTypes().add(this.getClass_()); implementsEClass.getESuperTypes().add(this.getClass_()); implementsEClass.getESuperTypes().add(this.getEnumeration()); extendsEClass.getESuperTypes().add(this.getInterface()); tamanioEClass.getESuperTypes().add(this.getMethod()); tamanioEClass.getESuperTypes().add(this.getClass_()); tamanioEClass.getESuperTypes().add(this.getFile()); tamanioEClass.getESuperTypes().add(this.getInterface()); tamanioEClass.getESuperTypes().add(this.getEnumeration()); parameterEClass.getESuperTypes().add(this.getMethod()); constructorEClass.getESuperTypes().add(this.getMethod()); returnEClass.getESuperTypes().add(this.getMethod()); attributeTypeEClass.getESuperTypes().add(this.getAttribute()); initializeEClass.getESuperTypes().add(this.getAttribute()); emptyEClass.getESuperTypes().add(this.getPackage()); emptyEClass.getESuperTypes().add(this.getMethod()); emptyEClass.getESuperTypes().add(this.getClass_()); emptyEClass.getESuperTypes().add(this.getInterface()); emptyEClass.getESuperTypes().add(this.getEnumeration()); emptyEClass.getESuperTypes().add(this.getFile()); isGenericEClass.getESuperTypes().add(this.getClass_()); isGenericEClass.getESuperTypes().add(this.getInterface()); isGenericEClass.getESuperTypes().add(this.getMethod()); isGenericEClass.getESuperTypes().add(this.getAttribute()); nameOperationEClass.getESuperTypes().add(this.getAttribute()); nameOperationEClass.getESuperTypes().add(this.getClass_()); nameOperationEClass.getESuperTypes().add(this.getMethod()); nameOperationEClass.getESuperTypes().add(this.getPackage()); nameOperationEClass.getESuperTypes().add(this.getInterface()); nameOperationEClass.getESuperTypes().add(this.getEnumeration()); nameOperationEClass.getESuperTypes().add(this.getFile()); stringPropertyEClass.getESuperTypes().add(this.getTypeProperty()); stringVariableEClass.getESuperTypes().add(this.getStringProperty()); stringValueEClass.getESuperTypes().add(this.getStringProperty()); nameTypeEClass.getESuperTypes().add(this.getAttribute()); nameTypeEClass.getESuperTypes().add(this.getClass_()); nameTypeEClass.getESuperTypes().add(this.getMethod()); nameTypeEClass.getESuperTypes().add(this.getPackage()); nameTypeEClass.getESuperTypes().add(this.getInterface()); nameTypeEClass.getESuperTypes().add(this.getEnumeration()); nameTypeEClass.getESuperTypes().add(this.getFile()); containsEClass.getESuperTypes().add(this.getClass_()); containsEClass.getESuperTypes().add(this.getEnumeration()); containsEClass.getESuperTypes().add(this.getFile()); containsEClass.getESuperTypes().add(this.getInterface()); containsEClass.getESuperTypes().add(this.getPackage()); javaDocEClass.getESuperTypes().add(this.getAttribute()); javaDocEClass.getESuperTypes().add(this.getClass_()); javaDocEClass.getESuperTypes().add(this.getMethod()); javaDocEClass.getESuperTypes().add(this.getInterface()); javaDocEClass.getESuperTypes().add(this.getEnumeration()); modifiersEClass.getESuperTypes().add(this.getAttribute()); modifiersEClass.getESuperTypes().add(this.getClass_()); modifiersEClass.getESuperTypes().add(this.getMethod()); modifiersEClass.getESuperTypes().add(this.getEnumeration()); modifiersEClass.getESuperTypes().add(this.getInterface()); typePrimitiveEClass.getESuperTypes().add(this.getTypeProperty()); isPrimitiveFuntionEClass.getESuperTypes().add(this.getTypeProperty()); isCollectionTypeEClass.getESuperTypes().add(this.getTypeProperty()); // Initialize classes, features, and operations; add parameters initEClass(ruleSetEClass, RuleSet.class, "RuleSet", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getRuleSet_ProjectName(), ecorePackage.getEString(), "ProjectName", null, 0, -1, RuleSet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getRuleSet_Sentences(), this.getSentence(), null, "sentences", null, 0, -1, RuleSet.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(sentenceEClass, Sentence.class, "Sentence", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSentence_Element(), this.getElement(), "element", null, 1, 1, Sentence.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getSentence_From(), this.getVariable(), null, "from", null, 0, 1, Sentence.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getSentence_In(), this.getVariable(), null, "in", null, 0, -1, Sentence.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getSentence_Satisfy(), this.getOr(), null, "satisfy", null, 0, 1, Sentence.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getSentence_Using(), this.getVariableSubtype(), null, "using", null, 0, -1, Sentence.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSentence_Name(), ecorePackage.getEString(), "name", null, 0, 1, Sentence.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(variableEClass, Variable.class, "Variable", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(ruleEClass, Rule.class, "Rule", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getRule_No(), ecorePackage.getEBoolean(), "no", "false", 1, 1, Rule.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getRule_Quantifier(), this.getQuantifier(), "quantifier", null, 1, 1, Rule.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getRule_Filter(), this.getOr(), null, "filter", null, 0, 1, Rule.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(orEClass, Or.class, "Or", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getOr_Op(), this.getAnd(), null, "op", null, 1, -1, Or.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(andEClass, And.class, "And", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getAnd_Op(), this.getPrimaryOp(), null, "op", null, 1, -1, And.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(primaryOpEClass, PrimaryOp.class, "PrimaryOp", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(propertyLiteralEClass, PropertyLiteral.class, "PropertyLiteral", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getPropertyLiteral_Property(), this.getProperty(), null, "property", null, 1, 1, PropertyLiteral.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(propertyEClass, Property.class, "Property", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getProperty_No(), ecorePackage.getEBoolean(), "no", "false", 1, 1, Property.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(fileEClass, File.class, "File", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(packageEClass, javaRule.Package.class, "Package", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(interfaceEClass, Interface.class, "Interface", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(classEClass, javaRule.Class.class, "Class", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(enumerationEClass, Enumeration.class, "Enumeration", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(methodEClass, Method.class, "Method", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(attributeEClass, Attribute.class, "Attribute", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(isImplementedEClass, IsImplemented.class, "IsImplemented", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getIsImplemented_Valores(), this.getRangoNames(), null, "valores", null, 1, 1, IsImplemented.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(isSuperInterfaceEClass, IsSuperInterface.class, "IsSuperInterface", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getIsSuperInterface_Valores(), this.getRangoNames(), null, "valores", null, 1, 1, IsSuperInterface.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(isSuperClassEClass, IsSuperClass.class, "IsSuperClass", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getIsSuperClass_Valores(), this.getRangoNames(), null, "valores", null, 1, 1, IsSuperClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(isSubClassEClass, IsSubClass.class, "IsSubClass", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getIsSubClass_Of(), this.getStringProperty(), null, "of", null, 0, 1, IsSubClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(implementsEClass, Implements.class, "Implements", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getImplements_Valores(), this.getRangoNames(), null, "valores", null, 1, 1, Implements.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(extendsEClass, Extends.class, "Extends", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getExtends_Valores(), this.getRangoNames(), null, "valores", null, 1, 1, Extends.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(rangoNamesEClass, RangoNames.class, "RangoNames", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getRangoNames_Min(), ecorePackage.getEInt(), "min", "1", 0, 1, RangoNames.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getRangoNames_Max(), ecorePackage.getEInt(), "max", "2147483647", 0, 1, RangoNames.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getRangoNames_Types(), this.getStringProperty(), null, "types", null, 0, -1, RangoNames.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(tamanioEClass, Tamanio.class, "Tamanio", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getTamanio_Min(), ecorePackage.getEInt(), "min", "1", 0, 1, Tamanio.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getTamanio_Max(), ecorePackage.getEInt(), "max", "2147483647", 0, 1, Tamanio.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getTamanio_Exact(), ecorePackage.getEInt(), "exact", "-2147483647", 0, 1, Tamanio.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(parameterEClass, Parameter.class, "Parameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getParameter_Min(), ecorePackage.getEInt(), "min", "1", 0, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getParameter_Max(), ecorePackage.getEInt(), "max", "2147483647", 0, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getParameter_Exact(), ecorePackage.getEInt(), "exact", "-2147483647", 0, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getParameter_Types(), this.getTypeProperty(), null, "types", null, 0, -1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(constructorEClass, Constructor.class, "Constructor", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(returnEClass, Return.class, "Return", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getReturn_Type(), this.getTypeProperty(), null, "type", null, 1, 1, Return.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(attributeTypeEClass, AttributeType.class, "AttributeType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getAttributeType_Type(), this.getTypeProperty(), null, "type", null, 1, 1, AttributeType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(initializeEClass, Initialize.class, "Initialize", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(emptyEClass, Empty.class, "Empty", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(isGenericEClass, IsGeneric.class, "IsGeneric", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(nameOperationEClass, NameOperation.class, "NameOperation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getNameOperation_Operator(), this.getNameOperator(), "operator", "EQUAL", 1, 1, NameOperation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getNameOperation_Language(), this.getLanguage(), "Language", "EMPTY", 0, 1, NameOperation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getNameOperation_Name(), this.getStringProperty(), null, "name", null, 1, 1, NameOperation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(stringPropertyEClass, StringProperty.class, "StringProperty", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(stringVariableEClass, StringVariable.class, "StringVariable", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getStringVariable_Variable(), this.getVariableSubtype(), null, "variable", null, 0, 1, StringVariable.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getStringVariable_Strings(), this.getElementString(), "strings", null, 1, 1, StringVariable.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(variableSubtypeEClass, VariableSubtype.class, "VariableSubtype", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getVariableSubtype_Variable(), this.getVariable(), null, "variable", null, 0, 1, VariableSubtype.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getVariableSubtype_Subtype(), this.getElement(), "subtype", null, 0, 1, VariableSubtype.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(stringValueEClass, StringValue.class, "StringValue", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getStringValue_Value(), ecorePackage.getEString(), "value", null, 1, 1, StringValue.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(nameTypeEClass, NameType.class, "NameType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getNameType_Type(), this.getNameCheck(), "type", "UPPER_CASE", 1, 1, NameType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(containsEClass, Contains.class, "Contains", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getContains_Rule(), this.getRule(), null, "rule", null, 1, 1, Contains.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(javaDocEClass, JavaDoc.class, "JavaDoc", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getJavaDoc_Author(), ecorePackage.getEBoolean(), "author", "false", 1, 1, JavaDoc.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getJavaDoc_Parameter(), ecorePackage.getEBoolean(), "parameter", "false", 1, 1, JavaDoc.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getJavaDoc_Return(), ecorePackage.getEBoolean(), "return", "false", 1, 1, JavaDoc.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getJavaDoc_Version(), ecorePackage.getEBoolean(), "version", "false", 1, 1, JavaDoc.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getJavaDoc_Throws(), ecorePackage.getEBoolean(), "throws", "false", 1, 1, JavaDoc.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getJavaDoc_See(), ecorePackage.getEBoolean(), "see", "false", 1, 1, JavaDoc.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(modifiersEClass, Modifiers.class, "Modifiers", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModifiers_Blend(), this.getBlendModifiers(), null, "blend", null, 1, -1, Modifiers.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(blendModifiersEClass, BlendModifiers.class, "BlendModifiers", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getBlendModifiers_Access(), this.getAccessModifier(), "access", "nothing", 0, 1, BlendModifiers.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getBlendModifiers_Static(), ecorePackage.getEBoolean(), "static", "false", 1, 1, BlendModifiers.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getBlendModifiers_Final(), ecorePackage.getEBoolean(), "final", "false", 1, 1, BlendModifiers.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getBlendModifiers_Abstract(), ecorePackage.getEBoolean(), "abstract", "false", 1, 1, BlendModifiers.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getBlendModifiers_Default(), ecorePackage.getEBoolean(), "default", "false", 1, 1, BlendModifiers.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getBlendModifiers_Synchronized(), ecorePackage.getEBoolean(), "synchronized", "false", 1, 1, BlendModifiers.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(typePropertyEClass, TypeProperty.class, "TypeProperty", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(typePrimitiveEClass, TypePrimitive.class, "TypePrimitive", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getTypePrimitive_TypePrimitive(), this.getPrimitive(), "typePrimitive", null, 0, 1, TypePrimitive.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(isPrimitiveFuntionEClass, IsPrimitiveFuntion.class, "IsPrimitiveFuntion", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(isCollectionTypeEClass, IsCollectionType.class, "IsCollectionType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getIsCollectionType_Of(), this.getTypeProperty(), null, "of", null, 0, 1, IsCollectionType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Initialize enums and add enum literals initEEnum(quantifierEEnum, Quantifier.class, "Quantifier"); addEEnumLiteral(quantifierEEnum, Quantifier.ONE); addEEnumLiteral(quantifierEEnum, Quantifier.EXISTS); addEEnumLiteral(quantifierEEnum, Quantifier.ALL); initEEnum(elementEEnum, Element.class, "Element"); addEEnumLiteral(elementEEnum, Element.NULL); addEEnumLiteral(elementEEnum, Element.PACKAGE); addEEnumLiteral(elementEEnum, Element.CLASS); addEEnumLiteral(elementEEnum, Element.INTERFACE); addEEnumLiteral(elementEEnum, Element.ENUMERATION); addEEnumLiteral(elementEEnum, Element.METHOD); addEEnumLiteral(elementEEnum, Element.ATTRIBUTE); addEEnumLiteral(elementEEnum, Element.FILE); initEEnum(elementStringEEnum, ElementString.class, "ElementString"); addEEnumLiteral(elementStringEEnum, ElementString.NAME); addEEnumLiteral(elementStringEEnum, ElementString.TYPE); initEEnum(languageEEnum, Language.class, "Language"); addEEnumLiteral(languageEEnum, Language.EMPTY); addEEnumLiteral(languageEEnum, Language.SPANISH); addEEnumLiteral(languageEEnum, Language.ENGLISH); initEEnum(nameCheckEEnum, NameCheck.class, "NameCheck"); addEEnumLiteral(nameCheckEEnum, NameCheck.UPPER_CASE); addEEnumLiteral(nameCheckEEnum, NameCheck.LOWER_CASE); addEEnumLiteral(nameCheckEEnum, NameCheck.UPPER_CAMEL_CASE); addEEnumLiteral(nameCheckEEnum, NameCheck.LOWER_CAMEL_CASE); addEEnumLiteral(nameCheckEEnum, NameCheck.START_UPPER_CASE); initEEnum(nameOperatorEEnum, NameOperator.class, "NameOperator"); addEEnumLiteral(nameOperatorEEnum, NameOperator.EQUAL); addEEnumLiteral(nameOperatorEEnum, NameOperator.START); addEEnumLiteral(nameOperatorEEnum, NameOperator.END); addEEnumLiteral(nameOperatorEEnum, NameOperator.CONTAIN); addEEnumLiteral(nameOperatorEEnum, NameOperator.LIKE); initEEnum(accessModifierEEnum, AccessModifier.class, "AccessModifier"); addEEnumLiteral(accessModifierEEnum, AccessModifier.NOTHING); addEEnumLiteral(accessModifierEEnum, AccessModifier.PUBLIC); addEEnumLiteral(accessModifierEEnum, AccessModifier.PROTECTED); addEEnumLiteral(accessModifierEEnum, AccessModifier.PRIVATE); initEEnum(primitiveEEnum, Primitive.class, "Primitive"); addEEnumLiteral(primitiveEEnum, Primitive.BYTE); addEEnumLiteral(primitiveEEnum, Primitive.SHORT); addEEnumLiteral(primitiveEEnum, Primitive.INT); addEEnumLiteral(primitiveEEnum, Primitive.LONG); addEEnumLiteral(primitiveEEnum, Primitive.FLOAT); addEEnumLiteral(primitiveEEnum, Primitive.DOUBLE); addEEnumLiteral(primitiveEEnum, Primitive.BOOLEAN); addEEnumLiteral(primitiveEEnum, Primitive.CHAR); addEEnumLiteral(primitiveEEnum, Primitive.STRING); // Create resource createResource(eNS_URI); } } //JavaRulePackageImpl <file_sep>/Code/es.uam.sara.tfg.ast2/src/Test.java import java.beans.beancontext.BeanContext; import java.util.ArrayList; import java.util.Collection; import java.util.List; public abstract class Test<T, K> implements Collection<T>, List<T>{ public BeanContext num; public ArrayList<Integer> in; public ColeccionInt i; public int getNumCasa(List<List<T>> i) { return 1; } public int compareTo(T arg0) { // TODO Auto-generated method stub return 0; } public String toString() { return "Test []"; } public static void prueba(String a, String b, String i, int j) { } }<file_sep>/Code/es.uam.sara.tfg.dsl.editor/xtend-gen/es/uam/sara/tfg/dsl/validation/JRuleValidator.java /** * generated by Xtext 2.9.2 */ package es.uam.sara.tfg.dsl.validation; import es.uam.sara.tfg.dsl.validation.AbstractJRuleValidator; /** * This class contains custom validation rules. * * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#validation */ @SuppressWarnings("all") public class JRuleValidator extends AbstractJRuleValidator { } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/elements/JavaElement.java package es.uam.sara.tfg.elements; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.Javadoc; import es.uam.sara.tfg.ast.UnitVisitor; import es.uam.sara.tfg.properties.BlendModifiers; import es.uam.sara.tfg.properties.all.Modifiers; public abstract class JavaElement implements IElements, IPosicionable{ private BodyDeclaration bd; private UnitVisitor uv; public JavaElement(BodyDeclaration bd, UnitVisitor uv){ this.uv=uv; this.bd=bd; } public BlendModifiers getModifiers(){ return Modifiers.getBlend(bd); } public Javadoc getJavadoc(){ return bd.getJavadoc(); } public BodyDeclaration getBodyDeclaration(){ return bd; } public int getStartLine(){ if (getJavadoc()!=null){ return uv.getLineNumber(bd.getStartPosition()+getJavadoc().getLength()); } return uv.getLineNumber(bd.getStartPosition()); } public int getEndLine(){ return uv.getLineNumber(bd.getStartPosition()+bd.getLength()-1); } public UnitVisitor getVisitor(){ return uv; } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/all/ContainClass.java package es.uam.sara.tfg.properties.all; import java.util.List; import es.uam.sara.tfg.elements.Container; import es.uam.sara.tfg.elements.type.MClass; import es.uam.sara.tfg.sentence.Rule; public class ContainClass<T extends Container> extends Contain<T, MClass> { public ContainClass(boolean no,Rule<MClass> r) { super(no, r); } @Override public List<MClass> getSubType(Container t) { return t.getClasses(); } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/Hola.java public enum Hola { Casa(0), Hotel(1); int i; private Hola (int i){ this.i=i; } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/sentence/PrimaryOp.java package es.uam.sara.tfg.sentence; import es.uam.sara.tfg.elements.IElements; import es.uam.sara.tfg.properties.Checkeable; public abstract class PrimaryOp <T extends IElements> extends Checkeable<T>{ public PrimaryOp(boolean no) { super(no); } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/Modifiers.java /** */ package javaRule; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Modifiers</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link javaRule.Modifiers#getBlend <em>Blend</em>}</li> * </ul> * * @see javaRule.JavaRulePackage#getModifiers() * @model * @generated */ public interface Modifiers extends Attribute, javaRule.Class, Method, Enumeration, Interface { /** * Returns the value of the '<em><b>Blend</b></em>' containment reference list. * The list contents are of type {@link javaRule.BlendModifiers}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Blend</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Blend</em>' containment reference list. * @see javaRule.JavaRulePackage#getModifiers_Blend() * @model containment="true" required="true" * @generated */ EList<BlendModifiers> getBlend(); } // Modifiers <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/RuleImpl.java /** */ package javaRule.impl; import javaRule.JavaRulePackage; import javaRule.Or; import javaRule.Quantifier; import javaRule.Rule; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Rule</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link javaRule.impl.RuleImpl#isNo <em>No</em>}</li> * <li>{@link javaRule.impl.RuleImpl#getQuantifier <em>Quantifier</em>}</li> * <li>{@link javaRule.impl.RuleImpl#getFilter <em>Filter</em>}</li> * </ul> * * @generated */ public class RuleImpl extends SentenceImpl implements Rule { /** * The default value of the '{@link #isNo() <em>No</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isNo() * @generated * @ordered */ protected static final boolean NO_EDEFAULT = false; /** * The cached value of the '{@link #isNo() <em>No</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isNo() * @generated * @ordered */ protected boolean no = NO_EDEFAULT; /** * The default value of the '{@link #getQuantifier() <em>Quantifier</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getQuantifier() * @generated * @ordered */ protected static final Quantifier QUANTIFIER_EDEFAULT = Quantifier.ONE; /** * The cached value of the '{@link #getQuantifier() <em>Quantifier</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getQuantifier() * @generated * @ordered */ protected Quantifier quantifier = QUANTIFIER_EDEFAULT; /** * The cached value of the '{@link #getFilter() <em>Filter</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFilter() * @generated * @ordered */ protected Or filter; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected RuleImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.RULE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isNo() { return no; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setNo(boolean newNo) { boolean oldNo = no; no = newNo; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.RULE__NO, oldNo, no)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Quantifier getQuantifier() { return quantifier; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setQuantifier(Quantifier newQuantifier) { Quantifier oldQuantifier = quantifier; quantifier = newQuantifier == null ? QUANTIFIER_EDEFAULT : newQuantifier; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.RULE__QUANTIFIER, oldQuantifier, quantifier)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Or getFilter() { return filter; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetFilter(Or newFilter, NotificationChain msgs) { Or oldFilter = filter; filter = newFilter; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, JavaRulePackage.RULE__FILTER, oldFilter, newFilter); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFilter(Or newFilter) { if (newFilter != filter) { NotificationChain msgs = null; if (filter != null) msgs = ((InternalEObject)filter).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - JavaRulePackage.RULE__FILTER, null, msgs); if (newFilter != null) msgs = ((InternalEObject)newFilter).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - JavaRulePackage.RULE__FILTER, null, msgs); msgs = basicSetFilter(newFilter, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.RULE__FILTER, newFilter, newFilter)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case JavaRulePackage.RULE__FILTER: return basicSetFilter(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case JavaRulePackage.RULE__NO: return isNo(); case JavaRulePackage.RULE__QUANTIFIER: return getQuantifier(); case JavaRulePackage.RULE__FILTER: return getFilter(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case JavaRulePackage.RULE__NO: setNo((Boolean)newValue); return; case JavaRulePackage.RULE__QUANTIFIER: setQuantifier((Quantifier)newValue); return; case JavaRulePackage.RULE__FILTER: setFilter((Or)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case JavaRulePackage.RULE__NO: setNo(NO_EDEFAULT); return; case JavaRulePackage.RULE__QUANTIFIER: setQuantifier(QUANTIFIER_EDEFAULT); return; case JavaRulePackage.RULE__FILTER: setFilter((Or)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case JavaRulePackage.RULE__NO: return no != NO_EDEFAULT; case JavaRulePackage.RULE__QUANTIFIER: return quantifier != QUANTIFIER_EDEFAULT; case JavaRulePackage.RULE__FILTER: return filter != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (no: "); result.append(no); result.append(", quantifier: "); result.append(quantifier); result.append(')'); return result.toString(); } } //RuleImpl <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/IsGenericImpl.java /** */ package javaRule.impl; import javaRule.IsGeneric; import javaRule.JavaRulePackage; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Is Generic</b></em>'. * <!-- end-user-doc --> * * @generated */ public class IsGenericImpl extends ClassImpl implements IsGeneric { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IsGenericImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.IS_GENERIC; } } //IsGenericImpl <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/TypePrimitive.java /** */ package javaRule; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Type Primitive</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link javaRule.TypePrimitive#getTypePrimitive <em>Type Primitive</em>}</li> * </ul> * * @see javaRule.JavaRulePackage#getTypePrimitive() * @model * @generated */ public interface TypePrimitive extends TypeProperty { /** * Returns the value of the '<em><b>Type Primitive</b></em>' attribute. * The literals are from the enumeration {@link javaRule.Primitive}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type Primitive</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type Primitive</em>' attribute. * @see javaRule.Primitive * @see #setTypePrimitive(Primitive) * @see javaRule.JavaRulePackage#getTypePrimitive_TypePrimitive() * @model * @generated */ Primitive getTypePrimitive(); /** * Sets the value of the '{@link javaRule.TypePrimitive#getTypePrimitive <em>Type Primitive</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type Primitive</em>' attribute. * @see javaRule.Primitive * @see #getTypePrimitive() * @generated */ void setTypePrimitive(Primitive value); } // TypePrimitive <file_sep>/Code/es.uam.sara.tfg.astPlugin/src/es/uam/sara/tfg/elements/ICanEmpty.java package es.uam.sara.tfg.elements; public interface ICanEmpty extends IElements{ public boolean isEmpty(); } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/Package.java /** */ package javaRule; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Package</b></em>'. * <!-- end-user-doc --> * * * @see javaRule.JavaRulePackage#getPackage() * @model abstract="true" * @generated */ public interface Package extends Property { } // Package <file_sep>/Code/es.uam.sara.tfg.ast/src/Main.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.TypeDeclaration; import es.uam.sara.tfg.ast.ParserAst; import es.uam.sara.tfg.ast.UnitVisitor; import es.uam.sara.tfg.ast.Visitors; import es.uam.sara.tfg.ast.properties.Attributes; import es.uam.sara.tfg.ast.properties.Classes; import es.uam.sara.tfg.ast.properties.Methods; import es.uam.sara.tfg.ast.properties.Modifiers; import es.uam.sara.tfg.ast.properties.Name; import es.uam.sara.tfg.ast.properties.Name.Type; import es.uam.sara.tfg.ast.properties.Result; public class Main { public static String readFileToString(String filePath) throws IOException { StringBuilder fileData = new StringBuilder(1000); BufferedReader reader = new BufferedReader(new FileReader(filePath)); char[] buf = new char[10]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); return fileData.toString(); } private static void getFiles(File f, ArrayList<File> list){ if (f.isFile()){ list.add(f); }else{ File[] files=f.listFiles(); for (File faux: files){ getFiles(faux, list); } } } public static void main(String[] args) throws IOException { File dirs = new File("."); String dirPath = dirs.getCanonicalPath() + File.separator+"src"+File.separator; File root = new File(dirPath); //System.out.println(rootDir.listFiles()); ArrayList<File> files= new ArrayList<File>(); getFiles (root, files); String filePath = null; Visitors visitors=new Visitors(); for (File f : files ) { filePath = f.getAbsolutePath(); if(f.isFile()){ UnitVisitor u=new UnitVisitor(f.getName()); visitors.addVisitor(u); ParserAst.parse(readFileToString(filePath), u); } } Modifiers aux=new Modifiers(); aux.addBlend("", false, false, true, false); Classes c=new Classes(visitors.getClasses()); System.out.println("r:"+c.Modifiers(null, aux).getRight()); System.out.println("w:"+c.Modifiers(null, aux).getWrong()); } } <file_sep>/Code/es.uam.sara.tfg.astPlugin/src/es/uam/sara/tfg/elements/ICanGeneric.java package es.uam.sara.tfg.elements; import java.util.ArrayList; import java.util.List; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; public interface ICanGeneric extends IElements{ public boolean isGeneric(); public default boolean comparaParam(List<Type> parameters, List<String> generics) { for (Type t : parameters) { if (t instanceof ParameterizedType) { if (comparaParam(getTypes(((ParameterizedType) t).typeArguments()), generics)) { return true; } } else { if (generics.contains(t.toString())) { return true; } } } return false; } public default List<String> getGenericTypes(List<?> lista) { List<String> ret = new ArrayList<String>(); for (Object o : lista) { ret.add(o.toString()); } return ret; } public default List<Type> getTypes(List<?> lista) { List<Type> ret = new ArrayList<Type>(); for (Object o : lista) { if (o instanceof SingleVariableDeclaration) { ret.add(((SingleVariableDeclaration) o).getType()); } if (o instanceof Type) { ret.add((Type) o); } } return ret; } public default List<Type> getTypes(Type returnType2) { List<Type> ret = new ArrayList<Type>(); ret.add(returnType2); return ret; } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/all/Size.java package es.uam.sara.tfg.properties.all; import java.util.HashMap; import java.util.Map; import es.uam.sara.tfg.elements.IPosicionable; import es.uam.sara.tfg.properties.Property; public class Size<T extends IPosicionable> extends Property<T>{ private int max, min; private Map<IPosicionable, Integer> map; public Size(int min, int max) { super(false); this.max = max; this.min = min; map = new HashMap<IPosicionable, Integer>(); } public int getSize(IPosicionable analyze) { int start = analyze.getStartLine(); int end = analyze.getEndLine(); int tam = (end - start) + 1; return tam; } @Override public boolean checkElement(T analyze) { int size = getSize(analyze); map.put(analyze, size); if (size < min || size > max) { return false; } else { return true; } } public String toString() { if (max == Integer.MAX_VALUE) { return "size [" + min + ".." + "*]"; } return "size [" + min + ".." + max + "]"; } public String print(T t) { return t.toString()+ "size="+getSize(t)+"\n"; } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/StringType.java package es.uam.sara.tfg.properties; public enum StringType { NAME, TYPE } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/type/TypePrimitive.java package es.uam.sara.tfg.properties.type; import java.util.List; public class TypePrimitive implements Type{ public enum Primitive { BYTE, SHORT, INT, LONG, FLOAT, DOUBLE, BOOLEAN, CHAR, STRING } private Primitive type; public TypePrimitive(Primitive type) { super(); this.type = type; } @Override public boolean compare(org.eclipse.jdt.core.dom.Type other) { List<String> strings= Type.getString(other); return strings.contains(type.toString().toLowerCase()); } @Override public String getString() { return type.toString().toLowerCase(); } @Override public void setString(String s) { } @Override public void deleteString(String s) { } @Override public boolean compare(String other) { return other.equalsIgnoreCase(this.type.toString()); } @Override public String toString() { return "Primitive."+type.toString().toLowerCase(); } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/sentence/And.java package es.uam.sara.tfg.sentence; import java.util.ArrayList; import java.util.List; import java.util.Map; import es.uam.sara.tfg.elements.IElements; import es.uam.sara.tfg.properties.Checkeable; public class And<T extends IElements> extends Checkeable<T> { private List<PrimaryOp<T>> properties; private boolean changeForContains = false; public And() { super(false); properties = new ArrayList<PrimaryOp<T>>(); } public void addPropertie(PrimaryOp<T> p) { properties.add(p); } @Override public void check(List<T> analyze) { for (PrimaryOp<T> p : properties) { p.check(analyze); } changeForContains = false; for (T a : analyze) { boolean wrong = false; for (PrimaryOp<T> p : properties) { if (p.isChangeForContains()) { if (p.getWrong().contains(a)) { changeForContains = true; this.addLastWrong(a); wrong = true; } } else { if (p.getWrong().contains(a)) { this.addWrong(a); wrong = true; } } if (wrong == false) { this.addRight(a); } } } } public void reset() { for (Checkeable<T> a : properties) { a.reset(); } super.reset(); } @Override public String toString() { String cad = ""; String and = ""; for (PrimaryOp<T> p : properties) { if (p instanceof Or<?>) { cad += and + "(" + p.toString() + ")"; } else { cad += and + p.toString(); } and = " and "; } return cad; } @Override public String print(boolean right) { String cad; if (right) { cad = "This elements satisfy " + this.toString() + ":\n"; } else { cad = "This elements don't satisfy " + this.toString() + ":\n"; } if (properties.size() <= 1) { cad = ""; } for (Checkeable<T> p : properties) { cad += p.print(right); } return cad + "\n"; } @Override public boolean checkElement(T analyze) { return false; } public boolean needVariables() { for (PrimaryOp<T> a : this.properties) { if (a.needVariables()) { return true; } } return false; } public void setUsing(Map<String, IElements> using) { for (PrimaryOp<T> a : this.properties) { a.setUsing(using); } super.setUsing(using); } public boolean isChangeForContains() { return changeForContains; } @Override public void reset(RuleSave<T> rs, int i) { this.reset(); this.addAllRight(rs.getRight(i)); this.addAllWrong(rs.getWrong(i)); int k=i++; for (PrimaryOp<T> a : properties){ a.reset(rs, k); k=1+a.getChildren(); } } @Override public int getChildren() { int i=0; for (PrimaryOp<T> p: this.properties){ i+=p.getChildren(); } return 1+i; } @Override public void save(RuleSave<T> rs, int i) { rs.save(i, getRight(), getWrong()); int k=i++; for (PrimaryOp<T> a : properties){ a.save(rs, k); k=1+a.getChildren(); } } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/NameCheck.java /** */ package javaRule; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Name Check</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see javaRule.JavaRulePackage#getNameCheck() * @model * @generated */ public enum NameCheck implements Enumerator { /** * The '<em><b>UPPER CASE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #UPPER_CASE_VALUE * @generated * @ordered */ UPPER_CASE(1, "UPPER_CASE", "UPPER_CASE"), /** * The '<em><b>LOWER CASE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #LOWER_CASE_VALUE * @generated * @ordered */ LOWER_CASE(2, "LOWER_CASE", "LOWER_CASE"), /** * The '<em><b>UPPER CAMEL CASE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #UPPER_CAMEL_CASE_VALUE * @generated * @ordered */ UPPER_CAMEL_CASE(3, "UPPER_CAMEL_CASE", "UPPER_CAMEL_CASE"), /** * The '<em><b>LOWER CAMEL CASE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #LOWER_CAMEL_CASE_VALUE * @generated * @ordered */ LOWER_CAMEL_CASE(4, "LOWER_CAMEL_CASE", "LOWER_CAMEL_CASE"), /** * The '<em><b>START UPPER CASE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #START_UPPER_CASE_VALUE * @generated * @ordered */ START_UPPER_CASE(5, "START_UPPER_CASE", "START_UPPER_CASE"); /** * The '<em><b>UPPER CASE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>UPPER CASE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #UPPER_CASE * @model * @generated * @ordered */ public static final int UPPER_CASE_VALUE = 1; /** * The '<em><b>LOWER CASE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>LOWER CASE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #LOWER_CASE * @model * @generated * @ordered */ public static final int LOWER_CASE_VALUE = 2; /** * The '<em><b>UPPER CAMEL CASE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>UPPER CAMEL CASE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #UPPER_CAMEL_CASE * @model * @generated * @ordered */ public static final int UPPER_CAMEL_CASE_VALUE = 3; /** * The '<em><b>LOWER CAMEL CASE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>LOWER CAMEL CASE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #LOWER_CAMEL_CASE * @model * @generated * @ordered */ public static final int LOWER_CAMEL_CASE_VALUE = 4; /** * The '<em><b>START UPPER CASE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>START UPPER CASE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #START_UPPER_CASE * @model * @generated * @ordered */ public static final int START_UPPER_CASE_VALUE = 5; /** * An array of all the '<em><b>Name Check</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final NameCheck[] VALUES_ARRAY = new NameCheck[] { UPPER_CASE, LOWER_CASE, UPPER_CAMEL_CASE, LOWER_CAMEL_CASE, START_UPPER_CASE, }; /** * A public read-only list of all the '<em><b>Name Check</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<NameCheck> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Name Check</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static NameCheck get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { NameCheck result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Name Check</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static NameCheck getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { NameCheck result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Name Check</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static NameCheck get(int value) { switch (value) { case UPPER_CASE_VALUE: return UPPER_CASE; case LOWER_CASE_VALUE: return LOWER_CASE; case UPPER_CAMEL_CASE_VALUE: return UPPER_CAMEL_CASE; case LOWER_CAMEL_CASE_VALUE: return LOWER_CAMEL_CASE; case START_UPPER_CASE_VALUE: return START_UPPER_CASE; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private NameCheck(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //NameCheck <file_sep>/Code/es.uam.sara.tfg.ast/src/es/uam/sara/tfg/ast/properties/Modifiers.java package es.uam.sara.tfg.ast.properties; import java.util.ArrayList; import java.util.List; import org.eclipse.jdt.core.dom.Modifier; public class Modifiers { private ArrayList<BlendModifiers> blends=new ArrayList<BlendModifiers>(); public void addBlend(String acceso, boolean static_, boolean final_, boolean abstract_, boolean synchronized_){ blends.add(new BlendModifiers(acceso, static_, final_, abstract_, synchronized_)); } boolean modifiers(List<Modifier> list){ BlendModifiers nuevo= createBlend(list); for (BlendModifiers b: this.blends){ if (b.compara(nuevo)==true){ return true; } } return false; } private BlendModifiers createBlend(List<Modifier> list){ String acceso=""; boolean static_=false; boolean final_=false; boolean abstract_=false; boolean synchronized_=false; for (Modifier m:list){ if (m.isPublic()){ acceso="public"; }else if (m.isPrivate()){ acceso="private"; }else if (m.isProtected()){ acceso="protected"; }else if(m.isStatic()){ static_=true; }else if(m.isFinal()){ final_=true; }else if(m.isAbstract()){ abstract_=true; }else if(m.isSynchronized()){ synchronized_=true; } } return new BlendModifiers(acceso, static_, final_, abstract_, synchronized_); } } <file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/IsCollectionTypeImpl.java /** */ package javaRule.impl; import javaRule.IsCollectionType; import javaRule.JavaRulePackage; import javaRule.TypeProperty; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Is Collection Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link javaRule.impl.IsCollectionTypeImpl#getOf <em>Of</em>}</li> * </ul> * * @generated */ public class IsCollectionTypeImpl extends TypePropertyImpl implements IsCollectionType { /** * The cached value of the '{@link #getOf() <em>Of</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOf() * @generated * @ordered */ protected TypeProperty of; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IsCollectionTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.IS_COLLECTION_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TypeProperty getOf() { return of; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetOf(TypeProperty newOf, NotificationChain msgs) { TypeProperty oldOf = of; of = newOf; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, JavaRulePackage.IS_COLLECTION_TYPE__OF, oldOf, newOf); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOf(TypeProperty newOf) { if (newOf != of) { NotificationChain msgs = null; if (of != null) msgs = ((InternalEObject)of).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - JavaRulePackage.IS_COLLECTION_TYPE__OF, null, msgs); if (newOf != null) msgs = ((InternalEObject)newOf).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - JavaRulePackage.IS_COLLECTION_TYPE__OF, null, msgs); msgs = basicSetOf(newOf, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JavaRulePackage.IS_COLLECTION_TYPE__OF, newOf, newOf)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case JavaRulePackage.IS_COLLECTION_TYPE__OF: return basicSetOf(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case JavaRulePackage.IS_COLLECTION_TYPE__OF: return getOf(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case JavaRulePackage.IS_COLLECTION_TYPE__OF: setOf((TypeProperty)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case JavaRulePackage.IS_COLLECTION_TYPE__OF: setOf((TypeProperty)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case JavaRulePackage.IS_COLLECTION_TYPE__OF: return of != null; } return super.eIsSet(featureID); } } //IsCollectionTypeImpl <file_sep>/Code/es.uam.sara.tfg.astPlugin/src/es/uam/sara/tfg/elements/type/MClass.java package es.uam.sara.tfg.elements.type; import org.eclipse.jdt.core.dom.TypeDeclaration; import es.uam.sara.tfg.ast.UnitVisitor; import es.uam.sara.tfg.elements.ClassInterface; public class MClass extends ClassInterface { public MClass(TypeDeclaration tp, UnitVisitor uv) { super(tp, uv); } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/classes/IsSubClass.java /** * */ package es.uam.sara.tfg.properties.classes; import org.eclipse.jdt.core.dom.Type; import es.uam.sara.tfg.elements.type.MClass; import es.uam.sara.tfg.properties.StringProperty; import es.uam.sara.tfg.properties.type.TypeString; /** * @author Sara * */ public class IsSubClass extends StringProperty<MClass>{ private TypeString of; private Type superClass=null; /** * @param analyze */ public IsSubClass(boolean no,TypeString subClass) { super(no); this.of=subClass; } public IsSubClass(boolean no) { super(no); of=null; } @Override public String toString() { String cad; if (no){ cad="is not "; }else{ cad="is "; } if (of==null) return cad +"subClass"; else return cad +"subClass of "+ of; } @Override public boolean checkElement(MClass t) { superClass=t.getSuperclass(); if (of==null){ if (superClass!=null){ return false; }else{ return true; } }else{ if (of.compare(superClass)){ return true; }else{ return false; } } } @Override public void setString(String string, int i) { this.of.setString(string); } @Override public void deleteString(String string, int i) { this.of.deleteString(string); } public String print(MClass t) { if (superClass==null){ return t.toString(); } return t.toString()+" is subClass of: "+superClass.toString(); } } <file_sep>/Code/es.uam.sara.tfg.ast2/src/es/uam/sara/tfg/properties/StringProperty.java package es.uam.sara.tfg.properties; import es.uam.sara.tfg.elements.IElements; public abstract class StringProperty<T extends IElements> extends Property<T>{ public StringProperty(boolean no) { super(no); } public abstract void setString(String string, int i); public abstract void deleteString(String string, int i); }<file_sep>/Code/es.uam.sara.tfg.metaModel/src/javaRule/impl/MethodImpl.java /** */ package javaRule.impl; import javaRule.JavaRulePackage; import javaRule.Method; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Method</b></em>'. * <!-- end-user-doc --> * * @generated */ public abstract class MethodImpl extends PropertyImpl implements Method { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MethodImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JavaRulePackage.Literals.METHOD; } } //MethodImpl
6d2db5f79faa940bf5f2a785cf5e1a785d3794c7
[ "Java" ]
49
Java
SaraPerezSoler/JavaCheck
3748292c28f2eabc12f030d44483e27bcd480f2f
e04ca2662e942745651d7f0f730d5a03846b96a6
refs/heads/master
<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* client.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/13 23:50:44 by gjensen #+# #+# */ /* Updated: 2015/06/22 22:45:54 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static void usage(char *str) { printf("Usage %s <addr> <port>\n", str); exit(-1); } static int create_client(char *addr, int port) { int sock; struct protoent *proto; struct sockaddr_in sin; char check[3]; proto = getprotobyname("tcp"); if (!proto) return (-1); sock = socket(PF_INET, SOCK_STREAM, proto->p_proto); sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = inet_addr(addr); if (connect(sock, (const struct sockaddr *)&sin, sizeof(sin)) < 0) ft_putendl_fd("Connect error", 2), exit(2); if (read(sock, check, 3)) { if (ft_strcmp(check, "ok") == 0) printf("Connected to server\n"); else ft_putendl_fd("Server not listening, exit", 2), exit(0); } return (sock); } static void ftp_recvstd(int sock) { int cr; int eol; char buf[2]; cr = 0; eol = 0; while (!eol) { if ((recv(sock, buf, 1, 0)) < 0) break ; buf[1] = 0; if (buf[0] == '\r') cr = 1; else if (cr == 1 && buf[0] == '\n') eol = 1; else if (cr && buf[0] != '\n') cr = 0; ft_putchar(buf[0]); } } static void ftp_clientmanage(int sock, char *addr, int port) { char *line; char home[1024]; char *nl; char **option; getcwd(home, 1024); printf("Client Home directory set at: %s\n", home); while (42) { ftp_cprompt(addr, port); if (get_next_line(0, &line) <= 0) exit(0); nl = ft_epur_tab(line); option = ft_strsplit(nl, ' '); if (ftp_client_cmd(sock, option, 0, home)) ftp_recvstd(sock); ft_strdel(&line); if (nl) ft_strdel(&nl); if (option) ft_arrfree(&option); } close(sock); } int main(int ac, char **av) { int port; int sock; char *addr; struct hostent *host; if (ac != 3) usage(av[0]); port = ft_atoi(av[2]); if (!(host = gethostbyname(av[1]))) { ft_putendl_fd("Ip error", 2); return (0); } addr = inet_ntoa(*((struct in_addr**)host->h_addr_list)[0]); sock = create_client(addr, port); ftp_clientmanage(sock, addr, port); return (0); } <file_sep>#**************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: gjensen <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2015/05/15 19:18:07 by gjensen #+# #+# # # Updated: 2015/07/25 19:33:00 by gjensen ### ########.fr # # # # **************************************************************************** # SERVEUR = serveur CLIENT = client SRCSERV = serveur.c createserv.c ftp_servcmd.c ftp_dataservcmd.c ftp_tool.c ftp_dataservcmd2.c SRCCL = client.c ftp_clientcmd.c ftp_dataclientcmd.c ftp_tool.c ftp_dataclientcmd2.c ftp_localclientcmd.c OBJSERV = $(SRCSERV:.c=.o) OBJCL = $(SRCCL:.c=.o) #CFLAGS = -I libft/includes -g CFLAGS = -Werror -Wextra -Wall -I libft/includes all: client serveur $(SERVEUR): $(OBJSERV) make -C libft/ gcc $(CFLAGS) -o $(SERVEUR) $(OBJSERV) -L libft/ -lft $(CLIENT): $(OBJCL) make -C libft/ gcc $(CFLAGS) -o $(CLIENT) $(OBJCL) -L libft/ -lft clean: rm -rf $(OBJSERV) $(OBJCL) fclean: clean rm -rf $(SERVEUR) $(CLIENT) Make -C libft/ fclean re: fclean all .PHONY: all clean fclean re <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_dataclientcmd2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/10 17:58:49 by gjensen #+# #+# */ /* Updated: 2016/02/19 19:33:23 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static int ftp_builtin_get_recv(int sock, int fd, int eol, int cr) { char buf[2]; char *lendata[2]; int ilen; lendata[0] = ft_strdup(""); while (!eol) { if ((recv(sock, buf, 1, 0)) < 0) break ; buf[1] = 0; if (buf[0] == '\r') cr = 1; else if (cr == 1 && buf[0] == '\n') eol = 1; else if (cr && buf[0] != '\n') cr = 0; lendata[0] = ft_strjoinfree(lendata[0], buf); } ilen = ft_atoi(lendata[0]); lendata[1] = (char *)malloc(sizeof(char) * (ilen)); if ((recv(sock, lendata[1], ilen, 0)) == -1) return (0); write(fd, lendata[1], ilen), ft_strdel(&lendata[0]); ft_strdel(&lendata[1]); return (1); } static int ftp_builtin_get_msg(int sock, int *fd, char *str) { char *file; while (42) { write(1, "File already exists, replace it?(y/n)\n", 37); if (get_next_line(1, &file) != 1) return (0); if (ft_tolower(file[0]) == 'y') { ft_strdel(&file), write(sock, "y", 1); if ((*fd = open(str, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) return (0); break ; } else if (ft_tolower(file[0]) == 'n') { ft_strdel(&file), write(sock, "n", 1); return (0); } } return (1); } static int ftp_builtin_get_cut(int sock, char *str) { int fd; if ((fd = open(str, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) { if (!ftp_builtin_get_msg(sock, &fd, str)) { close(fd); return (0); } } else write(sock, "y", 1); if (!ftp_builtin_get_recv(sock, fd, 0, 0)) { close(fd); return (0); } close(fd); return (1); } static int ftp_builtin_get_filever(char *str, int sock) { char *full_cmd; char *cmd; if (str) { if (ft_strstr(str, "..") || !ft_strncmp(str, "/", 1)) { ft_putendl_fd("ERROR: File not valid", 2); return (0); } cmd = ft_strdup(str); full_cmd = ft_strjoin("RETR ", cmd); write(sock, full_cmd, ft_strlen(full_cmd) + 1); ft_strdel(&cmd); ft_strdel(&full_cmd); } else { ft_putendl("ERROR: Can't get this file"); return (0); } return (1); } void ftp_builtin_get(char **option, int sock) { char **cmd; int i; char msg[3]; if (!ftp_builtin_get_filever(option[1], sock)) return ; if (read(sock, msg, 3)) { if (ft_strcmp(msg, "nf") == 0) { ft_putendl_fd("ERROR: Can't get this file", 2); return ; } } cmd = ft_strsplit(option[1], '/'); i = ft_arrlen(cmd) - 1; if (ftp_builtin_get_cut(sock, cmd[i])) ft_putendl("SUCCESS: Data successfully copied"); else ft_putendl_fd("ERROR: Can't get this data", 2); ft_arrfree(&cmd); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* show_alloc_mem.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/09 14:18:29 by gjensen #+# #+# */ /* Updated: 2016/12/12 16:01:47 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" static void print_type_name(char type) { if (type == TINY) ft_putstr("TINY"); else if (type == SMALL) ft_putstr("SMALL"); else if (type == LARGE) ft_putstr("LARGE"); } static void print_datas(void *ptr, size_t size) { print_adress(ptr); ft_putstr(" - "); print_adress(ptr + size); ft_putstr(" : "); ft_putnbr(size); ft_putendl(" octets"); } void show_alloc_mem(void) { t_page *page; t_mdata *mdata; if ((page = g_firstpage)) { while (page) { print_type_name(page->type); ft_putstr(" : "); print_adress(page->start); ft_putchar('\n'); mdata = page->start; while (mdata) { if (!mdata->free) print_datas(mdata + 1, mdata->size); mdata = mdata->next; } page = page->next; } } } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_localclientcmd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/22 17:28:05 by gjensen #+# #+# */ /* Updated: 2015/06/22 22:09:42 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static void ftp_builtin_lls(char **av) { pid_t father; free(av[0]); av[0] = ft_strdup("/bin/ls"); ft_putendl("Local list:"); father = fork(); if (father != -1) { if (father == 0) { if (execv(av[0], av) == -1) ft_putendl_fd("Format error", 2); exit (0); } else wait4(father, 0, 0, 0); } } static void ftp_builtin_lcd(char **av, char *home) { char *cmd; char pwd[1024]; cmd = av[1]; if (ft_arrlen(av) > 2) { ft_putendl_fd("lcd: too many arguments", 2); return ; } if (ft_arrlen(av) == 1 || (cmd && (ft_strcmp(cmd, "~") == 0))) cmd = home; if (access(cmd, F_OK) == 0) { if (ftp_isbin(cmd) == 1 || ftp_isbin(cmd) == 3) { if (chdir(cmd) != 0) ft_putendl_fd("Error", 2); getcwd(pwd, 1024); printf("Current local directory: %s\n", pwd); } else ft_putendl_fd("Error: lcd: not a directory", 2); } else ft_putendl_fd("Error: lcd: no such file or directory", 2); } static void ftp_builtin_lpwd(void) { char pwd[1024]; getcwd(pwd, 1024); printf("Current local directory: %s\n", pwd); } int ftp_local_cmd(char **cmd, char *home) { int state; state = 0; if (ft_strcmp(ft_tomin(cmd[0]), "lls") == 0) ftp_builtin_lls(cmd), state = 1; else if (ft_strcmp(ft_tomin(cmd[0]), "lcd") == 0) ftp_builtin_lcd(cmd, home), state = 1; else if (ft_strcmp(ft_tomin(cmd[0]), "lpwd") == 0) ftp_builtin_lpwd(), state = 1; return (state); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* tool2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/24 13:20:22 by gjensen #+# #+# */ /* Updated: 2015/05/06 19:25:25 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void ls_swapstr(char **a, char **b) { char *i; i = *b; *b = *a; *a = i; } char **ft_argsort(char **argv, int start, int end) { int left; int right; const char *pivot; left = start - 1; right = end + 1; pivot = argv[start]; if (start >= end) return (argv); while (left < right) { right--; while (ft_strcmp(argv[right], pivot) > 0) right--; left++; while (ft_strcmp(argv[left], pivot) < 0) left++; if (left < right) ls_swapstr(&argv[left], &argv[right]); } argv = ft_argsort(argv, start, right); argv = ft_argsort(argv, right + 1, end); return (argv); } t_lsalign *checkaligncut2(t_lsalign *align, t_lsdir *lsdir) { int majorl; int bytes; if (S_ISCHR(lsdir->stat->st_mode) || S_ISBLK(lsdir->stat->st_mode)) { align->minorl = 4; majorl = ft_intlen(MAJOR(lsdir->stat->st_rdev)); if (majorl > align->majorl) align->majorl = majorl; } bytes = ft_intlen(lsdir->stat->st_size); if (bytes > align->bytes) align->bytes = bytes; return (align); } t_lsdir *ft_ls_sorttimeascii(t_lsdir *lsdir, int exchange) { t_lsdir *tmp; tmp = lsdir; while (exchange) { exchange = 0; lsdir = tmp; while (lsdir && lsdir->next) { if (lsdir->stat->st_mtimespec.tv_sec == lsdir->next->stat->st_mtimespec.tv_sec) if (ft_strcmp(lsdir->name, lsdir->next->name) > 0) { swaplist(lsdir, lsdir->next); if (lsdir->next != NULL) lsdir->next->previous = lsdir; exchange = 1; } lsdir = lsdir->next; } } while (lsdir->previous) lsdir = lsdir->previous; return (lsdir); } t_lsdir *ls_addidandgrp(t_lsdir *new, char *name) { struct passwd *id; struct group *grp; ft_strcpy(new->name, name); id = getpwuid(new->stat->st_uid); grp = getgrgid(new->stat->st_gid); if (id) new->idn = ft_strdup(id->pw_name); else new->idn = NULL; if (grp) new->gn = ft_strdup(grp->gr_name); else new->gn = NULL; return (new); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* show_alloc_mem.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/07 17:21:41 by gjensen #+# #+# */ /* Updated: 2016/12/12 15:57:46 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" static uint64_t is_pow16(size_t pow) { uint64_t nb; size_t i; i = 0; nb = 1; while (i < pow && nb <= 1152921504606846976) { nb = nb * 16; i++; } return (nb); } static char get_char(int n) { if (n < 10) return (n + '0'); n -= 10; return (n + 'A'); } static void print_number(uint64_t nb, size_t num_digit, char *buff) { size_t i; int temp; uint64_t quotient; quotient = nb; i = num_digit - 1; while (quotient != 0) { temp = quotient % 16; buff[i] = get_char(temp); i--; quotient = quotient / 16; } buff[num_digit] = 0; } void ft_itoa_hex(uint64_t n, char *buff) { size_t num_digit; uint64_t nb; num_digit = 1; nb = n; if (n > 1152921504606846976) num_digit = 15; else { while (is_pow16(num_digit) <= nb) num_digit++; } print_number(nb, num_digit, buff); } void print_adress(void *addr) { char buff[20]; ft_bzero(buff, 20); ft_itoa_hex((uint64_t)addr, buff); ft_putstr("0x"); ft_putstr(buff); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* edition.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/02/23 15:58:37 by gjensen #+# #+# */ /* Updated: 2016/05/12 15:10:19 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_sh.h" char *micro_prompt(void) { static char pline[0xf000]; char *ptr; write(1, "\n\n", 1); ft_bzero(pline, 0xf000); ptr = pline; minimal_prompt(); while (ptr[ft_strlen(ptr) - 1] != '\n') ft_strlcpy(ptr, edit_slim(ptr), 0xf000); ptr = ft_strdup(pline); return (ptr); } char *niark2(char *to_edit, int cursor) { int ret; char *tmp; while ((ret = ft_check_key_words(to_edit)) == -1) { ft_putstr_cursor(to_edit, cursor); tmp = micro_prompt(); ft_strlcat(to_edit, tmp, 0xf000); ft_strdel(&tmp); } if (ret == -2) ft_bzero(to_edit, 0xf000); return (ft_return(to_edit)); } char *line_edition(char *to_edit, int key) { static int cursor = 0; ft_refresh(to_edit, cursor); cursor = set_cursor(cursor, to_edit); if (movement_key(key) == 1) cursor = cursor_movement(key, cursor, to_edit); else if (history_key(key) == 1) { to_edit = history_navigation(g_history_file, key, to_edit); cursor = ft_strlen(to_edit); } else if (key == RETURN) return (niark2(to_edit, cursor)); else if (edition_key(key) == 1) to_edit = edition_func(to_edit, &cursor, key); else if ((get_t(key) && (size_t)cursor <= ft_strlen(to_edit))) { to_edit = insert_char(to_edit, get_t(key), &cursor); cursor += 1; } ft_putstr_cursor(to_edit, cursor); return (to_edit); } char *ft_return(char *to_edit) { char *tmp; char *ptr; minimal_prompt(); ft_putstr(to_edit); tmp = to_edit; ptr = ft_strtrim(tmp); ft_strcpy(to_edit, ptr); ft_strdel(&ptr); ft_strlcat(to_edit, "\n", 0xf000); ptr = ft_strdup(to_edit); if (to_edit[0] != '\n' && to_edit[0]) ft_add_history(ptr); ft_strdel(&ptr); write(1, "\n", 1); return (to_edit); } char *ft_edit_and_history(char *str) { int key; struct termios term; static int col = 0; static int line = 0; key = 0; get_term_size(&col, &line); if (!getenv("TERM")) return (NULL); term = set_term_canon(); read(0, &key, sizeof(int)); if (key == 4 || ft_strlen(str) > 0xefff) { unset_term_canon(term, str, NULL); exit(1); } str = line_edition(str, key); unset_term_canon(term, str, NULL); return (str); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* recursive.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/29 15:50:10 by gjensen #+# #+# */ /* Updated: 2015/04/02 16:43:02 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void ft_start_recursive(t_lsdir *lsdir, t_lsoption *option) { DIR *dir; if (!option->optiona) option->hidden = 1; if (lsdir->name[0] != '.' || option->optiona) { ft_putchar('\n'); option->hidden = 0; ft_putstr(lsdir->path); ft_putendl(":"); } dir = opendir(lsdir->path); if (!lsdir->next && lsdir) free(lsdir->stat); if (dir != 0) ft_startls(dir, option, lsdir->path, NULL); else { ft_putstr(TITLE); ft_putstr(": "); perror(lsdir->name); } if (dir != NULL) closedir(dir); } void ls_recursiveon(t_lsdir *lsdir, t_lsoption *option) { if (!option->optionr) { while (lsdir->previous) lsdir = lsdir->previous; } else { while (lsdir && lsdir->next) lsdir = lsdir->next; } while (lsdir) { if (S_ISDIR(lsdir->stat->st_mode) && ft_strcmp(lsdir->name, ".") && ft_strcmp(lsdir->name, "..")) ft_start_recursive(lsdir, option); if (!option->optionr) lsdir = lsdir->next; else lsdir = lsdir->previous; } } char **ft_argsortreverse(char **argv, int start, int end) { int left; int right; const char *pivot; left = start - 1; right = end + 1; pivot = argv[start]; if (start >= end) return (argv); while (left < right) { right--; while (ft_strcmp(argv[right], pivot) < 0) right--; left++; while (ft_strcmp(argv[left], pivot) > 0) left++; if (left < right) ls_swapstr(&argv[left], &argv[right]); } argv = ft_argsortreverse(argv, start, right); argv = ft_argsortreverse(argv, right + 1, end); return (argv); } void ls_addpath(t_lsdir *new, char *name, char *path) { char *pathfile; if (path) { if (ft_strcmp(path, "/")) pathfile = ft_strjoin(path, ft_strjoin("/", name)); else pathfile = ft_strjoin(path, name); new->path = pathfile; lstat(pathfile, new->stat); } else { lstat(name, new->stat); new->path = ft_strjoin("./", name); } } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_dataservcmd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/01 21:34:58 by gjensen #+# #+# */ /* Updated: 2015/06/22 16:28:42 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static void ftp_putcmd_recdata(int cs, int fd, int eol, int cr) { char buf[2]; char *len; int ilen; char *data; len = ft_strdup(""); while (!eol) { if ((recv(cs, buf, 1, 0)) < 0) break ; buf[1] = 0; if (buf[0] == '\r') cr = 1; else if (cr == 1 && buf[0] == '\n') eol = 1; else if (cr && buf[0] != '\n') cr = 0; len = ft_strjoinfree(len, buf); } ilen = ft_atoi(len); data = (char *)malloc(sizeof(char) * (ilen)); if ((recv(cs, data, ilen, 0)) == -1) return ; write(fd, data, ilen); ft_strdel(&len), ft_strdel(&data), close(fd); } static void ftp_putcmd_cut(int cs, char *src) { int fd; char file[3]; if ((fd = open(src, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) { write(cs, "fl\0", 3); while ((read(cs, file, 2)) > 0) { file[1] = 0; if (ft_tolower(file[0]) == 'y') { if ((fd = open(src, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) return ; break ; } else if (ft_tolower(file[0]) == 'n') return ; } } else write(cs, "nl\0", 3); ftp_putcmd_recdata(cs, fd, 0, 0); } void ftp_putcmd(int cs, char *arrcmd) { char **cmd; char **src; int i; cmd = ft_strsplit(arrcmd, ' '); src = ft_strsplit(cmd[1], '/'); i = ft_arrlen(src) - 1; ftp_putcmd_cut(cs, src[i]); ft_arrfree(&cmd), ft_arrfree(&src); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* do_malloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/01 15:36:59 by gjensen #+# #+# */ /* Updated: 2016/12/12 16:10:23 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" char get_sizetype(size_t size) { if (size < TINY_SIZE) return (TINY); else if (size >= TINY_SIZE && size < SMALL_SIZE) return (SMALL); else if (size >= SMALL_SIZE) return (LARGE); print_error("Wrong size for allocation"); return (0); } void *malloc_large(size_t size) { t_page *page; page = page_push(g_firstpage, size, get_sizetype(size)); if (!g_firstpage) g_firstpage = page; page->size = size + sizeof(t_mdata); return (init_block(page->start, size)); } void *init_block(void *ptr, size_t size) { t_mdata *mdata; char *next; mdata = ptr; while (mdata->next) { if (mdata->free && mdata->size >= size) { set_metadata(size, mdata, mdata->next); return (mdata + 1); } mdata = mdata->next; } if (mdata->size) { next = (char *)(mdata) + mdata->size + sizeof(t_mdata); mdata->next = (void *)next; mdata = mdata->next; } set_metadata(size, mdata, NULL); return (mdata + 1); } void *first_malloc(size_t size) { t_page *page; g_firstpage = page_push(g_firstpage, size, get_sizetype(size)); page = g_firstpage; page->size += size + sizeof(t_mdata); return (init_block(page->start, size)); } void *do_malloc(size_t size) { t_page *page; if (get_sizetype(size) == LARGE) return (malloc_large(size)); else if (!g_firstpage) return (first_malloc(size)); else if ((page = find_page(size)) != NULL) return (init_block(page->start, size)); page = page_push(g_firstpage, size, get_sizetype(size)); page->size += size + sizeof(t_mdata); return (init_block(page->start, size)); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_quicksort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/21 23:19:59 by gjensen #+# #+# */ /* Updated: 2015/01/21 23:20:07 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void *ft_quicksort(void *base, int start, int end) { int left; int right; const void *pivot; left = start - 1; end = right - 1; pivot = base[start]; if (start >= end) return (base); while (left < right) { while (base[right] > pivot) right--; while (argv[left] < pivot) left++; if (left < right) ft_swap(left, right); } base = ft_quicksort(base, start, right); base = ft_quicksort(base, right + 1, end); return (base); } <file_sep>#**************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: gjensen <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2015/06/24 22:40:26 by gjensen #+# #+# # # Updated: 2015/07/21 19:55:14 by gjensen ### ########.fr # # # # **************************************************************************** # NAME = libfts.a NAME_TEST = test PATH_SRC = ./src/ AS = nasm ASFLAGS = -f macho64 CC = cc -Wall -Wextra -Werror LIBS = -L ./ -lfts SRC = ft_bzero.s ft_strcat.s ft_isalpha.s ft_isalnum.s ft_isascii.s ft_isdigit.s ft_isprint.s \ ft_toupper.s ft_tolower.s ft_strlen.s ft_memset.s ft_memcpy.s ft_puts.s ft_strdup.s \ ft_cat.s ft_putchar.s ft_putchar_fd.s ft_islower.s ft_isupper.s ft_strcmp.s ft_putstr.s \ ft_strequ.s ft_strcpy.s ft_memalloc.s ft_strnew.s OBJ = $(addprefix $(PATH_SRC), $(SRC:.s=.o)) .PHONY: clean fclean re test clean_test all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) ranlib $(NAME) clean: /bin/rm -f $(OBJ) fclean: clean /bin/rm -f $(NAME) re: fclean all test: $(OBJ) main.c $(CC) main.c $(LIBS) -o $(NAME_TEST) -g clean_test: /bin/rm -f $(NAME_TEST) <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_p.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/16 16:39:54 by gjensen #+# #+# */ /* Updated: 2015/07/21 23:54:15 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FT_P_H # define FT_P_H # include <unistd.h> # include <stdio.h> # include <stdlib.h> # include <sys/socket.h> # include <sys/stat.h> # include <netdb.h> # include <netinet/in.h> # include <arpa/inet.h> # include "libft.h" # include <sys/types.h> # include <fcntl.h> # include <sys/wait.h> typedef struct stat t_stat; int ftp_isbin(char *path); int ftp_acess(char *path); /* **fonctions serveur */ int create_server(int port); void ftp_acceptclient(int sock); void ftp_read_socket(int cs); void ftp_putcmd(int cs, char *buf); void ftp_getcmd(int cs, char *buf); char *ftp_opt_ls(char *buf); /* **fonctions client */ int ftp_client_cmd(int sock, char **option, int state, char *home); void ftp_builtin_get(char **option, int sock); void ftp_builtin_put(char **option, int sock); void ftp_cprompt(char *addr, int port); int ftp_local_cmd(char **cmd, char *home); #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_dataclientcmd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/01 22:49:06 by gjensen #+# #+# */ /* Updated: 2016/02/19 19:33:01 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static int ftp_builtin_put_send(int sock, char **av) { int fd; char *len; char *buf; t_stat filestat; if ((fd = open(av[1], O_RDWR)) != 1) { if (fstat(fd, &filestat) == -1) return (1); buf = (char *)malloc(sizeof(char) * filestat.st_size); read(fd, buf, filestat.st_size); len = ft_itoa(filestat.st_size); send(sock, len, ft_strlen(len) + 1, 0); ft_strdel(&len); send(sock, "\r\n", 2, 0); send(sock, buf, filestat.st_size, 0); ft_strdel(&buf); } close(fd); return (0); } static int ftp_builtin_put_cut(int sock) { char msg[3]; char *file; read(sock, msg, 3); if (ft_strcmp(msg, "fl") == 0) { while (42) { write(1, "File already exists, replace it?(y/n)\n", 37); if (get_next_line(1, &file) != 1) return (0); if (ft_tolower(file[0]) == 'y') { ft_strdel(&file), write(sock, "y\0", 2); break ; } else if (ft_tolower(file[0]) == 'n') { write(sock, file, 2), ft_strdel(&file); return (0); } ft_strdel(&file); } } return (1); } void ftp_builtin_put(char **av, int sock) { char *full_cmd; char *cmd; if (av[1] && !(ftp_acess(av[1]))) { cmd = ft_strdup(av[1]); full_cmd = ft_strjoin("STOR ", cmd); write(sock, full_cmd, ft_strlen(full_cmd) + 1); ft_strdel(&cmd); ft_strdel(&full_cmd); } else { ft_putendl("ERROR: Can't send this file"); return ; } if (ftp_builtin_put_cut(sock)) { if (ftp_builtin_put_send(sock, av)) ft_putendl_fd("ERROR: Unexpected error occured", 2); else ft_putendl("SUCCESS: Data successfully sent"); } else ft_putendl_fd("ERROR: File not sent", 2); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* managestart.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/12 04:25:40 by gjensen #+# #+# */ /* Updated: 2015/02/03 19:05:43 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" static void ft_checkarg(char c) { if (!(c == 'l' || c == 'R' || c == 'a' || c == 'r' || c == 't' || c == '-' || c == '1')) { ft_putstr(TITLE); ft_putstr(": "); ft_putstr(" illegal option -- "); ft_putchar(c); ft_putchar('\n'); ft_putstr("usage: "); ft_putstr(TITLE); ft_putendl(" [-lRart] [file ...]"); exit(1); } } void showblocks(t_lsdir *lsdir, t_lsalign *align, t_lsoption *option) { if (!option->optiona) { while (lsdir->next && (lsdir->name[0] == '.' && lsdir->stat->st_mode)) lsdir = lsdir->next; if (lsdir->name[0] != '.') { ft_putstr("total "); ft_putnbr(align->totalblocks); ft_putchar('\n'); } } else { ft_putstr("total "); ft_putnbr(align->totalblocks); ft_putchar('\n'); } } t_lsdir *ls_sort_lsdir(t_lsdir *lsdir, t_lsoption *option) { if (option->optiont) { lsdir = ft_ls_sorttime(lsdir, 1); lsdir = ft_ls_sorttimeascii(lsdir, 1); } else lsdir = ft_ls_sortascii(lsdir, 1); return (lsdir); } void ft_startlscut(t_lsdir *lsdir, t_lsoption *option, t_lsalign *align, DIR *dir) { if (dir && option->optionl) showblocks(lsdir, align, option); if (option->optionr) { while (lsdir && lsdir->next) lsdir = lsdir->next; } while (lsdir && !option->hidden) { if (!option->optiona) { if (lsdir->name[0] != '.' || dir == NULL) printls(lsdir, align, option); } else printls(lsdir, align, option); if (option->optionr) lsdir = lsdir->previous; else lsdir = lsdir->next; } } int ft_parsecut(t_lsoption *option, char **argv, int i) { int j; while (argv[i] && (argv[i][0] == '-')) { j = 1; while (argv[i][j]) { if (argv[i][j] == '-') return (i + 1); ft_checkarg(argv[i][j]); if (argv[i][j] == 'l') option->optionl = 1; if (argv[i][j] == 'R') option->optionrr = 1; if (argv[i][j] == 'a') option->optiona = 1; if (argv[i][j] == 'r') option->optionr = 1; if (argv[i][j] == 't') option->optiont = 1; j++; } i++; } return (i); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/24 16:19:54 by gjensen #+# #+# */ /* Updated: 2015/02/03 19:07:37 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" int main(int argc, char **argv) { DIR *dir; t_lsoption *option; int i; char **param; option = (t_lsoption*)malloc(sizeof(t_lsoption)); i = ft_parse(option, argv); param = argv + i; if (!option->optionr) param = ft_argsort(param, 0, argc - (i + 1)); else param = ft_argsortreverse(param, 0, argc - (i + 1)); if (argc == i) { dir = opendir("."); ft_startls(dir, option, param[0], NULL); } else { option->first = 1; ls_show_uk(argc - i, param, 0); ls_show_reg(argc - i, param, option, 0); ls_show_dir(argc - i, param, option, 0); } return (0); } int ft_parse(t_lsoption *option, char **argv) { int i; i = 1; option->optionl = 0; option->optionrr = 0; option->optiona = 0; option->optionr = 0; option->optiont = 0; option->hidden = 0; if (argv[i]) { if (ft_strcmp(argv[i], "-") == 0) return (i); } i = ft_parsecut(option, argv, i); return (i); } void ft_startls(DIR *dir, t_lsoption *option, char *argv, t_lsdir *lsdir) { struct dirent *fichier; t_lsdir *elem; t_lsalign *align; t_lsdir *temp; if (dir == NULL) { elem = ft_newlst(); ft_addlsdir(&lsdir, elem, argv, NULL); } else { while ((fichier = readdir(dir)) != NULL) { elem = ft_newlst(); ft_addlsdir(&lsdir, elem, fichier->d_name, argv); } } lsdir = ls_sort_lsdir(lsdir, option); align = checkalign(lsdir, option); temp = lsdir; ft_startlscut(lsdir, option, align, dir); free(align); if (option->optionrr) ls_recursiveon(temp, option); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sh_builtins.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/04/06 19:18:34 by gjensen #+# #+# */ /* Updated: 2015/06/22 22:03:07 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh1.h" void sh_notfound(char *av) { char *str; str = ft_strjoin("ft_minishell1: command not found: ", av); ft_putendl_fd(str, 2); ft_strdel(&str); } void sh_builtin_exit(char **av) { unsigned char val; val = 0; if (av && av[1]) { if (ft_isdigit(av[1][0])) val = ft_atoi(av[1]); else { ft_putendl_fd("exit: Expression Syntax.", 2); return ; } } exit(val); } int sh_search_builtin(char *av, char ***env) { int state; char **option; if (!av || !env || !(*av)) return (0); state = 0; option = ft_strsplit(av, ' '); if (option[0]) { if (ft_strcmp(option[0], "cd") == 0) sh_builtin_cd(option, env), state = 1; else if (ft_strcmp(option[0], "exit") == 0) sh_builtin_exit(option), state = 1; else if (ft_strcmp(option[0], "env") == 0) sh_builtin_env(option, env), state = 1; else if (ft_strcmp(option[0], "setenv") == 0) sh_builtin_setenv(option, env), state = 1; else if (ft_strcmp(option[0], "unsetenv") == 0) sh_builtin_unsetenv(option, env), state = 1; else if (ft_strcmp(option[0], "clear") == 0) ft_putstr("\033[1;1H\033[2J"), state = 1; } ft_arrfree(&option); return (state); } <file_sep># **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: gjensen <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2016/11/30 18:04:28 by gjensen #+# #+# # # Updated: 2016/12/12 17:07:42 by gjensen ### ########.fr # # # # **************************************************************************** # ifeq ($(HOSTTYPE),) HOSTTYPE := $(shell uname -m)_$(shell uname -s) endif NAME = libft_malloc_$(HOSTTYPE).so LS = libft_malloc.so CC = gcc CFLAGS = -Werror -Wextra -Wall CPATH = src/ INC = -I./includes -I./libft/includes LIB = ./libft/libft.a LINK = -Llibft -lft CFILES = ft_malloc.c \ do_malloc.c \ free.c \ manage_page.c \ realloc.c \ show_alloc_mem.c \ print_adress.c OPATH = obj/ OFILES = $(CFILES:.c=.o) OBJ = $(addprefix $(OPATH), $(OFILES)) .PHONY: all clean fclean re all: $(LIB) $(NAME) $(NAME): $(OBJ) @echo "Making $(NAME)..." $(CC) -shared -o $(NAME) $^ $(LINK) ln -s $(NAME) $(LS) @echo "Done !" $(OPATH)%.o: $(CPATH)%.c @mkdir -p $(OPATH) @echo "Making object..." $(CC) $(CFLAGS) -c $^ $(INC) -o $@ @echo "Done !" $(LIB): @echo "Compiling libft.." @make -C libft @echo "Done !" clean: /bin/rm -f $(OBJ) make -C libft clean fclean: clean /bin/rm -f $(LS) make -C ./libft fclean /bin/rm -rf $(NAME) re: fclean all <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_dataservcmd2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/10 18:07:13 by gjensen #+# #+# */ /* Updated: 2015/06/22 16:33:12 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static void ftp_getcmd_send(int cs, char *str) { char *buf; char *len; t_stat filestat; int fd; char file[2]; if ((fd = open(str, O_RDWR)) != 1) { if (fstat(fd, &filestat) == -1) return ; buf = (char *)malloc(sizeof(char) * filestat.st_size); read(fd, buf, filestat.st_size); if (read(cs, file, 1)) { file[1] = 0; if (file[0] == 'y') { len = ft_itoa(filestat.st_size); send(cs, len, ft_strlen(len) + 1, 0); send(cs, "\r\n", 2, 0); send(cs, buf, filestat.st_size, 0), ft_strdel(&len); } } close(fd), ft_strdel(&buf); } } void ftp_getcmd(int cs, char *line) { char **cmd; cmd = ft_strsplit(line, ' '); if (!ftp_acess(cmd[1])) { write(cs, "ok\0", 3); ftp_getcmd_send(cs, cmd[1]); } else write(cs, "nf\0", 3); ft_arrfree(&cmd); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/04/01 16:08:36 by gjensen #+# #+# */ /* Updated: 2015/06/22 20:28:40 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh1.h" void sh_execute_cmd(char *line, char ***sh_env, char **paths) { char **av; int n; char *nl; if (!(nl = ft_epur_tab(line))) nl = line; av = ft_strsplit(nl, ';'); n = 0; if (nl) free(nl); while (av[n]) { if (!sh_search_builtin(av[n], sh_env)) sh_execute_bin(av[n], sh_env, paths); n++; } if (av) ft_arrfree(&av); } void fork_process(char *path, char **env, char **av) { pid_t father; int stat_loc; father = fork(); save_cpid(&father); if (father != -1) { if (father == 0) { if (execve(path, av, env) == -1) ft_putendl_fd("Format error", 2); exit (0); } else waitpid(father, &stat_loc, 0); } if (WIFSIGNALED(stat_loc)) sh_wrong_exit(WTERMSIG(stat_loc), path); father = 0; save_cpid(&father); } static void free_memory(char *line, char **paths) { if (line) ft_strdel(&line); if (paths) ft_arrfree(&paths); } void sh_loop(char **env) { char *line; char **paths; char **sh_env; sh_env = ft_arrcpy(env); while (42) { sh_save_env(&sh_env); sh_prompt(&sh_env); if (get_next_line(0, &line) <= 0) exit(0); paths = sh_parse_env("PATH", sh_env); sh_execute_cmd(line, &sh_env, paths); free_memory(line, paths); } } int main(int ac, char **av, char **env) { (void)ac; (void)av; sh_signals(); sh_loop(env); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* tool.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/03/09 15:40:50 by gjensen #+# #+# */ /* Updated: 2015/03/26 17:30:50 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void get_center(t_env *e) { t_point p; int yl; int xl; double fx; double fy; fx = e->map->lines[0]->points[0]->x; fy = e->map->lines[0]->points[0]->y; yl = e->map->len; xl = e->map->lines[yl - 1]->len; p.x = (e->map->lines[yl - 1]->points[xl - 1]->x + fx) / 2; p.y = (e->map->lines[yl - 1]->points[xl - 1]->y + fy) / 2; e->center = p; } void init_window(char *title, int weight, int height, t_env *e) { if ((e->mlx = mlx_init()) == NULL) fdf_malloc_error(); e->win = mlx_new_window(e->mlx, weight, height, title); } int get_color(t_point *point1, t_point *point2) { int color; int z; if (point1->z_color > point2->z_color) z = point1->z_color; else z = point2->z_color; if (z < 0) color = 0x0D6386; else if (z >= 0 && z < 10) color = 0x74c615; else if (z >= 10 && z < 20) color = 0x8FC89A; else if (z >= 20) color = 0xFAECBE; else color = 0; return (color); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/03/26 15:20:58 by gjensen #+# #+# */ /* Updated: 2015/03/26 17:23:32 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void fdf_exit(void) { exit(1); } void fdf_malloc_error(void) { ft_putstr_fd("malloc error\n", 2); fdf_exit(); } void fdf_map_error(void) { ft_putstr_fd("map error\n", 2); fdf_exit(); } void fdf_arg_error(void) { ft_putstr_fd("Fdf: usage: ./fdf mapname.fdf\n", 2); fdf_exit(); } int main(int argc, char **argv) { t_env *e; t_map *map; if (argc == 2) { if (!(e = (t_env*)malloc(sizeof(t_env)))) fdf_malloc_error(); map = fd_parse(argv, 0, 0); if (map->len == 0) fdf_map_error(); e->map = map; get_center(e); init_window("Fdf", WINDOW_SIZE_W, WINDOW_SIZE_H, e); mlx_key_hook(e->win, key_hook, e); mlx_expose_hook(e->win, expose_hook, e); mlx_loop(e->mlx); } else fdf_arg_error(); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* free.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/01 15:37:26 by gjensen #+# #+# */ /* Updated: 2016/12/12 15:59:45 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" t_mdata *find_mdataptr(void *ptr, t_page *page) { t_mdata *mdata; if (page) { mdata = page->start; while (mdata) { if (mdata == (void *)ptr - sizeof(t_mdata)) return (mdata); mdata = mdata->next; } } return (NULL); } t_page *find_pageptr(void *ptr) { t_page *tmp; if (!g_firstpage) return (NULL); if ((tmp = g_firstpage)) { while (tmp) { if (ptr >= (void *)tmp->start && ptr < (void *)tmp->start + tmp->size) return (tmp); tmp = tmp->next; } } return (NULL); } int free_page(t_page *page) { t_page *tmp; if ((tmp = g_firstpage)) { if (page == g_firstpage) { g_firstpage = page->next; return (munmap((void *)page, page->size + sizeof(t_page))); } else { while (tmp->next) { if (page == tmp->next) { tmp->next = page->next; return (munmap((void *)page, page->size + sizeof(t_page))); } tmp = tmp->next; } } } return (1); } void free(void *ptr) { t_page *page; t_mdata *mdata; if (!ptr) return ; if ((page = find_pageptr(ptr)) == NULL) return ; if ((mdata = find_mdataptr(ptr, page)) == NULL) return ; if (page->type == LARGE) { free_page(page); return ; } mdata->free = 1; ptr = NULL; } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* manage_page.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/05 11:41:17 by gjensen #+# #+# */ /* Updated: 2016/12/12 16:13:41 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" size_t get_max_size(char type, size_t size) { if (type == TINY) return (TINY_SIZE_MAX); else if (type == SMALL) return (SMALL_SIZE_MAX); else return (size); print_error("Max size error"); return (0); } void *find_page(size_t size) { t_page *page; char type; page = g_firstpage; type = get_sizetype(size); while (page) { if (page->type == type && !page->full) { if ((page->size + size + sizeof(t_mdata)) > get_max_size(type, size)) { page->full = 1; return (NULL); } else { page->size += size + sizeof(t_mdata); return (page); } } page = page->next; } return (NULL); } void set_metadata(size_t size, t_mdata *mdata, void *next) { mdata->next = next; mdata->size = size; mdata->free = 0; } t_page *set_page(t_page *page, char type) { page->size = 0; page->full = 0; page->type = type; page->next = NULL; page->start = page + 1; return (page); } void *page_push(t_page *first, size_t size, char type) { t_page *tmp; if (!first) { if ((first = (void *)mmap(0, get_max_size(type, size) + sizeof(t_page), PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0)) == MAP_FAILED) print_error("Mapping failed"); first = set_page(first, type); } else { tmp = first; while (tmp->next) tmp = tmp->next; if ((tmp->next = (void *)mmap(0, get_max_size(type, size) + sizeof(t_page), PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0)) == MAP_FAILED) print_error("Mapping failed"); tmp->next = set_page(tmp->next, type); tmp = tmp->next; return (tmp); } return (first); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_clientcmd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/22 17:22:05 by gjensen #+# #+# */ /* Updated: 2015/06/23 19:03:02 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static void ftp_builtin_cd(char **option, int sock) { char *full_cmd; char ret[4]; if (option[1]) { full_cmd = ft_joinarray(&option[1]); full_cmd = ft_strjoin("CWD ", full_cmd); write(sock, full_cmd, ft_strlen(full_cmd) + 1); ft_strdel(&full_cmd); } else write(sock, "CWD", 3); if (read(sock, ret, 4)) { if (ft_strcmp(ret, "arg") == 0) ft_putendl_fd("ERROR: cd: Too many arguments", 2); else if (ft_strcmp(ret, "nof") == 0) ft_putendl_fd("ERROR: cd: Not a directory", 2); else if (ft_strcmp(ret, "err") == 0) ft_putendl_fd("ERROR: cd: Unexepected error occured", 2); else if (ft_strcmp(ret, "scc") == 0) ft_putendl("SUCCESS: Directory sucessfully changed"); } } static void ftp_builtin_ls(char **option, int sock) { char *full_cmd; if (option[1]) { full_cmd = ft_joinarray(&option[1]); full_cmd = ft_strjoin("LIST ", full_cmd); write(sock, full_cmd, ft_strlen(full_cmd) + 1); ft_strdel(&full_cmd); } else write(sock, "LIST", 4); } int ftp_client_cmd(int sock, char **option, int state, char *home) { if (!option || !sock || !(*option)) return (0); if (option[0]) { if (ft_strcmp(ft_tomin(option[0]), "ls") == 0) ftp_builtin_ls(option, sock), state = 1; else if (ft_strcmp(ft_tomin(option[0]), "cd") == 0) ftp_builtin_cd(option, sock); else if (ft_strcmp(ft_tomin(option[0]), "pwd") == 0) write(sock, "PWD", 3), state = 1; else if (ft_strcmp(ft_tomin(option[0]), "quit") == 0) write(sock, "QUIT", 4), ft_putendl("SUCCESS: exit ok"), exit(0); else if (ft_strcmp(ft_tomin(option[0]), "get") == 0) ftp_builtin_get(option, sock); else if (ft_strcmp(ft_tomin(option[0]), "put") == 0) ftp_builtin_put(option, sock); else if ((ftp_local_cmd(option, home))) ; else ft_putendl_fd("Command not found", 2); } return (state); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* long.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/17 11:58:11 by gjensen #+# #+# */ /* Updated: 2015/01/21 21:56:54 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void showlinks(t_lsdir *lsdir, t_lsalign *align) { int space; space = align->links; while (space > ft_intlen(lsdir->stat->st_nlink)) { ft_putchar(' '); space--; } ft_putnbr(lsdir->stat->st_nlink); ft_putchar(' '); } void showbytes(t_lsdir *lsdir, t_lsalign *align) { int space; if (S_ISCHR(lsdir->stat->st_mode) || S_ISBLK(lsdir->stat->st_mode)) { ft_putchar(' '); space = align->majorl; while (space > ft_intlen(MAJOR(lsdir->stat->st_rdev))) { ft_putchar(' '); space--; } ft_putnbr(MAJOR(lsdir->stat->st_rdev)); ft_putstr(","); space = align->minorl; while (space > ft_intlen(MINOR(lsdir->stat->st_rdev))) { ft_putchar(' '); space--; } ft_putnbr(MINOR(lsdir->stat->st_rdev)); align->alignmaj = align->minorl + align->majorl + 2; } else showbytescut(lsdir, align); } void show_id(t_lsdir *lsdir, t_lsalign *align) { size_t space; char *idname; space = align->user; if (lsdir->idn) idname = lsdir->idn; else idname = ft_itoa(lsdir->stat->st_uid); free(lsdir->idn); ft_putstr(idname); while (space > ft_strlen(idname)) { ft_putchar(' '); space--; } ft_putstr(" "); show_grp(lsdir, align); } void showtime(time_t *clock) { char *str; time_t ct; char *date; char *year; char *hours; ct = time(NULL); if ((str = ctime(clock)) == NULL) return ; date = ft_strsub(str, 3, 7); ft_putstr(date); if (*clock > ct || *clock + 15768000 < ct) { year = ft_strsub(str, 19, 5); ft_putchar(' '); ft_putstr(year); ft_putchar(' '); } else { hours = ft_strsub(str, 10, 6); ft_putstr(hours); ft_putchar(' '); } } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* argmanage.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/08 23:41:21 by gjensen #+# #+# */ /* Updated: 2016/02/23 19:05:50 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" int ft_checkelsedir(char *name) { t_stat *file_stat; if (!(file_stat = (t_stat*)malloc(sizeof(t_stat)))) exit(1); if (stat(name, file_stat) == -1) return (0); else if (S_ISDIR(file_stat->st_mode)) return (1); else return (2); return (0); } void ls_show_uk(int argc, char **argv, int i) { while (i < argc) { if (!ft_checkelsedir(argv[i]) && i < argc) while (!ft_checkelsedir(argv[i]) && i < argc) { ft_putstr(TITLE); ft_putstr(": "); perror(argv[i]); i++; } i++; } } void ls_show_reg(int argc, char **argv, t_lsoption *option, int i) { while (i < argc) { if (ft_checkelsedir(argv[i]) == 2) while (ft_checkelsedir(argv[i]) == 2 && i < argc) { ft_startls(NULL, option, argv[i], NULL); option->first = 0; i++; } i++; } } void ls_show_dir(int argc, char **argv, t_lsoption *option, int i) { int n; n = i; while (i < argc) { while (ft_checkelsedir(argv[i]) == 1 && i < argc) { if (argc > n + 1) { if (!option->first) ft_putchar('\n'); else option->first = 0; ft_putstr(argv[i]); ft_putendl(":"); } ls_show_dir2(argv[i], option); i++; } i++; } free(option); } void ls_show_dir2(char *title, t_lsoption *option) { DIR *dir; if ((dir = opendir(title)) != NULL) { ft_startls(dir, option, title, NULL); closedir(dir); } else { ft_putstr(TITLE); ft_putstr(": "); perror(title); } } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* malloc.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/30 15:56:19 by gjensen #+# #+# */ /* Updated: 2016/12/12 16:17:40 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FT_MALLOC_H # define FT_MALLOC_H # include <sys/mman.h> # include <stdlib.h> # include <sys/resource.h> # include "libft.h" # define TINY 'T' # define SMALL 'S' # define LARGE 'L' # define PAGE_SIZE getpagesize() # define TINY_SIZE (size_t)(PAGE_SIZE) # define SMALL_SIZE (size_t)(PAGE_SIZE * 20) # define TINY_SIZE_MAX TINY_SIZE * 101 # define SMALL_SIZE_MAX SMALL_SIZE * 101 void free(void *ptr); void *malloc(size_t size); void *realloc(void *ptr, size_t size); void show_alloc_mem(); void *calloc(size_t nmemb, size_t size); typedef struct s_mdata { size_t size; int free; void *next; } t_mdata; typedef struct s_page { size_t size; int full; void *start; char type; void *next; } t_page; extern t_page *g_firstpage; void *page_push(t_page *first, size_t size, char type); void set_metadata(size_t size, t_mdata *mdata, void *next); t_page *set_page(t_page *page, char type); void *find_page(size_t size); size_t get_max_size(char type, size_t size); void get_system_limit(size_t size); void print_error(char *str); char get_sizetype(size_t size); void *malloc_large(size_t size); void *init_block(void *ptr, size_t size); void *first_malloc(size_t size); void *do_malloc(size_t size); t_mdata *find_mdataptr(void *ptr, t_page *page); t_page *find_pageptr(void *ptr); int free_page(t_page *page); void *do_bigger_realloc(t_mdata *mdata, size_t size, t_page *page, void *ptr); void *do_smaller_realloc(void *ptr, size_t size); void print_adress(void *addr); void ft_itoa_hex(uint64_t n, char *buff); #endif <file_sep># **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: gjensen <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2015/04/01 15:26:04 by gjensen #+# #+# # # Updated: 2015/05/13 14:39:48 by gjensen ### ########.fr # # # # **************************************************************************** # NAME = ft_minishell1 SRC = main.c command.c envmanage.c sh_builtins.c sh_builtin_cd.c sh_builtin_env.c sh_builtin_setenv.c sh_builtin_unsetenv.c signals.c \ childsignals.c OBJ = $(SRC:.c=.o) CFLAGS = -Werror -Wextra -Wall -I libft/includes -g #CFLAGS = -I libft/includes -g all: $(NAME) $(NAME): $(OBJ) make -C libft/ fclean make -C libft/ gcc $(CFLAGS) -o $(NAME) $(OBJ) -L libft/ -lft clean: rm -rf $(OBJ) fclean: clean rm -rf $(NAME) re: fclean $(NAME) .PHONY: all re fclean clean <file_sep># **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: gjensen <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2014/11/26 10:48:25 by gjensen #+# #+# # # Updated: 2015/04/01 16:00:37 by gjensen ### ########.fr # # # # **************************************************************************** # NAME = ft_ls SRC = ft_ls.c main.c tool.c tool2.c long.c long2.c managestart.c argmanage.c recursive.c OBJ = ft_ls.o main.o tool.o tool2.o long.o long2.o managestart.o argmanage.o recursive.o CFLAGS = -Werror -Wall -Wextra LIB = -I ./libft/includes $(NAME): make -C libft/ fclean make -C libft/ gcc $(CFLAGS) -c $(SRC) $(LIB) -g gcc $(CFLAGS) -o $(NAME) $(OBJ) -L libft/ -lft -g all: $(NAME) .PHONY: clean fclean re clean: rm -rf $(OBJ) fclean: clean rm -rf $(NAME) re: fclean $(NAME) <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* realloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/01 15:40:39 by gjensen #+# #+# */ /* Updated: 2016/12/12 16:00:24 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" void *calloc(size_t nmemb, size_t size) { void *ptr; ptr = malloc(nmemb * size); ft_bzero(ptr, nmemb * size); return (ptr); } void *do_smaller_realloc(void *ptr, size_t size) { void *tmp; tmp = malloc(size); ptr = ft_memcpy(tmp, ptr, size); return (ptr); } void *do_bigger_realloc(t_mdata *mdata, size_t size, t_page *page, void *ptr) { void *tmp; if (page->size != LARGE) { if (mdata->next == NULL) { if ((page->size + size) < get_max_size(page->type, size)) { mdata->size = size; return (ptr); } } } tmp = malloc(size); return (ft_memcpy(tmp, ptr, mdata->size)); } void *realloc(void *ptr, size_t size) { t_page *page; t_mdata *mdata; if (!ptr) return (malloc(size)); if (!size && ptr) { free(ptr); malloc(TINY_SIZE); } if ((page = find_pageptr(ptr)) == NULL) return (NULL); if ((mdata = find_mdataptr(ptr, page)) == NULL) return (NULL); if (size > mdata->size) return (do_bigger_realloc(mdata, size, page, ptr)); else if (size < mdata->size) return (do_smaller_realloc(ptr, size)); else return (ptr); return (NULL); } <file_sep># 42_Project Some of my 42 projects <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_tool.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/09 21:47:23 by gjensen #+# #+# */ /* Updated: 2015/06/15 15:52:51 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" int ftp_isbin(char *path) { int state; t_stat filestat; state = 0; if (lstat(path, &filestat) == -1) state = 0; else if (S_ISDIR(filestat.st_mode)) state = 1; else if (S_ISLNK(filestat.st_mode)) state = 3; else if (S_ISREG(filestat.st_mode)) state = 2; return (state); } void ftp_cprompt(char *addr, int port) { printf("[%s:%d]\n", addr, port); ft_putstr("ft_p $>"); } int ftp_acess(char *path) { if (ftp_isbin(path) == 2) { if (access(path, R_OK) == 0) return (0); else return (-1); } return (-1); } char *ftp_opt_ls(char *buf) { char **option; option = ft_strsplit(buf, ' '); if (option[1]) { if (option[1][0] == '-') { if (ft_strchr(option[1], 'a')) { ft_arrfree(&option); return ("-la"); } } } ft_arrfree(&option); return ("-l"); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_malloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/30 15:55:21 by gjensen #+# #+# */ /* Updated: 2016/12/12 15:54:26 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" t_page *g_firstpage; void print_error(char *str) { ft_putendl_fd(str, 2); exit(1); } void get_system_limit(size_t size) { size_t total; struct rlimit rlp; getrlimit(RLIMIT_AS, &rlp); total = rlp.rlim_cur; if (total < size) print_error("Not enough space available"); } void *malloc(size_t size) { void *ptr; static int init; if (!init) { init = 1; g_firstpage = NULL; } get_system_limit(size); ptr = do_malloc(size); return (ptr); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftp_servcmd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/22 17:38:43 by gjensen #+# #+# */ /* Updated: 2015/06/22 20:42:47 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" static void ftp_pwdcmd(int cs, char *home) { char pwd[1024]; char *offsetpath; getcwd(pwd, 1024); dup2(cs, STDOUT_FILENO); dup2(cs, STDERR_FILENO); if ((offsetpath = ft_strstr(pwd, home)) && (ft_strlen(offsetpath) > ft_strlen(home))) offsetpath = pwd + ft_strlen(home); else offsetpath = "/"; ft_putchar('\"'); ft_putstr(offsetpath); ft_putchar('\"'); ft_putstr("\nSUCCESS: Current directory sent"); dup2(STDIN_FILENO, STDOUT_FILENO); dup2(STDIN_FILENO, STDERR_FILENO); send(cs, "\r\n", 2, 0); } static void ftp_lscmd(int cs, char *buf) { pid_t pid; char *opt; opt = ftp_opt_ls(buf); dup2(cs, STDOUT_FILENO); dup2(cs, STDERR_FILENO); pid = fork(); if (pid != -1) { if (pid == 0) { if (execl("/bin/ls", "/bin/ls", opt) == -1) return (ft_putendl_fd("ERROR: Can't send list", 2)); exit (0); } else wait4(pid, 0, 0, 0); } ft_putstr("SUCCESS: Directory list succesfully sent"); dup2(STDIN_FILENO, STDOUT_FILENO); dup2(STDIN_FILENO, STDERR_FILENO); send(cs, "\r\n", 2, 0); } static void ftp_cd_open(char *dir, char *home, int cs) { char pwd[1024]; if (chdir(dir) == 0) { getcwd(pwd, 1024); if (!(ft_strstr(pwd, home))) { if (chdir(home) == 0) write(cs, "scc\0", 4); else write(cs, "err\0", 4); } else write(cs, "scc\0", 4); } else write(cs, "err\0", 4); } static void ftp_cwdcmd(int cs, char *buf, char *home) { char **cmd; cmd = ft_strsplit(buf, ' '); if (ft_arrlen(cmd) > 2) { write(cs, "arg\0", 4), ft_arrfree(&cmd); return ; } if (ft_arrlen(cmd) == 1) { chdir(home), write(cs, "scc\0", 4), ft_arrfree(&cmd); return ; } else if (access(cmd[1], F_OK) == 0) { if (ftp_isbin(cmd[1]) == 1 || ftp_isbin(cmd[1]) == 3) ftp_cd_open(cmd[1], home, cs); else write(cs, "nof\0", 4); } else write(cs, "nof\0", 4); ft_arrfree(&cmd); } void ftp_read_socket(int cs) { char buf[1024]; int r; char home[1024]; write(cs, "ok\0", 3); getcwd(home, 1024); while ((r = read(cs, buf, 1023)) > 0) { buf[r] = 0; if (ft_strncmp("LIST", buf, 4) == 0) ftp_lscmd(cs, buf); else if (ft_strncmp("PWD", buf, 3) == 0) ftp_pwdcmd(cs, home); else if (ft_strncmp("QUIT", buf, 4) == 0) return ; else if (ft_strncmp("CWD", buf, 3) == 0) ftp_cwdcmd(cs, buf, home); else if (ft_strncmp("STOR", buf, 4) == 0) ftp_putcmd(cs, buf); else if (ft_strncmp("RETR", buf, 4) == 0) ftp_getcmd(cs, buf); } } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* tool.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/11/27 18:31:10 by gjensen #+# #+# */ /* Updated: 2016/02/17 17:28:23 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" t_lsdir *ft_newlst(void) { t_lsdir *ret; if ((ret = (t_lsdir*)malloc(sizeof(t_lsdir))) == NULL) return (NULL); if ((ret->stat = (struct stat*)malloc(sizeof(struct stat))) == NULL) return (NULL); ret->next = NULL; ret->previous = NULL; return (ret); } void swaplist(t_lsdir *lsdir, t_lsdir *lsdirnext) { t_lsdir *tmp; t_lsdir *tmp_lsdir; t_lsdir *tmp_lsdirprevious; tmp = lsdir->next; tmp_lsdir = lsdir; tmp_lsdirprevious = lsdir->previous; if (lsdir->previous != NULL) lsdir->previous->next = lsdirnext; lsdir->previous = lsdirnext; lsdir->next = lsdirnext->next; lsdir = tmp; lsdir->next = tmp_lsdir; lsdir->previous = tmp_lsdirprevious; } void printls(t_lsdir *lsdir, t_lsalign *align, t_lsoption *option) { char buf[1024]; if (option->optionl) { checkmode(lsdir); showlinks(lsdir, align); show_id(lsdir, align); showbytes(lsdir, align); showtime(&lsdir->stat->st_mtime); ft_putstr(lsdir->name); ft_bzero(buf, sizeof(buf)); readlink(lsdir->path, buf, sizeof(buf)); if (buf[0]) { ft_putstr(" -> "); ft_putstr(buf); } ft_putchar('\n'); } else ft_putendl(lsdir->name); } static t_lsalign *checkaligncut(t_lsalign *align, t_lsdir *lsdir) { int links; int user; int grp; links = ft_intlen(lsdir->stat->st_nlink); if (links > align->links) align->links = links; if (lsdir->idn) user = ft_strlen(lsdir->idn); else user = ft_strlen(ft_itoa(lsdir->stat->st_uid)); if (user > align->user) align->user = user; if (lsdir->gn) grp = ft_strlen(lsdir->gn); else grp = ft_strlen(ft_itoa(lsdir->stat->st_gid)); if (grp > align->grp) align->grp = grp; return (align); } t_lsalign *checkalign(t_lsdir *lsdir, t_lsoption *option) { t_lsalign *align; align = (t_lsalign*)malloc(sizeof(t_lsalign)); align->totalblocks = 0; align->links = 0; align->user = 0; align->grp = 0; align->bytes = 0; align->minorl = 0; align->majorl = 0; align->alignmaj = 0; while (lsdir) { if (!option->optiona) while (lsdir && lsdir->name[0] == '.') lsdir = lsdir->next; if (lsdir) { align->totalblocks += lsdir->stat->st_blocks; align = checkaligncut(align, lsdir); align = checkaligncut2(align, lsdir); lsdir = lsdir->next; } } return (align); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* createserv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/17 21:47:05 by gjensen #+# #+# */ /* Updated: 2015/06/22 16:33:25 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_p.h" void ftp_acceptclient(int sock) { int cs; unsigned int cslen; struct sockaddr_in csin; pid_t cpid; while (42) { cslen = sizeof(csin); if ((cs = accept(sock, (struct sockaddr*)&csin, &cslen)) > 0) printf("[%s:%d] connected\n", inet_ntoa(csin.sin_addr), ntohs(csin.sin_port)); cpid = fork(); if (cpid == 0) { ftp_read_socket(cs); printf("[%s:%d] disconnected\n", inet_ntoa(csin.sin_addr), ntohs(csin.sin_port)); close(sock); close(cs); exit(0); } else close(cs); } } int create_server(int port) { int sock; struct protoent *proto; struct sockaddr_in sin; proto = getprotobyname("tcp"); if (!proto) return (-1); sock = socket(PF_INET, SOCK_STREAM, proto->p_proto); sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock, (const struct sockaddr *)&sin, sizeof(sin)) < 0) ft_putendl_fd("Bind error", 2), exit(2); if (listen(sock, 42) == -1) ft_putendl_fd("Listen error", 2), exit (2); return (sock); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ls.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/11/26 10:02:38 by gjensen #+# #+# */ /* Updated: 2015/04/06 16:25:45 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FT_LS_H # define FT_LS_H # include <dirent.h> # include <unistd.h> # include "libft.h" # include <sys/stat.h> # include <sys/types.h> # include <pwd.h> # include <uuid/uuid.h> # include <grp.h> # include <sys/xattr.h> # include <time.h> # include <stdlib.h> # include <stdio.h> # define TITLE "ft_ls" # define MAJOR(x) ((int32_t)(((u_int32_t)(x) >> 24) & 0xff)) # define MINOR(x) ((int32_t)((x) & 0xffffff)) typedef struct stat t_stat; typedef struct s_lsdir { char name[256]; char *path; char *idn; char *gn; t_stat *stat; struct s_lsdir *next; struct s_lsdir *previous; } t_lsdir; typedef struct s_lsalign { int totalblocks; int links; int user; int grp; int bytes; int minorl; int majorl; int alignmaj; } t_lsalign; typedef struct s_lsoption { int hidden; int optionl; int optiona; int optionr; int optionrr; int optiont; int first; } t_lsoption; t_lsdir *ft_newlst(void); void swaplist(t_lsdir *lsdir, t_lsdir *lsdirnext); void ft_addlsdir(t_lsdir **tlsdir, t_lsdir *new, char *name, char *path); t_lsdir *ft_ls_sortascii(t_lsdir *lsdir, int exchange); void checkmode(t_lsdir *lsdir); void show_id(t_lsdir *lsdir, t_lsalign *align); void printls(t_lsdir *lsdir, t_lsalign *align, t_lsoption *option); void showtime(time_t *clock); t_lsalign *checkalign(t_lsdir *lsdir, t_lsoption *option); void showlinks(t_lsdir *lsdir, t_lsalign *align); void showbytes(t_lsdir *lsdir, t_lsalign *align); int ft_parse(t_lsoption *option, char **argv); void ft_startls(DIR *dir, t_lsoption *option, char *argv, t_lsdir *lsdir); char **ft_argsort(char **argv, int start, int end); t_lsdir *ft_ls_sorttime(t_lsdir *lsdir, int exchange); void ft_start_recursive(t_lsdir *lsdir, t_lsoption *option); t_lsalign *checkaligncut2(t_lsalign *align, t_lsdir *lsdir); t_lsdir *ft_ls_sorttimeascii(t_lsdir *lsdir, int exchange); t_lsdir *ls_addidandgrp(t_lsdir *new, char *name); void showbytescut(t_lsdir *lsdir, t_lsalign *align); void show_grp(t_lsdir *lsdir, t_lsalign *align); void showblocks(t_lsdir *lsdir, t_lsalign *align, t_lsoption *option); t_lsdir *ls_sort_lsdir(t_lsdir *lsdir, t_lsoption *option); void ls_recursiveon(t_lsdir *lsdir, t_lsoption *option); void ft_startlscut(t_lsdir *lsdir, t_lsoption *option, t_lsalign *align, DIR *dir); int ft_parsecut(t_lsoption *option, char **argv, int i); void ls_show_uk(int argc, char **argv, int i); void ls_show_reg(int argc, char **argv, t_lsoption *option, int i); void ls_show_dir(int argc, char **argv, t_lsoption *option, int i); int ft_checkelsedir(char *name); void ls_show_dir2(char *title, t_lsoption *option); void ls_swapstr(char **a, char **b); char **ft_argsortreverse(char **argv, int start, int end); void ls_addpath(t_lsdir *new, char *name, char *path); #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parsearg.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/02/17 19:19:11 by gjensen #+# #+# */ /* Updated: 2015/03/27 16:34:38 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" int fd_check_points(char *line, int nb_line, t_point ***point) { char **str; t_point *a_point; int i; str = ft_strsplit(line, ' '); i = 0; while (str[i] != NULL) i++; if (!((*point) = (t_point**)malloc(sizeof(t_point) * (i + 1)))) fdf_malloc_error(); i = 0; while (str[i] != NULL) { a_point = (t_point*)malloc(sizeof(t_point)); a_point->y = ((nb_line + i) * SIZE_H) / 2; a_point->x = (i - nb_line) * SIZE_W; a_point->z = ft_atoi(str[i]); a_point->z_color = a_point->z; (*point)[i] = a_point; i++; } (*point)[i] = NULL; return (i); } int fd_line_n(char *map) { int fd; int nb_lines; char buf; fd = 0; nb_lines = 0; if ((fd = open(map, O_RDONLY)) < 0) return (0); while (read(fd, &buf, 1)) { if (buf == '\n') nb_lines++; } close(fd); return (nb_lines); } t_map *fd_parse(char **argv, int fd, int nb_lines) { char *line; t_line *line_map; t_map *map; t_point **point; if (!(map = (t_map*)malloc(sizeof(t_map))) || !(map->lines = (t_line**)malloc(sizeof(t_line) * fd_line_n(argv[1]) + 1))) fdf_malloc_error(); map->len = 0; if ((fd = open(argv[1], O_RDONLY)) > 0) { while ((get_next_line(fd, &line)) > 0) { if (!(line_map = (t_line*)malloc(sizeof(t_line)))) fdf_malloc_error(); line_map->len = fd_check_points(line, nb_lines, &point); line_map->points = point; map->lines[nb_lines] = line_map; if (line_map->len) nb_lines++; } map->lines[nb_lines] = NULL; map->len = nb_lines; } return (map); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fdf.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/09 23:13:37 by gjensen #+# #+# */ /* Updated: 2015/03/27 16:27:37 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FDF_H # define FDF_H # include <mlx.h> # include <unistd.h> # include "libft.h" # include <stdio.h> # include <fcntl.h> # include <math.h> # define SIZE_W 30 # define SIZE_H 30 # define WINDOW_SIZE_H 1000 # define WINDOW_SIZE_W 2000 typedef struct s_point { double y; double x; double z; double s; int z_color; } t_point; typedef struct s_line { t_point **points; int len; } t_line; typedef struct s_map { t_line **lines; int len; } t_map; typedef struct s_env { t_map *map; void *mlx; void *win; t_point center; } t_env; t_map *fd_parse(char **argv, int fd, int nb_lines); int fd_check_points(char *line, int nb_line, t_point ***point); int ft_getnbr(char *str); void draw_map(t_env *e); int expose_hook(t_env *e); int key_hook(int keycode, t_env *e); int get_next_line(int const fd, char **line); int fd_line_n(char *map); void get_center(t_env *e); void init_window(char *title, int weight, int height, t_env *e); void draw(t_env *e, t_point *p1, t_point *p2); void fdf_exit(void); void fdf_malloc_error(void); void fdf_map_error(void); void fdf_arg_error(void); int get_color(t_point *point1, t_point *point2); void draw_linescut(t_point *p1, t_point *p2, double *dxy, double *tab); void draw_lines(t_env *e, t_point p1, t_point p2); #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ls.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/11/26 10:02:20 by gjensen #+# #+# */ /* Updated: 2015/02/03 19:30:08 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void ft_addlsdir(t_lsdir **tlsdir, t_lsdir *new, char *name, char *path) { t_lsdir *temp; if (*tlsdir == NULL) *tlsdir = new; else { temp = *tlsdir; while (temp->next) temp = temp->next; new->previous = temp; temp->next = new; } ls_addpath(new, name, path); new = ls_addidandgrp(new, name); } t_lsdir *ft_ls_sortascii(t_lsdir *lsdir, int exchange) { t_lsdir *tmp; tmp = lsdir; while (exchange) { exchange = 0; lsdir = tmp; while (lsdir->previous) lsdir = lsdir->previous; while (lsdir && lsdir->next) { if (ft_strcmp(lsdir->name, lsdir->next->name) > 0) { swaplist(lsdir, lsdir->next); if (lsdir->next != NULL) lsdir->next->previous = lsdir; exchange = 1; } lsdir = lsdir->next; } } while (lsdir->previous) lsdir = lsdir->previous; return (lsdir); } void checkmode(t_lsdir *lsdir) { if (S_ISDIR(lsdir->stat->st_mode)) ft_putchar('d'); else if (S_ISLNK(lsdir->stat->st_mode)) ft_putchar('l'); else if (S_ISCHR(lsdir->stat->st_mode)) ft_putchar('c'); else if (S_ISBLK(lsdir->stat->st_mode)) ft_putchar('b'); else if (S_ISFIFO(lsdir->stat->st_mode)) ft_putchar('p'); else if (S_ISSOCK(lsdir->stat->st_mode)) ft_putchar('s'); else ft_putchar('-'); (lsdir->stat->st_mode & S_IRUSR) ? ft_putchar('r') : ft_putchar('-'); (lsdir->stat->st_mode & S_IWUSR) ? ft_putchar('w') : ft_putchar('-'); (lsdir->stat->st_mode & S_IXUSR) ? ft_putchar('x') : ft_putchar('-'); (lsdir->stat->st_mode & S_IRGRP) ? ft_putchar('r') : ft_putchar('-'); (lsdir->stat->st_mode & S_IWGRP) ? ft_putchar('w') : ft_putchar('-'); (lsdir->stat->st_mode & S_IXGRP) ? ft_putchar('x') : ft_putchar('-'); (lsdir->stat->st_mode & S_IROTH) ? ft_putchar('r') : ft_putchar('-'); (lsdir->stat->st_mode & S_IWOTH) ? ft_putchar('w') : ft_putchar('-'); (lsdir->stat->st_mode & S_IXOTH) ? ft_putchar('x') : ft_putchar('-'); ft_putstr(" "); } t_lsdir *ft_ls_sorttime(t_lsdir *lsdir, int exchange) { t_lsdir *tmp; tmp = lsdir; while (exchange) { exchange = 0; lsdir = tmp; while (lsdir->previous) lsdir = lsdir->previous; while (lsdir && lsdir->next) { if (lsdir->stat->st_mtimespec.tv_sec < lsdir->next->stat->st_mtimespec.tv_sec) { swaplist(lsdir, lsdir->next); if (lsdir->next != NULL) lsdir->next->previous = lsdir; exchange = 1; } lsdir = lsdir->next; } } while (lsdir->previous) lsdir = lsdir->previous; return (lsdir); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* long2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/12 03:59:00 by gjensen #+# #+# */ /* Updated: 2015/01/15 21:27:06 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void showbytescut(t_lsdir *lsdir, t_lsalign *align) { int space; space = align->bytes + align->alignmaj; while (space > ft_intlen(lsdir->stat->st_size)) { ft_putchar(' '); space--; } ft_putnbr(lsdir->stat->st_size); } void show_grp(t_lsdir *lsdir, t_lsalign *align) { size_t space; char *grname; space = align->grp; if (lsdir->gn) grname = lsdir->gn; else grname = ft_itoa(lsdir->stat->st_gid); ft_putstr(grname); free(lsdir->gn); while (space > ft_strlen(grname)) { ft_putchar(' '); space--; } ft_putstr(" "); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ybarbier <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/04/12 23:25:31 by ybarbier #+# #+# */ /* Updated: 2015/07/21 19:20:10 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <ctype.h> #include <assert.h> #include <unistd.h> #include "libfts.h" #undef KO #undef OK #define KO "\x1B[1;31mKO\033[0m" #define OK "\x1B[1;34mOK\033[0m" #undef TRUE #undef FALSE #define TRUE 1 #define FALSE 0 #undef DEBUG #define DEBUG 0 typedef unsigned char t_bool; /* Functions test */ t_bool test_bzero(t_bool debug); t_bool test_isalpha(t_bool debug); t_bool test_isdigit(t_bool debug); t_bool test_isalnum(t_bool debug); t_bool test_isascii(t_bool debug); t_bool test_isprint(t_bool debug); t_bool test_islower(t_bool debug); t_bool test_isupper(t_bool debug); t_bool test_toupper(t_bool debug); t_bool test_tolower(t_bool debug); t_bool test_puts(t_bool debug); t_bool test_putstr(t_bool debug); t_bool test_strlen(t_bool debug); t_bool test_strcat(t_bool debug); t_bool test_strdup(t_bool debug); t_bool test_strcmp(t_bool debug); t_bool test_strequ(t_bool debug); t_bool test_strcpy(t_bool debug); t_bool test_strnew(t_bool debug); t_bool test_memset(t_bool debug); t_bool test_memcpy(t_bool debug); t_bool test_memcmp(t_bool debug); t_bool test_memdel(t_bool debug); t_bool test_memalloc(t_bool debug); t_bool test_putchar(t_bool debug); t_bool test_putchar_fd(t_bool debug); t_bool test_cat(t_bool debug); t_bool test_cat_fd_0(t_bool debug); t_bool test_cat_fd_test(t_bool debug); /* Print memory*/ void print_mem_ascii(unsigned char *buffer) { printf(" |"); for (int j = 0; j < 16; j++) printf("%c", buffer[j]); printf("|"); } void print_mem(char *desc, void *addr, t_bool ascii, int len) { unsigned char *p = addr; unsigned char buffer[16]; int i = 0; int pos = 0; printf("%s", desc); while (i < len) { printf("\n"); //ADDRESS if ((i % 16) == 0) printf("%p\t", &p[i]); //MEMORY int l = i + 16; int k = 0; bzero(buffer, 16); for (pos = i; (pos < l) && (pos < len); pos++) { printf("%02x", p[pos]); buffer[k] = p[pos]; k == 7 ? printf(" ") : printf(" "); ++k; } i = pos; //ASCII if ((i % 16) == 0 && ascii) print_mem_ascii(buffer); } if (ascii) print_mem_ascii(buffer); printf("\n"); } /* Print and execute test*/ void print_res_test(char *name, t_bool (*f)(t_bool)) { t_bool b; b = (*f)(DEBUG); printf("[\x1B[1;37m%s\033[0m] -> [%s]\n", name, (b ? OK : KO)); if (!b) b = (*f)(1); } int main(void) { print_res_test("ft_bzero", test_bzero); print_res_test("ft_isalpha", test_isalpha); print_res_test("ft_isdigit", test_isdigit); print_res_test("ft_isalnum", test_isalnum); print_res_test("ft_isascii", test_isascii); print_res_test("ft_isprint", test_isprint); print_res_test("ft_islower", test_islower); print_res_test("ft_isupper", test_isupper); print_res_test("ft_toupper", test_toupper); print_res_test("ft_tolower", test_tolower); print_res_test("ft_puts", test_puts); print_res_test("ft_putstr", test_putstr); print_res_test("ft_strlen", test_strlen); print_res_test("ft_strcat", test_strcat); print_res_test("ft_strdup", test_strdup); print_res_test("ft_strcmp", test_strcmp); print_res_test("ft_strequ", test_strequ); print_res_test("ft_strcpy", test_strcpy); print_res_test("ft_strnew", test_strnew); print_res_test("ft_memset", test_memset); print_res_test("ft_memcpy", test_memcpy); // print_res_test("ft_memcmp", test_memcmp); // print_res_test("ft_memdel", test_memdel); print_res_test("ft_memalloc", test_memalloc); print_res_test("ft_putchar", test_putchar); print_res_test("ft_putchar_fd", test_putchar_fd); print_res_test("ft_cat", test_cat); print_res_test("ft_cat fd 0", test_cat_fd_0); print_res_test("ft_cat test", test_cat_fd_test); return (0); } t_bool test_bzero(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test1 = TRUE; t_bool test2 = TRUE; char src1[][SIZE] = { "test", "ok", "iciAB", "", "x\0", "\x02", "\t", "OKokOKokOKOK" }; char src2[][SIZE] = { "test", "ok", "iciAB", "", "x\0", "\x02", "\t", "OKokOKokOKOK" }; int size_arr[] = {0, 2, 4, 4, 5, 5, 100, 3}; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test1 = TRUE; test2 = TRUE; bzero(src1[pos], size_arr[pos]); ft_bzero(src2[pos], size_arr[pos]); if (memcmp(src1[pos], src2[pos], SIZE) != 0) { ret = FALSE; test2 = FALSE; } if (debug) { printf("%s | %s | [%s]\n",src1[pos], src2[pos], test2 ? OK : KO); print_mem("bzero: src1", src1[pos], TRUE, SIZE); print_mem("ft_bzero: src2", src2[pos], TRUE, SIZE); printf("\n"); } } return (ret); } t_bool test_islower(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (islower(buffer[i]) != ft_islower(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], islower(buffer[i]), ft_islower(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_isupper(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (isupper(buffer[i]) != ft_isupper(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], isupper(buffer[i]), ft_isupper(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_isalpha(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (isalpha(buffer[i]) != ft_isalpha(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], isalpha(buffer[i]), ft_isalpha(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_isdigit(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (isdigit(buffer[i]) != ft_isdigit(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], isdigit(buffer[i]), ft_isdigit(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_isalnum(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (isalnum(buffer[i]) != ft_isalnum(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], isalnum(buffer[i]), ft_isalnum(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_isascii(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (isascii(buffer[i]) != ft_isascii(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], isascii(buffer[i]), ft_isascii(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_isprint(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (isprint(buffer[i]) != ft_isprint(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], isprint(buffer[i]), ft_isprint(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_toupper(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (toupper(buffer[i]) != ft_toupper(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], toupper(buffer[i]), ft_toupper(buffer[i]), test ? OK : KO); } return (ret); } t_bool test_tolower(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; int i; char buffer[256] = {0}; for (i = 0; i < 256; i++) buffer[i] = i; for (i = 0; i < 256; i++) { test = TRUE; if (tolower(buffer[i]) != ft_tolower(buffer[i])) { ret = FALSE; test = FALSE; } if (debug) printf("\t%d | %d | %d | [%s]\n", buffer[i], tolower(buffer[i]), ft_tolower(buffer[i]), test ? OK : KO); } return (ret); } void putstr(char const *s) { if (s) write(1, s, ft_strlen(s)); } t_bool test_putstr(t_bool debug) { #undef BUFF_SIZE #define BUFF_SIZE 50 t_bool ret = TRUE; t_bool test = TRUE; char *strings[] = {"test", "test2", "\n", "!@#$%^&*()-+", "\t", "A", " ", "0123", "dewdwedew", "lo\x00lololololpas vu", "lol ewf ewf ewf wef 909 ew0 9", NULL}; char buff1[BUFF_SIZE + 1] = {0}; char buff2[BUFF_SIZE + 1] = {0}; int out_pipe[2]; int saved_stdout; for (size_t pos = 0; pos < (sizeof(strings) / sizeof(char*)); pos++) { /*TEST 1*/ bzero(buff1, BUFF_SIZE); saved_stdout = dup(STDOUT_FILENO); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); putstr(strings[pos]); /*PUTS CMD*/ fflush(stdout); if (strings[pos]) read(out_pipe[0], buff1, BUFF_SIZE); /*TEST 2*/ bzero(buff2, BUFF_SIZE); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); ft_putstr(strings[pos]); /*FT_PUTS CMD*/ fflush(stdout); if(strings[pos]) read(out_pipe[0], buff2, BUFF_SIZE); /*AFF*/ dup2(saved_stdout, STDOUT_FILENO); test = TRUE; if (strcmp(buff1, buff2) != 0) { ret = FALSE; test = FALSE; } if (debug) { printf("->%s\n", strings[pos]); putstr(strings[pos]); ft_putstr(strings[pos]); printf("[%s]\n", test ? OK : KO); } } return (ret); } t_bool test_puts(t_bool debug) { #undef BUFF_SIZE #define BUFF_SIZE 50 t_bool ret = TRUE; t_bool test = TRUE; char *strings[] = {"test", "test2", "\n", "!@#$%^&*()-+", "\t", "A", "", " ", "0123", "dewdwedew", "lo\x00lololololpas vu", "lol ewf ewf ewf wef 909 ew0 9", NULL}; char buff1[BUFF_SIZE + 1] = {0}; char buff2[BUFF_SIZE + 1] = {0}; int out_pipe[2]; int saved_stdout; int i; for (size_t pos = 0; pos < (sizeof(strings) / sizeof(char*)); pos++) { /*TEST 1*/ bzero(buff1, BUFF_SIZE); saved_stdout = dup(STDOUT_FILENO); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); i = puts(strings[pos]); /*PUTS CMD*/ fflush(stdout); read(out_pipe[0], buff1, BUFF_SIZE); /*TEST 2*/ bzero(buff2, BUFF_SIZE); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); ft_puts(strings[pos]); /*FT_PUTS CMD*/ fflush(stdout); read(out_pipe[0], buff2, BUFF_SIZE); /*AFF*/ dup2(saved_stdout, STDOUT_FILENO); test = TRUE; if (strcmp(buff1, buff2) != 0) { ret = FALSE; test = FALSE; } if (debug) { printf("->%s\n", strings[pos]); puts(strings[pos]); ft_puts(strings[pos]); printf("[%s]\n", test ? OK : KO); } } return (ret); } t_bool test_strlen(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; char *strings[] = { "test", "test2", "\n", "!@#$%^&*()-+", "\t", "A", "", " ", "0123", "dewdwedew", "lo\x00lololololpas vu", "lol ewf ewf ewf wef 909 ew0 9", "salut =)\x90\x90", "42 FTW\x01\x00\x90", "hey ooo \x90 dewfewfewfew", "bon\x00 dwedeeeeeeeeeee", "", "lolo\x01lol" }; for (size_t pos = 0; pos < (sizeof(strings) / sizeof(char*)); pos++) { test = TRUE; if (strlen(strings[pos]) != ft_strlen(strings[pos])) { ret = FALSE; test = FALSE; } if (debug) printf("%s -> %lu | %lu | [%s]\n", strings[pos], strlen(strings[pos]), ft_strlen(strings[pos]), test ? OK : KO); } return (ret); } t_bool test_strcat(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test1 = TRUE; t_bool test2 = TRUE; char src1[][SIZE] = { "test", "ok", "ici", "", "x\0", "\x02", "\t" }; char src2[][SIZE] = { "test", "ok", "ici", "", "x\0", "\x02", "\t" }; char s_cat[][SIZE] = { "O", "B", "A", "AAsssdsdAsdasd", "\0", "\x02", "\t" }; char *dst1; char *dst2; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test1 = TRUE; test2 = TRUE; dst1 = strcat(src1[pos], s_cat[pos]); dst2 = ft_strcat(src2[pos], s_cat[pos]); if (memcmp(dst1, dst2, SIZE) != 0) { ret = FALSE; test1 = FALSE; } if (memcmp(src1[pos], src2[pos], SIZE) != 0) { ret = FALSE; test2 = FALSE; } if (debug) { printf("=====BY TEST=====\n"); printf("%s | %s | [%s]\n",dst1, dst2, test1 ? OK : KO); print_mem("strcat: dst1", dst1, TRUE, SIZE); print_mem("ft_strcat: dst2", dst2, TRUE, SIZE); printf("\n"); printf("%s | %s | [%s]\n",src1[pos], src2[pos], test2 ? OK : KO); print_mem("strcat: src1", src1[pos], TRUE, SIZE); print_mem("ft_strcat: src2", src2[pos], TRUE, SIZE); printf("\n"); } } return (ret); } t_bool test_strdup(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test1 = TRUE; t_bool test2 = TRUE; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340" }; char src2[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340" }; char *dst1; char *dst2; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test1 = TRUE; test2 = TRUE; dst1 = strdup(src1[pos]); dst2 = ft_strdup(src2[pos]); if (strcmp(dst1, dst2) != 0) { ret = FALSE; test1 = FALSE; } if (strcmp(src1[pos], src2[pos]) != 0) { ret = FALSE; test2 = FALSE; } if (debug) { printf("=====BY TEST=====\n"); printf("%s | %s | [%s]\n",dst1, dst2, test1 ? OK : KO); print_mem("strdup: dst1", dst1, TRUE, SIZE); print_mem("ft_strdup: dst2", dst2, TRUE, SIZE); printf("\n"); printf("%s | %s | [%s]\n",src1[pos], src2[pos], test2 ? OK : KO); print_mem("strdup: src1", src1[pos], TRUE, SIZE); print_mem("ft_strdup: src2", src2[pos], TRUE, SIZE); printf("\n"); } } return (ret); } t_bool test_strcmp(t_bool debug) { t_bool ret = TRUE; t_bool test = TRUE; char *src1[] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd", //DIFF "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340" }; char *src2[] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd ", //DIFF "Aok", "i1ci", "\0", "x", "\x02\t", "\t\n", "6789abcdefgh", "", "||||||\x00|||||||\\ _=+212312340 " }; for (size_t pos = 0; pos < (sizeof(src1) / (sizeof(char*))); pos++) { test = TRUE; if (strcmp(src1[pos], src2[pos]) != ft_strcmp(src1[pos], src2[pos])) { ret = FALSE; test = FALSE; } if (debug) printf("%s | %s | %d | %d | [%s]\n",src1[pos], src2[pos], strcmp(src1[pos], src2[pos]), ft_strcmp(src1[pos], src2[pos]), test ? OK : KO); } return (ret); } t_bool test_strequ(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test = TRUE; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0 42", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd", //DIFF "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "A\x00\t" }; char src2[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0 42", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd ", //DIFF "Aok", "i1ci", "\0", "x", "\x02\t", "\t\n", "6789abcdefgh", "", "||||||\x00|||||||\\ _=+212312340 ", "A\x00\x01" }; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test = TRUE; if ((strcmp(src1[pos], src2[pos]) == 0) != ft_strequ(src1[pos], src2[pos])) { ret = FALSE; test = FALSE; } if (debug) { printf("%s | %s | %d | %d | [%s]\n",src1[pos], src2[pos], (strcmp(src1[pos], src2[pos]) == 0), ft_strequ(src1[pos], src2[pos]), test ? OK : KO); printf("\n"); print_mem("src1", src1[pos], TRUE, SIZE); print_mem("src2", src2[pos], TRUE, SIZE); printf("\n"); } } return (ret); } t_bool test_strcpy(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test1 = TRUE; t_bool test2 = TRUE; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "HelloHelloHelloHelloHello", "Hello", "OOOOOOOOOOOOOOOOOOOOOOOOOOOO" }; char src2[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "HelloHelloHelloHelloHello", "Hello", "OOOOOOOOOOOOOOOOOOOOOOOOOOOO" }; char s_cpy[][SIZE] = { "O\x20", "B", "A", "AAsssdsdAsdasd", "\0", "\x02", "\t", "POPoPOpO", "\00\00ASF", "12345", "Monsieur", "MonsieurMonsieurMonsieurMonsieurMonsieur", "H" }; char *dst1; char *dst2; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test1 = TRUE; test2 = TRUE; dst1 = strcpy(src1[pos], s_cpy[pos]); dst2 = ft_strcpy(src2[pos], s_cpy[pos]); if (memcmp(dst1, dst2, strlen(dst1)) != 0) { ret = FALSE; test1 = FALSE; } if (memcmp(src1[pos], src2[pos], strlen(dst1)) != 0) { ret = FALSE; test2 = FALSE; } if (debug) { printf("=====BY TEST=====\n"); printf("%s | %s | [%s]\n",dst1, dst2, test1 ? OK : KO); print_mem("strcpy: dst1", dst1, TRUE, SIZE); print_mem("ft_strcpy: dst2", dst2, TRUE, SIZE); printf("\n"); printf("%s | %s | [%s]\n",src1[pos], src2[pos], test2 ? OK : KO); print_mem("strcpy: src1", src1[pos], TRUE, SIZE); print_mem("ft_strcpy: src2", src2[pos], TRUE, SIZE); printf("\n"); } } return (ret); } t_bool test_strnew(t_bool debug) { #undef SIZE #define SIZE 100 #undef SIZE_MEM #define SIZE_MEM 50 t_bool ret = TRUE; t_bool test = TRUE; char *str1; char *str2; char src1[][SIZE_MEM] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0 42", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd ", "Aok", "i1ci", "\0", "x", "\x02\t", "\t\n", "6789abcdefgh", "", "||||||\x00|||||||\\ _=+212312340 ", }; for (size_t pos = 0; pos < (sizeof(src1) / SIZE_MEM); pos++) { str1 = ft_strnew(SIZE_MEM); ft_strcat(str1, src1[pos]); str2 = malloc(SIZE_MEM + 1); str2 = memset(str2, 0, SIZE_MEM + 1); ft_strcat(str2, src1[pos]); test = TRUE; if (memcmp(str1, str2, SIZE_MEM + 1) != 0) { ret = FALSE; test = FALSE; } if (debug) { printf("%s | %s | [%s]\n",str1, str2, test ? OK : KO); print_mem("ft_strnew: str1", str1, TRUE, SIZE); print_mem("ft_strnew: str2", str2, TRUE, SIZE); printf("\n"); } free(str1); free(str2); } return (ret); } t_bool test_memset(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test1 = TRUE; t_bool test2 = TRUE; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340" }; char src2[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340" }; char c_set[] = { 'O', 'B', 'A', 'z', '\0', '\x02', '\t', 'X', 0, 'Z' }; int size_arr[] = {0, 2, 4, 4, 5, 5, 100, 2, 13, 5}; char *dst1; char *dst2; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test1 = TRUE; test2 = TRUE; dst1 = memset(src1[pos], c_set[pos], size_arr[pos]); dst2 = ft_memset(src2[pos], c_set[pos], size_arr[pos]); if (memcmp(dst1, dst2, SIZE) != 0) { ret = FALSE; test1 = FALSE; } if (memcmp(src1[pos], src2[pos], SIZE) != 0) { ret = FALSE; test2 = FALSE; } if (debug) { printf("=====BY TEST=====\n"); printf("%s | %s | %d | [%s]\n",dst1, dst2, size_arr[pos], test1 ? OK : KO); print_mem("memset: dst1", dst1, TRUE, SIZE); print_mem("ft_memset: dst2", dst2, TRUE, SIZE); printf("\n"); printf("%s | %s | %d | [%s]\n",src1[pos], src2[pos], size_arr[pos], test2 ? OK : KO); print_mem("memset: src1", src1[pos], TRUE, SIZE); print_mem("ft_memset: src2", src2[pos], TRUE, SIZE); printf("\n"); } } return (ret); } t_bool test_memcpy(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test1 = TRUE; t_bool test2 = TRUE; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340" }; char src2[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340" }; char s_cpy[][SIZE] = { "O", "B", "A", "AAsssdsdAsdasd", "\0", "\x02", "\t", "POPoPOpO", "\00\00ASF", "12345" }; int size_arr[] = {0, 2, 4, 4, 5, 5, 100, 2, 13, 5}; char *dst1; char *dst2; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test1 = TRUE; test2 = TRUE; dst1 = memcpy(src1[pos], s_cpy[pos], size_arr[pos]); dst2 = ft_memcpy(src2[pos], s_cpy[pos], size_arr[pos]); if (memcmp(dst1, dst2, SIZE) != 0) { ret = FALSE; test1 = FALSE; } if (memcmp(src1[pos], src2[pos], SIZE) != 0) { ret = FALSE; test2 = FALSE; } if (debug) { printf("=====BY TEST=====\n"); printf("%s | %s | %d | [%s]\n",dst1, dst2, size_arr[pos], test1 ? OK : KO); print_mem("memcpy: dst1", dst1, TRUE, SIZE); print_mem("ft_memcpy: dst2", dst2, TRUE, SIZE); printf("\n"); printf("%s | %s | %d | [%s]\n",src1[pos], src2[pos], size_arr[pos], test2 ? OK : KO); print_mem("memcpy: src1", src1[pos], TRUE, SIZE); print_mem("ft_memcpy: src2", src2[pos], TRUE, SIZE); printf("\n"); } } return (ret); } /*t_bool test_memcmp(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test = TRUE; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0 42", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd", //DIFF "ok", "ici", "", "x\0", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "A\x00\t" }; char src2[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0 42", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd ", //DIFF "Aok", "i1ci", "\0", "x", "\x02\t", "\t\n", "6789abcdefgh", "", "||||||\x00|||||||\\ _=+212312340 ", "A\x00\x01" }; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { test = TRUE; if (memcmp(src1[pos], src2[pos], SIZE) != ft_memcmp(src1[pos], src2[pos], SIZE)) { ret = FALSE; test = FALSE; } if (debug) { printf("%s | %s | %d | %d | [%s]\n",src1[pos], src2[pos], memcmp(src1[pos], src2[pos], SIZE/2), ft_memcmp(src1[pos], src2[pos], SIZE/2), test ? OK : KO); printf("\n"); print_mem("src1", src1[pos], FALSE, SIZE); print_mem("src2", src2[pos], FALSE, SIZE); printf("\n"); } } return (ret); } t_bool test_memdel(t_bool debug) { #undef SIZE #define SIZE 100 t_bool ret = TRUE; t_bool test = TRUE; char *str; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "test", "", {0} }; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { str = strdup(src1[pos]); ft_memdel((void*)&str); test = TRUE; if (str != NULL) { ret = FALSE; test = FALSE; } if (debug) { printf("%s | %s | [%s]\n", src1[pos], str, test ? OK : KO); print_mem("Str Free", &str, FALSE, SIZE); printf("\n"); } } return (ret); } */ void *memalloc(size_t size) { void *mem; if ((mem = (void*)malloc(size)) && size) { bzero(mem, size); return (mem); } return (NULL); } t_bool test_memalloc(t_bool debug) { #undef SIZE #define SIZE 100 #undef SIZE_MEM #define SIZE_MEM 24 t_bool ret = TRUE; t_bool test = TRUE; char *str1; char *str2; char *buff; char src1[][SIZE] = { "testOkA asd ddsd sww sadsd", "ok", "ici", "", "x\0 42", "\x02", "\t", "0123456789abcdefgh", "\n", "||||||\x00|||||||\\ _=+212312340", "testOkA asd ddsd sww sadsd ", //DIFF "Aok", "i1ci", "\0", "x", "\x02\t", "\t\n", "6789abcdefgh", "", "||||||\x00|||||||\\ _=+212312340 ", }; for (size_t pos = 0; pos < (sizeof(src1) / SIZE); pos++) { buff = malloc(SIZE); memset(buff, 'B', SIZE); free(buff); str1 = ft_memalloc(SIZE_MEM); free(str1); buff = malloc(SIZE); memset(buff, 'B', SIZE); free(buff); str2 = memalloc(SIZE_MEM); free(str2); test = TRUE; if (memcmp(str1, str2, SIZE_MEM) != 0) { ret = FALSE; test = FALSE; } if (debug) { printf("%s | %s | [%s]\n",str1, str2, test ? OK : KO); print_mem("memalloc: str1", str1, TRUE, SIZE); print_mem("ft_memalloc: str2", str2, TRUE, SIZE); printf("\n"); } } return (ret); } t_bool test_putchar(t_bool debug) { #undef BUFF_SIZE #define BUFF_SIZE 50 t_bool ret = TRUE; t_bool test = TRUE; char strings[] = {'a', 'b', 'c', 'd', 'A', 'Z', '\0', ' ', 1, -5, -1, -0, -128, 255, '\t', '\n', 0, '\01'}; char buff1[BUFF_SIZE + 1] = {0}; char buff2[BUFF_SIZE + 1] = {0}; int out_pipe[2]; int saved_stdout; int ret1; int ret2; for (size_t pos = 0; pos < (sizeof(strings) / sizeof(char)); pos++) { /*TEST 1*/ bzero(buff1, BUFF_SIZE); saved_stdout = dup(STDOUT_FILENO); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); ret1 = 0; ret1 = putchar(strings[pos]); /*PUTCHAR CMD*/ fflush(stdout); read(out_pipe[0], buff1, BUFF_SIZE); /*TEST 2*/ bzero(buff2, BUFF_SIZE); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); ret2 = 0; ret2 = ft_putchar(strings[pos]); /*FT_PUTCHAR CMD*/ fflush(stdout); read(out_pipe[0], buff2, BUFF_SIZE); /*AFF*/ dup2(saved_stdout, STDOUT_FILENO); test = TRUE; if (ret1 != ret2 || strcmp(buff1, buff2) != 0) { ret = FALSE; test = FALSE; } if (debug) printf(" -> %d -> %d | %d | [%s]\n", strings[pos], putchar(strings[pos]), ft_putchar(strings[pos]), test ? OK : KO); } return (ret); } t_bool test_putchar_fd(t_bool debug) { #undef BUFF_SIZE #define BUFF_SIZE 50 #undef FD_TEST #define FD_TEST 1 t_bool ret = TRUE; t_bool test = TRUE; char strings[] = {'a', 'b', 'c', 'd', 'A', 'Z', '\0', ' ', 1, -5, -1, -0, -128, 255, '\t', '\n', 0, '\01'}; char buff1[BUFF_SIZE + 1] = {0}; char buff2[BUFF_SIZE + 1] = {0}; int out_pipe[2]; int saved_stdout; int ret1; int ret2; for (size_t pos = 0; pos < (sizeof(strings) / sizeof(char)); pos++) { /*TEST 1*/ bzero(buff1, BUFF_SIZE); saved_stdout = dup(STDOUT_FILENO); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], FD_TEST); close(out_pipe[1]); ret1 = 0; ret1 = write(FD_TEST, &strings[pos], 1); /*PUTCHAR_FD FUNC*/ fflush(stdout); read(out_pipe[0], buff1, BUFF_SIZE); /*TEST 2*/ bzero(buff2, BUFF_SIZE); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], FD_TEST); close(out_pipe[1]); ret2 = 0; ret2 = ft_putchar_fd(strings[pos], FD_TEST); /*FT_PUTCHAR_FD FUNC*/ fflush(stdout); read(out_pipe[0], buff2, BUFF_SIZE); /*AFF*/ dup2(saved_stdout, STDOUT_FILENO); test = TRUE; if (strcmp(buff1, buff2) != 0) { ret = FALSE; test = FALSE; } if (debug) { printf(" -> %d", strings[pos]); write(FD_TEST, &strings[pos], 1); ft_putchar_fd(strings[pos], FD_TEST); printf("[%s]\n", test ? OK : KO); } } return (ret); } #include <fcntl.h> t_bool test_cat(t_bool debug) { #undef BUFF_SIZE #define BUFF_SIZE 10000 t_bool ret = TRUE; t_bool test = TRUE; char buff1[BUFF_SIZE + 1] = {0}; char buff2[BUFF_SIZE + 1] = {0}; int out_pipe[2]; int saved_stdout; pid_t father; int fd; char *files[] = { "./src/ft_bzero.s", "./src/ft_strcmp.s", "./src/ft_memset.s", "./Makefile", "./auteur" }; char cmd[] = "cat"; for (size_t pos = 0; pos < (sizeof(files) / sizeof(char*)); pos++) { char *args[] = {"cat", files[pos], NULL}; //TEST 1 bzero(buff1, BUFF_SIZE); saved_stdout = dup(STDOUT_FILENO); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); //CAT CMD// father = fork(); if (father > 0) wait(0); else if (father == 0) { if (execvp(cmd, args) == -1) puts("Exec format error.\n"); exit(0); } fflush(stdout); read(out_pipe[0], buff1, BUFF_SIZE); //TEST 2 bzero(buff2, BUFF_SIZE); if(pipe(out_pipe) != 0) { exit(1); } dup2(out_pipe[1], STDOUT_FILENO); close(out_pipe[1]); //FT_CAT CMD// fd = open(files[pos], O_RDONLY); ft_cat(fd); //FT_CAT CMD// close(fd); fflush(stdout); read(out_pipe[0], buff2, BUFF_SIZE); //AFF dup2(saved_stdout, STDOUT_FILENO); test = TRUE; if (memcmp(buff1, buff2, BUFF_SIZE) != 0) { ret = FALSE; test = FALSE; } if (debug) { printf("->%s\n", files[pos]); printf("[%s]\n", test ? OK : KO); printf("\x1B[1;37mCat:\033[0m\n"); //CAT CMD// father = fork(); if (father > 0) wait(0); else if (father == 0) { if (execvp(cmd, args) == -1) puts("Exec format error.\n"); exit(0); } //FT_CAT CMD// printf("\n\x1B[1;37mft_cat:\033[0m\n"); fd = open(files[pos], O_RDONLY); ft_cat(fd); //FT_CAT CMD// close(fd); } } return (ret); } t_bool test_cat_fd_0(t_bool debug) { t_bool ret = TRUE; pid_t father; (void)debug; //TEST FD 0// //CAT CMD// printf("\n\x1B[1;37mcat:\033[0m\n"); char cmd[] = "cat"; char *args[] = {"cat", NULL}; father = fork(); if (father > 0) wait(0); else if (father == 0) { if (execvp(cmd, args) == -1) puts("Exec format error.\n"); exit(0); } //FT_CAT CMD// printf("\n\x1B[1;37mft_cat:\033[0m\n"); ft_cat(0); //FT_CAT CMD// return (ret); } t_bool test_cat_fd_test(t_bool debug) { t_bool ret = TRUE; (void)debug; printf("\n\x1B[1;37mTest cat:\033[0m\n"); ft_cat(0); ft_cat(open(__FILE__, O_RDONLY)); ft_cat(open("test", O_RDONLY)); ft_cat(-42); return (ret); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* envmanage.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/04/02 19:50:26 by gjensen #+# #+# */ /* Updated: 2015/06/11 18:19:12 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh1.h" char **sh_save_env(char ***env) { static char **save; if (env && *env) { save = *env; return (NULL); } else return (save); } char *sh_replace_home(char *path, char **env) { char *home_path; char *pos; home_path = sh_get_env("HOME", env); if ((pos = ft_strstr(path, home_path)) && ft_strcmp("/", home_path) != 0) { path[0] = '~'; path[1] = 0; ft_strcat(path, pos + ft_strlen(home_path)); } return (path); } int sh_get_env_pos(char *find, char **env) { int i; i = 0; while (env[i]) { if (ft_strncmp(find, env[i], ft_strchr(env[i], '=') - env[i]) == 0) return (i); i++; } return (-1); } char *sh_get_env(char *find, char **env) { int i; i = 0; while (env[i]) { if (ft_strncmp(find, env[i], ft_strchr(env[i], '=') - env[i]) == 0) return (ft_strchr(env[i], '=') + 1); i++; } return (NULL); } char **sh_parse_env(char *find, char **env) { char **array_path; char *path; if ((path = sh_get_env(find, env)) == NULL) return (NULL); array_path = ft_strsplit(path, ':'); return (array_path); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sh1.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gjensen <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/04/01 16:12:31 by gjensen #+# #+# */ /* Updated: 2015/05/13 15:05:29 by gjensen ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef SH1_H # define SH1_H # include "libft.h" # include <unistd.h> # include <stdlib.h> # include <fcntl.h> # include <sys/wait.h> # include <sys/stat.h> # include <signal.h> # include <dirent.h> # include <sys/types.h> # include <sys/stat.h> typedef struct stat t_stat; void sh_loop(char **env); void sh_prompt(char ***env); void fork_process(char *path, char **env, char **av); void sh_execute_bin(char *av, char ***env, char **paths); int sh_get_env_pos(char *find, char **env); char *sh_get_env(char *find, char **env); char **sh_parse_env(char *find, char **env); char *sh_search_bin(char *line, char *dirpath); int sh_access(char *path); int sh_isbin(char *path); void sh_builtin_exit(char **av); int sh_search_builtin(char *av, char ***env); void sh_builtin_cd(char **av, char ***env); void sh_builtin_cd_open(char *dir, char ***env); void sh_builtin_env(char **av, char ***env); void sh_builtin_setenv(char **av, char ***env); void sh_builtin_setenv_add(char *name, char *value, char ***env); void sh_builtin_setenv_replace(char *name, char *value, char **env); void sh_builtin_setenv_mng(char *name, char *value, char ***env); void sh_builtin_unsetenv(char **av, char ***env); void sh_free_memory(char *line, char **av, char **paths); char **sh_save_env(char ***env); void sh_signals(void); void sh_wrong_exit(int signum, char *son); pid_t save_cpid(pid_t *father); char *sh_replace_home(char *path, char **env); void sh_execute_cmd(char *line, char ***sh_env, char **paths); void sh_notfound(char *av); #endif
532af30256c17033541a8ee097e10687eba1edf0
[ "Markdown", "C", "Makefile" ]
46
C
gj42/42_Project
2750159b85f491c2de6620e10c1f6657295f42eb
ef1b145f9a525e19db8c2035c079a5c376d7c30c
refs/heads/master
<file_sep>package com.android.demo.test; import com.android.demo.view.*; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; public class TestActivity extends Activity{ private CurveChartView dc = null; private boolean isRun = true; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); float d = 0; float sp = 0.1f; float[] data = new float[100]; float[] data1 = new float[100]; float[] data2 = new float[100]; for(int i = 0; i <100; i++){ data[i] = (float)(Math.sin(d) *10); data1[i] = (float)(Math.cos(d) *5); data2[i] = 3*data[i]- data1[i]*data1[i] * 2 ; d += sp; } CurveChartView chart = (CurveChartView)findViewById(R.id.chart); chart.setCurveCount(3); chart.setCurveColor(new int[]{Color.YELLOW,Color.BLUE,Color.RED}); chart.setCalibrationOn(true); chart.setData(0,data); chart.setData(1,data1); chart.setData(2,data2); dc = (CurveChartView)findViewById(R.id.dchart); dc.setCurveStatic(false); dc.setCurveCount(2); dc.setCalibrationLeft(true); dc.setCurveColor(new int[]{Color.BLUE,Color.YELLOW}); dc.setCalibrationOn(true); dc.setCalibrationLeft(true); dc.setDataScope(0, 100); DataThread dt = new DataThread(); dt.start(); PieChartView pcv = (PieChartView)findViewById(R.id.pie); pcv.setDataCount(5); pcv.setColor(new int[]{Color.YELLOW,Color.BLUE,Color.GRAY,Color.MAGENTA,Color.RED}); pcv.setData(new float[]{200,700,45,190,409}); pcv.setSpecial(4); BarChartView br = (BarChartView)findViewById(R.id.bar); br.setGroupCount(3); br.setDataCount(3); br.setGroupData(0, new float[]{277f,2101f,3222f}); br.setGroupData(1, new float[]{1213f,11194f,444f}); br.setGroupData(2, new float[]{193f,2645f,858f}); br.setBarColor(new int[]{Color.YELLOW,Color.BLUE,Color.GREEN}); br.setDataTitle(new String[]{"±ýͼ²âÊÔ","Title","123234"}); br.setGroupTitle(new String[]{"group1","group2","group3"}); } private Handler handler = new Handler(){ public void handleMessage(Message msg) { Bundle d = msg.getData(); float d1 = d.getFloat("d1"); float d2 = d.getFloat("d2"); dc.appendData(new float[]{d1,d2}); } }; class DataThread extends Thread{ private float d = 0; private float sp = 0.1f; private int t = 1; private boolean flat = true; public void run(){ while(isRun){ float d1 = (float)(Math.sin(d) *t); float d2 = (float)(Math.cos(d) * t); Message msg = handler.obtainMessage(); Bundle b = new Bundle(); b.putFloat("d1", d1); b.putFloat("d2", d2); msg.setData(b); handler.sendMessage(msg); d += sp; if(flat){ t++; if(t > 300) flat = false; }else{ t--; if(t <= 1) flat = true; } SystemClock.sleep(200); } } } public void onDestroy(){ super.onDestroy(); isRun = false; } } <file_sep># chartView 自定义控件-柱形图,饼状图,曲线图
cbcb622b551bb4a487cb008c274bed2e71ed8e16
[ "Markdown", "Java" ]
2
Java
wangyin8866/chartView
d9c186a94226fe29f6c08cd75b23209efd75536d
077b1eaac1f7047eb3494c753cad69b1a0da9fad
refs/heads/master
<file_sep>#include <windows.h> #include <stdio.h> #include <string.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <AR/ar.h> #include <AR/param.h> #include <AR/video.h> #include <AR/gsub.h> #include "controller.h" // キーボードによる制御 #include "GLMetaseq.h" // モデルローダ // ライブラリの設定 #ifdef _DEBUG #pragma comment(lib,"libARd.lib") #pragma comment(lib,"libARgsubd.lib") #pragma comment(lib,"libARvideod.lib") #pragma comment(linker,"/NODEFAULTLIB:libcmtd.lib") #else #pragma comment(lib,"libAR.lib") #pragma comment(lib,"libARgsub.lib") #pragma comment(lib,"libARvideo.lib") #pragma comment(linker,"/NODEFAULTLIB:libcmt.lib") #endif // キャラクタデータ構造体 typedef struct { MQO_MODEL model; GLfloat rot; GLfloat x; GLfloat y; GLfloat z; } CHARACTER_DATA; // インベーダーの数 #define INVADER_COUNT 20 // スコア表示に使うフォント名とサイズ // 上手いやり方がわからん #define FONT_NAME GLUT_BITMAP_HELVETICA_18 #define FONT_SIZE 18 #define FONT_R 1 #define FONT_G 0 #define FONT_B 0 // グローバル変数 static char *g_vconf_name = "Data/WDM_camera_flipV.xml"; // ビデオデバイスの設定ファイル static char *g_cparam_name = "Data/camera_para.dat"; // カメラパラメータファイル static char *g_patt_name = "Data/patt.sample1"; // パターンファイル static int g_patt_id; // パターンのID static double g_patt_trans[3][4]; // 座標変換行列 static double g_patt_center[2] = { 0.0, 0.0 }; // パターンの中心座標 static double g_patt_width = 80.0; // パターンのサイズ(単位:mm) static int g_thresh = 100; // 2値化の閾値 static CHARACTER_DATA g_airplane = { NULL, 0.0, 0.0, 0.0, 0.0 }; // キャラクタのデータ static char *g_mqo_airplane_name = "Data/mqo/airplane.mqo"; // MQOファイル static CHARACTER_DATA g_invader[INVADER_COUNT] = { NULL, 0.0, 0.0, 0.0, 0.0 }; // インベーダー static char *g_mqo_invader_name = "Data/mqo/invader_small.mqo"; static int invader_show[INVADER_COUNT]; static int invader_x[INVADER_COUNT]; static int invader_y[INVADER_COUNT]; static int invader_z[INVADER_COUNT]; static CHARACTER_DATA g_bullet = { NULL, 0.0, 0.0, 0.0, 0.0 }; // 弾丸 static char *g_mqo_bullet_name = "Data/mqo/bullet.mqo"; static int g_light_on = TRUE; // シェーディングのOn/Off static int g_optcmf_on = FALSE; // 光学迷彩のOn/Off static int score = 0; // スコア // プロトタイプ宣言 static void MainLoop(void); static void Cleanup(void); static void DrawObject( ARUint8 *image ); static void CalcState(void); static void SetLight( GLenum light ); static void OpticalCamouflage( unsigned char *image ); static void GetObjectDepth( GLfloat *depth, int width, int height, GLfloat *depth_min, GLfloat *depth_max ); static void DrawImage( unsigned char *color_buf, int width, int height ); static void DrawString(float x, float y, char* _string); // =========================================================================== // main関数 // =========================================================================== int main( int argc, char **argv ) { ARParam cparam; // カメラパラメータ ARParam wparam; // カメラパラメータ(作業用変数) int xsize, ysize; // 画像サイズ int i; // GLUTの初期化 glutInit( &argc, argv ); // ビデオデバイスの設定 if ( arVideoOpen( g_vconf_name ) < 0 ) { printf("ビデオデバイスのエラー"); return -1; } // カメラパラメータの設定 if ( arVideoInqSize( &xsize, &ysize ) < 0 ) { printf("画像サイズを取得できませんでした\n"); return -1; } if ( arParamLoad( g_cparam_name, 1, &wparam ) < 0 ) { printf("カメラパラメータの読み込みに失敗しました\n"); return -1; } arParamChangeSize( &wparam, xsize, ysize, &cparam ); arInitCparam( &cparam ); // パターンファイルのロード if ( (g_patt_id = arLoadPatt(g_patt_name)) < 0 ) { printf("パターンファイルの読み込みに失敗しました\n"); return -1; } // ウィンドウの設定 argInit( &cparam, 1.0, 0, 0, 0, 0 ); glutSetWindowTitle("ARインベーダー"); // GLMetaseqの初期化 mqoInit(); // モデルの読み込み if ( ( g_airplane.model = mqoCreateModel( g_mqo_airplane_name, 1.0 )) == NULL ) { printf("モデルの読み込みに失敗しました\n"); return -1; } for (i = 0; i < INVADER_COUNT; i++){ if ( ( g_invader[i].model = mqoCreateModel( g_mqo_invader_name, 1.0 )) == NULL ) { printf("モデルの読み込みに失敗しました\n"); return -1; } invader_show[i] = 1; } if ( ( g_bullet.model = mqoCreateModel( g_mqo_bullet_name, 1.0 )) == NULL ) { printf("モデルの読み込みに失敗しました\n"); return -1; } // ビデオキャプチャの開始 arVideoCapStart(); // 終了時に呼ぶ関数を指定 atexit( Cleanup ); // キーボード関数の登録 glutKeyboardUpFunc( KeyUp ); glutSpecialFunc( SpecialKeyDown ); glutSpecialUpFunc( SpecialKeyUp ); glutJoystickFunc( joystick, 100 ); // ジョイスティック printf("<<操作方法>>\n"); printf("方向キー : 移動\n"); printf(" %c : 初期位置にリセット\n", KEY_B); printf(" %c : シェーディングOn/Off\n", KEY_A); printf(" %c : 光学迷彩On/Off \n", KEY_C); printf(" ESC : 終了\n"); // メインループの開始 argMainLoop( NULL, KeyDown, MainLoop ); return 0; } // =========================================================================== // メインループ関数 // =========================================================================== static void MainLoop(void) { ARUint8 *image; ARMarkerInfo *marker_info; int marker_num; int j, k; char score_str[64]; // カメラ画像の取得 if ( (image = arVideoGetImage()) == NULL ) { arUtilSleep( 2 ); return; } // カメラ画像の描画 argDrawMode2D(); argDispImage( image, 0, 0 ); // マーカの検出と認識 if ( arDetectMarker( image, g_thresh, &marker_info, &marker_num ) < 0 ) { exit(0); } // 次の画像のキャプチャ指示 arVideoCapNext(); // マーカの信頼度の比較 k = -1; for( j = 0; j < marker_num; j++ ) { if ( g_patt_id == marker_info[j].id ) { if ( k == -1 ) k = j; else if ( marker_info[k].cf < marker_info[j].cf ) k = j; } } if ( k != -1 ) { // マーカの位置・姿勢(座標変換行列)の計算 arGetTransMat( &marker_info[k], g_patt_center, g_patt_width, g_patt_trans ); // 3Dオブジェクトの描画 DrawObject( image ); } // スコア表示に使う文字列処理 sprintf_s(score_str, 64, "score: %d", score); // スコア表示 DrawString(0.0f, 0.0f, score_str); // バッファの内容を画面に表示 argSwapBuffers(); } // =========================================================================== // 終了処理関数 // =========================================================================== static void Cleanup(void) { int i; arVideoCapStop(); // ビデオキャプチャの停止 arVideoClose(); // ビデオデバイスの終了 argCleanup(); // グラフィック処理の終了 // モデルの削除 mqoDeleteModel( g_airplane.model ); mqoDeleteModel( g_bullet.model ); for (i = 0; i < INVADER_COUNT; i++){ mqoDeleteModel( g_invader[i].model ); } mqoCleanup(); // GLMetaseqの終了処理 } // =========================================================================== // 3Dオブジェクトの描画を行う関数 // =========================================================================== static void DrawObject( ARUint8 *image ) { double gl_para[16]; int i; int invader_row; int invader_col; // オブジェクトの状態を計算 CalcState(); // 3Dオブジェクトを描画するための準備 argDrawMode3D(); argDraw3dCamera( 0, 0 ); // 光源の設定 glPushMatrix(); SetLight(GL_LIGHT0); glPopMatrix(); // 座標変換行列の適用 argConvGlpara( g_patt_trans, gl_para ); glMatrixMode( GL_MODELVIEW ); glLoadMatrixd( gl_para ); // 3Dオブジェクトの描画 glClear( GL_DEPTH_BUFFER_BIT ); // Zバッファの初期化 glEnable( GL_DEPTH_TEST ); // 隠面処理の適用 // シェーディング if ( g_light_on ) { glEnable( GL_LIGHTING ); // ライトOn } else { glDisable( GL_LIGHTING ); // ライトOff } // モデルの描画 glPushMatrix(); glTranslatef( g_airplane.x, g_airplane.y, g_airplane.z ) ; // モデルの位置 glRotatef( g_airplane.rot, 0.0, 0.0, 1.0); // モデルの向き glRotatef( 90.0, 1.0, 0.0, 0.0 ); // モデルを立たせる mqoCallModel( g_airplane.model ); // モデルの描画 glPopMatrix(); for (i = 0; i < INVADER_COUNT; i++){ if (invader_show[i] == 1){ // インベーダーの行と列を計算 invader_col = i % 5; invader_row = i / 5; // インベーダーの座標を計算 invader_x[i] = invader_col * 80 - 100; invader_y[i] = invader_col * 50 - 100; invader_z[i] = 300 - invader_row * 60; // 描画 glPushMatrix(); glTranslatef( invader_x[i], invader_y[i], invader_z[i] ); glRotatef( invader_col * 20, 0.0, 0.0, 1.0); glRotatef( 90.0, 1.0, 0.0, 0.0 ); mqoCallModel( g_invader[i].model ); glPopMatrix(); } } glPushMatrix(); glTranslatef( g_bullet.x, g_bullet.y, g_bullet.z ); glRotatef( 0.0, 0.0, 0.0, 1.0); glRotatef( 90.0, 1.0, 0.0, 0.0 ); mqoCallModel( g_bullet.model ); glPopMatrix(); g_bullet.z += 20; for (i = 0; i < INVADER_COUNT; i++){ // インベーダーとの衝突判定 if (invader_show[i] == 1 && abs(g_bullet.x - invader_x[i]) < 40 && abs(g_bullet.y - invader_y[i]) < 20 && abs(g_bullet.z - invader_z[i]) < 20){ // 衝突したら invader_show[i] = 0; g_bullet.x = g_airplane.x; g_bullet.y = g_airplane.y; g_bullet.z = 40; score += 10; } } if (g_bullet.z > 400){ g_bullet.x = g_airplane.x; g_bullet.y = g_airplane.y; g_bullet.z = 40; } glDisable( GL_LIGHTING ); glDisable( GL_DEPTH_TEST ); // 光学迷彩 if ( g_optcmf_on ) { OpticalCamouflage( image ); } } // =========================================================================== // オブジェクトの状態を計算する関数 // =========================================================================== static void CalcState(void) { CONTROLLER_DATA control; // コントローラ(キーボード) static GLfloat v = 0; // 進行方向の速度 // 強制的にジョイスティックを読みに行く glutForceJoystickFunc(); // コントローラのデータを取得 GetControllerData( &control ); if (control.up == KEY_DOWN) { g_airplane.y += 10; } if (control.down == KEY_DOWN) { g_airplane.y -= 10; } if (control.right == KEY_DOWN) { g_airplane.x += 10; } if (control.left == KEY_DOWN) { g_airplane.x -= 10; } /* // 加速と減速 if ( control.up == KEY_DOWN ) { // 正方向に加速 v = 20; } else if ( control.down == KEY_DOWN ) { // 逆方向に加速 v = -20; } else { // 減速 if (v>0) { v--; } else if (v<0) { v++; } } // 回転 if ( control.right == KEY_DOWN ) { g_airplane.rot -= 20.0; } if ( control.left == KEY_DOWN ) { g_airplane.rot += 20.0; } // 移動 g_airplane.x += v * sin(g_airplane.rot*3.14/180); g_airplane.y += -v * cos(g_airplane.rot*3.14/180); */ // シェーディングのOn/Off if ( control.A == KEY_DOWN ) g_light_on = !g_light_on; // 初期位置にリセット if ( control.B == KEY_DOWN ) { g_airplane.rot = 0; g_airplane.x = 0; g_airplane.y = 0; g_airplane.z = 0; } // 光学迷彩のOn/Off if ( control.C == KEY_DOWN ) g_optcmf_on = !g_optcmf_on; } // =========================================================================== // 光源の設定を行う関数 // =========================================================================== static void SetLight( GLenum light ) { GLfloat light_diffuse[] = { 0.9, 0.9, 0.9, 1.0 }; // 拡散反射光 GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 }; // 鏡面反射光 GLfloat light_ambient[] = { 0.3, 0.3, 0.3, 0.1 }; // 環境光 GLfloat light_position[] = { 0.0, 0.0, 0.0, 1.0 }; // 位置と種類 // 光源の設定 glLightfv( light, GL_DIFFUSE, light_diffuse ); // 拡散反射光の設定 glLightfv( light, GL_SPECULAR, light_specular ); // 鏡面反射光の設定 glLightfv( light, GL_AMBIENT, light_ambient ); // 環境光の設定 glLightfv( light, GL_POSITION, light_position ); // 位置と種類の設定 glEnable( light ); // 光源の有効化 } // =========================================================================== // 光学迷彩処理を行う関数 // =========================================================================== static void OpticalCamouflage( unsigned char *image ) { GLfloat *depth_buf, *pDepth; // デプスバッファ unsigned char *color_buf, *pColor; // カラーバッファ GLfloat depth_obj_min, depth_obj_max; // 物体のデプス値の最小値・最大値 GLfloat depth, depth_obj_n; // デプス値、物体の正規化デプス値 unsigned char cmfR, cmfG, cmfB; // 光学迷彩の色 int width, height; // 画像サイズ int i, x, y, dx, dy; // 迷彩の色(迷彩の領域に薄っすら色をつけるための設定。それぞれ0〜255) cmfR = 255; cmfG = 255; cmfB = 255; // 画像サイズの取得(ARToolKitのグローバル変数から取得) width = arImXsize; height = arImYsize; // デプスバッファの取得 depth_buf = (GLfloat*)malloc( width * height * sizeof(GLfloat) ); glReadPixels( 0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, depth_buf); // 描画用のバッファを作成 color_buf = (unsigned char*)malloc( width * height * 4 ); if ( color_buf == NULL || depth_buf == NULL ) return; // オブジェクトのデプス値の最大最小を求める GetObjectDepth( depth_buf, width, height, &depth_obj_min, &depth_obj_max); // ラスタスキャン用のポインタの準備 pDepth = depth_buf; pColor = color_buf; for (y=0; y<height; y++) { for (x=0; x<width; x++) { // デプス値 depth = *pDepth++; if ( depth < 1.0 ) { // オブジェクト領域の場合 // デプス値を正規化 depth_obj_n = ( depth - depth_obj_min )/( depth_obj_max - depth_obj_min ); // デプス値を元に読み取り座標をずらす(=歪ませる) dx = (int)( x -0.05 * width * depth_obj_n * ((x-width/2.0)*0.01) ); dy = (int)( y -0.05 * height * depth_obj_n * ((y-height/2.0)*0.01) ); if ( dx < 0 ) dx = x; if ( dy < 0 ) dy = y; // インデックスを求める i = 4 * ( (height-1-dy) * width + dx ); // 画素値の書き込み *pColor++ = (unsigned char)( image[i+2] * 0.9 + cmfR * 0.1 ); // R *pColor++ = (unsigned char)( image[i+1] * 0.9 + cmfG * 0.1 ); // G *pColor++ = (unsigned char)( image[i] * 0.9 + cmfB * 0.1 ); // B *pColor++ = 255; // A } else { // 背景の場合 pColor += 3; *pColor++ = 0; } } } // 画像の描画 DrawImage( color_buf, width ,height ); // バッファの開放 free( depth_buf ); free( color_buf ); } // =========================================================================== // オブジェクトのデプス値の最小値、最大値を求める関数 // depth : デプスバッファ // width, height : 画像サイズ // depth_min : デプス値の最小値 // depth_max : デプス値の最大値(背景=1.0を除く) // =========================================================================== static void GetObjectDepth( GLfloat *depth, int width, int height, GLfloat *depth_min, GLfloat *depth_max ) { GLfloat min = 0; GLfloat max = 0; GLfloat d; int i; for ( i=0; i<width*height; i++ ) { d = *depth++; if ( i==0 ) { min = d; max = 0; } else { if ( d > max && d <1.0 ) max = d; if ( d < min ) min = d; } } *depth_min = min; *depth_max = max; } // =========================================================================== // 画像の描画を行う関数 // color_buf : カラーバッファ // width, height : 画像サイズ // =========================================================================== void DrawImage( unsigned char *color_buf, int width, int height ) { // 射影行列を保存 glMatrixMode( GL_PROJECTION ); glPushMatrix(); // 射影行列を変更 glLoadIdentity(); gluOrtho2D( 0, width, 0, height ); // モデルビュー行列を保存 glMatrixMode( GL_MODELVIEW ); glPushMatrix(); // 画像の描画 glLoadIdentity(); glRasterPos2i( 0, 0 ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_BLEND); glDrawPixels( width, height, GL_RGBA, GL_UNSIGNED_BYTE, color_buf ); glDisable( GL_BLEND ); // モデルビュー行列を復元 glPopMatrix(); // 射影行列を復元 glMatrixMode( GL_PROJECTION ); glPopMatrix(); } /* 文字描画関数 http://wiki.livedoor.jp/eruvasu/d/glutSting */ static void DrawString(float x, float y, char* _string) { glDisable(GL_LIGHTING); // 平行投影にする glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT), 0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor3f(FONT_R, FONT_G, FONT_B); glRasterPos2f(x, y + FONT_SIZE); //char* p = (char*)_string; while (*_string != '\0') glutBitmapCharacter(FONT_NAME, *_string++); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); }<file_sep>ARInvader ========= Original: http://kougaku-navi.net/ARToolKit/<file_sep> #ifndef __CONTROLLER_H__ #define __CONTROLLER_H__ #define KEY_DOWN 1 #define KEY_UP 0 #define KEY_ESC 27 #define KEY_A 'x' #define KEY_B 'z' #define KEY_C 'c' // コントローラデータ構造体 typedef struct { int up; int down; int left; int right; int A; int B; int C; } CONTROLLER_DATA; void GetControllerData( CONTROLLER_DATA *cntl ); void KeyDown( unsigned char key, int x, int y ); void KeyUp( unsigned char key, int x, int y ); void SpecialKeyDown(int key, int x, int y); void SpecialKeyUp(int key, int x, int y); void joystick( unsigned int buttonMask, int x, int y, int z ); #endif<file_sep> #include "controller.h" #include <gl/glut.h> // 10ボタン ジョイスティック #define GLUT_JOYSTICK_BUTTON_E 0x10 // 5 #define GLUT_JOYSTICK_BUTTON_F 0x20 // 6 #define GLUT_JOYSTICK_BUTTON_G 0x40 // 7 #define GLUT_JOYSTICK_BUTTON_H 0x80 // 8 #define GLUT_JOYSTICK_BUTTON_I 0x100 // 9b #define GLUT_JOYSTICK_BUTTON_J 0x200 // 10 static CONTROLLER_DATA g_cntl = { KEY_UP, KEY_UP, KEY_UP, KEY_UP, KEY_UP, KEY_UP, KEY_UP }; //=========================================================================== // コントローラの状態を取得する関数 //=========================================================================== void GetControllerData( CONTROLLER_DATA *cntl ) { *cntl = g_cntl; } //=========================================================================== // キーが押された場合に呼ばれる関数 //=========================================================================== void KeyDown( unsigned char key, int x, int y ) { switch ( key ) { case KEY_ESC: exit(0); break; // ESC case KEY_A: g_cntl.A = KEY_DOWN; break; // A case KEY_B: g_cntl.B = KEY_DOWN; break; // B case KEY_C: g_cntl.C = KEY_DOWN; break; // C default: break; } } //=========================================================================== // キーが離された場合に呼ばれる関数 //=========================================================================== void KeyUp( unsigned char key, int x, int y ) { switch ( key ) { case KEY_A: g_cntl.A = KEY_UP; break; // A case KEY_B: g_cntl.B = KEY_UP; break; // B case KEY_C: g_cntl.C = KEY_UP; break; // C default: break; } } //=========================================================================== // 特殊キーが押された場合に呼ばれる関数 //=========================================================================== void SpecialKeyDown(int key, int x, int y) { switch ( key ) { case GLUT_KEY_UP: g_cntl.up = KEY_DOWN; break; case GLUT_KEY_DOWN: g_cntl.down = KEY_DOWN; break; case GLUT_KEY_LEFT: g_cntl.left = KEY_DOWN; break; case GLUT_KEY_RIGHT: g_cntl.right = KEY_DOWN; break; default: break; } } //=========================================================================== // 特殊キーが離された場合に呼ばれる関数 //=========================================================================== void SpecialKeyUp(int key, int x, int y) { switch ( key ) { case GLUT_KEY_UP: g_cntl.up = KEY_UP; break; case GLUT_KEY_DOWN: g_cntl.down = KEY_UP; break; case GLUT_KEY_LEFT: g_cntl.left = KEY_UP; break; case GLUT_KEY_RIGHT: g_cntl.right = KEY_UP; break; default: break; } } void joystick(unsigned int buttonMask, int x, int y, int z) { if(300<x){ g_cntl.left = KEY_UP; g_cntl.right = KEY_DOWN; }else if(x<-300){ g_cntl.left = KEY_DOWN; g_cntl.right = KEY_UP; }else{ g_cntl.left = KEY_UP; g_cntl.right = KEY_UP; } if(300<y){ g_cntl.up = KEY_UP; g_cntl.down = KEY_DOWN; }else if(y<-300){ g_cntl.up = KEY_DOWN; g_cntl.down = KEY_UP; }else{ g_cntl.up = KEY_UP; g_cntl.down = KEY_UP; } switch (buttonMask) { case GLUT_JOYSTICK_BUTTON_A: break; case GLUT_JOYSTICK_BUTTON_B: break; case GLUT_JOYSTICK_BUTTON_C: break; case GLUT_JOYSTICK_BUTTON_D: break; case GLUT_JOYSTICK_BUTTON_E: break; case GLUT_JOYSTICK_BUTTON_F: break; case GLUT_JOYSTICK_BUTTON_G: break; case GLUT_JOYSTICK_BUTTON_H: break; case GLUT_JOYSTICK_BUTTON_I: break; case GLUT_JOYSTICK_BUTTON_J: break; } }
b1cccfc352735267ec1c84797c8e3f24e4926767
[ "Markdown", "C" ]
4
C
misodengaku/ARInvader
24a2b6745203452c4d373ab05dced86fda83836d
c8b0eaa830827c96b64619bb9bda07b6f994c3f1
refs/heads/master
<repo_name>MirkoGriffo/js-snack-es6<file_sep>/js/script.js /* Snack 1 Creare un array di oggetti: Ogni oggetto descriverà una bici da corsa con le seguenti proprietà: nome e peso. */ const bici = [ { name: "bici1", peso: 7, }, { name: "bici2", peso: 8, }, { name: "bici3", peso: 6, }, ]; let biciLeggera = bici[0] for (let i = 0; i < bici.length; i++) { if (bici[i].peso < biciLeggera.peso) { biciLeggera = bici[i]; }; }; console.log(biciLeggera); /* * Snack 2 Creare un array di oggetti di squadre di calcio. Ogni squadra avrà diverse proprietà: nome, punti fatt, falli subiti. Nome sarà l'unica proprietà da compilare, le altre saranno tutte settate a 0. Generare numeri random al posto degli 0 nelle proprietà: punti fatti e falli subiti. Infine usando la destrutturazione creiamo un nuovo array i cui elementi contengono solo nomi e falli subiti e stampiamo tutto in console. */ const squadre = [ { nome: "Juventus", punti: 0, falli: 0, }, { nome: "Atalanta", punti: 0, falli: 0, }, { nome: "Sassuolo", punti: 0, falli: 0, }, ]; for (let i = 0; i < squadre.length; i++) { squadre[i].punti = randomNumber(0, 100); squadre[i].falli = randomNumber(0, 100); } console.log(squadre); const nuovoArray = []; for (let i = 0; i < squadre.length; i++) { nuovoArray.push({ nome: squadre[i].nome, falli: squadre[i].falli, }) } console.log(nuovoArray); // Funzione function randomNumber(min, max) { return Math.floor(Math.random() * (max - min)) + min; } /* Snack 3 Si scriva una funzione che accetti tre argomenti, un array e due numeri (a più piccolo di b). La funzione ritornerà un nuovo array con i valori che hanno la posizione compresa tra i due numeri inseriti dall'utente (è possibile usare, ad esempio, for/foreach/filter */ let numMin = parseInt(prompt("inseire numero minimo")); let numMax = parseInt(prompt("inseire numero massimo")); const array = ["Paolo", "Fabio", "Lorenzo", "Mirko"]; const array2 = []; array.forEach((element, index) => { if (index >= numMin && index <= numMax) { array2.push(element); }; }); console.log(array2); /* Snack 4 Dato un'array con dei capi d'abbigliamento - oggetti che contengono informazioni su nome modello, tipologia e colore - si aggiunga a ciascun elemento una ulteriore proprietà che indichi il costo del prodotto. Per inserire il costo del singolo prodotto si scriva una funzione che generi un numero random da 10 a 50 (potete sfruttare il map per aggiungere la nuova proprietà) */ const vestiti = [ { nome: "maglia", tipo: "tipo1", colore: "giallo" }, { nome: "pantaloni", tipo: "tipo2", colore: "nero" }, { nome: "gonna", tipo: "tipo3", colore: "verde" } ] vestiti.forEach((element) => { element.prezzo = random(10, 50); }); console.log(vestiti); // Funzione function random(min, max) { return Math.floor(Math.random() * (max - min)) + min; }
b0fda56d7477bb6b8dce697a1c2e1aa8b5720e2a
[ "JavaScript" ]
1
JavaScript
MirkoGriffo/js-snack-es6
31c09445d30f807c907e59d4cc7654fe7e48c87f
d7c3583d31dd293ad5e6f32375c081f2dc13f43d
refs/heads/master
<repo_name>JLQmiller/ts-node-dev-environment<file_sep>/test/server.spec.ts import { expect } from "chai"; import { hello, Producer, Province, sampleProvinceData, } from "../src/server"; describe("Province", () => { let asia: Province; beforeEach(function() { asia = new Province(sampleProvinceData()); }); test("it should hello", () => { expect(hello()).to.equal(5); }); test("it should province profit", () => { expect(asia.profit).to.equal(158); }); test("it should province shortfall", () => { expect(asia.shortfall).to.equal(14); }); test("it should province name", () => { expect(asia.name).to.equal("Asia"); }); test("it should province set totalProduction", () => { asia.totalProduction = 3; expect(asia.totalProduction).to.equal(3); }); test("it should province set demand", () => { asia.demand = 2; expect(asia.demand).to.equal(2); }); }); // describe("Producer", () => { // let producer: Producer; // beforeEach(function() { // producer = new Producer(new Province(sampleProvinceData()), ); // }) // })<file_sep>/src/server.ts export function hello(): number { console.log("fuck"); return 5; } hello(); export function sampleProvinceData() { return { name: "Asia", producers: [ { name: "By", cost: 10, production: 9 }, { name: "Attalia", cost: 12, production: 1 }, { name: "Sinope", cost: 10, production: 6 }, ], demand: 30, price: 20 }; } export class Province { private _name: string; private _producers: any[]; private _totalProduction: number; private _demand: number; private _price: number; constructor(doc: any) { this._name = doc.name; this._producers = []; this._totalProduction = 0; this._demand = doc.demand; this._price = doc.price; doc.producers.forEach((d: any) => this.addProducer(new Producer(this, d))); } public get name() { return this._name; } public get producers() { return this._producers.slice(); } public get totalProduction() { return this._totalProduction; } public set totalProduction(arg) { this._totalProduction = arg; } public get demand() { return this._demand; } public set demand(arg) { this._demand = arg; } public get price() { return this._price; } public set price(arg) { this._price = arg; } public get shortfall(): number { return this._demand - this.totalProduction; } public get profit() { return (this.demandValue - this.demandCost) as number; } public get demandCost() { let remainingDemand = this.demand; let result = 0; this.producers .sort((a, b) => a.cost - b.cost) .forEach(p => { const contribution = Math.min(remainingDemand, p.production); remainingDemand -= contribution; result += contribution * p.cost; }); return result; } private get demandValue() { return this.satisfiedDemand * this.price; } private get satisfiedDemand() { return Math.min(this._demand, this.totalProduction); } private addProducer(arg: any) { this._producers.push(arg); this._totalProduction += arg.production; } } export class Producer { private _province: Province; private _cost: number; private _name: string; private _production: any; constructor(aProvince: Province, data: any) { this._province = aProvince; this._cost = data.cost; this._name = data.name; this._production = data.production || 0; } public get name() { return this._name; } public get cost() { return this._cost; } public set cost(arg) { this._cost = parseInt(arg.toString()); } public get production() { return this._production; } public set production(amountStr) { const amount = parseInt(amountStr); const newProduction = Number.isNaN(amount) ? 0 : amount; this._production.totalProduction += newProduction - this._production; this._production = newProduction; } } const newInstance = new Province(sampleProvinceData()); console.log(`console.log: ${newInstance.name}`); newInstance.totalProduction = 3; console.log(`console.log: ${newInstance.totalProduction}`);
ef82a1cd606495d496ca75fd4914cd3b294fd878
[ "TypeScript" ]
2
TypeScript
JLQmiller/ts-node-dev-environment
d1d9add84b0e92d6d680f4f792b145935fb32749
20f8e6cf9adfde274affb83d7ea427f5916fa0e0
refs/heads/master
<file_sep>let n1 = parseFloat(window.prompt("Primeira nota")|| 0); let n2 = parseFloat(window.prompt("Segunda nota") || 0) ; let n3 = parseFloat(window.prompt("Terceira nota") || 0); let n4 = parseFloat(window.prompt("Quarta nota") || 0); const media = ((n1 + n2 + n3 + n4) / 4); if (n1 < 0 || n2 < 0 || n3 < 0 || n4 < 0 || n1 > 10 || n1 > 10 || n2 > 10 || n3 > 10 || n4 > 10) { window.alert("Aceito apenas números de 0 á 10"); } else if (media < 5) { window.alert(`Você ficou com média ${media}. Resultado: Reprovado`) } else if (media >= 5 && media <= 6) { window.alert(`Você ficou com média ${media}. Resultado: Em recuperação`) } else { window.alert(`Você ficou com média ${media}. Resultado: Aprovado`) }
a9ed47a7d914048192d36b410594e1f242602b3b
[ "JavaScript" ]
1
JavaScript
isaacgeazy/Media4NotasJs
ab95358d878232524199c6eb9767c09a4771314e
9ca0f0e3ee65a3b97c1acc326990e32fb310de06
refs/heads/master
<file_sep>#include <stdio.h> #include <unistd.h> #include "using_mkstemp.h" /* Desc: create a temp file and write "buffer" to it with "length" bytes Param: char *buffer - the stuff to be written to the file size_t length - the size of the buffer to be written Return value: int - the fd of the temporary file */ int write_temp_file(char *buffer, size_t length) { int fd = 0; char temp_file[] = "/tmp/tmp_file.XXXXXX"; fd = mkstemp(temp_file); printf("Try to write %d bytes to %s\n", length, temp_file); /* call unlink() immediately, so that it will be removed when the file is no more used. (file reference count is zero) */ unlink(temp_file); /* write the size first */ write(fd, &length, sizeof(size_t)); /* write data */ write(fd, buffer, length); printf("Writing file is done.\n"); /* return the fd to caller */ return fd; } /* Desc: read back the stored data of temporary file Params: int fd - the file descriptor of the temporary file size_t length - the size to be read Return value: char * - the NUL-terminated character string */ char *read_temp_file(int fd, size_t *length) { char *buffer = NULL; /* rewind to the beginning of the temporary file */ lseek(fd, 0, SEEK_SET); /* read the size of the data in the temporary file */ read(fd, length, sizeof(size_t)); printf("length is %d\n", *length); /* allocating memory buffer to store the data */ buffer = (char *) malloc(*length * sizeof(char)); /* read the data in temporary file */ read(fd, buffer, *length); /* close the temporary file */ close(fd); return buffer; } <file_sep>#ifndef __RECIPROCAL_H #define __RECIPROCAL_H #ifdef __cplusplus extern "C" { #endif double reciprocal(int i); #ifdef __cplusplus } #endif #endif <file_sep>#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(int argc, char **argv) { pid_t child_pid; pid_t parent_pid; child_pid = getpid(); parent_pid = getppid(); printf("PID is %d\n", child_pid); printf("PPID is %d\n", parent_pid); return 0; } <file_sep>#include <stdio.h> #include "using_mkstemp.h" int main(int argc, char *argv[]) { int temp_fd = (-1); char msg[] = "Stay hungry, stay foolish."; char *readBack = NULL; int length = sizeof(msg); printf("length of msg is %d\n", length); temp_fd = write_temp_file(msg, length+1/* don't forget the "\0" character */); /* Read back data */ readBack = read_temp_file(temp_fd, &length); printf("%s(): read length = %d\n", __func__, length); printf("%s(): msg is %s\n", __func__, readBack); free(readBack); return 0; } <file_sep>ALP_examples ============ Examples of the Advanced Linux Programming <file_sep>#include <stdio.h> #include <getopt.h> #include <stdlib.h> /* Short-Form Long-Form Purpose -h --help print the help message -o filename --output file name assing the name of output file -v --verbose print verbose message */ /*An array describing valid long options */ const struct option long_options[] = { {"help", 0, NULL, 'h'}, {"output", 1, NULL, 'o'}, {"verbose", 0, NULL, 'v'}, {NULL, 0, NULL, 0} }; const char *prog_name; void print_usage(FILE *stream, int exit_code) { fprintf(stream, "Usage: %s options [ inputfile...]\n", prog_name); fprintf(stream, " -h --help Display this message\n" " -o --output Write output to file\n" " -v --verbose Print verbose messages\n"); exit(exit_code); } int main(int argc, char *argv[]) { int next_option; /* A string listing valid short options letters. */ const char * const short_options = "ho:v"; const char * output_filename = NULL; /* Whether to display verbose message. */ int verbose = 0; prog_name = argv[0]; do{ next_option = getopt_long(argc, argv, short_options, long_options, NULL); switch(next_option) { case 'h': print_usage(stdout, 0); break; case 'o': output_filename = optarg; printf("Output file name is %s\n", output_filename); break; case 'v': verbose = 1; break; case '?': print_usage(stderr, 1); break; case -1: printf("No more options!\n"); break; } }while(next_option != -1); if(verbose == 1) { int i = 0; for(i = 0; i < argc; i++) printf("argv[%d] = %s\n", i, argv[i]); } return 0; } <file_sep>#ifndef __USING_MKSTEMP_H #define __USING_MKSTEMP_H int write_temp_file(char *buffer, size_t length); char *read_temp_file(int fd, size_t *length); #endif <file_sep>CC=gcc CPP=g++ C_FLAGS= CPP_FLAGS= LIBS= reciprocal: main.o reciprocal.o $(CPP) $(CFLAGS) -o reciprocal main.o reciprocal.o main.o: main.c reciprocal.hpp $(CC) $(CFLAGS) -c main.c reciprocal.o: reciprocal.cpp reciprocal.hpp $(CPP) $(CFLAGS) -c reciprocal.cpp clean: rm -f *.o reciprocal <file_sep>#include <stdio.h> #include <stdlib.h> extern char **environ; int main(int argc, char *argv[]) { char **var; char *env = NULL; for(var = environ; *var != NULL; ++var) { printf("%s\n", *var); } printf("Get PATH:\n"); env = getenv("PATH"); if(env != NULL) { printf("PATH = %s\n", env); } else { printf("PATH is not defined\n"); } return 0; }
3590a81bda3f7e8fd46fb2ce2aa2be5ab1f4a9e7
[ "Markdown", "C", "Makefile", "C++" ]
9
C
chubahowsmall/ALP_examples
7b68a9bedf7cbd3af308c999140e424b44df90b4
448e4da95b8b93617b17ac298ea7a91676cfe7d5
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class PlayerAnim : MonoBehaviour { private Animator animator; private string boolIsMove = "isMove"; void Awake() { animator = GetComponent<Animator>(); } public void PlayIdleAnim() { animator.SetBool(boolIsMove,false); } public void PlayWalkAnim() { animator.SetBool(boolIsMove, true); } } <file_sep>using UnityEngine; using System.Collections; public class Card : MonoBehaviour { private int _Id; public int Id { get { return _Id; } set { _Id = value; } } private string _Name; public string Name { get { return _Name; } set { _Name = value; } } private string _Des; public string Des { get { return _Des; } set { _Des = value; } } private string _Icon; public string Icon { get { return _Icon; } set { _Icon = value; } } } <file_sep>using UnityEngine; using System.Collections; public class BuildingPoint : MonoBehaviour { private RoadPoint road; public RoadPoint Road { get { return road; } set { road = value; } } private MapBlock mapblock; public MapBlock Mapblock { get { return mapblock; } set { mapblock = value; } } private int level = 0;//房屋等级 public int Level { set { level = value; } get { return level; } } private Player player; public Player Player { get { return player; } set { player = value; } } public int MaxLevel = 1; //升级房屋 public void UpgradeBlock(Player player) { //Debug.Log(type); if (mapblock.Type == BlockType.Build) { this.player = player; gameObject.AddComponent<BuildUpgrade>().UpdateBuild(player); } } } <file_sep>using UnityEngine; using System.Collections; public class BuyBuild : MonoBehaviour { //public static BuyBuild _Instance; private UILabel label_gold; private UIButton btn_buy; private UIButton btn_nobuy; private UIButton btn_close; private TweenPosition tween; // Use this for initialization void Awake () { //_Instance = this; label_gold = transform.Find("LabelGold").GetComponent<UILabel>(); btn_buy = transform.Find("BtnBuy").GetComponent<UIButton>(); btn_nobuy = transform.Find("BtnNoBuy").GetComponent<UIButton>(); btn_close = transform.Find("BtnClose").GetComponent<UIButton>(); tween = GetComponent<TweenPosition>(); //EventDelegate ed_buy = new EventDelegate(this, "OnBuyClick"); //btn_buy.onClick.Add(ed_buy); EventDelegate ed_nobuy = new EventDelegate(this, "OnNoBuyClick"); btn_nobuy.onClick.Add(ed_nobuy); EventDelegate ed_close = new EventDelegate(this, "OnCloseClick"); btn_close.onClick.Add(ed_close); } void Start() { this.gameObject.SetActive(false); } public void Show() { this.gameObject.SetActive(true); tween.PlayForward(); } void Dismiss() { StartCoroutine(SetWindowEnable()); tween.PlayReverse(); } IEnumerator SetWindowEnable() { yield return new WaitForSeconds(0.5f); this.gameObject.SetActive(false); } public void OnBuyClick() { //Debug.Log("OnBuyClick"); GameManager._Instance.BuyBuild(); Dismiss(); } void OnNoBuyClick() { Dismiss(); } void OnCloseClick() { Dismiss(); } } <file_sep>using UnityEngine; using System.Collections; public class PlayerPanel : MonoBehaviour { public static PlayerPanel _Instance; private UIButton btn_Roll; private UIButton btn_EndBtn; private UILabel btnRoll_label; private UITexture texture_head; private UISprite sprite_frame; void Awake() { _Instance = this; btn_Roll = transform.Find("BtnRoll").GetComponent<UIButton>(); btn_Roll.gameObject.SetActive(false); btn_EndBtn = transform.Find("BtnEndRound").GetComponent<UIButton>(); btn_EndBtn.gameObject.SetActive(false); texture_head = transform.Find("HeadTexture").GetComponent<UITexture>(); texture_head.gameObject.SetActive(false); sprite_frame=texture_head.transform.Find("Head").GetComponent<UISprite>(); btnRoll_label = btn_Roll.transform.Find("Label").GetComponent<UILabel>(); //TextAsset text = Resources.Load("Text/map1", typeof(TextAsset)) as TextAsset; //string s=text.text; //string[] s2 = s.Split('\n'); //Debug.Log(s); //btnRoll_label.text = s2[0]; } void Start() { } public void OnRollClick() { btn_Roll.gameObject.SetActive(false); Touzi._Instance.ShowDice(); btn_EndBtn.gameObject.SetActive(true); } public void OnEndRoundClick() { btn_EndBtn.gameObject.SetActive(false); btn_Roll.gameObject.SetActive(true); GameManager._Instance.OnEndRoundClick(); sprite_frame.color = GameManager._Instance.ThisRoundPlayer.GetComponent<Player>().Color; } public void SetText(string s) { btnRoll_label.text = s; } public void ShowUI() { texture_head.gameObject.SetActive(true); btn_Roll.gameObject.SetActive(true); } public void SetFrameColor(Color color) { sprite_frame.color = color; } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using DG.Tweening; public class MapManager : MonoBehaviour { public static MapManager _Instance; public string mapXmlPath = "Text/map1.xml"; public GameObject roadPointPrefeb;//路径点预制品 public GameObject playerPrefeb; private List<MapBlock> blocksList = new List<MapBlock>(); private List<BuildingPoint> buildList = new List<BuildingPoint>(); public List<MapBlock> roadBuildList = new List<MapBlock>(); //private List<RoadPoint> roadpointList = new List<RoadPoint>();//存放路径点 public bool isXMLReadComplete = false; private bool isMapComplete = false; private bool isPlayerSetupOver = false; //Row列 Column行 public int Row = 14; public int Colums = 15; public int PlayerNum = 2; private GameObject newroadPoint; public Color[] playerColors; public int[] playerPos; void Awake() { _Instance = this; #if UNITY_ANDROID //StartCoroutine(LoadXmlAndroid()); LoadXmlAndroid(); #endif #if UNITY_STANDALONE_WIN LoadXml(); #endif //GameObject go = null; //GameObject prefeb = null; //prefeb = Resources.Load("Prefebs/Road/" + "roadTile_" + string.Format("{0:000}", 1)) as GameObject; //go = GameObject.Instantiate(prefeb, new Vector3(0, 1, 0), Quaternion.Euler(0, 0, 0)) as GameObject; } void Start() { GetBuildingInMap(); } public void FallFirstBlock() { blocksList[0].FallBlock(); } void PaseXml(XmlDocument xml) { //得到objects节点下的所有子节点 XmlNodeList xmlNodeList = xml.SelectSingleNode("map/Enenty").ChildNodes; //遍历所有子节点 foreach (XmlElement xl1 in xmlNodeList) { foreach (XmlElement xl2 in xl1.ChildNodes) { string type = (xl2.GetAttribute("type") + xl2.InnerText); BlockType blocktype = BlockType.Null; switch (type) { case "Road": blocktype = BlockType.Road; //PlayerPanel._Instance.SetText(type); break; case "Build": blocktype = BlockType.Build; break; case "Normal": blocktype = BlockType.Normal; break; default: blocktype = BlockType.Null; break; } int id = int.Parse(xl2.GetAttribute("id") + xl2.InnerText); int x = int.Parse(xl2.GetAttribute("x") + xl2.InnerText); int y = int.Parse(xl2.GetAttribute("y") + xl2.InnerText); int rotate = int.Parse(xl2.GetAttribute("rotate") + xl2.InnerText); //x += 30; //y += 30; int height = 30; GameObject go = null; GameObject prefeb = null; if (blocktype == BlockType.Road) { prefeb = Resources.Load("Prefebs/Road/" + "roadTile_" + string.Format("{0:000}", id)) as GameObject; newroadPoint = GameObject.Instantiate(roadPointPrefeb, new Vector3(x - 1.5f, 0.25f, y - 1.5f), Quaternion.identity) as GameObject; newroadPoint.transform.parent = GameObject.Find("RoadPoints").transform; //roadpointList.Add(newroadPoint.GetComponent<RoadPoint>()); } else if (blocktype == BlockType.Build) { prefeb = Resources.Load("Prefebs/Building/" + "modularBuildings_" + string.Format("{0:000}", id)) as GameObject; } else if (blocktype == BlockType.Normal) { prefeb = Resources.Load("Prefebs/Road/" + "roadTile_" + string.Format("{0:000}", id)) as GameObject; } if (rotate == 0) { go = GameObject.Instantiate(prefeb, new Vector3(x, height, y), Quaternion.identity) as GameObject; } else if (rotate == 90) { go = GameObject.Instantiate(prefeb, new Vector3(x, height, y - 3), Quaternion.Euler(0, rotate, 0)) as GameObject; } else if (rotate == 180) { go = GameObject.Instantiate(prefeb, new Vector3(x - 3, height, y - 3), Quaternion.Euler(0, rotate, 0)) as GameObject; } else if (rotate == 270) { go = GameObject.Instantiate(prefeb, new Vector3(x - 3, height, y), Quaternion.Euler(0, rotate, 0)) as GameObject; } if (blocktype == BlockType.Road) { go.gameObject.name = "Road-" + x / 3 + "-" + y / 3; } else if (blocktype == BlockType.Build) { go.gameObject.name = "Building-" + x / 3 + "-" + y / 3; } else if (blocktype == BlockType.Normal) { go.gameObject.name = "Normal-" + x / 3 + "-" + y / 3; } go.transform.parent = GameObject.Find("Terrain").transform; MapBlock block = go.GetComponent<MapBlock>(); if (newroadPoint != null) { newroadPoint.GetComponent<RoadPoint>().MapBlock = block; } newroadPoint = null; //Debug.Log(rotate); block.InitBlock(blocktype, id, x, y, blocksList.Count, rotate); blocksList.Add(block); } } isXMLReadComplete = true; } #if UNITY_STANDALONE_WIN //读取地图配置 void LoadXml() { XmlDocument xml = new XmlDocument(); XmlReaderSettings set = new XmlReaderSettings(); set.IgnoreComments = true;//这个设置是忽略xml注释文档的影响。有时候注释会影响到xml的读取 //Resources.Load(mapXmlPath) //yield return new WaitForSeconds(0.01f); xml.Load(XmlReader.Create("Assets/Resources/" + mapXmlPath, set)); PaseXml(xml); } #endif #if UNITY_ANDROID void LoadXmlAndroid() { XmlDocument xml = new XmlDocument(); XmlReaderSettings set = new XmlReaderSettings(); set.IgnoreComments = true;//这个设置是忽略xml注释文档的影响。有时候注释会影响到xml的读取 string path=Application.dataPath + "/Resources/" + mapXmlPath; xml.Load(XmlReader.Create(path, set)); PaseXml(xml); } #endif void GetBuildingInMap() { for (int i = 0; i < blocksList.Count; i++) { if (blocksList[i].Type == BlockType.Build) { blocksList[i].gameObject.AddComponent<BuildingPoint>(); blocksList[i].gameObject.GetComponent<BuildingPoint>().Mapblock = blocksList[i]; buildList.Add(blocksList[i].GetComponent<BuildingPoint>()); } } SetBuildRoad(); } /// <summary> /// 设置建筑物对应的路 /// </summary> void SetBuildRoad() { for (int i = 0; i < buildList.Count; i++) { //Debug.Log(buildList[i].Mapblock.Rotate); int count = 0; if (buildList[i].Mapblock.Rotate == 270) { //获得左侧的Road count = buildList[i].Mapblock.Count - Row - 2; // Debug.Log(blocksList[count].gameObject.transform.localPosition); } else if (buildList[i].Mapblock.Rotate == 90) { count = buildList[i].Mapblock.Count + Row + 2; //roadBuildList.Add(blocksList[count]); } else if (buildList[i].Mapblock.Rotate == 0) { count = buildList[i].Mapblock.Count - 1; //roadBuildList.Add(blocksList[count]); } else if (buildList[i].Mapblock.Rotate == 180) { count = buildList[i].Mapblock.Count + 1; //roadBuildList.Add(blocksList[count]); } blocksList[count].RoadType = RoadType.CanBuild; blocksList[count].Build = buildList[i]; //Debug.Log(blocksList[count].Build.Mapblock.Count); roadBuildList.Add(blocksList[count]); } } public void FallBlockOneByOne(int i) { if (i < blocksList.Count && blocksList[i].IsSet == false) { StartCoroutine(FallBlock(i)); //Debug.Log(i); if (i == blocksList.Count - 1) { //Debug.Log("isMapComplete"); isMapComplete = true; } } } IEnumerator FallBlock(int i) { yield return new WaitForSeconds(0.1f); blocksList[i].FallBlock(); } void Update() { if (isMapComplete) { SetUpPlayer(); } } void SetUpPlayer() { if (!isPlayerSetupOver) { for (int i = 0; i < PlayerNum; i++) { GameObject player = CreatePlayerWithPos(playerPos[i]); player.name = "Player" + (i + 1); player.GetComponent<Player>().Color = playerColors[i]; //改变对应颜色 //player.GetComponent<Renderer>().material.color = player.GetComponent<Player>().Color; } isPlayerSetupOver = true; GameManager._Instance.AddPlayer(); GameManager._Instance.ThisRoundPlayer = GameManager._Instance.players[0]; //现在玩家开启相机 PlayerPanel._Instance.ShowUI(); PlayerPanel._Instance.SetFrameColor(GameManager._Instance.ThisRoundPlayer.GetComponent<Player>().Color); } } public MapBlock GetRoadByCount(int count) { return blocksList[count]; } GameObject CreatePlayerWithPos(int count) { RoadPoint road0 = null; RoadManager._Instance.dict_Road.TryGetValue(count, out road0); Vector3 pos = Vector3.zero; if (road0 != null) { pos = new Vector3(road0.gameObject.transform.position.x,// road0.gameObject.transform.position.y + 10,// road0.gameObject.transform.position.z); } //生成玩家 GameObject player = GameObject.Instantiate(playerPrefeb, pos, Quaternion.identity) as GameObject; player.transform.DOMoveY(0.5f, 2f).SetEase(Ease.InCubic); player.GetComponent<PlayerMove>().FootRoad = road0; player.GetComponent<Player>().Count = road0.MapBlock.Count; return player; } } <file_sep>using UnityEngine; using System.Collections; public class CardInventoryItemUI : MonoBehaviour { private CardInventory cardInventory; private UISprite sprite; private UILabel label; // Use this for initialization void Awake () { sprite = transform.Find("Sprite").GetComponent<UISprite>(); label = transform.Find("Label").GetComponent<UILabel>(); this.GetComponent<UISprite>().width = 100; } public void SetCardInventory(CardInventory cardInventory) { this.cardInventory = cardInventory; Init(); } void Init() { Debug.Log(cardInventory.Card.Icon); sprite.spriteName = cardInventory.Card.Icon; //sprite.spriteName = "robber.png"; label.text = cardInventory.Num.ToString(); } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class CardManager : MonoBehaviour { public static CardManager _Instance; public TextAsset CardInfoText; //方案1--Hashtable protected Hashtable hashtable; private int DataRow; //方案2--Dict private Dictionary<int, Card> dicr_card = new Dictionary<int, Card>(); void Awake() { _Instance = this; // ReadCardInfo(); ReadCardInfoText(); //Debug.Log(GetCardById(2).Name); } void ReadCardInfoText() { string[] cardsInfos = CardInfoText.ToString().Split('\r'); for (int i = 1; i < cardsInfos.Length;i++ ) { string[] cardInfos = cardsInfos[i].Split(','); Card card=new Card(); card.Id = int.Parse(cardInfos[0]); card.Name = cardInfos[1]; card.Des = cardInfos[2]; card.Icon = cardInfos[3]; dicr_card.Add(card.Id, card); } //Debug.Log(dicr_card.Count); } public Card GetCardById(int id) { if (dicr_card.ContainsKey(id)) { Card card; dicr_card.TryGetValue(id,out card); return card; }else return null; } #region HashTable void ReadCardInfo() { hashtable = new Hashtable(); string[] lineArray = CardInfoText.text.Split('\r'); string[][] cardInfoArray = new string[lineArray.Length][]; //把csv中的数据存在二维数组中 for (int i = 0; i < lineArray.Length; i++) { cardInfoArray[i] = lineArray[i].Split(','); //Debug.Log(lineArray[i]); //Debug.Log(cardInfoArray[i]); } int nRow = cardInfoArray.Length; int nCow = cardInfoArray[0].Length; //Debug.Log("nRow:" + nRow); for (int i = 1; i < nRow; ++i) { //Debug.Log(cardInfoArray[i][0]); if (cardInfoArray[i][0] == "\n" || cardInfoArray[i][0] == "" || cardInfoArray[i][0] == "\r")//排空 { nRow--; continue; } //ID信息 string id = cardInfoArray[i][0].Trim(); for (int j = 1; j < nCow; j++) { hashtable.Add(cardInfoArray[0][j] + "_" + id, cardInfoArray[i][j]); } } //Debug.Log("nRow:" + nRow); //Debug.Log("nCow:" + nCow); DataRow = nRow - 1; } public int GetAllCardType() { return DataRow; } public string GetProperty(string name, int id) { return GetProperty(name, id.ToString()); } public string GetProperty(string name, string id) { string key = name + "_" + id; if (hashtable.ContainsKey(key)) { return hashtable[key].ToString(); } else return "NO KEY"; } #endregion } <file_sep>using UnityEngine; using System.Collections; public class CameraFollowPlayer : MonoBehaviour { public Vector3 offset; private Transform player; public float smoothing = 1; private bool isRotating = false;//正在旋转 private float m_RotateSpeed = 2f; public float MaxRotateX = 70f; public float MinRotateX = 10f; private float distance = 0; public float m_ScrollSpeed = 5f; public float MaxDistance = 10f; public float MinDistance = 3f; void Start() { transform.localRotation = Quaternion.Euler(new Vector3(70, -135, 0)); transform.LookAt(player); } // Update is called once per frame void FixedUpdate() { if (GameManager._Instance.ThisRoundPlayer != null) { SetPlayer(GameManager._Instance.ThisRoundPlayer.transform); transform.LookAt(player); } if (player != null) { Vector3 targetPos = player.position + offset; transform.position = Vector3.Lerp(transform.position, targetPos, smoothing * Time.deltaTime); RotateView(); ScrollView(); } } void RotateView() { if (Input.GetMouseButtonDown(1)) { isRotating = true; } if (Input.GetMouseButtonUp(1)) isRotating = false; Vector3 orginalPosition = transform.position; Quaternion orginalRotation = transform.rotation; if (isRotating) { transform.RotateAround(player.position, player.up, Input.GetAxis("Mouse X") * m_RotateSpeed); transform.RotateAround(player.position, -transform.right, Input.GetAxis("Mouse Y") * m_RotateSpeed); offset = transform.position - player.position; } //对旋转范围进行限定 float x = transform.eulerAngles.x; if (x < MinRotateX || x > MaxRotateX) { transform.position = orginalPosition; transform.rotation = orginalRotation; } } void ScrollView() { //Debug.Log (Input.GetAxis("Mouse ScrollWheel")); //向前正--向后负 //向前-->拉近视野 //向后-->拉远视野 distance = offset.magnitude; distance -= Input.GetAxis("Mouse ScrollWheel") * m_ScrollSpeed; // distance = Mathf.Max (distance,MinDistance); // distance = Mathf.Min (distance,MaxDistance); distance = Mathf.Clamp(distance, MinDistance, MaxDistance); //normalized-->单位向量 offset = offset.normalized * distance; } void SetPlayer(Transform player) { this.player = player; } } <file_sep># Unity3D-Monopoly 大富翁小Demo 包含地图生成 <file_sep>using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { public static GameManager _Instance; public int _round = 1; public GameObject[] players; private int playerIndex = 0; private GameObject thisRoundPlayer; public GameObject ThisRoundPlayer { get { return thisRoundPlayer; } set { thisRoundPlayer = value; } } public BuyBuild buyBuildUI; public PayBuild pauBuildUI; void Awake() { _Instance = this; } void Start () { } public void OnRollClick(int number) { LotNumber(number); } public void OnEndRoundClick() { //切换至下一个player playerIndex++; thisRoundPlayer.GetComponent<PlayerMove>().CLoseHeadCamera(); if (playerIndex>=players.Length) { //关闭相机 playerIndex = 0; _round++; thisRoundPlayer = players[0]; } else { thisRoundPlayer = players[playerIndex]; } thisRoundPlayer.GetComponent<PlayerMove>().ShowHeadCamera(); PlayerCard._Instance.ShowNextPlayerCard(ThisRoundPlayer.GetComponent<Player>()); } /// <summary> /// 摇骰子 /// </summary> void LotNumber(int number) { //通知player前进 MovePlayer(thisRoundPlayer.GetComponent<PlayerMove>(), number); } void MovePlayer(PlayerMove player, int number) { player.SendMessage("Move", number); } public void AddPlayer() { players = GameObject.FindGameObjectsWithTag("Player"); } public void ShowBuyBuild(RoadPoint roadpoint) { buyBuildUI.Show(); } void ShowPayBuild() { pauBuildUI.Show(); } public void BuyBuild() { //Debug.Log("BuyBuild"); //当前路的对应房子 int count=thisRoundPlayer.GetComponent<Player>().Count; //得到当前的路 MapBlock block=MapManager._Instance.GetRoadByCount(count); //Debug.Log("BuyBuild2222"); if (thisRoundPlayer!=null&&block.Build!=null) { block.Build.UpgradeBlock(thisRoundPlayer.GetComponent<Player>()); } } public void PayBuild() { ShowPayBuild(); } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class RoadManager : MonoBehaviour { public static RoadManager _Instance; private int roadCount; public int RoadCount { get { return roadCount; } } private List<RoadPoint> list_Road = new List<RoadPoint>(); public Dictionary<int, RoadPoint> dict_Road = new Dictionary<int, RoadPoint>(); private List<RoadPoint> list_restRoad = new List<RoadPoint>(); public List<RoadPoint> list_lastRoad = new List<RoadPoint>(); private bool isInit = false; void Awake() { _Instance = this; } void Start() { RoadPoint[] roads = this.GetComponentsInChildren<RoadPoint>(); for (int i = 0; i < roads.Length; i++) { //roads[i].Num = i; list_Road.Add(roads[i]); list_restRoad.Add(roads[i]); } roadCount = list_Road.Count; } void Update() { InitRoad(); } void InitRoad() { if (MapManager._Instance.isXMLReadComplete&&isInit==false) { isInit = true; CreatePath(); //PlayerPanel._Instance.SetText("ReadXml Success"); MapManager._Instance.FallFirstBlock(); } } /// <summary> /// 创建封闭路径 /// </summary> void CreatePath() { for (int i = 0; i < 2; i++) { list_Road[i].Id = i; list_Road[i].name = "RoadPoint" + list_Road[i].Id; dict_Road.Add(list_Road[i].Id, list_Road[i]); list_restRoad.Remove(list_Road[i]); list_lastRoad.Add(list_Road[i]); } RoadPoint tempRoad = list_Road[1]; int temp = 1; while (temp != list_Road.Count-1) { tempRoad = CompileToRelistRoad(tempRoad); if (tempRoad != null) { temp++; tempRoad.Id = temp; tempRoad.name = "RoadPoint" + tempRoad.Id; dict_Road.Add(tempRoad.Id, tempRoad); list_restRoad.Remove(tempRoad); list_lastRoad.Add(tempRoad); } } } bool ISRoadBehind(RoadPoint thisroad, RoadPoint otherroad) { bool isBehind = false; if (thisroad.transform.position.z == otherroad.transform.position.z) { float x = Mathf.Abs(thisroad.transform.position.x - otherroad.transform.position.x); if (x == 3.0f) { isBehind = true; } } else if (thisroad.transform.position.x == otherroad.transform.position.x) { float z = Mathf.Abs(thisroad.transform.position.z - otherroad.transform.position.z); if (z == 3.0f) { isBehind = true; } } return isBehind; } /// <summary> /// 获得与此路相邻的路 /// </summary> /// <param name="road"></param> /// <returns></returns> RoadPoint CompileToRelistRoad(RoadPoint road) { for (int i = 0; i < list_restRoad.Count; i++) { if (ISRoadBehind(road, list_restRoad[i])) { return list_restRoad[i]; } } return null; } public RoadPoint GetRoadById(int id) { RoadPoint road = null; dict_Road.TryGetValue(id, out road); return road; } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class Player : MonoBehaviour { private int gold; public int Gold { set { gold = value; } get { return gold; } } /// <summary> /// 在地图中的位置 /// </summary> private int count; public int Count { get { return count; } set { count = value; } } private Color color; public Color Color { get { return color; } set { color = value; } } //拥有的卡牌 private List<CardInventory> cards; public List<CardInventory> Cards { get { return cards; } set { cards = value; } } public void AddCard(Card card) { //cards.Add(card); } } <file_sep>using UnityEngine; using System.Collections; public class Touzi : MonoBehaviour { public static Touzi _Instance; public int diceCount = 0; public int MaxRandom = 30; private int RandomCount = 0; void Awake() { _Instance = this; } void Start() { gameObject.SetActive(false); } //Method Roll the Dice void RollTheDice() { //骰子随机显示数字 InvokeRepeating("RollDiceOneTime", 0.01f, 0.05f); } void RollDiceOneTime() { RandomCount++; int count; if (RandomCount<=MaxRandom) { count = Random.Range(1, 7); if (RandomCount==MaxRandom) { diceCount = count; } RotateDice(count); } else { RandomCount = 0; CancelInvoke(); HideDice(); Debug.Log(diceCount); GameManager._Instance.OnRollClick(diceCount); } } void RotateDice(int count) { switch (count) { case 1: gameObject.transform.localRotation = Quaternion.identity; break; case 2: gameObject.transform.localRotation = Quaternion.Euler(new Vector3(90,0,0)); break; case 3: gameObject.transform.localRotation = Quaternion.Euler(new Vector3(90, 90, 0)); break; case 4: gameObject.transform.localRotation = Quaternion.Euler(new Vector3(90, 180, 0)); break; case 5: gameObject.transform.localRotation = Quaternion.Euler(new Vector3(90, 270, 0)); break; case 6: gameObject.transform.localRotation = Quaternion.Euler(new Vector3(0, -180, 0)); break; } } public void ShowDice() { gameObject.SetActive(true); RollTheDice(); } public void HideDice() { gameObject.SetActive(false); } } <file_sep>using UnityEngine; using System.Collections; using DG.Tweening; public enum BlockType { Road, Build, Normal, Null } public enum RoadType { Normal, CanBuild } public class MapBlock : MonoBehaviour { private BlockType type; private int id; private int x; private int y; public int count;//在地图中的编号 private int rotate; private bool isSet = false; //特殊Road相关 private RoadType roadType; public RoadType RoadType { get { return roadType; } set { roadType = value; } } //如果改道路可以建造道路的话 private BuildingPoint build; public BuildingPoint Build { get { return build; } set { build = value; } } #region setget public BlockType Type { set { type = value; } get { return type; } } public int Id { set { id = value; } get { return id; } } public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } public int Count { set { count = value; } get { return count; } } public bool IsSet { set { isSet = value; } get { return isSet; } } public int Rotate { set { rotate = value; } get { return rotate; } } #endregion void Start() { } public void InitBlock(BlockType blocktype, int id, int x, int y, int count, int rotate) { SetBlock(blocktype, id, x, y, count, rotate); } void SetBlock(BlockType blocktype, int id, int x, int y, int count,int rotate) { //Debug.Log(blocktype); this.Type = blocktype; this.Id = id; this.X = x; this.Y = y; this.Count = count; this.Rotate = rotate; if (type==BlockType.Road) { roadType = RoadType.Normal; } } public void FallBlock() { isSet = true; Tweener tweener = transform.DOMoveY(0, 0.1f); tweener.SetEase(Ease.InCubic); tweener.OnComplete(FallComplete); } void FallComplete() { int Row = MapManager._Instance.Row+2; int rows = Count / Row; // Debug.Log(rows); MapManager._Instance.FallBlockOneByOne(Count + 1); MapManager._Instance.FallBlockOneByOne((rows + 1) * Row); } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerCard : MonoBehaviour { public static PlayerCard _Instance; public GameObject CardInventoryPrefeb; private UIGrid grid; private List<CardInventory> cardList = new List<CardInventory>(); void Awake() { _Instance = this; grid = transform.Find("Scroll View/Grid").GetComponent<UIGrid>(); } void Start() { CreateCardInventory(); } void CreateCardInventory() { //GetCardInventory(GameManager._Instance.ThisRoundPlayer.GetComponent<Player>()); CardInventory card1 = new CardInventory(); card1.Card = CardManager._Instance.GetCardById(1); card1.Num = 1; CardInventory card2 = new CardInventory(); card2.Card = CardManager._Instance.GetCardById(2); card2.Num = 3; cardList.Add(card1); cardList.Add(card2); for (int i = 0; i < cardList.Count; i++) { GameObject cardItemUI = GameObject.Instantiate(CardInventoryPrefeb); cardItemUI.GetComponent<CardInventoryItemUI>().SetCardInventory(cardList[i]); //NGUITools.AddChild(this.gameObject, CardInventoryPrefeb); grid.AddChild(cardItemUI.transform); } } public void ShowNextPlayerCard(Player player) { cardList.Clear(); CardInventory card1 = new CardInventory(); card1.Card = CardManager._Instance.GetCardById(3); card1.Num = 2; CardInventory card2 = new CardInventory(); card2.Card = CardManager._Instance.GetCardById(4); card2.Num = 4; CardInventory card3 = new CardInventory(); card3.Card = CardManager._Instance.GetCardById(1); card3.Num = 1; cardList.Add(card1); cardList.Add(card2); cardList.Add(card3); List<Transform> listChild = grid.GetChildList(); for (int i = 0; i < listChild.Count;i++ ) { grid.RemoveChild(listChild[i]); Destroy(listChild[i].gameObject); } for (int i = 0; i < cardList.Count; i++) { GameObject cardItemUI = GameObject.Instantiate(CardInventoryPrefeb); cardItemUI.GetComponent<CardInventoryItemUI>().SetCardInventory(cardList[i]); //NGUITools.AddChild(this.gameObject, CardInventoryPrefeb); grid.AddChild(cardItemUI.transform); } } void GetCardInventory(Player player) { cardList = player.Cards; } } <file_sep>using UnityEngine; using System.Collections; public class RoadPoint : MonoBehaviour { public MapBlock mapBlock; public MapBlock MapBlock { get { return mapBlock; } set { mapBlock = value; } } private int id; public int Id { get { return id; } set { id = value; } } } <file_sep>using UnityEngine; using System.Collections; public class PlayerMove : MonoBehaviour { //脚下的 private RoadPoint footRoad; public RoadPoint FootRoad { get { return footRoad; } set { footRoad = value; } } private bool isMoveOver = true; private bool isMoveing = false; public float m_MoveSpeed = 3f; private Vector3 nowPos; private Vector3 targetPos; private int step = 0; private PlayerAnim playerAnim; public Camera headCamera; void Start() { playerAnim = GetComponent<PlayerAnim>(); //characterController = GetComponent<CharacterController>(); int footId = footRoad.Id; targetPos = RoadManager._Instance.GetRoadById(footId+1).transform.position + new Vector3(0, 0.5f, 0); FaceToPos(targetPos); headCamera=transform.Find("HeadCamera").GetComponent<Camera>(); //headCamera.gameObject.SetActive(false); if(this.gameObject==GameManager._Instance.ThisRoundPlayer) { ShowHeadCamera(); } else { CLoseHeadCamera(); } } public void CLoseHeadCamera() { headCamera.gameObject.SetActive(false); } public void ShowHeadCamera() { headCamera.gameObject.SetActive(true); } //移动到下一块 默认走一步 public void Move(int step = 1) { //Debug.Log("step" + step); this.step = step; //开始移动 isMoveOver = false; MoveOnStep(); } //移动到下一个格子 void MoveOnStep() { this.step -= 1; //得到脚下的ID int footId = footRoad.Id; //得到总路径 int MAXROAD = RoadManager._Instance.RoadCount - 1; //移动到footid+1 if (footId == MAXROAD) { //移动到 id=0的格子 MoveToRoad(0); } else { //移动到 下一格 MoveToRoad(footId + 1); } } void MoveToRoad(int id) { footRoad = RoadManager._Instance.GetRoadById(id); //目标位置 targetPos = footRoad.transform.position + new Vector3(0, 0.5f, 0); FaceToPos(targetPos); isMoveing = true; gameObject.GetComponent<Player>().Count = footRoad.MapBlock.Count; } void MoveToPos(Vector3 targetpos) { transform.position = Vector3.MoveTowards(transform.position, targetpos, m_MoveSpeed * Time.deltaTime); if (Vector3.Distance(targetPos, transform.position) < 0.1f) { isMoveing = false; transform.position = targetpos; if (step == 0) { //没有步数了 isMoveing = false; isMoveOver = true; ShowBuyBuild(); } else { MoveOnStep(); } } } void ShowBuyBuild() { if (footRoad.MapBlock.RoadType == RoadType.CanBuild && footRoad.MapBlock.Build.Level == 0) { //显示购买 GameManager._Instance.ShowBuyBuild(footRoad); } else if (footRoad.MapBlock.RoadType == RoadType.CanBuild &&// footRoad.MapBlock.Build.Player == this.gameObject.GetComponent<Player>() &&// footRoad.MapBlock.Build.Level < footRoad.MapBlock.Build.MaxLevel) { //显示升级 Debug.Log("升级房子"); } else if (footRoad.MapBlock.RoadType == RoadType.CanBuild && footRoad.MapBlock.Build.Player != this.gameObject.GetComponent<Player>()) { Debug.Log("别人的房子"); GameManager._Instance.PayBuild(); } //没人买,等级为0级时 //走上别人买过的时候 //走上自己的房子时候 } void Update() { if (isMoveing) { //Debug.Log("targetpos" + targetPos); MoveToPos(targetPos); playerAnim.PlayWalkAnim(); } else { playerAnim.PlayIdleAnim(); } } void FaceToPos(Vector3 targetPos) { //判断格子在player的什么位置 //仅仅判断x,z float x = targetPos.x - transform.position.x; float z = targetPos.z - transform.position.z; if (x > 0) { //朝下 //Debug.Log("Down"); //判断是否需要转动 transform.rotation = Quaternion.Euler(new Vector3(0,90,0)); //if (88 < transform.rotation.eulerAngles.y || transform.rotation.eulerAngles.y < 92) // transform.Rotate(new Vector3(0, 90, 0)); } if (x < 0) { //朝上 //Debug.Log("Up"); //if (-92 < transform.rotation.eulerAngles.y || transform.rotation.eulerAngles.y < -88) // transform.Rotate(new Vector3(0, -90, 0)); transform.rotation = Quaternion.Euler(new Vector3(0, -90, 0)); } if (z > 0) { //朝右 //Debug.Log("Right"); transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0)); } if (z < 0) { //朝左 //Debug.Log("Left"); transform.rotation = Quaternion.Euler(new Vector3(0, 180, 0)); } } } <file_sep>using UnityEngine; using System.Collections; using DG.Tweening; public class BuildUpgrade : MonoBehaviour { public int MAXLEVEL = 4; public BuildingPoint buildPoint; void Awake() { buildPoint = GetComponent<BuildingPoint>(); } public void UpdateBuild(Player player) { //已经最高级,不能再升级 if (buildPoint.Level > MAXLEVEL) { return; } if (buildPoint.Level==0) { buildPoint.Level += 1; UpgradeToLevel1(player); } } void UpgradeToLevel1(Player player) { //Debug.Log(buildPoint.Mapblock.Rotate); //升级 //实例化三根柱子 GameObject prefeb = Resources.Load("Prefebs/Building/" + "modularBuildings_100") as GameObject; GameObject polo1 = GameObject.Instantiate(prefeb, Vector3.zero, Quaternion.Euler(0, buildPoint.Mapblock.Rotate, 0)) as GameObject; polo1.transform.parent = transform; polo1.transform.localPosition = new Vector3(-0.036f, -0.5f, -0.03f); GameObject polo2 = GameObject.Instantiate(prefeb, Vector3.zero, Quaternion.Euler(new Vector3(0, buildPoint.Mapblock.Rotate + 90, 0))) as GameObject; polo2.transform.parent = transform; polo2.transform.localPosition = new Vector3(-0.5f, -0.5f, -0.95f); polo1.transform.DOMoveY(0.2f, 0.5f); polo2.transform.DOMoveY(0.2f, 0.7f); //从地下冒出建筑 GameObject prefeb_build = Resources.Load("Prefebs/Building/" + "modularBuildings_026") as GameObject; GameObject build = GameObject.Instantiate(prefeb_build, Vector3.zero, Quaternion.Euler(0, buildPoint.Mapblock.Rotate + 180, 0)) as GameObject; build.transform.parent = transform; build.transform.localPosition = new Vector3(-1f, -2.5f, -1f); build.transform.DOMoveY(0f, 1.2f); //从天上掉下屋顶 GameObject prefeb_loft = Resources.Load("Prefebs/Building/" + "modularBuildings_044") as GameObject; GameObject loft = GameObject.Instantiate(prefeb_loft, Vector3.zero, Quaternion.Euler(0, buildPoint.Mapblock.Rotate + 180, 0)) as GameObject; loft.transform.parent = transform; loft.transform.localPosition = new Vector3(-1f, 10f, -1f); //Mesh1_Group1_Model GameObject loftmesh = loft.transform.Find("Mesh1_Group1_Model").gameObject; loftmesh.GetComponent<Renderer>().materials[1].color = player.Color; Tweener tweener_loft=loft.transform.DOMoveY(2.5f, 3f); tweener_loft.SetEase(Ease.InCubic); StartCoroutine(DestoryGameObject(polo1, 3f)); StartCoroutine(DestoryGameObject(polo2, 3f)); } IEnumerator DestoryGameObject(GameObject go,float time) { yield return new WaitForSeconds(time); Destroy(go, time); } } <file_sep>using UnityEngine; using System.Collections; public class PayBuild : MonoBehaviour { private TweenPosition tween; private UIButton btnOk; private UILabel labelGold; // Use this for initialization void Awake () { tween = GetComponent<TweenPosition>(); btnOk = transform.Find("BtnOk").GetComponent<UIButton>(); labelGold = transform.Find("LabelGold").GetComponent<UILabel>(); EventDelegate ed = new EventDelegate(this, "OnOkClick"); btnOk.onClick.Add(ed); gameObject.SetActive(false); } public void Show() { gameObject.SetActive(true); tween.PlayForward(); } void Dismiss() { StartCoroutine(SetWindowEnable()); tween.PlayReverse(); } IEnumerator SetWindowEnable() { yield return new WaitForSeconds(0.5f); this.gameObject.SetActive(false); } void OnOkClick() { Dismiss(); } } <file_sep>using UnityEngine; using System.Collections; public class CameraMove : MonoBehaviour { public float m_CameraMoveSpeed = 8f; public float m_CameraMoveDis = -20f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (transform.position.x >= m_CameraMoveDis&&GameManager._Instance.ThisRoundPlayer==null) { transform.Translate(new Vector3(0.5f, -0.5f, 0f) * m_CameraMoveSpeed * Time.deltaTime); }else { transform.GetComponent<CameraFollowPlayer>().enabled = true; this.enabled = false; } } } <file_sep>using UnityEngine; using System.Collections; public class FirstUI : MonoBehaviour { // Use this for initialization public void StartGame() { Application.LoadLevel(1); } } <file_sep>using UnityEngine; using System.Collections; public class CardInventory : MonoBehaviour { private Card card; public Card Card { get { return card; } set { card = value; } } private int num; public int Num { get { return num; } set { num = value; } } }
fc56f7f61e22325810017a3e71c7e135dc027d10
[ "Markdown", "C#" ]
23
C#
PcloD/Unity3D-Monopoly
d3c61bcb8dd28b25cb500a91a13681db9ee9937f
630e8799c4ee258eabd931188923567cfcaaced1
refs/heads/master
<file_sep>/******************************************************************************* Copyright (c) 2010, Perforce Software, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ /******************************************************************************* * Name : PythonSpecData.cpp * * Author : <NAME> <<EMAIL>> * * Description : Python bindings for the Perforce API. SpecData subclass for * P4Python. This class allows for manipulation of Spec data * stored in a Python dict using the standard Perforce classes * ******************************************************************************/ #include <Python.h> #include <bytesobject.h> #include "undefdups.h" #include "python2to3.h" #include <clientapi.h> #include <i18napi.h> #include <spec.h> #include "debug.h" #include "P4PythonDebug.h" #include "PythonSpecData.h" #include <iostream> using namespace std; StrPtr * PythonSpecData::GetLine( SpecElem *sd, int x, const char **cmt ) { PyObject * val = PyDict_GetItemString( dict, sd->tag.Text() ); if( val == NULL ) return 0; if( !sd->IsList() ) { if ( ! PyObject_IsInstance( val, (PyObject *) &StringType ) ) { PyErr_Warn(PyExc_TypeError, "PythonSpecData::GetLine: value is not of type String"); return 0; } last = GetPythonString( val ); return &last; } // It's a list, which means we should have an array value here // Ignore error checking for now! if ( ! PyObject_IsInstance( val, (PyObject *) &PyList_Type ) ) { cout << "GetLine: SEVERE error. val is not a list!" << endl; return 0; } // GetLine keeps on asking for lines until we are exhausted. // This throws Python, so we need to bail early if ( x >= PyList_Size(val) ) { return 0; } val = PyList_GetItem( val, x ); if( val == NULL ) { cout << "GetLine: SEVERE error!" << endl; return 0; } if ( ! PyObject_IsInstance( val, (PyObject *) &StringType ) ) { PyErr_Warn(PyExc_TypeError, "PythonSpecData::GetLine: value is not of type String"); return 0; } last = GetPythonString( val ); return &last; } void PythonSpecData::SetLine( SpecElem *sd, int x, const StrPtr *v, Error *e ) { char * key = sd->tag.Text(); PyObject * val = CreatePythonString( v->Text() ); if( sd->IsList() ) { PyObject * list = PyDict_GetItemString( dict, key ); if( list == NULL ) { list = PyList_New(0); PyDict_SetItemString( dict, key, list ); Py_DECREF(list); } PyList_Append( list, val ); Py_DECREF( val ); } else { PyDict_SetItemString( dict, key, val ); Py_DECREF( val ); } return; } <file_sep>#!/usr/bin/env python # # Fetch and install the Perforce API from Perforce Software. # # Modified by <NAME> <<EMAIL>> from # <http://reviewboard.googlecode.com/svn/trunk/P4PythonInstaller/> # which is stated at <https://pypi.python.org/pypi/P4PythonInstaller/0.2> # and at <https://code.google.com/p/reviewboard/> # to be under the MIT License <http://opensource.org/licenses/MIT>. import copy import ftplib import os import os.path import platform import re import shutil import subprocess import sys import tarfile import tempfile p4api_version = "13.1" perforce_hostname = "ftp.perforce.com" perforce_path = "/perforce/r%s" % p4api_version p4python_path = "%s/bin.tools" % perforce_path def download(paths, path = '.'): """ Downloads files from the Perforce FTP server. """ ftp = ftplib.FTP(perforce_hostname) ftp.login() for remote_path in paths: filename = remote_path.rsplit("/", 1)[1] print "Downloading Perforce API from %s..." % filename ftp.retrbinary("RETR %s" % remote_path, open(os.path.join(path, filename), "wb").write) ftp.quit() def extract(filename, path = '.'): """ Extracts a tarball into the current directory, and returns the directory name where the files were extracted. """ print "Extracting Perforce API from %s..." % filename tar = tarfile.open(filename, "r:gz") dirname = tar.getnames()[0].rstrip("/") if hasattr(tar, "extractall"): tar.extractall(path = path) else: # Simulate extractall directories = [] for tarinfo in tar: if tarinfo.isdir(): directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 0700 tar.extract(tarinfo, path = path) directories.sort(lambda a, b: cmp(a.name, b.name)) directories.reverse() # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: tar.chown(tarinfo, dirpath) tar.utime(tarinfo, dirpath) tar.chmod(tarinfo, dirpath) except ExtractError, e: if self.errorlevel > 1: raise else: print e tar.close() return os.path.join(path, dirname) def get_p4api_path(): """ Returns the p4api.tgz download path, based on the platform information. """ arch = platform.machine() if re.match("i\d86", arch): arch = "x86" elif arch in ("x86_64", "amd64"): arch = "x86_64" else: sys.stderr.write("Unsupported system architecture: %s\n" % arch) sys.exit(1) osname = platform.system() if osname == "Linux": linuxver = platform.release() if linuxver.startswith('2.6') or linuxver.startswith('3.'): osname = "linux26" elif linuxver.startswith("2.4"): osname = "linux24" else: sys.stderr.write("Unsupported Linux version: %s" % linuxver) sys.exit(1) elif osname == "Windows": # TODO: Download and run the Windows installer. print "Download the Windows installer at:" print "http://public.perforce.com/guest/robert_cowham/perforce/API/python/index.html" sys.exit(1) elif osname == "Darwin": osname = 'macosx105' elif osname == "FreeBSD": osname = "freebsd" freebsd_ver = platform.release() freebsd_major = int(freebsd_ver.split(".")[0]) if freebsd_major == 5: osname += "54" elif freebsd_major == 6: osname += "60" elif freebsd_major >= 7: osname += "70" else: sys.stderr.write("Unsupported FreeBSD version: %s" % freebsd_ver) sys.exit(1) else: # TODO: Should support Solaris/OpenSolaris sys.stderr.write("Unsupported operating system: %s" % osname) sys.exit(1) return "%s/bin.%s%s" % (perforce_path, osname, arch) def get_p4api(): tmpdir = tempfile.mkdtemp() remote_path = "%s/p4api.tgz" % get_p4api_path() download([remote_path], path = tmpdir) local_path = os.path.join(tmpdir, "p4api.tgz") p4api_dir = os.path.abspath(extract(local_path, path = tmpdir)) return p4api_dir def main(): p4api_path = get_p4api_path() download(["%s/p4api.tgz" % p4api_path]) curdir = os.getcwd() tmpdir = tempfile.mkdtemp() os.chdir(tmpdir) download(["%s/p4api.tgz" % p4api_path, "%s/p4python.tgz" % p4python_path]) p4api_dir = os.path.abspath(extract("p4api.tgz")) p4python_dir = extract("p4python.tgz") os.chdir(p4python_dir) # Generate the setup.cfg file. fp = open("setup.cfg", "w") fp.write("[p4python_config]\n") fp.write("p4_api=%s" % p4api_dir) fp.close() args = [] # for arg in sys.argv[1:]: # if arg.startswith("bdist"): # args.append("install") # elif arg. # else: # args.append(arg) p = subprocess.Popen([sys.executable, "setup.py", "install"]) rc = p.wait() os.chdir(curdir) shutil.rmtree(tmpdir) if __name__ == "__main__": main() <file_sep>/* * Python wrapper for the Perforce ClientApi object. * * Copyright (c) 2007-2008, Perforce Software, Inc. All rights reserved. * Portions Copyright (c) 1999, <NAME>. All rights reserved. * Portions Copyright (c) 2004-2007, <NAME>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTR * IBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: //depot/r13.1/p4-python/P4API.cpp#1 $ * * Build instructions: * Use Distutils - see accompanying setup.py * * python setup.py install * */ #include <Python.h> #include <bytesobject.h> #include <structmember.h> #include "undefdups.h" #include "python2to3.h" #include <clientapi.h> #include <strtable.h> #include <spec.h> #include <ident.h> #include <mapapi.h> #include "SpecMgr.h" #include "P4Result.h" #include "PythonClientUser.h" #include "PythonClientAPI.h" #include "PythonMergeData.h" #include "PythonActionMergeData.h" #include "P4MapMaker.h" #include "PythonMessage.h" #include "PythonTypes.h" // #include <alloca.h> #include <iostream> #include <cstring> #include <sstream> #include <vector> using namespace std; static Ident ident = { IdentMagic "P4PYTHON" "/" ID_OS "/" ID_REL "/" ID_PATCH " (" ID_API " API)", ID_Y "/" ID_M "/" ID_D }; // =================== // ==== P4Adapter ==== // =================== PyObject * P4Error; PyObject * P4OutputHandler; PyObject * P4Progress; /* * P4Adapter destructor */ static void P4Adapter_dealloc(P4Adapter *self) { delete self->clientAPI; Py_TYPE(self)->tp_free((PyObject*)self); } /* * P4Adapter constructor. */ static PyObject * P4Adapter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { P4Adapter *self = (P4Adapter *) type->tp_alloc(type, 0); if (self != NULL) { self->clientAPI = new PythonClientAPI(); } return (PyObject *) self; } /* * P4Adapter initializer. */ static int P4Adapter_init(P4Adapter *self, PyObject *args, PyObject *kwds) { if (kwds != NULL && PyDict_Check(kwds)) { Py_ssize_t pos = 0; PyObject *key, *value; while (PyDict_Next(kwds, &pos, &key, &value)) { const char * name = GetPythonString(key); if (PyInt_Check(value)) { PythonClientAPI::intsetter isetter = self->clientAPI->GetIntSetter(name); if (isetter) { int result = (self->clientAPI->*isetter)(PyInt_AS_LONG(value)); if (result) return result; } else { ostringstream os; os << "No integer keyword with name " << name; PyErr_SetString(PyExc_AttributeError, os.str().c_str()); return -1; } } else if (IsString(value)) { PythonClientAPI::strsetter ssetter = self->clientAPI->GetStrSetter(name); if (ssetter) { int result = (self->clientAPI->*ssetter)(GetPythonString(value)); if (result) return result; } else { ostringstream os; os << "No string keyword with name " << name; PyErr_SetString(PyExc_AttributeError, os.str().c_str()); return -1; } } } } return 0; } static PyObject * P4Adapter_repr(P4Adapter *self) { return CreatePythonString("P4Adapter"); } // ************************************** // P4Adapter directly implemented methods // ************************************** static PyObject * P4Adapter_connect(P4Adapter * self) { return self->clientAPI->Connect(); } static PyObject * P4Adapter_connected(P4Adapter * self) { return self->clientAPI->Connected(); } static PyObject * P4Adapter_disconnect(P4Adapter * self) { return self->clientAPI->Disconnect(); } // // Get a value from the environment following the Perforce conventions, // including honouring P4CONFIG files etc. // static PyObject * P4Adapter_env(P4Adapter * self, PyObject * var) { if ( !var ) Py_RETURN_NONE; const char *val = self->clientAPI->GetEnv( GetPythonString( var ) ); if( !val ) Py_RETURN_NONE; return CreatePythonString( val ); } static PyObject * P4Adapter_set_env(P4Adapter * self, PyObject *args) { const char * var; const char * val = 0; // if not provided, will reset the registry value if ( PyArg_ParseTuple(args, "s|s", &var, &val) ) { return self->clientAPI->SetEnv( var, val ); } return NULL; } static PyObject * P4Adapter_run(P4Adapter * self, PyObject * args) { PyObject * cmd = PyTuple_GetItem(args, 0); if (cmd == NULL) { return NULL; } // assume the args are flattened already vector<const char *> argv; for (Py_ssize_t i = 1; i < PyTuple_Size(args); ++i) { PyObject * item = PyTuple_GET_ITEM(args, i); if( ! PyBytes_Check(item) ) { item = PyObject_Str(item); } argv.push_back(GetPythonString(item)); } // this is a bit of a hack: it assumes the storage layout of the vector is continuous // the other hack is that the API expects (char * const *), but this cannot be stored // a std::vector<>, because it cannot exchange pointers return self->clientAPI->Run(GetPythonString(cmd), argv.size(), (argv.size() > 0) ? (char * const *) &argv[0] : NULL ); } static PyObject * P4API_identify(PyObject * self) { StrBuf s; ident.GetMessage( &s ); return CreatePythonString( s.Text() ); } static PyObject * P4Adapter_formatSpec(P4Adapter * self, PyObject * args) { const char * type; PyObject * dict; if ( PyArg_ParseTuple(args, "sO", &type, &dict) ) { if ( PyDict_Check(dict) ) { return self->clientAPI->FormatSpec(type, dict); } else { PyErr_SetString(PyExc_TypeError, "Second argument needs to be a dictionary"); return NULL; } } return NULL; } static PyObject * P4Adapter_parseSpec(P4Adapter * self, PyObject * args) { const char * type; const char * form; if ( PyArg_ParseTuple(args, "ss", &type, &form) ) { return self->clientAPI->ParseSpec(type, form); } return NULL; } static PyObject * P4Adapter_protocol(P4Adapter * self, PyObject *args) { const char * var; const char * val = 0; if ( PyArg_ParseTuple(args, "s|s", &var, &val) ) { if ( val ) { return self->clientAPI->SetProtocol( var, val ); } else { return self->clientAPI->GetProtocol( var ); } } return NULL; } #if PY_MAJOR_VERSION >= 3 static PyObject * P4Adapter_convert(P4Adapter * self, PyObject *args) { const char * charset; PyObject * content; if( PyArg_ParseTuple(args, "sO", &charset, &content)) { return self->clientAPI->Convert(charset, content); } return NULL; } #endif static PyMethodDef P4Adapter_methods[] = { {"connect", (PyCFunction)P4Adapter_connect, METH_NOARGS, "Connects to the Perforce Server"}, {"connected", (PyCFunction)P4Adapter_connected, METH_NOARGS, "Checks whether we are (still) connected"}, {"disconnect", (PyCFunction)P4Adapter_disconnect, METH_NOARGS, "Closes the connection to the Perforce Server"}, {"env", (PyCFunction)P4Adapter_env, METH_O, "Get values from the Perforce environment"}, {"set_env", (PyCFunction)P4Adapter_set_env, METH_VARARGS, "Set values in the registry (if available on the platform) for the Perforce environment"}, {"run", (PyCFunction)P4Adapter_run, METH_VARARGS, "Runs a command"}, {"format_spec", (PyCFunction)P4Adapter_formatSpec, METH_VARARGS, "Converts a dictionary-based form into a string"}, {"parse_spec", (PyCFunction)P4Adapter_parseSpec, METH_VARARGS, "Converts a string form into a dictionary"}, {"protocol", (PyCFunction)P4Adapter_protocol, METH_VARARGS, "Sets a server protocol variable to the given value or gets the protocol level"}, #if PY_MAJOR_VERSION >= 3 {"__convert", (PyCFunction)P4Adapter_convert, METH_VARARGS, "Converts a Unicode string into a Perforce-converted String" }, #endif {NULL} /* Sentinel */ }; static PyMemberDef P4Adapter_members[] = { // {"first", T_OBJECT_EX, offsetof(Noddy, first), 0, // "first name"}, {NULL} /* Sentinel */ }; static PyObject * P4Adapter_getattro(P4Adapter *self, PyObject * nameObject) { const char * name = GetPythonString(nameObject); PythonClientAPI::intgetter igetter = self->clientAPI->GetIntGetter(name); if (igetter) { return PyInt_FromLong((self->clientAPI->*igetter)()); } PythonClientAPI::strgetter sgetter = self->clientAPI->GetStrGetter(name); if (sgetter) { return CreatePythonString((self->clientAPI->*sgetter)()); } PythonClientAPI::objgetter ogetter = self->clientAPI->GetObjGetter(name); if (ogetter) { return (self->clientAPI->*ogetter)(); } return PyObject_GenericGetAttr((PyObject *) self, nameObject); } static int P4Adapter_setattro(P4Adapter *self, PyObject * nameObject, PyObject * value) { const char * name = GetPythonString(nameObject); // Special case first: // If there is a specific ObjectSetter for this name available use this one PythonClientAPI::objsetter osetter = self->clientAPI->GetObjSetter(name); if (osetter) { return (self->clientAPI->*osetter)(value); } else if (PyInt_Check(value)) { PythonClientAPI::intsetter isetter = self->clientAPI->GetIntSetter(name); if (isetter) { return (self->clientAPI->*isetter)(PyInt_AS_LONG(value)); } else { ostringstream os; os << "No integer attribute with name " << name; PyErr_SetString(PyExc_AttributeError, os.str().c_str()); return -1; } } else if (IsString(value)) { PythonClientAPI::strsetter ssetter = self->clientAPI->GetStrSetter(name); if (ssetter) { return (self->clientAPI->*ssetter)(GetPythonString(value)); } else { ostringstream os; os << "No string attribute with name " << name; PyErr_SetString(PyExc_AttributeError, os.str().c_str()); return -1; } } // can only set int and string or certain object values -> bail out with exception ostringstream os; os << "Cannot set attribute : " << name << " with value " << GetPythonString(PyObject_Str(value)); PyErr_SetString(PyExc_AttributeError, os.str().c_str()); return -1; } /* PyObject object for the P4Adapter */ static PyTypeObject P4AdapterType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "P4API.P4Adapter", /* name */ sizeof(P4Adapter), /* basicsize */ 0, /* itemsize */ (destructor) P4Adapter_dealloc, /* dealloc */ 0, /* print */ 0, /* getattr */ 0, /* setattr */ 0, /* compare */ (reprfunc) P4Adapter_repr, /* repr */ 0, /* number methods */ 0, /* sequence methods */ 0, /* mapping methods */ 0, /* tp_hash */ 0, /* tp_call*/ 0, /* tp_str*/ (getattrofunc) P4Adapter_getattro, /* tp_getattro*/ (setattrofunc) P4Adapter_setattro, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ "P4Adapter - base class for P4", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ P4Adapter_methods, /* tp_methods */ P4Adapter_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)P4Adapter_init, /* tp_init */ 0, /* tp_alloc */ P4Adapter_new, /* tp_new */ }; // ===================== // ==== P4MergeData ==== // ===================== /* * P4MergeData destructor */ static void P4MergeData_dealloc(P4MergeData *self) { delete self->mergeData; Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * P4MergeData_repr(P4MergeData *self) { // TODO: add more output information to give full representation return CreatePythonString(self->mergeData->GetString().Text()); } // **************************************** // P4MergeData directly implemented methods // **************************************** static PyObject * P4MergeData_run_merge(P4MergeData * self) { return self->mergeData->RunMergeTool(); } static PyMethodDef P4MergeData_methods[] = { {"run_merge", (PyCFunction)P4MergeData_run_merge, METH_NOARGS, "Runs the merge tool with this data"}, {NULL} /* Sentinel */ }; static PyObject * P4MergeData_getattro(P4MergeData * self, PyObject * nameObject) { const char * name = GetPythonString(nameObject); if( !strcmp( name, "your_name" ) ) { return self->mergeData->GetYourName(); } else if( !strcmp( name, "their_name" ) ) { return self->mergeData->GetTheirName(); } else if( !strcmp( name, "base_name" ) ) { return self->mergeData->GetBaseName(); } else if( !strcmp( name, "your_path" ) ) { return self->mergeData->GetYourPath(); } else if( !strcmp( name, "their_path" ) ) { return self->mergeData->GetTheirPath(); } else if( !strcmp( name, "base_path" ) ) { return self->mergeData->GetBasePath(); } else if( !strcmp( name, "result_path" ) ) { return self->mergeData->GetResultPath(); } else if( !strcmp( name, "merge_hint" ) ) { return self->mergeData->GetMergeHint(); } // no matching name found, falling back to default return PyObject_GenericGetAttr((PyObject *) self, nameObject); } /* PyObject object for the P4MergeData */ PyTypeObject P4MergeDataType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "P4API.P4MergeData", /* name */ sizeof(P4MergeData), /* basicsize */ 0, /* itemsize */ (destructor) P4MergeData_dealloc, /* dealloc */ 0, /* print */ 0, /* getattr */ 0, /* setattr */ 0, /* compare */ (reprfunc) P4MergeData_repr, /* repr */ 0, /* number methods */ 0, /* sequence methods */ 0, /* mapping methods */ 0, /* tp_hash */ 0, /* tp_call*/ 0, /* tp_str*/ (getattrofunc) P4MergeData_getattro, /* tp_getattro*/ 0, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /* tp_flags*/ "P4MergeData - contains merge information for resolve", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ P4MergeData_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; // =========================== // ==== P4ActionMergeData ==== // =========================== /* * P4ActionMergeData destructor */ static void P4ActionMergeData_dealloc(P4ActionMergeData *self) { delete self->mergeData; Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * P4ActionMergeData_repr(P4ActionMergeData *self) { // TODO: add more output information to give full representation return CreatePythonString(self->mergeData->GetString().Text()); } // **************************************** // P4MergeData directly implemented methods // **************************************** static PyObject * P4ActionMergeData_getattro(P4ActionMergeData * self, PyObject * nameObject) { const char * name = GetPythonString(nameObject); if( !strcmp( name, "merge_action" ) ) { return self->mergeData->GetMergeAction(); } else if( !strcmp( name, "yours_action" ) ) { return self->mergeData->GetYoursAction(); } else if( !strcmp( name, "their_action" ) ) { return self->mergeData->GetTheirAction(); } else if( !strcmp( name, "type" ) ) { return self->mergeData->GetType(); } else if( !strcmp( name, "merge_hint" ) ) { return self->mergeData->GetMergeHint(); } else if( !strcmp( name, "info" ) ) { return self->mergeData->GetMergeInfo(); } // no matching name found, falling back to default return PyObject_GenericGetAttr((PyObject *) self, nameObject); } /* PyObject object for the P4MergeData */ PyTypeObject P4ActionMergeDataType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "P4API.P4ActionMergeData", /* name */ sizeof(P4ActionMergeData), /* basicsize */ 0, /* itemsize */ (destructor) P4ActionMergeData_dealloc, /* dealloc */ 0, /* print */ 0, /* getattr */ 0, /* setattr */ 0, /* compare */ (reprfunc) P4ActionMergeData_repr, /* repr */ 0, /* number methods */ 0, /* sequence methods */ 0, /* mapping methods */ 0, /* tp_hash */ 0, /* tp_call*/ 0, /* tp_str*/ (getattrofunc) P4ActionMergeData_getattro, /* tp_getattro*/ 0, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /* tp_flags*/ "P4ActionMergeData - contains action merge information for resolve", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; // =============== // ==== P4Map ==== // =============== extern PyTypeObject P4MapType; // forward /* * P4Map destructor */ static void P4Map_dealloc(P4Map *self) { delete self->map; Py_TYPE(self)->tp_free((PyObject*)self); } /* * P4Map constructor. */ static PyObject * P4Map_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { P4Map *self = (P4Map *) type->tp_alloc(type, 0); if (self != NULL) { self->map = new P4MapMaker(); } return (PyObject *) self; } /* * P4Map initializer. */ static int P4Map_init(P4Map *self, PyObject *args, PyObject *kwds) { // nothing to do for now return 0; } static PyObject * P4Map_repr(P4Map *self) { return self->map->Inspect(); } static PyObject * P4Map_insert(P4Map *self, PyObject * args) { // expects one, or two arguments, lhs, and optional rhs. In the // absence of rhs, lhs is assumed to contain both halves. PyObject *lhs; PyObject *rhs = NULL; // ugly hack for now #if PY_MAJOR_VERSION >= 3 const char * format = "U|U"; #else const char * format = "S|S"; #endif int ok = PyArg_ParseTuple(args, format, &lhs, &rhs ); if (ok) { if( !rhs ) self->map->Insert( lhs ); else self->map->Insert(lhs, rhs ); Py_RETURN_NONE; } return NULL; } static PyObject * P4Map_clear(P4Map *self) { // clears out the map self->map->Clear(); Py_RETURN_NONE; } static PyObject * P4Map_translate(P4Map *self, PyObject * args) { // expects two arguments, the string and the direction // True (default) ==> Left to Right // False ==> Right to Left PyObject *str; int direction = 1; #if PY_MAJOR_VERSION >= 3 const char * format = "U|b"; #else const char * format = "S|b"; #endif int ok = PyArg_ParseTuple(args, format, &str, &direction); if (ok) { return self->map->Translate(str, direction); } return NULL; } static PyObject * P4Map_reverse(P4Map *self) { P4Map * rmap = (P4Map *) P4MapType.tp_alloc(&P4MapType, 0); if (!rmap) return (PyObject *) rmap; rmap->map = new P4MapMaker( *self->map ); rmap->map->Reverse(); return (PyObject *) rmap; } static PyObject * P4Map_count(P4Map *self) { return PyInt_FromLong( self->map->Count() ); } static PyObject * P4Map_lhs(P4Map *self) { return self->map->Lhs(); } static PyObject * P4Map_rhs(P4Map *self) { return self->map->Rhs(); } static PyObject * P4Map_as_array(P4Map *self) { return self->map->ToA(); } static PyObject * P4Map_join(PyTypeObject *type, PyObject * args) { // expects two P4Map objects P4Map *left; P4Map *right; P4Map *result; int ok = PyArg_ParseTuple(args, "O!O!", &P4MapType, (PyObject **) &left, &P4MapType, (PyObject **) &right); if (!ok) return NULL; PyObject * p4Module = PyImport_ImportModule("P4"); PyObject * p4Dict = PyModule_GetDict(p4Module); PyObject * mapClass = PyDict_GetItemString(p4Dict, "Map"); if (mapClass == NULL) { cout << "Could not find class P4.Map" << endl; return NULL; } result = (P4Map *) PyObject_CallObject(mapClass, NULL); delete result->map; result->map = P4MapMaker::Join(left->map, right->map); return (PyObject *) result; } static PyMethodDef P4Map_methods[] = { {"insert", (PyCFunction) P4Map_insert, METH_VARARGS, "Insert left hand, right hand, and the maptype ('', '+', '-')"}, {"clear", (PyCFunction) P4Map_clear, METH_NOARGS, "Clears out the map."}, {"translate", (PyCFunction) P4Map_translate, METH_VARARGS, "Translates the passed arguments using the map and returns a string"}, {"count", (PyCFunction) P4Map_count, METH_NOARGS, "Returns number of entries in the maps"}, {"reverse", (PyCFunction) P4Map_reverse, METH_NOARGS, "Swap the left and right sides of the map"}, {"lhs", (PyCFunction) P4Map_lhs, METH_NOARGS, "Returns a list containing the LHS"}, {"rhs", (PyCFunction) P4Map_rhs, METH_NOARGS, "Returns a list containing the RHS"}, {"as_array", (PyCFunction) P4Map_as_array, METH_NOARGS, "Returns the map contents as a list"}, {"join", (PyCFunction) P4Map_join, METH_VARARGS | METH_CLASS, "Joins two maps together and returns a third"}, {NULL} /* Sentinel */ }; /* PyObject object for the P4MergeData */ PyTypeObject P4MapType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "P4API.P4Map", /* name */ sizeof(P4Map), /* basicsize */ 0, /* itemsize */ (destructor) P4Map_dealloc, /* dealloc */ 0, /* print */ 0, /* getattr */ 0, /* setattr */ 0, /* compare */ (reprfunc) P4Map_repr, /* repr */ 0, /* number methods */ 0, /* sequence methods */ 0, /* mapping methods */ 0, /* tp_hash */ 0, /* tp_call*/ 0, /* tp_str*/ 0, /* tp_getattro*/ 0, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ "P4Map - client mapping interface", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ P4Map_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) P4Map_init, /* tp_init */ 0, /* tp_alloc */ P4Map_new, /* tp_new */ }; // =================== // ==== P4Message ==== // =================== static void P4Message_dealloc(P4Message *self) { delete self->msg; Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * P4Message_str(P4Message *self) { return self->msg->getText(); } static PyObject * P4Message_repr(P4Message *self) { return self->msg->getRepr(); } static int P4Message_init(P4Message *self, PyObject *args, PyObject *kwds) { return 0; } static PyMethodDef P4Message_methods[] = { {NULL} /* Sentinel */ }; static PyObject * P4Message_getattro(P4Message * self, PyObject * nameObject) { const char * name = GetPythonString(nameObject); if( strcmp(name, "severity") == 0) { return self->msg->getSeverity(); } else if( strcmp(name, "generic") == 0) { return self->msg->getGeneric(); } else if( strcmp(name, "msgid") == 0) { return self->msg->getMsgid(); } else if( strcmp(name, "dict") == 0) { return self->msg->getDict(); } else return PyObject_GenericGetAttr((PyObject *) self, nameObject); } PyTypeObject P4MessageType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "P4API.P4Message", /* name */ sizeof(P4Message), /* basicsize */ 0, /* itemsize */ (destructor) P4Message_dealloc, /* dealloc */ 0, /* print */ 0, /* getattr */ 0, /* setattr */ 0, /* compare */ (reprfunc) P4Message_repr, /* repr */ 0, /* number methods */ 0, /* sequence methods */ 0, /* mapping methods */ 0, /* tp_hash */ 0, /* tp_call*/ (reprfunc) P4Message_str, /* tp_str*/ (getattrofunc) P4Message_getattro, /* tp_getattro*/ 0, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ "P4Message - errors and warnings", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ P4Message_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) P4Message_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; // =============== // ==== P4API ==== // =============== struct P4API_state { PyObject * error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct P4API_state*)PyModule_GetState(m)) #else #define GETSTATE(m) (&_state) static struct P4API_state _state; #endif static struct PyMethodDef P4API_methods[] = { {"identify", (PyCFunction)P4API_identify, METH_NOARGS, "Identify module version"}, {NULL} /* Sentinel */ }; // =================== // ==== initP4API ==== // =================== #if PY_MAJOR_VERSION >= 3 static int P4API_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int P4API_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef P4API_moduledef = { PyModuleDef_HEAD_INIT, "P4API", "P4 Python Adapter Module", sizeof(struct P4API_state), P4API_methods, NULL, P4API_traverse, P4API_clear, NULL }; #define INITERROR return NULL PyMODINIT_FUNC PyInit_P4API(void) #else #define INITERROR return PyMODINIT_FUNC initP4API(void) #endif { if (PyType_Ready(&P4AdapterType) < 0) INITERROR; #if PY_MAJOR_VERSION >= 3 PyObject * module = PyModule_Create(&P4API_moduledef); #else PyObject * module = Py_InitModule3("P4API", P4API_methods, "P4 Python Adapter Module"); #endif if (module == NULL) INITERROR; Py_INCREF(&P4AdapterType); PyModule_AddObject(module, "P4Adapter", (PyObject*) &P4AdapterType); Py_INCREF(&P4MergeDataType); PyModule_AddObject(module, "P4MergeData", (PyObject*) &P4MergeDataType); Py_INCREF(&P4ActionMergeDataType); PyModule_AddObject(module, "P4ActionMergeData", (PyObject*) &P4ActionMergeDataType); Py_INCREF(&P4MapType); PyModule_AddObject(module, "P4Map", (PyObject*) &P4MapType); Py_INCREF(&P4MessageType); PyModule_AddObject(module, "P4Message", (PyObject*) &P4MessageType); struct P4API_state *st = GETSTATE(module); st->error = PyErr_NewException((char *)"P4API.Error", NULL, NULL); if (st->error == NULL) { Py_DECREF(module); INITERROR; } // Get a reference to P4.P4Error // Not declared as an exception here because of module inconsistencies // Better for the user to have an exception of type P4.P4Error than // P4API.P4Error PyObject * p4Module = PyImport_ImportModule("P4"); PyObject * p4Dict = PyModule_GetDict(p4Module); P4Error = PyDict_GetItemString(p4Dict, "P4Exception"); if (P4Error) Py_INCREF(P4Error); else { PyErr_SetString(st->error, "Could not find P4.P4Exception." ); Py_DECREF(module); INITERROR; } P4OutputHandler = PyDict_GetItemString(p4Dict, "OutputHandler"); if (P4OutputHandler) Py_INCREF(P4OutputHandler); else { PyErr_SetString(st->error, "Could not find P4.OutputHandler." ); Py_DECREF(module); INITERROR; } P4Progress = PyDict_GetItemString(p4Dict, "Progress"); if (P4Progress) Py_INCREF(P4Progress); else { PyErr_SetString(st->error, "Could not find P4.Progress." ); Py_DECREF(module); INITERROR; } #if PY_MAJOR_VERSION >= 3 return module; #endif } <file_sep># -*- encoding: UTF8 -*- from __future__ import print_function import glob, sys, time, stat pathToBuild = glob.glob('build/lib*') if len(pathToBuild) > 0: versionString = "%d.%d" % (sys.version_info[0], sys.version_info[1]) for i in pathToBuild: if versionString in i: sys.path.insert(0, i) import P4 from P4 import P4Exception import P4API import unittest, os, types, shutil, stat from subprocess import Popen, PIPE import sys def onRmTreeError( function, path, exc_info ): os.chmod( path, stat.S_IWRITE) os.remove( path ) class TestP4Python(unittest.TestCase): def setUp(self): self.setDirectories() self.p4d = "p4d" self.port = "rsh:%s -r \"%s\" -L log -vserver=3 -i" % ( self.p4d, self.server_root ) self.p4 = P4.P4() self.p4.port = self.port def enableUnicode(self): cmd = [self.p4d, "-r", self.server_root, "-L", "log", "-vserver=3", "-xi"] f = Popen(cmd, stdout=PIPE).stdout for s in f.readlines(): pass f.close() def tearDown(self): if self.p4.connected(): self.p4.disconnect() time.sleep( 1 ) self.cleanupTestTree() def setDirectories(self): self.startdir = os.getcwd() self.server_root = os.path.join(self.startdir, 'testroot') self.client_root = os.path.join(self.server_root, 'client') self.cleanupTestTree() self.ensureDirectory(self.server_root) self.ensureDirectory(self.client_root) def cleanupTestTree(self): os.chdir(self.startdir) if os.path.isdir(self.server_root): shutil.rmtree(self.server_root, False, onRmTreeError) def ensureDirectory(self, directory): if not os.path.isdir(directory): os.mkdir(directory) class TestP4(TestP4Python): def testInfo(self): self.assertTrue(self.p4 != None, "Could not create p4") self.p4.connect() self.assertTrue(self.p4.connected(), "Not connected") info = self.p4.run_info() self.assertTrue(isinstance(info, list), "run_info() does not return a list") info = info.pop() self.assertTrue(isinstance(info, dict), "run_info().pop() is not a dict") self.assertEqual(info['serverRoot'], self.server_root, "Server root incorrect") def testEnvironment(self): self.assertTrue(self.p4 != None, "Could not create p4") self.p4.charset = "iso8859-1" self.p4.client = "myclient" self.p4.host = "myhost" self.p4.language = "german" self.p4.maxresults = 100000 self.p4.maxscanrows = 1000000 self.p4.maxlocktime = 10000 self.p4.password = "<PASSWORD>" self.p4.port = "myserver:1666" self.p4.prog = "myprogram" self.p4.tagged = True self.p4.ticket_file = "myticket" self.p4.user = "myuser" self.assertEqual( self.p4.charset, "iso8859-1", "charset" ) self.assertEqual( self.p4.client, "myclient", "client" ) self.assertEqual( self.p4.host, "myhost", "host" ) self.assertEqual( self.p4.language, "german", "language" ) self.assertEqual( self.p4.maxresults, 100000, "maxresults" ) self.assertEqual( self.p4.maxscanrows, 1000000, "maxscanrows" ) self.assertEqual( self.p4.maxlocktime, 10000, "maxlocktime" ) self.assertEqual( self.p4.password, "<PASSWORD>", "<PASSWORD>" ) self.assertEqual( self.p4.port, "myserver:1666", "port" ) self.assertEqual( self.p4.tagged, 1, "tagged" ) self.assertEqual( self.p4.ticket_file, "myticket", "ticket_file" ) self.assertEqual( self.p4.user, "myuser", "user" ) def testClient(self): self.p4.connect() self.assertTrue(self.p4.connected(), "Not connected") client = self.p4.fetch_client() self.assertTrue( isinstance(client, P4.Spec), "Client is not of type P4.Spec") client._root = self.client_root client._description = 'Some Test Client\n' try: self.p4.save_client(client) except P4.P4Exception: self.fail("Saving client caused exception") client2 = self.p4.fetch_client() self.assertEqual( client._root, client2._root, "Client root differs") self.assertEqual( client._description, client2._description, "Client description differs") try: client3 = self.p4.fetch_client('newtest') client3._view = [ '//depot/... //newtest/...'] self.p4.save_client(client3) except P4.P4Exception: self.fail("Saving client caused exception") def createFiles(self, testDir): testAbsoluteDir = os.path.join(self.client_root, testDir) os.mkdir(testAbsoluteDir) # create a bunch of files files = ('foo.txt', 'bar.txt', 'baz.txt') for file in files: fname = os.path.join(testAbsoluteDir, file) f = open(fname, "w") f.write("Test Text") f.close() self.p4.run_add(testDir + "/" + file) self.assertEqual(len(self.p4.run_opened()), len(files), "Unexpected number of open files") return files def testFiles(self): self.p4.connect() self.assertTrue(self.p4.connected(), "Not connected") self._setClient() self.assertEqual(len(self.p4.run_opened()), 0, "Shouldn't have open files") testDir = 'test_files' files = self.createFiles(testDir) change = self.p4.fetch_change() self.assertTrue( isinstance(change, P4.Spec), "Change spec is not of type P4.Spec") change._description = "My Add Test" self._doSubmit("Failed to submit the add", change) # make sure there are no open files and all files are there self.assertEqual( len(self.p4.run_opened()), 0, "Still files in the open list") self.assertEqual( len(self.p4.run_files('...')), len(files), "Less files than expected") # edit the files self.assertEqual( len(self.p4.run_edit('...')), len(files), "Not all files open for edit") self.assertEqual( len(self.p4.run_opened()), len(files), "Not enough files open for edit") change = self.p4.fetch_change() change._description = "My Edit Test" self._doSubmit("Failed to submit the edit", change) self.assertEqual( len(self.p4.run_opened()), 0, "Still files in the open list") # branch testing branchDir = 'test_branch' try: result = self.p4.run_integ(testDir + '/...', branchDir + '/...') self.assertEqual(len(result), len(files), "Not all files branched") except P4.P4Exception: self.fail("Integration failed") change = self.p4.fetch_change() change._description = "My Branch Test" self._doSubmit("Failed to submit branch", change) # branch testing again branchDir = 'test_branch2' try: result = self.p4.run_integ(testDir + '/...', branchDir + '/...') self.assertEqual(len(result), len(files), "Not all files branched") except P4.P4Exception: self.fail("Integration failed") change = self.p4.fetch_change() change._description = "My Branch Test" self._doSubmit("Failed to submit branch", change) # filelog checks filelogs = self.p4.run_filelog( testDir + '/...' ) self.assertEqual( len(filelogs), len(files) ) df = filelogs[0] self.assertEqual( df.depotFile, "//depot/test_files/bar.txt", "Unexpected file in the filelog" ) self.assertEqual( len(df.revisions), 2, "Unexpected number of revisions" ) rev = df.revisions[0] self.assertEqual( rev.rev, 2, "Unexpected revision") self.assertEqual( len(rev.integrations), 2, "Unexpected number of integrations") self.assertEqual( rev.integrations[ 0 ].how, "branch into", "Unexpected how" ) self.assertEqual( rev.integrations[ 0 ].file, "//depot/test_branch/bar.txt", "Unexpected target file" ) def testShelves(self): self.p4.connect() self.assertTrue(self.p4.connected(), "Not connected") self._setClient() self.assertEqual(len(self.p4.run_opened()), 0, "Shouldn't have open files") if self.p4.server_level >= 28: testDir = 'test_shelves' files = self.createFiles(testDir) change = self.p4.fetch_change() self.assertTrue( isinstance(change, P4.Spec), "Change spec is not of type P4.Spec") change._description = "My Shelve Test" s = self.p4.save_shelve(change) c = s[0]['change'] self.p4.run_revert('...'); self.assertEqual(len(self.p4.run_opened()), 0, "Some files still opened") self.p4.run_unshelve('-s', c, '-f') self.assertEqual(len(self.p4.run_opened()), len(files), "Files not unshelved") self.p4.run_shelve('-d', '-c', c) self._doSubmit("Failed to submit after deleting shelve", change) else: print( "Need Perforce Server 2009.2 or greater to test shelving") def testPasswords(self): ticketFile = self.client_root + "/.p4tickets" password = "<PASSWORD>" self.p4.ticket_file = ticketFile self.assertEqual( self.p4.ticket_file, ticketFile, "Ticket file not set correctly") self.p4.connect() client = self.p4.fetch_client() client._root = self.client_root self.p4.save_client(client) try: self.p4.run_password( "", password ) except P4.P4Exception: self.fail( "Failed to change the password" ) self.p4.password = <PASSWORD> self.assertEqual( self.p4.password, password, "Could not set password" ) try: self.p4.run_login( ) except P4.P4Exception: self.fail( "Failed to log on") try: self.p4.run_password( password, "" ) except P4.P4Exception: self.fail( "Failed to reset the password" ) self.assertTrue( os.path.exists(ticketFile), "Ticket file not found") tickets = self.p4.run_tickets() self.assertEqual(len(tickets), 1, "Expected only one ticket") self.assertEqual(len(tickets[0]), 3, "Expected exactly three entries in tickets") def testOutput(self): self.p4.connect() self._setClient() testDir = 'test_output' files = self.createFiles(testDir) change = self.p4.fetch_change() self.assertTrue( isinstance(change, P4.Spec), "Change spec is not of type P4.Spec") change._description = "My Output Test" s = self.p4.run_submit(change) self.p4.exception_level = P4.P4.RAISE_NONE self.p4.run_sync(); self.p4.run_sync(); self.assertNotEqual( len(self.p4.warnings), 0, "No warnings reported") self.assertEqual( len(self.p4.errors), 0, "Errors reported") self.assertNotEqual( len(self.p4.messages), 0, "No messages reported") self.assertTrue( isinstance(self.p4.warnings[0],str), "Warning is not a string" ) m = self.p4.messages[0] self.assertTrue( isinstance(m, P4API.P4Message), "First object of messages is not a P4Message") self.assertEqual( m.severity, P4.P4.E_WARN, "Severity was not E_WARN" ) self.assertEqual( m.generic, P4.P4.EV_EMPTY, "Wasn't an empty message" ) self.assertEqual( m.msgid, 6532, "Got the wrong message: %d" % m.msgid ) def testExceptions(self): self.assertRaises(P4.P4Exception, self.p4.run_edit, "foo") self.p4.connect() self.assertRaises(P4.P4Exception, self.p4.run_edit, "foo") self.assertEqual( len(self.p4.errors), 1, "Did not find any errors") # father's little helpers def _setClient(self): """Creates a client and makes sure it is set up""" self.assertTrue(self.p4.connected(), "Not connected") self.p4.cwd = self.client_root self.p4.client = "TestClient" client = self.p4.fetch_client() client._root = self.client_root self.p4.save_client(client) def _doSubmit(self, msg, *args): """Submits the changes""" try: result = self.p4.run_submit(*args) self.assertTrue( 'submittedChange' in result[-1], msg) except P4.P4Exception as inst: self.fail("submit failed with exception ") def testResolve(self): testDir = 'test_resolve' testAbsoluteDir = os.path.join(self.client_root, testDir) os.mkdir(testAbsoluteDir) self.p4.connect() self.assertTrue(self.p4.connected(), "Not connected") self._setClient() self.assertEqual(len(self.p4.run_opened()), 0, "Shouldn't have open files") # create the file for testing resolve file = "foo" fname = os.path.join(testAbsoluteDir, file) f = open(fname, "w") f.write("First Line") f.close() textFile = testDir + "/" + file self.p4.run_add(textFile) file = "bin" bname = os.path.join(testAbsoluteDir, file) f = open(bname, "w") f.write("First Line") f.close() binFile = testDir + "/" + file self.p4.run_add("-tbinary", binFile) change = self.p4.fetch_change() change._description = "Initial" self._doSubmit("Failed to submit initial", change) # create a second revision self.p4.run_edit(textFile, binFile) with open(fname, "a") as f: f.write("Second Line") with open(bname, "a") as f: f.write("Second Line") change = self.p4.fetch_change() change._description = "Second" self._doSubmit("Failed to submit second", change) # now sync back to first revision self.p4.run_sync(textFile + "#1") # edit the first revision, thus setting up the conflict self.p4.run_edit(textFile) # sync back the head revision, this will schedule the resolve self.p4.run_sync(textFile) class TextResolver(P4.Resolver): def __init__(self, testObject): self.t = testObject def resolve(self, mergeData): self.t.assertEqual(mergeData.your_name, "//TestClient/test_resolve/foo", "Unexpected your_name: %s" % mergeData.your_name) self.t.assertEqual(mergeData.their_name, "//depot/test_resolve/foo#2", "Unexpected their_name: %s" % mergeData.their_name) self.t.assertEqual(mergeData.base_name, "//depot/test_resolve/foo#1", "Unexpected base_name: %s" % mergeData.base_name) self.t.assertEqual(mergeData.merge_hint, "at", "Unexpected merge hint: %s" % mergeData.merge_hint) return "at" self.p4.run_resolve(resolver = TextResolver(self)) # test binary file resolve which crashed previous version of P4Python self.p4.run_sync(binFile + "#1") self.p4.run_edit(binFile) self.p4.run_sync(binFile) class BinaryResolver(P4.Resolver): def __init__(self, testObject): self.t = testObject def resolve(self, mergeData): self.t.assertEqual(mergeData.your_name, "", "Unexpected your_name: %s" % mergeData.your_name) self.t.assertEqual(mergeData.their_name, "", "Unexpected their_name: %s" % mergeData.their_name) self.t.assertEqual(mergeData.base_name, "", "Unexpected base_name: %s" % mergeData.base_name) self.t.assertNotEqual(mergeData.your_path, None, "YourPath is empty") self.t.assertNotEqual(mergeData.their_path, None, "TheirPath is empty") self.t.assertEqual(mergeData.base_path, None, "BasePath is not empty") self.t.assertEqual(mergeData.merge_hint, "at", "Unexpected merge hint: %s" % mergeData.merge_hint) return "at" self.p4.run_resolve(resolver = BinaryResolver(self)) change = self.p4.fetch_change() change._description = "Third" self._doSubmit("Failed to submit third", change) if self.p4.server_level >= 31: self.p4.run_integrate("//TestClient/test_resolve/foo", "//TestClient/test_resolve/bar") self.p4.run_reopen("-t+w", "//TestClient/test_resolve/bar") self.p4.run_edit("-t+x", "//TestClient/test_resolve/foo") change = self.p4.fetch_change() change._description = "Fourth" self._doSubmit("Failed to submit fourth", change) self.p4.run_integrate("-3", "//TestClient/test_resolve/foo", "//TestClient/test_resolve/bar") result = self.p4.run_resolve("-n") self.assertEqual(len(result), 2, "No two resolves scheduled") class ActionResolver(P4.Resolver): def __init__(self, testObject): self.t = testObject def resolve(self, mergeData): self.t.assertEqual(mergeData.your_name, "//TestClient/test_resolve/bar", "Unexpected your_name: %s" % mergeData.your_name) self.t.assertEqual(mergeData.their_name, "//depot/test_resolve/foo#4", "Unexpected their_name: %s" % mergeData.their_name) self.t.assertEqual(mergeData.base_name, "//depot/test_resolve/foo#3", "Unexpected base_name: %s" % mergeData.base_name) self.t.assertEqual(mergeData.merge_hint, "at", "Unexpected merge hint: %s" % mergeData.merge_hint) return "at" def actionResolve(self, mergeData): self.t.assertEqual(mergeData.merge_action, "(text+wx)", "Unexpected mergeAction: '%s'" % mergeData.merge_action ) self.t.assertEqual(mergeData.yours_action, "(text+w)", "Unexpected mergeAction: '%s'" % mergeData.yours_action ) self.t.assertEqual(mergeData.their_action, "(text+x)", "Unexpected mergeAction: '%s'" % mergeData.their_action ) self.t.assertEqual(mergeData.type, "Filetype resolve", "Unexpected type: '%s'" % mergeData.type) # check the info hash values self.t.assertTrue(mergeData.info['clientFile'].endswith(os.path.join('client','test_resolve', 'bar')), "Unexpected clientFile info: '%s'" % mergeData.info['clientFile']) self.t.assertEqual(mergeData.info['fromFile'], '//depot/test_resolve/foo', "Unexpected fromFile info: '%s'" % mergeData.info['fromFile']) self.t.assertEqual(mergeData.info['resolveType'], 'filetype', "Unexpected resolveType info: '%s'" % mergeData.info['resolveType']) return "am" self.p4.run_resolve(resolver=ActionResolver(self)) def testMap(self): # don't need connection, simply test all the Map features map = P4.Map() self.assertEqual(map.count(), 0, "Map does not have count == 0") self.assertEqual(map.is_empty(), True, "Map is not empty") map.insert("//depot/main/... //ws/...") self.assertEqual(map.count(), 1, "Map does not have 1 entry") self.assertEqual(map.is_empty(), False, "Map is still empty") self.assertEqual(map.includes("//depot/main/foo"), True, "Map does not map //depot/main/foo") self.assertEqual(map.includes("//ws/foo", False), True, "Map does not map //ws/foo") map.insert("-//depot/main/exclude/... //ws/exclude/...") self.assertEqual(map.count(), 2, "Map does not have 2 entries") self.assertEqual(map.includes("//depot/main/foo"), True, "Map does not map foo anymore") self.assertEqual(map.includes("//depot/main/exclude/foo"), False, "Map still maps foo") self.assertEqual(map.includes("//ws/foo", False), True, "Map does not map foo anymore (reverse)") self.assertEqual(map.includes("//ws/exclude/foo"), False, "Map still maps foo (reverse)") map.clear() self.assertEqual(map.count(), 0, "Map has elements after clearing") self.assertEqual(map.is_empty(), True, "Map is still not empty after clearing") a = [ "//depot/main/... //ws/main/..." , "//depot/main/doc/... //ws/doc/..."] map = P4.Map(a) self.assertEqual(map.count(), 3, "Map does not contain 3 elements") map2 = P4.Map("//ws/...", "C:\Work\...") self.assertEqual(map2.count(), 1, "Map2 does not contain any elements") map3 = P4.Map.join(map, map2) self.assertEqual(map3.count(), 3, "Join did not produce three entries") map.clear() map.insert( '"//depot/dir with spaces/..." "//ws/dir with spaces/..."' ) self.assertEqual( map.includes("//depot/dir with spaces/foo"), True, "Quotes not handled correctly" ) def testThreads( self ): import threading class AsyncInfo( threading.Thread ): def __init__( self, port ): threading.Thread.__init__( self ) self.p4 = P4.P4() self.p4.port = port def run( self ): self.p4.connect() info = self.p4.run_info() self.p4.disconnect() threads = [] for i in range(1,10): threads.append( AsyncInfo(self.port) ) for thread in threads: thread.start() for thread in threads: thread.join() def testArguments( self ): p4 = P4.P4(debug=3, port="9999", client="myclient") self.assertEqual(p4.debug, 3) self.assertEqual(p4.port, "9999") self.assertEqual(p4.client, "myclient") def testUnicode( self ): self.enableUnicode() testDir = 'test_files' testAbsoluteDir = os.path.join(self.client_root, testDir) os.mkdir(testAbsoluteDir) self.p4.charset = 'iso8859-1' self.p4.connect() self._setClient() # create a bunch of files tf = os.path.join(testDir, "unicode.txt") fname = os.path.join(self.client_root, tf) if sys.version_info < (3,0): with open(fname, "w") as f: f.write("This file cost \xa31") else: with open(fname, "wb") as f: f.write("This file cost \xa31".encode('iso8859-1')) self.p4.run_add('-t', 'unicode', tf) self.p4.run_submit("-d", "Unicode file") self.p4.run_sync('...#0') self.p4.charset = 'utf8' self.p4.run_sync() if sys.version_info < (3,0): with open(fname, 'r') as f: buf = f.read() self.assertTrue(buf == "This file cost \xc2\xa31", "File not found, UNICODE support broken?") else: with open(fname, 'rb') as f: buf = f.read() self.assertTrue(buf == "This file cost \xa31".encode('utf-8'), "File not found, UNICODE support broken?") ch = self.p4.run_changes(b'-m1') self.assertEqual(len(ch), 1, "Byte strings broken") self.p4.disconnect() def testTrack( self ): success = self.p4.track = 1 self.assertTrue(success, "Failed to set performance tracking") self.p4.connect() self.assertTrue(self.p4.connected(), "Failed to connect") try: self.p4.track = 0 self.assertTrue(self.p4.track, "Changing performance tracking is not allowed") except P4Exception: pass self.p4.run_info() self.assertTrue(len(self.p4.track_output), "No performance tracking reported") def testOutputHandler( self ): self.assertEqual( self.p4.handler, None ) # create the standard iterator and try to set it h = P4.OutputHandler() self.p4.handler = h self.assertEqual( self.p4.handler, h ) # test the resetting self.p4.handler = None self.assertEqual( self.p4.handler, None ) self.assertEqual( sys.getrefcount(h), 2 ) self.p4.connect() self._setClient() class MyOutputHandler(P4.OutputHandler): def __init__(self): P4.OutputHandler.__init__(self) self.statOutput = [] self.infoOutput = [] self.messageOutput = [] def outputStat(self, stat): self.statOutput.append(stat) return P4.OutputHandler.HANDLED def outputInfo(self, info): self.infoOutput.append(info) return P4.OutputHandler.HANDLED def outputMessage(self, msg): self.messageOutput.append(msg) return P4.OutputHandler.HANDLED testDir = 'test-handler' files = self.createFiles(testDir) change = self.p4.fetch_change() change._description = "My Handler Test" self._doSubmit("Failed to submit the add", change) h = MyOutputHandler() self.assertEqual( sys.getrefcount(h), 2 ) self.p4.handler = h self.assertEqual( len(self.p4.run_files('...')), 0, "p4 does not return empty list") self.assertEqual( len(h.statOutput), len(files), "Less files than expected") self.assertEqual( len(h.messageOutput), 0, "Messages unexpected") self.p4.handler = None self.assertEqual( sys.getrefcount(h), 2 ) if False: # test currently disabled def testProgress( self ): self.p4.connect() self._setClient() testDir = "progress" testAbsoluteDir = os.path.join(self.client_root, testDir) os.mkdir(testAbsoluteDir) if self.p4.server_level >= 33: class TestProgress( P4.Progress ): def __init__(self): P4.Progress.__init__(self) self.invoked = 0 self.types = [] self.descriptions = [] self.units = [] self.totals = [] self.positions = [] self.dones = [] def init(self, type): self.types.append(type) def setDescription(self, description, unit): self.descriptions.append(description) self.units.append(unit) def setTotal(self, total): self.totals.append(total) def update(self, position): self.positions.append(position) def done(self, fail): self.dones.append(fail) # first, test the submits self.p4.progress = TestProgress() # create a bunch of files, fill them with content, and add them total = 100 for i in range(total): fname = os.path.join(testAbsoluteDir, "file%02d" % i) with open(fname, 'w') as f: f.write('A'*1024) # write 1024 'A' characters to create 1K file self.p4.run_add(fname) self.p4.run_submit('-dSome files') self.assertEqual(len(self.p4.progress.types), total, "Did not receive %d progress initialize calls" % total) self.assertEqual(len(self.p4.progress.descriptions), total, "Did not receive %d progress description calls" % total) self.assertEqual(len(self.p4.progress.totals), total, "Did not receive %d progress totals calls" % total) self.assertEqual(len(self.p4.progress.positions), total, "Did not receive %d progress positions calls" % total) self.assertEqual(len(self.p4.progress.dones), total, "Did not receive %d progress dones calls" % total) class TestOutputAndProgress( P4.Progress, P4.OutputHandler ): def __init__(self): P4.Progress.__init__(self) P4.OutputHandler.__init__(self) self.totalFiles = 0 self.totalSizes = 0 def outputStat(self, stat): if 'totalFileCount' in stat: self.totalFileCount = int(stat['totalFileCount']) if 'totalFileSize' in stat: self.totalFileSize = int(stat['totalFileSize']) return P4.OutputHandler.HANDLED def outputInfo(self, info): return P4.OutputHandler.HANDLED def outputMessage(self, msg): return P4.OutputHandler.HANDLED def init(self, type): self.type = type def setDescription(self, description, unit): pass def setTotal(self, total): pass def update(self, position): self.position = position def done(self, fail): self.fail = fail callback = TestOutputAndProgress() self.p4.run_sync('-f', '-q', '//...', progress=callback, handler=callback) self.assertEqual(callback.totalFileCount, callback.position, "Total does not match position %d <> %d" % (callback.totalFileCount, callback.position)) self.assertEqual(total, callback.position, "Total does not match position %d <> %d" % (total, callback.position)) else: print("Test case testProgress needs a 2012.2+ Perforce Server to run") def testStreams( self ): self.p4.connect() self._setClient() if self.p4.server_level >= 30: self.assertEqual( self.p4.streams, 1, "Streams are not enabled") # Create the streams depot d = self.p4.fetch_depot( "streams" ) d._type = 'stream' self.p4.save_depot( d ) # create a stream s = self.p4.fetch_stream( "//streams/main" ) s._description = 'Main line stream' s._type = 'mainline' self.p4.save_stream( s ) # check if stream exists # due to a server "feature" we need to disconnect and reconnect first self.p4.disconnect() self.p4.connect() streams = self.p4.run_streams() self.assertEqual( len(streams), 1, "Couldn't find any streams") else: print("Test case testStreams needs a 2010.2+ Perforce Server to run") def testSpecs( self ): self.p4.connect() # create a bunch of specs # try to iterate through them afterwards # 'clients' : ('client', 'client'), # 'labels' : ('label', 'label'), # 'branches' : ('branch', 'branch'), # 'changes' : ('change', 'change'), # 'streams' : ('stream', 'Stream'), # 'jobs' : ('job', 'Job'), # 'users' : ('user', 'User'), # 'groups' : ('group', 'group'), # 'depots' : ('depot', 'name'), # 'servers' : ('server', 'Name') clients = [] c = self.p4.fetch_client('client1') self.p4.save_client(c) clients.append(c._client) c = self.p4.fetch_client('client2') self.p4.save_client(c) clients.append(c._client) for c in self.p4.iterate_clients(): self.assertTrue(c._client in clients, "Cannot find client in iteration") labels = [] l = self.p4.fetch_label('label1') self.p4.save_label(l) labels.append(l._label) l = self.p4.fetch_label('label2') self.p4.save_label(l) labels.append(l._label) for l in self.p4.iterate_labels(): self.assertTrue(l._label in labels, "Cannot find labels in iteration") # P4.encoding is only available (and undoc'd) in Python 3 if sys.version_info[0] >= 3: def testEncoding( self ): self.p4.connect() self.p4.encoding = 'raw' self.assertEqual(self.p4.encoding, 'raw', "Encoding is not raw") info = self.p4.run_info()[0] self.assertEqual(type(info['serverVersion']), bytes, "Type of string is not bytes") if __name__ == '__main__': unittest.main() <file_sep>/* * PythonClientUser. Subclass of P4::ClientUser * * Copyright (c) 2007-2008, Perforce Software, Inc. All rights reserved. * Portions Copyright (c) 1999, <NAME>. All rights reserved. * Portions Copyright (c) 2004-2007, <NAME>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: //depot/r13.1/p4-python/PythonClientUser.h#1 $ * * Build instructions: * Use Distutils - see accompanying setup.py * * python setup.py install * */ #ifndef PYTHON_CLIENT_USER_H #define PYTHON_CLIENT_USER_H class ClientProgress; class PythonClientUser : public ClientUser, public KeepAlive { public: PythonClientUser( SpecMgr *s ); virtual ~PythonClientUser(); // Client User methods overridden here virtual void HandleError( Error *e ); virtual void Message( Error *err ); virtual void OutputText( const char *data, int length ); virtual void OutputInfo( char level, const char *data ); virtual void OutputStat( StrDict *values ); virtual void OutputBinary( const char *data, int length ); virtual void InputData( StrBuf *strbuf, Error *e ); virtual void Diff( FileSys *f1, FileSys *f2, int doPage, char *diffFlags, Error *e ); virtual void Prompt( const StrPtr &msg, StrBuf &rsp, int noEcho, Error *e ); virtual int Resolve( ClientMerge *m, Error *e ); virtual int Resolve( ClientResolveA *m, int preview, Error *e ); virtual ClientProgress *CreateProgress( int ); virtual int ProgressIndicator(); virtual void Finished(); // Local methods PyObject * SetInput( PyObject * i ); PyObject * GetInput() { Py_INCREF(input); return input; } PyObject * SetResolver( PyObject * i ); PyObject * GetResolver() { Py_INCREF(resolver); return resolver; } PyObject * SetHandler( PyObject * i ); PyObject * GetHandler() { Py_INCREF(handler); return handler; } PyObject * SetProgress( PyObject * p ); PyObject * GetProgress() { Py_INCREF(progress); return progress; } void SetCommand( const char *c ) { cmd = c; } void SetApiLevel( int level ); void SetTrack(bool t) { track = t; } P4Result& GetResults() { return results; } int ErrorCount(); void Reset(); // Debugging support void SetDebug( int d ) { debug = d; } // override from KeepAlive virtual int IsAlive() { return alive; } private: PyObject * MkMergeInfo( ClientMerge *m, StrPtr &hint ); PyObject * MkActionMergeInfo( ClientResolveA *m, StrPtr &hint ); void ProcessOutput( const char * method, PyObject * data); void ProcessMessage( Error * e); bool CallOutputMethod( const char * method, PyObject * data); private: StrBuf cmd; SpecMgr * specMgr; P4Result results; PyObject * input; PyObject * resolver; PyObject * handler; PyObject * progress; int debug; int apiLevel; int alive; bool track; }; #endif <file_sep>======== P4Python ======== :Author: <NAME> <<EMAIL>> :Organization: Ravenbrook Limited <http://www.ravenbrook.com/> .. note:: This repository is obsolete. Perforce Software support pip installation themselves starting at version 2016.1. Just try:: pip install p4python Thank you, Perforce! This is P4Python, the Python interface to the Perforce API , enables you to write Python code that interacts with a Perforce server. For details, see the P4Python chapter of the Perforce scripting manual <http://www.perforce.com/perforce/doc.current/manuals/p4script/03_python.html>. Please see RELNOTES.txt for hints how to build and use P4Python and for a list of changes. This is a fork of P4Python by <NAME> of Ravenbrook Limited, with the goal of making a command like:: pip install p4python work smoothly, quickly, and without manual intervention. This should make it much easier for people to develop Python apps that use Perforce. The P4Python distributed by Perforce Software relies on the user manually fetching the Perforce C/C++ API (P4API). In addition, on some platforms (such as Mac OS X 8) the user must fetch, configure, and build dependent packages such as OpenSSL 1.0.1. All of this hinders development and distribution of Python packages using Perforce. So far, this fork includes a script ``p4apiget.py`` that attempts to fetch a relevant version of the Perforce API from Perforce Software's FTP server. This is called from ``setup.py`` if the user didn't specify a directory containing the API. Open issues: 1. p4apiget.py may not guess the right place to get P4API on all supported platforms. 2. Nothing has been done to fetch libraries that P4API depends on, such as OpenSSL 1.0.1. <file_sep>"""P4Python - Python interface to Perforce API Perforce is the fast SCM system at www.perforce.com. This package provides a simple interface from Python wrapping the Perforce C++ API to gain performance and ease of coding. Similar to interfaces available for Ruby and Perl. """ classifiers = """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: Freely Distributable Programming Language :: Python Topic :: Software Development :: Libraries :: Python Modules Topic :: Software Development :: Version Control Topic :: Software Development Topic :: Utilities Operating System :: Microsoft :: Windows Operating System :: Unix """ # Customisations needed to use to build: # 1. Set directory for p4api in setup.cfg # See notes in P4API documentation for building with API on different # platforms: # http://www.perforce.com/perforce/doc.current/manuals/p4api/02_clientprog.html from distutils.core import setup, Extension import os, os.path, sys, re, shutil, stat from platform import uname, python_compiler if sys.version_info < (3,0): from ConfigParser import ConfigParser else: from configparser import ConfigParser # Fix for older versions of Python if sys.version_info < (2, 3): _setup = setup def setup(**kwargs): if kwargs.has_key("classifiers"): del kwargs["classifiers"] _setup(**kwargs) global_dist_directory = "p4python-" class VersionInfo: def __init__(self, p4ApiDir): self.release_year = None self.release_version = None self.release_special = None self.patchlevel = None self.suppdate_year = None self.suppdate_month = None self.suppdate_day = None releasePattern = re.compile("RELEASE\s+=\s+(?P<year>\d+)\s+(?P<version>\d+)\s*(?P<special>.*?)\s*;") patchlevelPattern = re.compile("PATCHLEVEL\s+=\s+(?P<level>\d+)") suppdatePattern = re.compile("SUPPDATE\s+=\s+(?P<year>\d+)\s+(?P<month>\d+)\s+(?P<day>\d+)") self.patterns=[] self.patterns.append((releasePattern, self.handleRelease)) self.patterns.append((patchlevelPattern, self.handlePatchlevel)) self.patterns.append((suppdatePattern, self.handleSuppDate)) verFile = os.path.join(p4ApiDir, "sample", "Version") if not os.path.exists(verFile): verFile = os.path.join(p4ApiDir, "Version") input = open(verFile) for line in input: for pattern, handler in self.patterns: m = pattern.match(line) if m: handler(**m.groupdict()) input.close() def handleRelease(self, year=0, version=0, special=''): self.release_year = year self.release_version = version self.release_special = re.sub("\s+", ".", special) def handlePatchlevel(self, level=0): self.patchlevel = level def handleSuppDate(self, year=0, month=0, day=0): self.suppdate_year = year self.suppdate_month = month self.suppdate_day = day def getP4Version(self): return "%s.%s" % (self.release_year, self.release_version) def getFullP4Version(self): version = "%s.%s" % (self.release_year, self.release_version) if self.release_special: version += ".%s" % self.release_special return version def getDistVersion(self): version = "%s.%s.%s" % (self.release_year, self.release_version, self.patchlevel) if self.release_special: version += ".%s" % self.release_special return version def getPatchVersion(self): version = "%s.%s" % (self.release_year, self.release_version) if self.release_special: version += ".%s" % self.release_special version += "/%s" % self.patchlevel return version doclines = __doc__.split("\n") NAME = "p4python" VERSION = "2011.1" PY_MODULES = ["P4"] P4_API_DIR = "p4api" DESCRIPTION=doclines[0] AUTHOR="Perforce Software Inc" MAINTAINER="Perforce Software Inc" AUTHOR_EMAIL="<EMAIL>" MAINTAINER_EMAIL="<EMAIL>" LICENSE="LICENSE.txt" URL="http://www.perforce.com" KEYWORDS="Perforce perforce P4Python" P4_CONFIG_FILE="setup.cfg" P4_CONFIG_SECTION="p4python_config" P4_CONFIG_P4APIDIR="p4_api" P4_CONFIG_SSLDIR="p4_ssl" P4_DOC_RELNOTES="../p4-doc/user/p4pythonnotes.txt" P4_RELNOTES="RELNOTES.txt" P4_P4_VERSION="../p4/Version" P4_VERSION="Version" def copyReleaseNotes(): """Copies the relnotes from the doc directory to the local directory if they exist Returns True if the release notes were copied, otherwise False """ if os.path.exists(P4_DOC_RELNOTES): try: shutil.copy(P4_DOC_RELNOTES, P4_RELNOTES) return True except Exception as e: print (e) return False else: return False def deleteReleaseNotes(): """Removes RELNOTES.txt from the current directory again""" os.chmod(P4_RELNOTES, stat.S_IWRITE) os.remove(P4_RELNOTES) def copyVersion(): """Copies the Version file from the p4 directory to the local directory if it exists. Returns True if the file was copied, otherwise False """ if os.path.exists(P4_P4_VERSION): try: shutil.copy(P4_P4_VERSION, P4_VERSION) os.chmod(P4_VERSION, stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH | \ stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) return True except Exception as e: print (e) return False else: return False def deleteVersion(): """Removes the Version file from the current directory again""" try: os.chmod(P4_VERSION, stat.S_IWRITE) os.remove(P4_VERSION) except: pass # ignore error, file might be owned by root from install class PlatformInfo: def __init__(self, apiVersion, releaseVersion, withSSL): self.libraries=None self.extra_compile_args=None self.define_macros=None self.extra_link_args=None unameOut = uname() if os.name == "nt": if python_compiler().find("64 bit") > 0: pl = "NTX64" platform = "64" else: pl = "NTX86" platform = "32" self.ID_OS=self.inStrStr(pl) self.ID_REL=self.inStrStr(releaseVersion.getFullP4Version()) self.ID_PATCH=self.inStrStr(releaseVersion.patchlevel) self.ID_API=self.inStrStr(apiVersion.getPatchVersion()) self.ID_Y=self.inStrStr(releaseVersion.suppdate_year) self.ID_M=self.inStrStr(releaseVersion.suppdate_month) self.ID_D=self.inStrStr(releaseVersion.suppdate_day) self.libraries=["oldnames", "wsock32", "advapi32", "ws2_32", "User32", "Gdi32", # MSVC libs "libclient", "librpc", "libsupp"] # P4API libs if withSSL: self.libraries.append("libeay%s" % platform) self.libraries.append("ssleay%s" % platform) else: self.libraries.append("libp4sslstub") self.extra_compile_args=["/DOS_NT", "/DMT", "/DCASE_INSENSITIVE", "/EHsc"] self.extra_link_args=["/NODEFAULTLIB:libcmt"] elif os.name == "posix": self.libraries=["client", "rpc", "supp"] # P4API libs if withSSL: self.libraries.append("ssl") self.libraries.append("crypto") else: self.libraries.append("p4sslstub") self.extra_compile_args = [] # it is UNIX, but which one? Let's ask uname() # details later if unameOut[0] == "Linux": unix = "LINUX" release = unameOut[2][0:1] + unameOut[2][2:3] platform = self.architecture(unameOut[4]) self.libraries.append("rt") # for clock_gettime elif unameOut[0] == "Darwin": unix = "DARWIN" self.extra_compile_args.append("-fvisibility-inlines-hidden") self.extra_compile_args.append("-DCASE_INSENSITIVE") if unameOut[2][0] == "8": release = "104" elif unameOut[2][0] == "9" : release = "105" self.extra_link_args = ["-framework", "Carbon"] elif unameOut[2][0:2] in ("10", "11", "12") : release = "106" self.extra_link_args = ["-framework", "Carbon"] elif unameOut[2][0:2] in ("12") : release = "100" self.extra_link_args = ["-framework", "Carbon"] platform = self.architecture(unameOut[4]) # The following is another hack # There is no way to remove the standard compile flags. The default on a MAC # is to build a universal binary. The Perforce API is only built for one # platform, so we need to remove these flags. By setting the environment # variable ARCHFLAGS the defaults can be overriden. if platform == "PPC": os.environ["ARCHFLAGS"] = "-arch ppc" elif platform == "i386": os.environ["ARCHFLAGS"] = "-arch i386" elif platform == "X86_64": os.environ["ARCHFLAGS"] = "-arch x86_64" elif unameOut[0] == "SunOS": unix = "SOLARIS" release = re.match("5.(\d+)", unameOut[2]).group(1) platform = self.architecture(unameOut[4]) elif unameOut[0] == 'FreeBSD': unix = "FREEBSD" release = unameOut[2][0] if release == '5': release += unameOut[2][2] platform = self.architecture(unameOut[4]) elif unameOut[0] == 'CYGWIN_NT-5.1': unix = "CYGWIN" release = "" platform = self.architecture(unameOut[4]) self.ID_OS = self.inStr(unix + release + platform) self.ID_REL=self.inStr(releaseVersion.getFullP4Version()) self.ID_PATCH=self.inStr(releaseVersion.patchlevel) self.ID_API=self.inStr(apiVersion.getPatchVersion()) self.ID_Y=self.inStr(releaseVersion.suppdate_year) self.ID_M=self.inStr(releaseVersion.suppdate_month) self.ID_D=self.inStr(releaseVersion.suppdate_day) self.extra_compile_args.append("-DOS_" + unix) self.extra_compile_args.append("-DOS_" + unix + release) self.extra_compile_args.append("-DOS_" + unix + platform) self.extra_compile_args.append("-DOS_" + unix + release + platform) self.define_macros = [('ID_OS', self.ID_OS), ('ID_REL', self.ID_REL), ('ID_PATCH', self.ID_PATCH), ('ID_API', self.ID_API), ('ID_Y', self.ID_Y), ('ID_M', self.ID_M), ('ID_D', self.ID_D)] def inStr(self, str): return '"' + str + '"' def inStrStr(self, str): return '"\\"' + str + '\\""' def architecture(self, str): if str == 'x86_64': return "X86_64" elif re.match('i.86', str): return "X86" elif str == 'i86pc': return "X86" elif str == 'Power Macintosh': return 'PPC' elif str == 'powerpc': return 'PPC' elif str == 'amd64': return 'X86_64' elif str == 'sparc': return 'SPARC' elif re.match('arm.*', str): return "ARM" def do_setup(p4_api_dir, ssl): global global_dist_directory try: apiVersion = VersionInfo(p4_api_dir) releaseVersion = VersionInfo(".") except IOError: print ("Cannot find Version file in API dir or distribution dir.") print ("API path = ", p4_api_dir) exit(1) ryear = int(apiVersion.release_year) rversion = int(apiVersion.release_version) global_dist_directory += releaseVersion.getDistVersion() if (ryear < 2012) or (ryear == 2012 and rversion < 2): print ("API Release %s.%s not supported. Minimum requirement is 2012.2." % (ryear, rversion)) print ("Please download a more recent API release from the Perforce ftp site.") exit(1) else: print ("API Release %s.%s" % (ryear, rversion)) inc_path = [p4_api_dir, os.path.join(p4_api_dir, "include", "p4")] lib_path = [p4_api_dir, os.path.join(p4_api_dir, "lib")] if ssl: lib_path.append( ssl ) info = PlatformInfo(apiVersion, releaseVersion, ssl != None) setup(name=NAME, version=releaseVersion.getDistVersion(), description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, license=LICENSE, url=URL, keywords=KEYWORDS, classifiers = filter(None, classifiers.split("\n")), long_description = "\n".join(doclines[2:]), py_modules=PY_MODULES, ext_modules=[Extension("P4API", ["P4API.cpp", "PythonClientAPI.cpp", "PythonClientUser.cpp", "SpecMgr.cpp", "P4Result.cpp", "PythonMergeData.cpp", "P4MapMaker.cpp", "PythonSpecData.cpp", "PythonMessage.cpp", "PythonActionMergeData.cpp", "PythonClientProgress.cpp"], include_dirs = inc_path, library_dirs = lib_path, libraries = info.libraries, extra_compile_args = info.extra_compile_args, define_macros = info.define_macros, extra_link_args = info.extra_link_args )]) def get_api_dir(): p4_api_dir = None if '--apidir' in sys.argv: index = sys.argv.index("--apidir") if index < len(sys.argv) - 1: p4_api_dir = sys.argv[index + 1] del sys.argv[index:index+2] else: print ("Error: --apidir needs API dir as an argument") sys.exit(99) if not p4_api_dir: config = ConfigParser() config.read(P4_CONFIG_FILE) p4_api_dir = None if config.has_section(P4_CONFIG_SECTION): if config.has_option(P4_CONFIG_SECTION, P4_CONFIG_P4APIDIR): p4_api_dir = config.get(P4_CONFIG_SECTION, P4_CONFIG_P4APIDIR) if not p4_api_dir: try: import p4apiget p4_api_dir = p4apiget.get_p4api() except Exception as exn: print ("Error: Unable to download API:", repr(exn)) if not p4_api_dir: print ("Error: %s section in setup.cfg needs option %s set to the directory containing the perforce API!" % ( P4_CONFIG_SECTION, P4_CONFIG_P4APIDIR)) sys.exit(100) return p4_api_dir def force_remove_file(function, path, excinfo): os.chmod( path, stat.S_IWRITE ) os.unlink( path ) if __name__ == "__main__": # Clean up from any prior build if os.path.exists(P4_P4_VERSION): deleteVersion() copyVersion() if 'sdist' in sys.argv: if os.path.exists(P4_RELNOTES): deleteReleaseNotes() copyReleaseNotes() distdir = global_dist_directory + VersionInfo(".").getDistVersion() if os.path.exists(distdir): shutil.rmtree(distdir, False, force_remove_file) p4_api_dir = get_api_dir() ssl = None if '--ssl' in sys.argv: index = sys.argv.index("--ssl") if index < len(sys.argv) - 1: ssl = sys.argv[index + 1] del sys.argv[index:index+2] else: ssl = "" del sys.argv[index:index+1] else: config = ConfigParser() config.read(P4_CONFIG_FILE) if config.has_section(P4_CONFIG_SECTION): if config.has_option(P4_CONFIG_SECTION, P4_CONFIG_SSLDIR): ssl = config.get(P4_CONFIG_SECTION, P4_CONFIG_SSLDIR) do_setup(p4_api_dir, ssl)
cf65db42e0d07c3ec7ba747f1c0267acb06c6cb3
[ "Python", "Text", "C++" ]
7
C++
laosierZhao/p4python
949f0e7a889b777a652e9c8e152b26c0c2e95840
03f03c53e4175e25140ce94aa052abd16d51dba3
refs/heads/master
<repo_name>feyzanursaka/Introduction-to-Computer-Engineering<file_sep>/README.md # Introduction-to-Computer-Engineering Make-up Homework Clustering 2D data with k-means algorithm: k-means algorithm is one of the most elemantary and easy to implement clustering algorithm. It enables to partition and group the corresponding data into k groups. In this homework, the followings are desired: 1. Learn the k-means algorithm. 2. Use 2D dataset in data.txt. You can find the data file as the attachment in Google Classroom. 3. Import the data into your program. 4. Partition the data into three groups using k-means algorithm. 5. You can use any pogramming language you prefer. 6. Find the corresponding group index of each point (each row of the data depicts a point in 2D Cartesian space) 7. Plot a scatter graph where each group has a unique color. <file_sep>/FeyzaNurSAKA_1521221051_HW3/src/k/algorithm/KMeans.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 k.algorithm; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class KMeans { static ArrayList<Double> x = new ArrayList<>();//dosyadaki 1. column (x ler) static ArrayList<Double> y = new ArrayList<>();//dosyadaki 2. column (y ler) static ArrayList<Double> c1_x = new ArrayList<>();//c1 kümesinin x leri static ArrayList<Double> c1_y = new ArrayList<>();//c1 kümesinin y leri static ArrayList<Double> c2_x = new ArrayList<>();//c2 kümesinin x leri static ArrayList<Double> c2_y = new ArrayList<>();//c1 kümesinin y leri static ArrayList<Double> c3_x = new ArrayList<>();//c3 kümesinin x leri static ArrayList<Double> c3_y = new ArrayList<>();//c1 kümesinin y leri public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br1 = null; br1 = new BufferedReader(new FileReader("C:\\Users\\<NAME>\\Desktop\\FeyzaNurSAKA_1521221051_HW3\\src\\k\\algorithm\\data.txt")); readFile(br1); double x_max = findMax(x); double x_min = findMin(x); double y_max = findMax(y); double y_min = findMin(y); ArrayList<Double> random_x = new ArrayList<>(); ArrayList<Double> random_y = new ArrayList<>(); //1. kümenin random x ve y aralığı dataların x ve y sınırları içerisinde double random1_x = (x_min + (double) (Math.random() * (x_max - x_min))); double random1_y = (y_min + (double) (Math.random() * (y_max - y_min))); //2. kümenin random x ve y aralığı dataların x ve y sınırları içerisinde double random2_x = (x_min + (double) (Math.random() * (x_max - x_min))); double random2_y = (y_min + (double) (Math.random() * (y_max - y_min))); //3. kümenin random x ve y aralığı dataların x ve y sınırları içerisinde double random3_x = (x_min + (double) (Math.random() * (x_max - x_min))); double random3_y = (y_min + (double) (Math.random() * (y_max - y_min))); //seçilen random x değerlerini random_x ve random y değerlerini random_y arraylistlerinde tuttum random_x.add(random1_x); random_x.add(random2_x); random_x.add(random3_x); random_y.add(random1_y); random_y.add(random2_y); random_y.add(random3_y); System.out.println("================================================"); System.out.println("=> random x değerleri"); for (Double x : random_x) { System.out.println(x); } System.out.println("================================================"); System.out.println("=> random y değerleri"); for (Double y : random_y) { System.out.println(y); } KMeans(random_x, random_y); } public static void KMeans( ArrayList<Double> random_x, ArrayList<Double> random_y) {//Gelen Arraylistlere göre benim datamın uzaklığı hangisine yakınsa o kümeye attım for (int i = 0; i < x.size(); i++) { //random_x ve random_y lerin 0. sıyla kıyaslama yaptım eğer şart sağlanırsa c1 kümesine ekledim if( Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(0)*random_x.get(0))+(random_y.get(0)*random_y.get(0))))< Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(1)*random_x.get(1))+(random_y.get(1)*random_y.get(1))))&& Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(0)*random_x.get(0))+(random_y.get(0)*random_y.get(0))))< Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(2)*random_x.get(2))+(random_y.get(2)*random_y.get(2))))) { c1_x.add(x.get(i));c1_y.add(y.get(i)); } //random_x ve random_y lerin 1. siyle kıyaslama yaptım eğer şart sağlanırsa c2 kümesine ekledim if( Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(1)*random_x.get(1))+(random_y.get(1)*random_y.get(1))))< Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(0)*random_x.get(0))+(random_y.get(0)*random_y.get(0))))&& Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(1)*random_x.get(1))+(random_y.get(1)*random_y.get(1))))< Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(2)*random_x.get(2))+(random_y.get(2)*random_y.get(2))))) { c2_x.add(x.get(i));c2_y.add(y.get(i)); } //random_x ve random_y lerin 2. sıyla kıyaslama yaptım eğer şart sağlanırsa c3 kümesine ekledim if( Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(2)*random_x.get(2))+(random_y.get(2)*random_y.get(1))))< Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(0)*random_x.get(0))+(random_y.get(0)*random_y.get(0))))&& Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(2)*random_x.get(2))+(random_y.get(2)*random_y.get(2))))< Math.abs(Math.sqrt((x.get(i)*x.get(i))+(y.get(i)*y.get(i)))-Math.sqrt((random_x.get(1)*random_x.get(1))+(random_y.get(1)*random_y.get(1))))) { c3_x.add(x.get(i));c3_y.add(y.get(i)); } } System.out.println("================================================"); System.out.println("=> c1 kümesinin x leri ; \n" + c1_x + "\n=> c1 kümesinin y leri ;\n" + c1_y); System.out.println("================================================"); System.out.println("=> c2 kümesinin x leri ; \n" + c2_x + "\n=> c2 kümesinin y leri ;\n" + c2_y); System.out.println("================================================"); System.out.println("=> c3 kümesinin x leri ; \n" + c3_x + "\n=> c3 kümesinin y leri ;\n" + c3_y); } public static double findMax(ArrayList<Double> a) {//dataların maxını bulur double max = 0; for (int i = 0; i < a.size(); i++) { if (max < a.get(i)) { max = a.get(i); } } return max; } public static double findMin(ArrayList<Double> a) {//dataların minini bulur double min = a.get(0); for (int i = 0; i < a.size(); i++) { if (min > a.get(i)) { min = a.get(i); } } return min; } public static void readFile(BufferedReader br1) throws IOException {//bütün dataları okuyup hepsini data ismindeki array liste atadım String s = null; String a[] = null; int i = 0; while ((s = br1.readLine()) != null) {//satırları böldü a = s.split("\t"); x.add(Double.parseDouble(a[i]));// x noktaları i++;//arttırma işlemi y.add(Double.parseDouble(a[i]));// y noktaları i = 0;//sıfırladım } System.out.println("================================================"); System.out.println("HW3 2D data clustering with k-means"); System.out.println("================================================"); System.out.println("=> dosyadaki x değerleri \n"+x); System.out.println("=> dosyadaki y değerleri \n"+y); } }
aef3453433122029f52665df9602dec8dc9f9d70
[ "Markdown", "Java" ]
2
Markdown
feyzanursaka/Introduction-to-Computer-Engineering
ec1864965104817d2bf806c56a4fc598d484a4c3
3c7b9b7daf3b08ad9bca12bdc4ba2dad233742e3
refs/heads/master
<repo_name>danialmalik/react_tictactoe<file_sep>/src/modules/Game/helper.js export const calculateWinner = squares => { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; } export const getGameStatus = (movesHistory, stepNumber, xIsNext) => { const current = movesHistory[stepNumber]; const winner = calculateWinner(current.squares); const movesCount = stepNumber; let status; if (winner) { status = "Winner: " + winner; } else if (movesCount === 9) { status = "Draw"; } else { status = "Next player: " + (xIsNext ? "X" : "O"); } return status; } <file_sep>/src/modules/Game/Game.js import React from "react"; import Board from "../Board/Board"; import MovesHistory from "../MovesHistory/MovesHistory"; import { calculateWinner, getGameStatus } from "./helper"; import "./Game.css"; class Game extends React.Component { constructor(props) { super(props); this.state = { history: [ { squares: Array(9).fill(null) } ], stepNumber: 0, xIsNext: true }; } handleClick(i) { const history = this.state.history.slice(0, this.state.stepNumber + 1); const current = history[history.length - 1]; const squares = current.squares.slice(); if (calculateWinner(squares) || squares[i]) { return; } squares[i] = this.state.xIsNext ? "X" : "O"; this.setState({ history: history.concat([ { squares: squares } ]), stepNumber: history.length, xIsNext: !this.state.xIsNext }); } jumpTo(step) { this.setState({ stepNumber: step, xIsNext: (step % 2) === 0 }); } render() { const status = getGameStatus(this.state.history, this.state.stepNumber, this.state.xIsNext); const { squares } = this.state.history[this.state.stepNumber]; return ( <div className="game"> <div className="game-board"> <Board squares={squares} onClick={i => this.handleClick(i)} /> </div> <div className="game-info"> <div>{status}</div> <MovesHistory onClickHandler={move => this.jumpTo(move)} history={this.state.history} /> </div> </div> ); } } export default Game; <file_sep>/src/modules/MovesHistory/MovesHistory.js import React from "react"; import Button from "./Button"; const MovesHistory = ({history, onClickHandler}) => { const moves = history.map((step, move) => { const desc = move ? 'Go to move #' + move : 'Go to game start'; return ( <li key={move}> <Button onClickHandler={()=>onClickHandler(move)} move={move} desc={desc} /> </li> ); }); return moves; } export default MovesHistory; <file_sep>/src/modules/Board/Board.js import React from "react"; import Square from "../Square/Square"; import './Board.css'; class Board extends React.Component { renderSquare(i) { return ( <Square key={i} value={this.props.squares[i]} onClick={() => this.props.onClick(i)} /> ); } render() { let boardMatrix = []; let squareNum = 0; for (let rowNum = 0; rowNum < 3; rowNum++) { let row = []; for (let colNum = 0; colNum < 3; colNum++) { row.push( this.renderSquare( squareNum++ ) ); } boardMatrix.push( <div key={squareNum} className="board-row"> {row} </div> ); } return ( <div> {boardMatrix} </div> ); } } export default Board;
7c201d96a194b646c8c648823731899640de93bf
[ "JavaScript" ]
4
JavaScript
danialmalik/react_tictactoe
7fa6e559121c2cf5ea9fc57abe99c074f6ebdca0
03cc12e1e11893aa23f79657b535c02480286e5a
refs/heads/main
<repo_name>Rehab2004/WouldYouRather<file_sep>/src/components/404.js import { React } from 'react' function notFound({ location }) { return ( <div> <p style={{ marginLeft: '30px', fontWeight: 'bold', fontSize: '16px' }}> no matching path<code>{location.pathname}</code> </p> </div> ) } export default notFound <file_sep>/src/components/Questionpage.js import React, { Component } from 'react' import { connect } from 'react-redux' import QuestionCard from './QuestionCard' //import {addAnswerAction} from '../actions/users' //import {addAnsweredQuestion} from '../actions/questions' import { handleSaveAnswer } from '../actions/shared' import { Redirect } from 'react-router' class Questionpage extends Component { state = { select: '', name: '', screen: false } handleChange = (e) => { this.setState({ select: e.target.value, name: e.target.name }) } handleSetValues = (authedUser, qid, answer) => { answer = this.state.name qid = this.props.id authedUser = this.props.authedUser console.log(answer) console.log(qid) this.props.dispatch(handleSaveAnswer(authedUser, qid, answer)) } handleSubmit = (e) => { e.preventDefault() this.handleSetValues() this.setState({ screen: true }) } render() { if (this.props.exist === false) { return <Redirect to="/404" /> } console.log(this.props) const { answers, id, question, answered } = this.props const { optionOne, optionTwo } = question const vote = id in answers ? answers[id] : null let totalAnswers = optionOne.votes.length + optionTwo.votes.length let numberOfOption_1 = totalAnswers - optionTwo.votes.length let numberOfOption_2 = totalAnswers - optionOne.votes.length let option_1 = (optionOne.votes.length / (optionOne.votes.length + optionTwo.votes.length)) * 100 let option_2 = (optionTwo.votes.length / (optionOne.votes.length + optionTwo.votes.length)) * 100 return ( <div className="container"> {answered === false && this.state.screen === false ? ( <div className="card"> <br></br> <QuestionCard id={id} /> <form className="question-page-form" onSubmit={this.handleSubmit}> <div className="item"> <input id="optionOne" name="optionOne" value={optionOne.text} checked={this.state.select === optionOne.text} type="radio" onChange={this.handleChange} /> <label htmlFor="optionOne">{optionOne.text}</label> </div> <div className="item"> <input id="optionTwo" name="optionTwo" value={optionTwo.text} checked={this.state.select === optionTwo.text} type="radio" onChange={this.handleChange} /> <label htmlFor="optionTwo">{optionTwo.text}</label> </div> <button className="question-page-btn" type="submit" disabled={this.state.select === ''} > submit </button> </form> </div> ) : ( <div className="result-page"> <div> <QuestionCard id={id} /> </div> <div className="result"> <h5 style={{ color: 'green' }}>Results:</h5> <div className="option-prec"> <p> would you rather <span style={{ marginLeft: '5px' }}>{optionOne.text}</span> </p> {(this.state.select === optionOne.text) | answered && vote === 'optionOne' && ( <span className="your-vote">your vote</span> )} <div className="progress bar"> <div className="progress-bar bg-success" role="progressbar" style={{ width: `${option_1}%` }} aria-valuenow={option_1} aria-valuemin="0" aria-valuemax="100" >{`${option_1}%`}</div> </div> <div className="total"> <p>{`${numberOfOption_1} out of ${totalAnswers} votes`}</p> </div> </div> <hr></hr> <div className="option-prec"> <p> would you rather <span style={{ marginLeft: '5px' }}>{optionTwo.text}</span> </p> {(this.state.select === optionTwo.text) | answered && vote === 'optionTwo' && ( <span className="your-vote">your vote</span> )} <div className="progress bar"> <div className="progress-bar bg-success" role="progressbar" style={{ width: `${option_2}%` }} aria-valuenow={option_2} aria-valuemin="0" aria-valuemax="100" >{`${option_2}%`}</div> </div> <div className="total"> <p>{`${numberOfOption_2} out of ${totalAnswers} votes`}</p> </div> </div> </div> </div> )} </div> ) } } function mapStateToProps({ questions, authedUser, users }, props) { const { id } = props.match.params const exist = id in questions ? true : false const user = users[authedUser] const { answers } = user return { exist, answers, id, authedUser, question: exist ? questions[id] : null, answered: id in answers ? true : false } } export default connect(mapStateToProps)(Questionpage) <file_sep>/src/actions/users.js import { _saveQuestionAnswer, _saveAccount } from '../utils/_Data' export const RECEIVE_USERS = 'RECEIVE_USERS' export const ADD_ANSWER = 'ADD_ANSWER' export const ADD_ACCOUNT = 'ADD_ACCOUNT' export const CREATE_QUESTION='CREATE_QUESTION' export function receiveUsersAction(users) { return { type: RECEIVE_USERS, users } } export function addAnswerAction({ authedUser, qid, answer }) { return { type: ADD_ANSWER, authedUser, qid, answer } } export function createQuestion(question){ return{ type:CREATE_QUESTION, question } } export function handleSaveAnswer(id, answer) { return (dispatch, getState) => { const { authedUser } = getState() return _saveQuestionAnswer({ authedUser, id, answer }).then(() => { dispatch(addAnswerAction({ authedUser, id, answer })) }) } } function addUserAccount(account) { return { type: ADD_ACCOUNT, account } } export function handleSaveAccount(id, name, avatarURL) { return (dispatch) => { return _saveAccount(id, name, avatarURL).then((account) => { dispatch(addUserAccount(account)) }) } } <file_sep>/README.md <h1> would you Rather</h1> Get the Project from starter code from here <span>https://github.com/udacity/reactnd-project-would-you-rather-starter</span> <h3>Tools</h3> <p>1-node.js</p> <p>2-react library</p> <p>3-redux library</p> <h4>start</h4> <p>1-install npm</p> npm install <p>2-install yarn package</p> npm i yarn <p> run development server</p> yarn start <p> arrange files</p> <p>the state tree is represented in three slices</p> users,questions,authedUser <p> according to Redux the state is located at store and to update it, it is needed an action to hit a reducer which is responsible for making the update </p> <p>src</p> <p>actions</p> <p>authoredUser</p> <p>shared</p> <p>questions</p> <p> users</p> <p>components</p> <p>App</p> .......... <p> middleware</p> <p>index</p> <p> logger </p> <p> reducers </p> <p> authoredUser</p> <p> index</p> <p>questions</p> <p>users</p> <p> index.js </p> <p>install redux,redux-thunk,react-redux </p> npm i redux redux-thunk react-redux <p> in index.js import App component , createStore from redux then create store with combineReducer and applyMiddleware const store=createStor(reducers,middlewaew</p> <p>wrap App with <Provider> component from react-redux library,this component will stick store in it's context and provides it to App as a props <P><Provider store={store}> <App/> </Provider></p> </p> <p> to connect each component to store we use connect() from react-redux,it converts normal react component to container one</p> <p> connect() envokes another function (mapStateToProps),to get needed data to component</p> <p> throw project you will use store state which is provided from redux, but also you will need to use react state</p> <p> install react-router to wrap components with Route to navigate between them</p> npm i react-router-dom <file_sep>/src/components/Newquestion.js import React, { Component } from 'react' import { connect } from 'react-redux' import { handleSaveQuestion } from '../actions/shared' import { Redirect } from 'react-router-dom' class Newquestion extends Component { state = { optionOne: '', optionTwo: '', toHome: false } handleChangeOption_1 = (e) => { this.setState({ optionOne: e.target.value }) } handleChangeOption_2 = (e) => { this.setState({ optionTwo: e.target.value }) } handelSubmit = (e) => { e.preventDefault() const { optionOne, optionTwo } = this.state console.log(optionOne) console.log(optionTwo) this.props.dispatch(handleSaveQuestion(optionOne, optionTwo)) this.setState({ optionOne: '', optionTwo: '', toHome: true }) } render() { const { optionOne, optionTwo, toHome } = this.state if (toHome === true) { return <Redirect to="/" /> } return ( <div className="container"> <div className="card"> <h5 style={{ color: 'green' }}>Create New Question</h5> <hr style={{ height: '3px', boxShadow: ` 1px 1px 1px rgb(136, 134, 134)` }} ></hr> <p style={{ color: 'green' }}>complete question</p> <div> <p> <b>Would you rather...</b> </p> <form className="new-question-form" onSubmit={this.handelSubmit}> <input type="text" placeholder="Enter option one text" value={optionOne} onChange={this.handleChangeOption_1} /> <h6 className="line">OR</h6> <input type="text" placeholder="Enter option two text" value={optionTwo} onChange={this.handleChangeOption_2} /> <button className="new-question-btn" type="submit" disabled={optionOne | (optionTwo === '')} > submit </button> </form> </div> </div> </div> ) } } function mapStateToProps({ authedUser }) { return { authedUser } } export default connect(mapStateToProps)(Newquestion) <file_sep>/src/components/QuestionCard.js import { React, Component } from 'react' import { connect } from 'react-redux' class QuestionCard extends Component { render() { console.log(this.props) const { question, user } = this.props if (question === null) { return <p>this question doesn't exist</p> } const { name, avatarURL } = user //const{optionOne,optionTwo}=question return ( <div className="container"> <h5 className="user-name"> {name} asks</h5> <img src={avatarURL} alt="avatar" className="avatar" /> <div> <p> <b>would you rather</b>{' '} </p> </div> </div> ) } } function mapStateToProps({ authedUser, users, questions }, { id }) { const question = questions[id] const user = question ? users[question.author] : null return { authedUser, user, question: question ? question : null } } export default connect(mapStateToProps)(QuestionCard) <file_sep>/src/actions/shared.js import { receiveUsersAction, addAnswerAction,createQuestion } from './users' import { receiveQuestionsAction, addAnsweredQuestion,addQuestion } from './questions' import { authoredIdAction } from './authoredUser' import { getInitialData, _saveQuestionAnswer,_saveQuestion } from '../utils/_Data' import { showLoading, hideLoading } from 'react-redux-loading' const authorId = null export function handleIntialData() { return (dispatch) => { dispatch(showLoading()) return getInitialData().then(({ users, questions }) => { console.log({ users, questions }) dispatch(receiveUsersAction(users)) dispatch(receiveQuestionsAction(questions)) dispatch(authoredIdAction(authorId)) dispatch(hideLoading()) }) } } export function handleSaveAnswer(authedUser, qid, answer) { return (dispatch) => { //const {authedUser}=getState() return _saveQuestionAnswer({ authedUser, qid, answer }).then(() => { dispatch(addAnswerAction({ authedUser, qid, answer })) dispatch(addAnsweredQuestion({ authedUser, qid, answer })) }) } } export function handleSaveQuestion(optionOneText, optionTwoText) { return (dispatch, getState) => { const { authedUser } = getState() return _saveQuestion({ optionOneText, optionTwoText, authedUser }).then( (question) => { dispatch(addQuestion(question)) dispatch(createQuestion(question)) } ) } }
ef3d5ea3c1ff43bcb720979e1893742d533d6d7e
[ "JavaScript", "Markdown" ]
7
JavaScript
Rehab2004/WouldYouRather
ff4571acb1c24e96b43d8f2208f2ec0b57b69794
79a47a41bb3d9091fa66a823a2a5c414630a9991
refs/heads/master
<repo_name>VlasiukRV/inconnect<file_sep>/src/reducer/securityScore.js import { Record, Map } from 'immutable' import { LOAD_SECURITYSCORE, START, SUCCESS, FAIL } from '../constants' import { getFirstRecordFromArray } from '../utils/arrays' const SecurityScore = Record({ 'securityScore': 0, 'securityScoreStatus': '', 'securityScoreToday': 0, 'securityScoreLastMonth': 0, 'securityScoreAllTime': 0, 'presenceToday': 0, 'presenceLastMonth': 0, 'presenceAllTime': 0 }) const defaultEntity = getFirstRecordFromArray(SecurityScore, []) const defaultState = new Map({ loading: false, loaded: false, error: false, userSecurityScore: defaultEntity }) export default (state = defaultState, action) => { const {type, response} = action switch (type) { case LOAD_SECURITYSCORE + START: return state .set('loading', true) .set('loaded', false) .set('error', false) case LOAD_SECURITYSCORE + SUCCESS: return state .set('loading', false) .set('loaded', true) .set('error', false) .set('userSecurityScore', getFirstRecordFromArray(SecurityScore, response)) case LOAD_SECURITYSCORE + FAIL: { const currentState = defaultState return currentState .set('loading', false) .set('loaded', true) .set('error', true) } } return state } <file_sep>/src/middlewares/api.js import $ from 'jquery' import { START, SUCCESS, FAIL } from '../constants' import { THROW_ERROR } from '../constants' import { isAuthenticated } from '../utils/authentification' export default ( /*store*/ ) => next => action => { const {checkAuthenticated, callAPI, type, ...rest} = action if (!callAPI) return next(action) let authenticated = true; if (checkAuthenticated) { authenticated = isAuthenticated() } next({ type: type + START, ...rest }) if (authenticated) { $.get(callAPI) .done(response => next({ type: type + SUCCESS, response, ...rest })) .fail(error => next({ type: type + FAIL, error, ...rest })) } else { const error = { errorType: 401, msg: 'Unauthorized.' } next({ type: THROW_ERROR, error: error, ...rest }) next({ type: type + FAIL, ...rest }) } }<file_sep>/src/components/UserNotification.js import React, { Component } from 'react' import PropTypes from 'prop-types'; class UserNotification extends Component { render() { if (!this.props.notification) return <h3>Haw no notification</h3> const {notification} = this.props return ( <div> <p> { notification.name } </p> <p> { notification.date } </p> </div> ) } } UserNotification.propTypes = { comment: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string }) } export default UserNotification<file_sep>/src/constants.js // API export const START = '_START' export const SUCCESS = '_SUCCESS' export const FAIL = '_FAIL' export const THROW_ERROR = '@@INCONNECT/THROW_ERROR' export const CLEAR_ERRORS = '@@INCONNECT/CLEAR_ERRORS' export const LOAD_USER = '@@INCONNECT/LOAD_USER' export const LOGOUT_USER = '@@INCONNECT/LOAD_USER' export const LOAD_SECURITYSCORE = '@@INCONNECT/LOAD_SECURITYSCORE' export const USERDEVICE_LIST = '@@INCONNECT/USERDEVICE_LIST' export const LOAD_USERDEVICES = '@@INCONNECT/LOAD_USERDEVICES' export const USERNOTIFICATION_LIST = '@@INCONNECT/USERNOTIFICATION_LIST' export const LOAD_USERNOTIFICATIONS = '@@INCONNECT/LOAD_USERNOTIFICATIONS' export const INSURANCE_LIST = '@@INCONNECT/INSURANCE_LIST' export const LOAD_INSURANCE = '@@INCONNECT/LOAD_INSURANCE' export const CHANGE_ENTITY_INSURANCE_NODE = '@@INCONNECT/CHANGE_VALUE_INSURANCE_NODE' // FILTERS export const CHANGE_FILTERS = '@@INCONNECT/CHANGE_FILTERS'<file_sep>/src/containers/AppPageLogin.js import React, { Component } from 'react' import { connect } from 'react-redux' import LoginForm from '../components/LoginForm'; import { logInUser } from '../actions/users' class AppPageLogin extends Component { constructor(props) { super(props) this.state = { errors: {}, successMessage: '', user: { email: '', password: '' } } this.processForm = this.processForm.bind(this) this.changeUser = this.changeUser.bind(this) } changeUser(event) { const field = event.target.name const user = this.state.user user[field] = event.target.value this.setState({ user }); } processForm(event) { event.preventDefault() this.props.logInUser() } render() { return (<div> <LoginForm onSubmit={ this.processForm } onChange={ this.changeUser } errors={ this.state.errors } successMessage={ this.state.successMessage } user={ this.state.user } /> </div> ); } } export default connect(null, { logInUser })(AppPageLogin) <file_sep>/src/actions/devices.js import { LOAD_USERDEVICES } from '../constants' export function loadUserDeviceList() { return { type: LOAD_USERDEVICES, checkAuthenticated: true, callAPI: '/api/user/devices' } }<file_sep>/src/utils/tree.js import keyBy from 'lodash/keyBy' import { changeEntityValueInList } from './arrays' let newEntityList export function sumUpEntityList(entityList) { const tree = arrayToTree(entityList.valueSeq().toArray(), { parentProperty: 'parent_id', customID: 'id', rootID: '0' }) newEntityList = entityList const sum = sumUpTree(tree) return { newEntityList, sum } } var sumUpTree = function(tree) { let result = 0; tree.forEach(function(item) { let elResult = item.value if (item.children) { elResult = sumUpTree(item.children) newEntityList = changeEntityValueInList(newEntityList, item.id, { key: 'value', value: elResult }) } result = result + elResult }); return result } export function arrayToTree(data, options) { if (!data) { return [] } if (!options) { options = {} } options = Object.assign({ parentProperty: 'parent_id', customID: 'id', rootID: '0' }, options) var grouped = groupByParents(data, options); return createTree(grouped, grouped[options.rootID], options.customID); } var createTree = function(array, rootNodes, customID) { var tree = []; for (var rootNode in rootNodes) { var node = rootNodes[rootNode]; var childNode = array[node[customID]]; if (!node && !rootNodes.hasOwnProperty(rootNode)) { continue ; } if (childNode) { node.children = createTree(array, childNode, customID); } tree.push(node); } return tree; }; var groupByParents = function(array, options) { var arrayByID = keyBy(array, options.customID); return array.reduce(function(prev, item) { var parentID = item[options.parentProperty]; if (!parentID || !arrayByID.hasOwnProperty(parentID)) { parentID = options.rootID; } if (parentID && prev.hasOwnProperty(parentID)) { prev[parentID].push(item); return prev; } if (parentID != item[options.customID]) { prev[parentID] = [item] } return prev; }, {}); }; <file_sep>/src/components/InsuranceList.js import React, { Component } from 'react' import InsuranceNode from './InsuranceNode' class InsuranceList extends Component { render() { return <div> { this.getBody() } </div> } getBody() { const {insuranceList} = this.props const insuranceItems = insuranceList.map(insuranceItem => <li key={ insuranceItem.id }> <InsuranceNode insuranceNode={ insuranceItem } /> </li> ) return ( <div> <ul> { insuranceItems } </ul> </div> ) } } export default InsuranceList <file_sep>/src/containers/UserDevices.js import React, { Component } from 'react' import { connect } from 'react-redux' import UserDeviceList from './../components/UserDeviceList' import Spinner from './../stylesheets/img/Spinner' import '../stylesheets/UserDevicesStyle.css'; class UserDevices extends Component { componentDidMount() {} render() { return ( <div className='user-devices'> { this.getBody() } </div> ) } getBody() { const {loading, userDeviceList} = this.props const head = (<div className='user-devices-title'> <h3>My Smart Devices</h3></div>) if (loading) { return ( <div> { head } <h1><Spinner width='50' height='50' /></h1> </div> ) } return ( <div> { head } <UserDeviceList userDeviceList={ userDeviceList } /> </div> ) } } export default connect( ({userDeviceList, userDeviceListFilters}) => ( { loading: userDeviceList.get('loading'), userDeviceList: filterList(userDeviceList.get('userDeviceList'), userDeviceListFilters) } ) )(UserDevices) function filterList(entityList, filters) { let entityListFiltered = entityList const term = filters.term.toLowerCase(); if (term != '') { entityListFiltered = entityList.filter(entity => { return entity.name.toLowerCase().includes(term); }) } return entityListFiltered.valueSeq(); }<file_sep>/src/reducer/errors.js import { Record, Map } from 'immutable' import { THROW_ERROR, CLEAR_ERRORS } from '../constants' import { recordsFromArray } from '../utils/arrays' const AppError = Record({ errorType: '', msg: '' } ) const defaulErrorsMap = recordsFromArray(AppError, []) const defaultState = new Map({ errors: defaulErrorsMap }) export default (state = defaultState, action) => { const {type, error} = action switch (type) { case THROW_ERROR: { const appError = new AppError(error) const errors = state.get('errors') return state .set('errors', errors.set(error.errorType, appError)) } case CLEAR_ERRORS: { return state .set('errors', defaulErrorsMap) } } return state }<file_sep>/src/components/UserNotificationsList.js import React, { Component } from 'react' import UserNotificationsListSearchBar from '../containers/UserNotificationsListSearchBar' import UserNotification from './UserNotification' class UserNotificationsList extends Component { render() { return <div> { this.getBody() } </div> } getBody() { const {notificationsList} = this.props const notifacationItems = notificationsList.map(userNotification => <li key={ userNotification.id }> <UserNotification notification={ userNotification } /> </li>) return ( <div> <UserNotificationsListSearchBar /> <ul> { notifacationItems } </ul> </div> ) } } export default UserNotificationsList <file_sep>/src/reducer/users.js import { Record, Map } from 'immutable' import { LOGOUT_USER, LOAD_USER, START, SUCCESS } from '../constants' import { getFirstRecordFromArray } from '../utils/arrays' import { setUser, deauthenticateUser } from '../utils/authentification' const User = Record({ 'id': '0', 'name': 'Undefined', 'email': '', 'password': '', 'userAvatar': '' }) const defaultUser = getFirstRecordFromArray(User, []) const defaultState = new Map({ loading: false, loaded: false, error: false, user: defaultUser }) export default (state = defaultState, action) => { const {type, response} = action switch (type) { case LOAD_USER + START: return state .set('loading', true) .set('loaded', false) case LOAD_USER + SUCCESS: { const activeUser = getFirstRecordFromArray(User, response) setUser('09w87rehfiogpvjeq0r54q0j') return state .set('loading', false) .set('loaded', true) .set('user', activeUser) } case LOGOUT_USER: { deauthenticateUser() const currentState = defaultState return currentState } } return state } <file_sep>/src/stylesheets/img/IconUserDevice.js import React, { Component } from 'react' export default class IconUserDevice extends Component { render(){ const { width, height, deviceType } = this.props let deviceIcon = '' if(deviceType == 'Camera'){ deviceIcon = this.getIconCamera() } const viewBox = '0 0 '+(44)+' '+(44) return <div> <svg className='user-device-ico' width={width} height={height} xmlns='http://www.w3.org/2000/svg' viewBox={viewBox} > {deviceIcon} </svg> </div> } getIconCamera(){ return ( <path d='M41.9,16.1L11.3,5.1c-0.5-0.2-0.9,0.1-1.1,0.5l-1.9,5.3c-0.2,0.5,0.1,0.9,0.5,1.1l1.8,0.6c-0.3,0.2-0.5,0.5-0.6,0.9L9.4,15 c-0.4,1,0.2,2.2,1.2,2.6l8.2,3l-1.4,3.9c-1.5,0-2.9,0.9-3.4,2.3c-0.1,0.4-0.2,0.7-0.2,1.1l-6.2,2.8c-1-1.1-2.6-1.4-4-0.8 c-1.8,0.8-2.6,2.9-1.8,4.7s2.9,2.6,4.7,1.8c1.3-0.6,2.1-1.9,2.1-3.3l6.1-2.7c0.4,0.4,0.9,0.8,1.5,1c1.8,0.7,3.9-0.3,4.6-2.1 c0.5-1.4,0.1-2.8-0.9-3.8l1.4-4l9.7,3.5c1,0.4,2.2-0.2,2.6-1.2l0.6-1.6c0.1-0.4,0.1-0.7,0.1-1.1l2.8,1c0.3,0.1,0.7,0,0.9-0.2 l4.4-4.4C42.7,17.1,42.5,16.3,41.9,16.1z'></path> ) } }<file_sep>/src/components/SignUpForm.js import React, { Component } from 'react' import { Link } from 'react-router-dom'; import { Card, CardText } from 'material-ui/Card'; import RaisedButton from 'material-ui/RaisedButton'; import TextField from 'material-ui/TextField'; class SignUpForm extends Component { render() { const {onSubmit, onChange, errors, user} = this.props return ( <div> <Card className='login-form'> <form action='/' onSubmit={ onSubmit }> <h2 className='card-heading'>Sign Up</h2> { errors.summary && <p className='error-message'> { errors.summary } </p> } <div className='field-line'> <TextField floatingLabelText='Name' name='name' errorText={ errors.name } onChange={ onChange } value={ user.name } /> </div> <div className='field-line'> <TextField floatingLabelText='Email' name='email' errorText={ errors.email } onChange={ onChange } value={ user.email } /> </div> <div className='field-line'> <TextField floatingLabelText='<PASSWORD>' type='<PASSWORD>' name='password' onChange={ onChange } errorText={ errors.password } value={ user.password } /> </div> <div className='button-line'> <RaisedButton type='submit' label='Create New Account' primary /> </div> <CardText>Already have an account? <Link to={ '/login' }>Log in</Link> </CardText> </form> </Card> </div>) } } export default SignUpForm<file_sep>/src/containers/UserSecurityScore.js import React, { Component } from 'react' /*import { findDOMNode } from 'react-dom'*/ import { connect } from 'react-redux' import { Link } from 'react-router-dom'; import Spinner from './../stylesheets/img/Spinner' import '../stylesheets/UserSecurityScoreStyle.css'; class UserSecurityScore extends Component { componentDidMount() {} render() { const head = (<div className='information-block-title'> <h3>My Security Score</h3></div>); return ( <div className='information-block user-security-score'> { head } <div className='information-block-body'> { this.getBody() } </div> <div> <ul className='information-block-nav'> <li> <Link to='#'>Get Recommendations</Link> </li> <li> <Link to='/score/coverage'>View History</Link> </li> <li> <Link to='/score/coverage'>See Coverages</Link> </li> <li> <Link to='#' onClick={ this.handleRecalculate.bind(this) }>Recalculate</Link> </li> </ul> </div> </div> ) } getBody() { const {loading, userSecurityScore, monthlyPayment} = this.props if (loading) { return ( <div> <Spinner width='50' height='50' /> </div> ) } return ( <div> <h4>monthly payment: { monthlyPayment }</h4> <div className='chart'> <div className='pieChart'></div> <div ref='chart' className='pieChartBody'></div> <div className='chartInformation'> <h2>{ userSecurityScore.securityScore }%</h2> <p> { userSecurityScore.securityScoreStatus } </p> </div> </div> </div> ) } handleRecalculate(event) { event.preventDefault() this.props.loadUserSecurityScore() } } export default connect( ({securityScore, insuranceList}) => ( { loading: securityScore.get('loading'), userSecurityScore: securityScore.get('userSecurityScore'), monthlyPayment: insuranceList.get('monthlyPayment') } ) )(UserSecurityScore)<file_sep>/src/stylesheets/img/Spinner.js import React, { Component } from 'react' export default class Spinner extends Component { render(){ const { width, height } = this.props const viewBox = '0 0 '+(100)+' '+(100) var style = {backgroundColor: 'none'} return <div className='spiner'> <svg style={style} width={width} height={height} xmlns='http://www.w3.org/2000/svg' viewBox={viewBox} preserveAspectRatio='xMidYMid' > <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.9166666666666666s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(30 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.8333333333333334s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(60 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.75s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(90 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.6666666666666666s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(120 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.5833333333333334s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(150 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.5s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(180 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.4166666666666667s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(210 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.3333333333333333s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(240 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.25s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(270 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.16666666666666666s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(300 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='-0.08333333333333333s' repeatCount='indefinite'/> </rect> <rect x='47' y='24' rx='9.4' ry='4.8' width='6' height='12' fill='#dd1d21' transform='rotate(330 50 50)'> <animate attributeName='opacity' values='1;0' dur='1s' begin='0s' repeatCount='indefinite'/> </rect> </svg> </div> } }<file_sep>/src/components/AppPageHeader.js import React, { Component } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router-dom'; import ActiveUser from '../containers/ActiveUser' import Logo from '../stylesheets/img/Logo' import { logOutUser } from '../actions/users' class AppPageHeader extends Component { constructor(props) { super(props) } render() { const {isLoadedUser} = this.props return <div className='navbar navbar-default navbar-fixed-top' role='navigation'> <div className='container-fluid'> <div className='navbar-header'> <button type='button' className='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'> <span className='sr-only'>Toggle navigation</span> <span className='icon-bar'></span> <span className='icon-bar'></span> <span className='icon-bar'></span> </button> <Link className='navbar-brand' to='/'>Inconnect <Logo /> </Link> </div> <div className='collapse navbar-collapse'> <ul className='nav navbar-nav navbar-right'> { isLoadedUser && <li> <Link to='/' title='Home'>Home</Link> </li> } { isLoadedUser && <li> <Link to='#connect'>Connect</Link> </li> } { isLoadedUser && <li> <Link to='#' title='Active user'> <ActiveUser /> </Link> </li> } { !isLoadedUser && <li> <Link to='/login'>Log in</Link> </li> } { isLoadedUser && <li> <Link to='#' onClick={ this.LogOut.bind(this) }>Log out</Link> </li> } </ul> </div> </div> </div> } LogOut(event) { event.preventDefault() this.props.logOutUser() } } export default connect( ({users}) => ( { isLoadedUser: users.get('loaded') } ), { logOutUser } )(AppPageHeader) <file_sep>/src/reducer/index.js import { combineReducers } from 'redux' import errors from './errors' import users from './users' import securityScore from './securityScore' import userDeviceList from './userDeviceList' import userDeviceListFilters from './userDeviceListFilters' import userNotificationList from './userNotificationList' import userNotificationListFilters from './userNotificationListFilters' import insuranceList from './insuranceList' import insuranceListFilters from './insuranceListFilters' export default combineReducers({ errors: errors, users: users, securityScore: securityScore, userDeviceList: userDeviceList, userDeviceListFilters: userDeviceListFilters, userNotificationList: userNotificationList, userNotificationListFilters: userNotificationListFilters, insuranceList: insuranceList, insuranceListFilters: insuranceListFilters })<file_sep>/src/components/LoginForm.js import React, { Component } from 'react' import { Link } from 'react-router-dom' import Avatar from 'material-ui/Avatar' import { Card, CardText } from 'material-ui/Card'; import RaisedButton from 'material-ui/RaisedButton'; import TextField from 'material-ui/TextField'; import '../stylesheets/LoginFormStyle.css'; class LoginForm extends Component { render() { const {onSubmit, onChange, errors, successMessage, user} = this.props return (<div> <Card className='login-form'> <form action='/' onSubmit={ onSubmit }> <h2 className='card-heading'>Login</h2> { successMessage && <p className='success-message'> { successMessage } </p> } { errors.summary && <p className='error-message'> { errors.summary } </p> } <div> <Avatar size={ 80 } src={ user.userAvatar } /> </div> <div className='field-line'> <TextField floatingLabelText='Email' name='email' errorText={ errors.email } onChange={ onChange } value={ user.email } /> </div> <div className='field-line'> <TextField floatingLabelText='<PASSWORD>' type='<PASSWORD>' name='password' onChange={ onChange } errorText={ errors.password } value={ user.password } /> </div> <div className='button-line'> <RaisedButton type='submit' label='Log in' primary /> </div> <CardText>Don't have an account? <Link to={ '/signup' }>Create one</Link>.</CardText> </form> </Card> </div>) } } export default LoginForm<file_sep>/src/actions/securityScore.js import { LOAD_SECURITYSCORE } from '../constants' export function loadUserSecurityScore() { return { type: LOAD_SECURITYSCORE, checkAuthenticated: true, callAPI: '/api/user/securityScore' } }<file_sep>/apiServer/api/mock.js var users = [ { "id": "56c782f18990ecf954f6e027", "name": '<NAME>', "email": '', "password": '', "userAvatar": 'https://lh3.googleusercontent.com/-nbae2Oajx0g/AAAAAAAAAAI/AAAAAAAAAbU/h_-8EmrlLYQ/photo.jpg' } ] var userSecurityScore = [ { 'securityScore': 86, 'securityScoreStatus': 'GOOD', 'securityScoreToday': 76, 'securityScoreLastMonth': 84, 'securityScoreAllTime': 84, 'presenceToday': 47, 'presenceLastMonth': 35, 'presenceAllTime': 45 } ] var userNotifications = [ { 'id': '1', 'name': 'Low battery level', 'date': '' }, { 'id': '2', 'name': 'Detected smoke', 'date': '' } ] var userDevices = [ { "id": "1", "name": "Backyard Camera", "deviceType": "Camera", "mfr": "Nest", "deviceInfo": { "status": "Armed", "is_online": true, "is_streaming": true } }, { "id": "2", "name": "Front Yard Camera", "deviceType": "Camera", "mfr": "Nest", "deviceInfo": { "status": "Armed", "is_online": true, "is_streaming": true } }, { "id": "3", "name": "Light Sensor 0", "deviceType": "Motion", "mfr": "Wirelesstag ", "deviceInfo": { "status": "Armed" } } ] var insurance = [ { "id": "0", "parent_id": "0", "isGrup": true, "name": "", "description": "", "value": 0 }, { "id": "10", "parent_id": "0", "isGrup": true, "name": "Buildings Insurance", "description": "Loss or damage to your building caused by: <ul> <li>Fire, Smoke, Explosion</li> <li>Weather (rain, air, snow)</li> <li>Intrusion (burglary, theft, vandalism, riots)</li> </ ul>", "value": 0 }, { "id": "11", "parent_id": "0", "isGrup": false, "name": "Monitoring and Emergency", "description": "Monitoring improving safety in and around the house by: <ul> <li>Recommendations — Notifications — Alerts;</li> <li>Escalation according to intervention scenario </li> </ul>", "value": 0 }, { "id": "2", "parent_id": "0", "isGrup": false, "name": "Home Assistance", "description": "Arrange assitance to repair/mitigate the damage", "value": 1800 }, { "id": "3", "parent_id": "10", "isGrup": false, "name": "Main Building", "description": "", "value": 30000 }, { "id": "4", "parent_id": "10", "isGrup": false, "name": "Outbuildings", "description": "", "value": 10000 }, { "id": "5", "parent_id": "10", "isGrup": false, "name": "Garden", "description": "", "value": 1000 }, { "id": "6", "parent_id": "10", "isGrup": false, "name": "Glass", "description": "", "value": 1000 }, { "id": "7", "parent_id": "0", "isGrup": true, "name": "Home Content Insurance", "description": "Loss or damage to your building caused by: <ul> <li>Fire, Smoke, Explosion</li> <li>Weather (rain, air, snow)</li> <li>Intrusion (burglary, theft, vandalism, riots)</li> </ ul>", "value": 0 }, { "id": "8", "parent_id": "7", "isGrup": false, "name": "General Coverage", "description": "", "value": 8000 }, { "id": "9", "parent_id": "7", "isGrup": false, "name": "Including Valuables with Single Limit", "description": "", "value": 100 }, { "id": "12", "parent_id": "7", "isGrup": false, "name": "Including Valuables with Total Limit", "description": "", "value": 200 }, ] module.exports = { users: users, userDevices: userDevices, insurance: insurance, userSecurityScore: userSecurityScore, userNotifications: userNotifications };<file_sep>/src/components/InsuranceNode.js import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import InsuranceList from './InsuranceList' import { changeEntityInsuranceNode } from '../actions/insurance' import '../stylesheets/InsuranceNodeStyle.css' class InsuranceNode extends Component { render() { if (!this.props.insuranceNode) return <h3>Haw no insurance</h3> const {insuranceNode} = this.props let insuranceNodeChildren = '' if (insuranceNode.children && insuranceNode.children.length > 0) { insuranceNodeChildren = (<InsuranceList insuranceList={ insuranceNode.children } />) } let opts = {}; if (insuranceNode.isGrup) { opts['readOnly'] = 'readOnly' } return ( <div> <p className='insuranceName'> <b>{ insuranceNode.name }</b> <input type='number' className='form-control insuranceValue' placeholder='Search device by name...' value={ insuranceNode.value } onChange={ this.handleValueChange.bind(this) } {...opts} /> </p> <p> <div dangerouslySetInnerHTML={ { __html: insuranceNode.description } } /> </p> <p></p> { insuranceNodeChildren } <hr /> </div> ) } handleValueChange(event) { event.preventDefault() const {insuranceNode, changeEntityInsuranceNode} = this.props changeEntityInsuranceNode(insuranceNode.id, 'value', +event.target.value) } handleValueChangeUp(event) { event.preventDefault() const {insuranceNode, changeEntityInsuranceNode} = this.props changeEntityInsuranceNode(insuranceNode.id, 'value', (insuranceNode.value + 100)) } handleValueChangeDovn(event) { event.preventDefault() const {insuranceNode, changeEntityInsuranceNode} = this.props changeEntityInsuranceNode(insuranceNode.id, 'value', (insuranceNode.value - 100)) } } InsuranceNode.propTypes = { comment: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string }) } export default connect( ({insuranceList}) => ( { insuranceList: insuranceList } ), { changeEntityInsuranceNode } )(InsuranceNode)<file_sep>/src/containers/AppPageSignUp.js import React, { Component } from 'react' import SignUpForm from '../components/SignUpForm'; class AppPageSignUp extends Component { constructor(props) { super(props) this.state = { errors: {}, user: { email: '', name: '', password: '' } } this.processForm = this.processForm.bind(this); this.changeUser = this.changeUser.bind(this); } changeUser(event) { const field = event.target.name; const user = this.state.user; user[field] = event.target.value; this.setState({ user }); } processForm(event) { event.preventDefault(); console.log('name:', this.state.user.name); console.log('email:', this.state.user.email); console.log('password:', <PASSWORD>); } render() { return ( <SignUpForm onSubmit={ this.processForm } onChange={ this.changeUser } errors={ this.state.errors } user={ this.state.user } /> ); } } export default AppPageSignUp;<file_sep>/src/containers/Errors.js import React, { Component } from 'react' import { connect } from 'react-redux' class Errors extends Component { render() { const {errors} = this.props const errorsLength = errors.size if (errorsLength == 0) return null const errorsList = errors.map(error => <li key={ error.errorType }> { error.msg } </li>) return <div className='information-block'> <div className='information-block-title'> Errors </div> <div className='information-block-body'> <ul className=''> { errorsList } </ul> </div> </div> } } export default connect( ({errors}) => ( { errors: errors.get('errors').valueSeq() } ) )(Errors) <file_sep>/src/stylesheets/img/Logo.js import React, { Component } from 'react' export default class IconUserDevice extends Component { render(){ const { width, height } = this.props let icon = this.getIcon() const viewBox = '0 0 '+(223.2)+' '+(59) return <div> <svg width={width} height={height} xmlns='http://www.w3.org/2000/svg' viewBox={viewBox} > {icon} </svg> </div> } getIcon(){ return (<div> </div> ) } }<file_sep>/src/components/AppRoute.js import React, { Component } from 'react' import { Switch, Route } from 'react-router-dom' import AppPageHome from './AppPageHome' import AppPageSignUp from '../containers/AppPageSignUp' import AppPageLogin from '../containers/AppPageLogin' import UserSecurityScoreHistory from '../containers/UserSecurityScoreHistory' import Insurance from '../containers/Insurance' export default class AppRoute extends Component { render() { return <div className='contant'> <Switch> <Route exact path='/' component={ AppPageHome } /> <Route path='/signup' component={ AppPageSignUp } /> <Route path='/login' component={ AppPageLogin } /> <Route path='/score/coverage' component={ Insurance } /> <Route path='/score/index' component={ UserSecurityScoreHistory } /> </Switch> </div> } }<file_sep>/src/containers/Insurance.js import React, { Component } from 'react' import { connect } from 'react-redux' import InsuranceList from './../components/InsuranceList' import Spinner from './../stylesheets/img/Spinner' import InsuranceListSearchBar from './InsuranceListSearchBar' import { arrayToTree } from '../utils/tree' class Insurance extends Component { componentDidMount() {} render() { const {loading, insuranceSum, monthlyPayment, insuranceList} = this.props const head = <h3>My Coverages</h3> if (loading) { return ( <div> { head } <h1><Spinner width='50' height='50' /></h1> </div> ) } return ( <div> { head } <p><b>total summ: { insuranceSum }<br /> monthlyPayment: { monthlyPayment } </b></p> <InsuranceListSearchBar /> <InsuranceList insuranceList={ insuranceList } /> </div> ) } } export default connect( ({insuranceList, insuranceListFilters}) => ( { loading: insuranceList.get('loading'), insuranceList: buildTree(filterList(insuranceList.get('insuranceList'), insuranceListFilters)), insuranceSum: insuranceList.get('insuranceSum'), monthlyPayment: insuranceList.get('monthlyPayment') } ) )(Insurance) function filterList(entityList, filters) { let entityListFiltered = entityList const term = filters.term.toLowerCase(); if (term != '') { entityListFiltered = entityList.filter(entity => { return entity.name.toLowerCase().includes(term); }) } return entityListFiltered.valueSeq(); } export function buildTree(entityList) { return arrayToTree(entityList.toArray()) } <file_sep>/src/containers/UserNotifications.js import React, { Component } from 'react' import { connect } from 'react-redux' import UserNotificationsList from './../components/UserNotificationsList' import Spinner from './../stylesheets/img/Spinner' import '../stylesheets/UserNotificationsStyle.css'; class UserNotifications extends Component { componentDidMount() {} render() { const head = (<div className='information-block-title'> <h3>Notifications</h3></div>); return ( <div className='information-block user-notifications'> { head } <div className='information-block-body'> { this.getBody() } </div> <ul className='information-block-nav'> <li> <a href='#' title='More'>More</a></li> </ul> </div> ) } getBody() { const {loading, notificationsList} = this.props if (loading) { return ( <h1><Spinner width='50' height='50' /></h1> ) } return ( <div> <UserNotificationsList notificationsList={ notificationsList } /> </div> ) } } export default connect( ({userNotificationList, userNotificationListFilters}) => ( { loading: userNotificationList.get('loading'), notificationsList: filterNotificationsList(userNotificationList.get('userNotificationList'), userNotificationListFilters) } ) )(UserNotifications) function filterNotificationsList(entityList, filters) { let entityListFiltered = entityList const term = filters.term.toLowerCase(); if (term != '') { entityListFiltered = entityList.filter(entity => { return entity.name.toLowerCase().includes(term); }) } return entityListFiltered.valueSeq(); } <file_sep>/src/decorators/AuthentificateDecorator.js import React from 'react' import { isAuthenticated } from '../utils/authentification' export default (Component) => class AuthentificateDecorator extends React.Component { constructor(props) { super(props) this.state = { isAuthenticated: isAuthenticated() } } render() { return <Component {...this.props} isAuthenticated={ this.state.isAuthenticated } /> } } <file_sep>/src/actions/userNotifications.js import { LOAD_USERNOTIFICATIONS } from '../constants' export function loadUserNotificationsList() { return { type: LOAD_USERNOTIFICATIONS, checkAuthenticated: true, callAPI: '/api/user/notifications' } }<file_sep>/src/reducer/userNotificationList.js import { Record, Map } from 'immutable' import { LOAD_USERNOTIFICATIONS, START, SUCCESS, FAIL } from '../constants' import { recordsFromArray } from '../utils/arrays' const UserNotification = Record({ 'id': '0', 'name': 'Undefined', 'date': '' }) const defaultUserNotification = recordsFromArray(UserNotification, []) const defaultState = new Map({ loading: false, loaded: false, error: false, userNotificationList: defaultUserNotification }) export default (state = defaultState, action) => { const {type, response} = action switch (type) { case LOAD_USERNOTIFICATIONS + START: return state .set('loading', true) .set('loaded', false) .set('error', false) case LOAD_USERNOTIFICATIONS + SUCCESS: return state .set('loading', false) .set('loaded', true) .set('error', false) .set('userNotificationList', recordsFromArray(UserNotification, response)) case LOAD_USERNOTIFICATIONS + FAIL: { const currentState = defaultState return currentState .set('loading', false) .set('loaded', true) .set('error', true) } } return state }
3476c0c28dbb6a0c1def6977bdad8920c06013fb
[ "JavaScript" ]
31
JavaScript
VlasiukRV/inconnect
b4edca8c7624c30ef7ac6f5e2e2e6fae5d88c175
972adb07439725cfe64a5012454b99cbf4cf826c
refs/heads/master
<file_sep> from reportlab.pdfgen import canvas def genPef(): c = canvas.Canvas("Olamundo.pdf") c.drawString(100, 750, "Welcome to Reportlab!") c.save() <file_sep>from wsgiref import validate from django.contrib.auth.models import User from django.db import models # Create your models here. from django.utils.html import format_html import datetime CERTIDAO = ( ('nas', 'Nascimento'), ('cas', 'Casamento'), ('div', 'Divórcio'), ) CONSULTA = ( ('pend', 'Pendente'), ('des', 'Desistir'), ('rem', 'Remarcar'), ('falt', 'Faltou'), ('conc', 'Concluído'), ) PERIODO = ( ('mat', 'Matutino'), ('ves', 'Vespertino'), ) ESTADOS = (('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins')) ENTIEMISS = (('SSP', 'Secretaria de Segurança Pública'), ('PM', 'Polícia Militar'), ('PC', 'Policia Civil'), ('CNT', 'Carteira Nacional de Habilitação'), ('DIC', 'Diretoria de Identificação Civil'), ('CTPS', 'Carteira de Trabaho e Previdência Social'), ('FGTS', 'Fundo de Garantia do Tempo de Serviço'), ('IFP', 'Instituto F<NAME>'), ('IPF', 'Instituto Pereira Faustino'), ('IML', 'Instituto Médico-Legal'), ('MTE', 'Ministério do Trabalho e Emprego'), ('MMA', 'Ministério da Marinha'), ('MAE', 'Ministério da Aeronáutica'), ('MEX', 'Ministério do Exército'), ('POF', 'Polícia Federal'), ('POM', 'Polícia Militar'), ('SES', 'Carteira de Estrangeiro'), ('SJS', 'Secretaria da Justiça e Segurança'), ('SJTS', 'Secretaria da Justiça do Trabalho e Segurança'), ('ZZZ', 'Outros (inclusive exterior')) SIMNAO = ( ('NAO', 'NÃO'), ('SIM', 'SIM'), ) PROFISSIONAISSAUDE = ( ('psiq', 'Psiquiatra'), ('psic', 'Psicólogo(a)'), ('enferm', 'Enfermeiro(a)'), ('psicoterap', 'Psicoterapeuta'), ('assissoc', 'Assistente social'), ('fisioterap', 'Fisioterapeuta'), ('terapocup', 'Terapeuta ocupacional'), ('clinico', 'Clínico Geral'), ) HORARIO = ( (1, 'Matutino'), (2, 'Vespertino'), ) LOGRATIPO = ( ('Aeroporto', 'Aeroporto'), ('Alameda', 'Alameda'), ('Área', 'Área'), ('Avenida', 'Avenida'), ('Campo', 'Campo'), ('Chácara', 'Chácara'), ('Colônia', 'Colônia'), ('Condomínio', 'Condomínio'), ('Conjunto', 'Conjunto'), ('Distrito', 'Distrito'), ('Esplanada', 'Esplanada'), ('Estação', 'Estação'), ('Estrada', 'Estrada'), ('Favela', 'Favela'), ('Fazenda', 'Fazenda'), ('Feira', 'Feira'), ('Jardim', 'Jardim'), ('Ladeira', 'Ladeira'), ('Lago', 'Lago'), ('Lagoa', 'Lagoa'), ('Largo', 'Largo'), ('Loteamento', 'Loteamento'), ('Morro', 'Morro'), ('Núcleo', 'Núcleo'), ('Parque', 'Parque'), ('Passarela', 'Passarela'), ('Pátio', 'Pátio'), ('Praça', 'Praça'), ('Quadra', 'Quadra'), ('Recanto', 'Recanto'), ('Residencial', 'Residencial'), ('Rodovia', 'Rodovia'), ('Rua', 'Rua'), ('Setor', 'Setor'), ('Sítio', 'Sítio'), ('Travessa', 'Travessa'), ('Trecho', 'Trecho'), ('Trevo', 'Trevo'), ('Vale', 'Vale'), ('Vereda', 'Vereda'), ('Via', 'Via'), ('Viaduto', 'Viaduto'), ('Viela', 'Viela'), ('Vila', 'Vila')) class paciente(models.Model): numsus = models.CharField(max_length=255) nprontuario = models.CharField(max_length=255, default="", null=True, blank=True) nome = models.CharField(max_length=255) tipoendereco = models.CharField(max_length=30,choices=LOGRATIPO, default="", null=True, blank=True) logradouro = models.CharField(max_length=255, default="", null=True, blank=True) logradouronum = models.CharField(max_length=30, default="", null=True, blank=True) pontoreferencia = models.CharField(max_length=255, default="", null=True, blank=True) bairro = models.CharField(max_length=100) cidade = models.CharField(max_length=255) uf = models.CharField(max_length=2, choices=ESTADOS, default="", null=True, blank=True) fone = models.CharField(max_length=16, default="", null=True, blank=True) fonefixo = models.CharField(max_length=15, default="", null=True, blank=True) email = models.CharField(max_length=255, default="", null=True, blank=True) certidao = models.CharField(max_length=3, choices=CERTIDAO) livro = models.CharField(max_length=100, default="", null=True, blank=True) fls = models.CharField(max_length=100, default="", null=True, blank=True) termo = models.CharField(max_length=100, default="", null=True, blank=True) dataemissao = models.DateField(auto_now=False, null=True, blank=True) datanascimento = models.DateField(auto_now=False) rg = models.CharField(max_length=50) rgorgemissor = models.CharField(max_length=255, choices=ENTIEMISS) rguf = models.CharField(max_length=2, choices=ESTADOS) rgdataemissao = models.DateField(auto_now=False) cpf = models.CharField(max_length=15) apelido = models.CharField(max_length=255, default="", null=True, blank=True) nomepai = models.CharField(max_length=255) nomemae = models.CharField(max_length=255) nomeresponsavel = models.CharField(max_length=255, default="", null=True, blank=True) festratamento = models.CharField(max_length=255, choices=SIMNAO) encaminhadopor = models.CharField(max_length=255, default="", null=True, blank=True) foto = models.ImageField(blank=True, null=True, upload_to='uploaded_images') entregadedocumentos = models.BooleanField(default=False) avaliacaopsiquiatrica = models.BooleanField(default=False) enfermagem = models.BooleanField(default=False) psicologa = models.BooleanField(default=False) #psicoterapeuta = models.BooleanField(default=False) assistentesocial = models.BooleanField(default=False) fisioterapeuta = models.BooleanField(default=False) #terapeutaocupacional = models.BooleanField(default=False) def ficha(self): return format_html( '<a href="/genpdf/{}" target="_blank">Ficha</a>', self.id, ) def __str__(self): return self.nome from django import forms from material import Layout, Fieldset, Row class Profissional(models.Model): nome = models.CharField(max_length=255, null=True, blank=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) especialidade = models.CharField(max_length=255, choices=PROFISSIONAISSAUDE) quantmaxconsulta = models.IntegerField(null=True, blank=True) # Quantidade de consultas por período disponivel = models.BooleanField(default=False) def __str__(self): return self.user.get_full_name() class ProfissionalForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProfissionalForm, self).__init__(*args, **kwargs) self.fields['quantmaxconsulta'].label = "Quantidade máxima de consultas por período" class Meta: model = Profissional exclude = ['nome'] from django.utils.timezone import now class Horario(models.Model): segundaM = models.BooleanField(default=False) tercaM = models.BooleanField(default=False) quartaM = models.BooleanField(default=False) quintaM = models.BooleanField(default=False) sextaM = models.BooleanField(default=False) segundaT = models.BooleanField(default=False) tercaT = models.BooleanField(default=False) quartaT = models.BooleanField(default=False) quintaT = models.BooleanField(default=False) sextaT = models.BooleanField(default=False) horainicioM = models.TimeField(null=True, blank=True) horafimM = models.TimeField(null=True, blank=True) horainicioT = models.TimeField(null=True, blank=True) horafimT = models.TimeField(null=True, blank=True) validadeinicio = models.DateField(null=True, blank=True) validadefim = models.DateField(null=True, blank=True) profissional = models.ForeignKey(Profissional, on_delete=models.CASCADE) class HorarioForm(forms.ModelForm): # validadeinicio = forms.DateField(input_formats = ("%d/%m/%Y"), required=False) # validadefim = forms.DateField(input_formats =("%d/%m/%Y"), required=False) class Meta: model = Horario fields = '__all__' exclude = ('validadeinicio', 'validadefim') # Gera birthchoides de 100 anos BIRTH_YEAR_CHOICES = ('1980', '1981', '1982') class UserForm(forms.ModelForm): class Meta: model = User fields = ('username','<PASSWORD>', 'first_name', 'last_name', 'email') class PacientForm(forms.ModelForm): id = forms.HiddenInput() def __init__(self, *args, **kwargs): super(PacientForm, self).__init__(*args, **kwargs) self.fields['nome'].label = "Nome Completo" self.fields['dataemissao'].label = "Data de Emissão" self.fields['numsus'].label = "Número do SUS" self.fields['pontoreferencia'].label = "Ponto de referência" self.fields['fone'].label = "Telefone Celular" self.fields['fonefixo'].label = "Telefone Fixo" self.fields['rgorgemissor'].label = "Orgão emissor" self.fields['rguf'].label = "Estado" self.fields['cpf'].label = "CPF" self.fields['nomepai'].label = "Nome do pai" self.fields['nomemae'].label = "Nome da mãe" self.fields['festratamento'].label = "Já fez tratamento?" self.fields['encaminhadopor'].label = "Encaminhado por" self.fields['datanascimento'].label = "Data de nascimento" self.fields['rgdataemissao'].label = "Data de emissão do RG" self.fields['fls'].label = "Folha" self.fields['rg'].label = "RG" self.fields['logradouronum'].label = "Número" self.fields['nomeresponsavel'].label = "Nome do responsável" self.fields['entregadedocumentos'].label = "Entrega de documentos" self.fields['avaliacaopsiquiatrica'].label = "Avaliação Psiquiátrica" self.fields['psicologa'].label = "Psicóloga" self.fields['assistentesocial'].label = "Assistente Social" self.fields['fisioterapeuta'].label = "Fisioterapeuta" # self.fields['terapeutaocupacional'].label = "Terapeuta ocupacional" self.fields['nprontuario'].label = "Número do prontuário" class Meta: model = paciente fields = '__all__' layout = Layout('foto','numsus', 'nprontuario', 'nome', 'apelido', Fieldset('Endereço', Row('tipoendereco', 'logradouro', 'logradouronum'), 'pontoreferencia', 'bairro', 'cidade', 'uf'), Fieldset('Contato', Row('fone', 'fonefixo'), 'email'), Fieldset('Certidão', Row('datanascimento', 'certidao', 'livro', 'fls', 'termo'), 'dataemissao'), Fieldset('Documentos', Row('rgorgemissor', 'rguf', 'rg', 'rgdataemissao'), 'cpf'), Fieldset('Outras informações', Row('nomepai', 'nomemae'), 'nomeresponsavel', 'festratamento', 'encaminhadopor', ), Fieldset('Etapas', 'entregadedocumentos', 'avaliacaopsiquiatrica', 'enfermagem', 'psicologa', # 'psicoterapeuta', 'assistentesocial', 'fisioterapeuta', #'terapeutaocupacional' ), ) class UsuarioForm(forms.Form): usuario = forms.CharField(max_length=255) senha = forms.CharField(max_length=255, widget=forms.PasswordInput) # # STATUS = ( # ('') # ) class Consulta(models.Model): paciente = models.ForeignKey(paciente, on_delete=models.CASCADE) profissional = models.ForeignKey(Profissional, on_delete=models.CASCADE) data = models.DateField() # Data padrão hora = models.TimeField(null=True, blank=True) periodo = models.CharField(choices=PERIODO, max_length=50, null=True, blank=True) status = models.CharField(choices=CONSULTA, max_length=50, default='pend', null=True, blank=True) anotacoes = models.TextField(null=True, blank=True) horario = models.ForeignKey(Horario, null=True, blank=True, on_delete=models.CASCADE) # Deixei assim, mas depois tenho que mudar def __str__(self): return str(self.id) class ConsultaForm(forms.ModelForm): class Meta: model = Consulta fields ="__all__" class Teste(models.Model): fone = models.CharField(max_length=255) class Evolucao(models.Model): profissional = models.ForeignKey(Profissional, on_delete=models.CASCADE) anotacoes = models.TextField() paciente = models.ForeignKey(paciente, on_delete=models.CASCADE) anotacaoconsulta = models.ForeignKey(Consulta, on_delete=models.CASCADE, null=True, blank=True) ultimaatualizacao = models.DateTimeField() <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-22 12:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0022_auto_20170321_2236'), ] operations = [ migrations.RemoveField( model_name='horario', name='diasemana', ), migrations.RemoveField( model_name='horario', name='horafim', ), migrations.RemoveField( model_name='horario', name='horainicio', ), migrations.RemoveField( model_name='horario', name='periodo', ), migrations.AddField( model_name='horario', name='horafimM', field=models.TimeField(blank=True, null=True), ), migrations.AddField( model_name='horario', name='horafimT', field=models.TimeField(blank=True, null=True), ), migrations.AddField( model_name='horario', name='horainicioM', field=models.TimeField(blank=True, null=True), ), migrations.AddField( model_name='horario', name='horainicioT', field=models.TimeField(blank=True, null=True), ), migrations.AddField( model_name='horario', name='quartaM', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='quartaT', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='quintaM', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='quintaT', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='segundaM', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='segundaT', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='sextaM', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='sextaT', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='tercaM', field=models.BooleanField(default=False), ), migrations.AddField( model_name='horario', name='tercaT', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='horario', name='validadefim', field=models.DateField(auto_now_add=True, null=True), ), migrations.AlterField( model_name='horario', name='validadeinicio', field=models.DateField(auto_now_add=True, null=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-12 16:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='paciente', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=255)), ('numsus', models.IntegerField()), ('endereco', models.CharField(max_length=255)), ('pontoreferencia', models.CharField(max_length=255)), ('bairro', models.CharField(max_length=100)), ('cidade', models.CharField(max_length=255)), ('fone', models.CharField(max_length=14)), ('certidao', models.CharField(choices=[('nasc', 'Nascimento'), ('casa', 'Casamento'), ('divo', 'Divórcio')], max_length=3)), ('livro', models.CharField(max_length=100)), ('fls', models.CharField(max_length=100)), ('termo', models.CharField(max_length=100)), ('dataemissao', models.DateField()), ('datanascimento', models.DateField()), ('rg', models.CharField(max_length=50)), ('rgorgemissor', models.CharField(max_length=255)), ('rguf', models.CharField(max_length=2)), ('rgdataemissao', models.DateField()), ('cpf', models.CharField(max_length=15)), ('apelido', models.CharField(max_length=255)), ('nomepai', models.CharField(max_length=255)), ('nomemae', models.CharField(max_length=255)), ('nomeresponsavel', models.CharField(max_length=255)), ('festratamento', models.CharField(max_length=255)), ('encaminhadopor', models.CharField(max_length=255)), ], ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-21 16:50 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0018_auto_20170321_1346'), ] operations = [ migrations.AlterField( model_name='paciente', name='dataemissao', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='paciente', name='fls', field=models.CharField(blank=True, default='', max_length=100, null=True), ), migrations.AlterField( model_name='paciente', name='fone', field=models.CharField(blank=True, default='', max_length=16, null=True), ), migrations.AlterField( model_name='paciente', name='fonefixo', field=models.CharField(blank=True, default='', max_length=15, null=True), ), migrations.AlterField( model_name='paciente', name='livro', field=models.CharField(blank=True, default='', max_length=100, null=True), ), migrations.AlterField( model_name='paciente', name='pontoreferencia', field=models.CharField(blank=True, default='', max_length=255, null=True), ), migrations.AlterField( model_name='paciente', name='termo', field=models.CharField(blank=True, default='', max_length=100, null=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-01 18:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0028_auto_20170501_1731'), ] operations = [ migrations.AddField( model_name='consulta', name='anotacoes', field=models.TextField(blank=True, null=True), ), migrations.AlterField( model_name='consulta', name='status', field=models.CharField(blank=True, choices=[('pend', 'Pendente'), ('des', 'Desistir'), ('rem', 'Remarcar'), ('falt', 'Faltou'), ('conc', 'Concluído')], default='pend', max_length=50, null=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-21 22:36 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('caps', '0021_auto_20170321_2227'), ] operations = [ migrations.AlterField( model_name='horario', name='validadefim', field=models.DateField(default=datetime.datetime(2017, 3, 21, 22, 36, 11, 994055, tzinfo=utc)), ), migrations.AlterField( model_name='horario', name='validadeinicio', field=models.DateField(default=datetime.datetime(2017, 3, 21, 22, 36, 11, 994030, tzinfo=utc)), ), ] <file_sep># Generated by Django 2.0 on 2018-01-02 12:41 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('caps', '0032_auto_20170525_1736'), ] operations = [ migrations.AddField( model_name='profissional', name='user', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='profissional', name='nome', field=models.CharField(blank=True, max_length=255, null=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-13 18:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0012_paciente_psicoterapeuta'), ] operations = [ migrations.AlterField( model_name='paciente', name='nomeresponsavel', field=models.CharField(blank=True, default='', max_length=255, null=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-12 16:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0001_initial'), ] operations = [ migrations.AlterField( model_name='paciente', name='certidao', field=models.CharField(choices=[('nas', 'Nascimento'), ('cas', 'Casamento'), ('div', 'Divórcio')], max_length=3), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-20 16:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0030_consulta_horario'), ] operations = [ migrations.AddField( model_name='paciente', name='nprontuario', field=models.CharField(blank=True, default='', max_length=255, null=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-25 21:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('caps', '0023_auto_20170322_1211'), ] operations = [ migrations.CreateModel( name='Consulta', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('data', models.DateTimeField()), ('paciente', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='caps.paciente')), ], ), migrations.AddField( model_name='profissional', name='quantmaxconsulta', field=models.IntegerField(blank=True, max_length=5, null=True), ), migrations.AlterField( model_name='horario', name='validadefim', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='horario', name='validadeinicio', field=models.DateField(blank=True, null=True), ), migrations.AddField( model_name='consulta', name='profissional', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='caps.Profissional'), ), ] <file_sep># Generated by Django 2.0 on 2018-01-03 15:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('caps', '0033_auto_20180102_1241'), ] operations = [ migrations.CreateModel( name='Evolucao', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('anotacoes', models.TextField()), ('ultimaatualizacao', models.DateTimeField()), ('anotacaoconsulta', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='caps.Consulta')), ('paciente', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='caps.paciente')), ('profissional', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='caps.Profissional')), ], ), ] <file_sep>usuario: admin senha: <PASSWORD> Upload de relatórios do caps: - Documentos relat.- 1 para a equipe - Relatorio por periodo inicial e final -- upload de receitas emitidas pelos profs. - 1 por prof. -- Evolução Relatório de consultas por paciente - Consultas realizadas -- histórico - OK - Data, horário, profissional, especialidade e se foi receitado algum medicamento <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11b1 on 2017-03-12 23:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('caps', '0009_paciente_terapeutaocupacional'), ] operations = [ migrations.RemoveField( model_name='paciente', name='assistentesocial', ), migrations.RemoveField( model_name='paciente', name='avaliacaopsiquiatrica', ), migrations.RemoveField( model_name='paciente', name='enfermagem', ), migrations.RemoveField( model_name='paciente', name='entregadedocumentos', ), migrations.RemoveField( model_name='paciente', name='fisioterapeuta', ), migrations.RemoveField( model_name='paciente', name='psicologa', ), migrations.RemoveField( model_name='paciente', name='terapeutaocupacional', ), ] <file_sep>{% extends "base2.html" %} {% load material_form %} {% block conteudo %} <div style="max-width: 600px;"> <form method="POST" action=""> {% ifequal action "" %} <h3>Novo registro</h3> {% else %} <h3>Editar</h3> {% endifequal %} {% csrf_token %} <div style="color: red"> <ol> {% for erro in form.errors %} <li>{{ erro }}</li> {% endfor %} </ol> </div> <input type="hidden" value="{{ id }}" name="id" /> {% form form=form %}{% endform %} <input type="submit" class="btn" value="Salvar" /> </form> </div> {% endblock %} <file_sep>Django==2.0 django-filter==1.1.0 django-input-mask==2.0.2 django-localflavor==2.0 django-localflavor-br==1.0 django-material==1.2.0 django-viewflow==1.2.0 olefile==0.44 Pillow==4.3.0 pytz==2017.3 reportlab==3.4.0 six==1.11.0 <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11b1 on 2017-03-12 20:48 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0003_auto_20170312_1954'), ] operations = [ migrations.AlterField( model_name='paciente', name='encaminhadopor', field=models.CharField(default='', max_length=255, null=True), ), migrations.AlterField( model_name='paciente', name='festratamento', field=models.CharField(choices=[('NAO', 'NÃO'), ('SIM', 'SIM')], max_length=255), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11b1 on 2017-03-12 23:42 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0010_auto_20170312_2337'), ] operations = [ migrations.AddField( model_name='paciente', name='assistentesocial', field=models.BooleanField(default=False), ), migrations.AddField( model_name='paciente', name='avaliacaopsiquiatrica', field=models.BooleanField(default=False), ), migrations.AddField( model_name='paciente', name='enfermagem', field=models.BooleanField(default=False), ), migrations.AddField( model_name='paciente', name='entregadedocumentos', field=models.BooleanField(default=False), ), migrations.AddField( model_name='paciente', name='fisioterapeuta', field=models.BooleanField(default=False), ), migrations.AddField( model_name='paciente', name='psicologa', field=models.BooleanField(default=False), ), migrations.AddField( model_name='paciente', name='terapeutaocupacional', field=models.BooleanField(default=False), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-25 22:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0025_auto_20170325_2155'), ] operations = [ migrations.AddField( model_name='profissional', name='disponivel', field=models.BooleanField(default=False), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-10 11:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0026_profissional_disponivel'), ] operations = [ migrations.AddField( model_name='consulta', name='hora', field=models.TimeField(blank=True, null=True), ), migrations.AddField( model_name='consulta', name='periodo', field=models.CharField(blank=True, choices=[('mat', 'Matutino'), ('ves', 'Vespertino')], max_length=50, null=True), ), migrations.AlterField( model_name='consulta', name='data', field=models.DateField(), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-21 13:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0017_auto_20170321_1337'), ] operations = [ migrations.AlterField( model_name='paciente', name='numsus', field=models.CharField(max_length=255), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-21 22:21 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('caps', '0019_auto_20170321_1650'), ] operations = [ migrations.CreateModel( name='Horario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('diasemana', models.IntegerField()), ('periodo', models.IntegerField(choices=[(1, 'Matutino'), (2, 'Vespertino')])), ('horainicio', models.TimeField()), ('horafim', models.TimeField()), ], ), migrations.CreateModel( name='Profissional', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=255)), ('especialidade', models.CharField(choices=[('psiq', 'Psiquiatra'), ('psic', 'Psicólogo(a)'), ('enferm', 'Enfermeiro(a)'), ('psicoterap', 'Psicoterapeuta'), ('assissoc', 'Assistente social'), ('fisioterap', 'Fisioterapeuta'), ('terapocup', 'Terapeuta ocupacional')], max_length=255)), ], ), migrations.AddField( model_name='horario', name='profissional', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='caps.Profissional'), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-25 21:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0024_auto_20170325_2154'), ] operations = [ migrations.AlterField( model_name='profissional', name='quantmaxconsulta', field=models.IntegerField(blank=True, null=True), ), ] <file_sep>from django.shortcuts import render from reportlab.pdfgen import canvas from django.http import HttpResponse # Create your views here. from django.contrib.auth.decorators import login_required from reportlab.lib import colors from django.db.models import Q import time from datetime import date, timedelta from reportlab.lib.enums import TA_JUSTIFY, TA_CENTER, TA_RIGHT, TA_LEFT from reportlab.lib.pagesizes import letter, A4 from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Frame, PageTemplate from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) from .models import paciente from io import BytesIO import datetime from reportlab.platypus import SimpleDocTemplate, Table, TableStyle from reportlab.platypus.flowables import Spacer, HRFlowable, PageBreak, CondPageBreak from reportlab.lib.units import cm from django.contrib.auth import authenticate, login, logout from django.shortcuts import render import json from django.http import JsonResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.shortcuts import redirect from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.models import User @login_required def gerarFicha(request, id): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') nomearquivo="ficha"+datetime.date.today().strftime("%d/%m/%Y")+".pdf" response['Content-Disposition'] = 'filename="'+nomearquivo+'"' # attachment; filename= buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=72) Story = [] logo = os.path.join(BASE_DIR,"logopref.png") im = Image(logo, 0.7 * inch, 0.7 * inch) Story.append(im) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT)) styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT)) p = paciente.objects.get(pk=id) ptext = "PREFEITURA DE BARRA DO GARÇAS<br/>" ptext += "SECRETARIA MUNICIPAL DE SAÚDE<br/>" ptext += "Centro de Atenção Psicossoail CAPS II TM<br/><br/>" ptext += "<br/>IMPORTANTE -- Cartão SUS nº: "+str( p.numsus ) ptext += "<br/><br/><br/>FICHA DE ACOLHIMENTO<br/><br/><br/><br/>" Story.append(Paragraph(ptext, styles["Center"])) try: ptext = "Número do prontuário: "+p.nprontuario except: ptext = "Número do prontuário: " ptext += "<br/>Nome: "+p.nome try: ptext +="<br/>Endereço: "+ p.get_tipoendereco_display()+" "+p.logradouro+", n° "+p.logradouronum except: pass try: ptext +="<br />Ponto de referência: "+p.pontoreferencia except: pass try: ptext +="<br />Bairro: "+p.bairro except: pass try: ptext += " Cidade: "+p.cidade except: pass try: ptext +=" Fone: " + p.fone except: ptext += " Fone: " pass try: ptext +="<br />Certidão de: " + p.get_certidao_display() except: ptext += "<br />Certidão de: " pass try: ptext +=" Livro: " + p.livro except: ptext += " Livro: " pass try: ptext += " Folha: " +p.fls except: ptext += " Folha: " pass try: ptext += "<br/>Termo: "+p.termo except: ptext += "<br/>Termo: " try: ptext +=" Data de emissão: "+ p.dataemissao.isoformat().capitalize() except: ptext += " Data de emissão: " try: ptext += " Data de nascimento: " + p.datanascimento.isoformat().capitalize() except: ptext += " Data de nascimento: " try: ptext += " RG: "+p.rg except: ptext += " RG: " try: ptext += " Orgão emissor: "+ p.get_rgorgemissor_display() except: ptext += " Orgão emissor: " try: ptext += " UF: " + p.rguf except: ptext += " UF: " try: ptext += " Data de emissão: " + p.rgdataemissao.isoformat().capitalize() except: ptext += " Data de emissão: " try: ptext += "<br />CPF: " + p.cpf except: ptext += "<br />CPF: " try: ptext += "<br/>Apelido: " + p.apelido except: ptext += "<br/>Apelido: " try: ptext += "<br/>Nome do pai: " + p.nomepai except: ptext += "<br/>Nome do pai: " try: ptext += "<br/>Nome da mãe: " + p.nomemae except: ptext += "<br/>Nome da mãe: " try: ptext += "<br/>Nome do responsável: " + p.nomeresponsavel except: ptext += "<br/>Nome do responsável: " try: ptext += "<br/>Já fez tratamento anteriormente? " + p.get_festratamento_display() except: ptext += "<br/>Já fez tratamento anteriormente? " try: ptext += "<br/>Encaminhado por: " + p.encaminhadopor except: ptext += "<br/>Encaminhado por: " Story.append(Paragraph(ptext, styles["Justify"])) today = datetime.date.today() ptext = "Barra do Garças-MT, " + today.strftime("%d/%m/%Y")+".<br/><br/><br/> <br/><br/><br/>" Story.append(Paragraph(ptext, styles["Right"])) ptext="_____________________________________________" ptext+="<br/>Responsável pelo acolhimento<br /><br />" Story.append(Paragraph(ptext, styles["Center"])) Story.append(Paragraph("", styles["Left"])) steps=[] if p.entregadedocumentos: steps.append("X") else: steps.append("") if p.avaliacaopsiquiatrica: steps.append("X") else: steps.append("") # if p.enfermagem: steps.append("X") else: steps.append("") if p.psicologa: steps.append("X") else: steps.append("") # if p.psicoterapeuta: # steps.append("X") # else: # steps.append("") if p.assistentesocial: steps.append("X") else: steps.append("") if p.fisioterapeuta: steps.append("X") else: steps.append("") # if p.terapeutaocupacional: # steps.append("X") # else: # steps.append("") # Passos cumpridos data = [[steps[0], 'Entrega de documentos'], [steps[1], 'Avaliação psiquiátrica'], [steps[2], 'Enfermagem'], [steps[3], 'Psicóloga'], # [steps[4], 'Psicoterapeuta'], [steps[4], 'Assistente social'], [steps[5], 'Fisioterapeuta'], # [steps[7], 'Terapeuta ocupacional'], ] t = Table(data, hAlign='LEFT') t.setStyle(TableStyle([ ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),])) Story.append(t) Story.append(Paragraph("<br/><br/>", styles["Center"])) Story.extend([Spacer(0, 0.1*cm), HRFlowable(width="100%", thickness=0.5, color=colors.black), Spacer(0,0.1*cm)]) ptext = "<NAME>, 1470, <NAME>. CEP 78.600-000 - Barra do Garças-MT<br/>" ptext += "Tel.: (66) 3401-7805" Story.append(Paragraph(ptext, styles["Center"])) doc.build(Story) response.write(buff.getvalue()) buff.close() return response @login_required def gerarRelatorio(request): # Se for informado algo será considerado pcr="t" try: pcr = request.GET['pcr'] pcrq = paciente.objects.get(pk=int(pcr)) except: pcr="t" Story = [] styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT)) styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT)) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') nomearquivo="relatorio"+datetime.date.today().strftime("%d/%m/%Y")+".pdf" response['Content-Disposition'] = 'filename="'+nomearquivo+'"' # attachment; filename= buff = BytesIO() styleN = styles['Normal'] def footer(canvas, doc): canvas.saveState() P = Paragraph("<hr/><br/>Rua <NAME>, 1470, <NAME>. CEP 78.600-000 - Barra do Garças-MT <br/>Tel.: (66) 3401-7805 " , styles["Center"]) w, h = P.wrap(doc.width, doc.bottomMargin) P.drawOn(canvas, doc.leftMargin, h) canvas.line(doc.leftMargin, 62, doc.width+67, 62) logo = os.path.join(BASE_DIR, "logopref.png") im = Image(logo, 0.7 * inch, 0.7 * inch) h = im.imageHeight w = im.imageWidth c = w/2 ch = h/2 print("Width: ", w) print("Height: ", h) print("c: ", c) print("ch: ", ch) print("Doc width: ", doc.width) print("LeftM width: ", doc.leftMargin) print("Centro: ", (doc.width/2)+c-37) im.drawOn(canvas, (doc.width/2)+c-(doc.leftMargin/2), doc.height + doc.topMargin-5) # # header = Paragraph(im, styles['Center']) # w, h = header.wrap(doc.width, doc.topMargin) # header.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - h) # ptext = "<br/>PREFEITURA DE BARRA DO GARÇAS<br/>" ptext += "SECRETARIA MUNICIPAL DE SAÚDE<br/>" ptext += "Centro de Atenção Psicossoail CAPS II TM<br/><br/>" header = Paragraph(ptext, styles['Center']) w, h = header.wrap(doc.width, doc.topMargin) header.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - h) canvas.restoreState() doc = SimpleDocTemplate(buff, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=135, bottomMargin=72, ) frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal') template = PageTemplate(id='test', frames=frame, onPage=footer) doc.addPageTemplates([template]) ptext = "<b>RELATÓRIO</b><br/> <br/>" if pcr == "t": datainicialr = request.GET['datainicialr'] datafinalr = request.GET['datafinalr'] datainicialrt = datetime.datetime.strptime(datainicialr, '%Y-%m-%d') datafinalrt = datetime.datetime.strptime(datafinalr, '%Y-%m-%d') Story.append(Paragraph(ptext, styles["Center"])) ptext = "<b>Relatório gerado no dia </b> "+datetime.date.today().strftime("%d/%m/%Y")+"<br/>" if pcr == "t": ptext += "<b>Data inicial: </b> "+datainicialrt.strftime("%d/%m/%Y")+"<br/>" else: ptext +="<b>Paciente: </b> "+pcrq.nome+"<br/><br/>" l = "" tadd="" try: l = request.GET['lista'] if l == 't': tadd = "" else: profl = Profissional.objects.get(pk=int(l)) tadd = " <br/><b>Profissional:</b> " + profl.user.get_full_name() tadd += " <br/><b>Especialidade:</b> " + profl.get_especialidade_display() except: print("Erro lista : ", tadd) # tadd = "" if pcr == "t": ptext += " <b>Data final:</b> "+datafinalrt.strftime("%d/%m/%Y") +tadd+" <br/><br/>" Story.append(Paragraph(ptext, styles["Left"])) datatable = [] evolucao = [] # consultasInt = Consulta.objects.filter(data__gte=datafinalr).filter(data__lte=datainicialr) if pcr == "t": consultasInt = Consulta.objects.filter(data__lte=datafinalr).filter(data__gte=datainicialr).filter(status='conc').order_by("data") # em = Horario.objects.filter(profissional_id__exact=hora.profissional.id).filter( # validadefim__gte=hora.validadeinicio).filter( # validadeinicio__lte=hora.validadeinicio).exclude(id=hora.id) try: l = request.GET['lista'] if l != 't': profl = Profissional.objects.get(pk=int(l)) consultasInt = consultasInt.filter(profissional=profl) except: pass print('quantidade de consultasInt:', len(consultasInt)) else: consultasInt = Consulta.objects.filter(paciente=pcrq).filter(status='conc').order_by("data") cont=1 if l == 't': datatable.append(['Num','Data', 'Hora', 'Nome', 'Especialidade','Paciente']) else: if pcr == 't': datatable.append(['Num', 'Data', 'Hora', 'Paciente']) # Relatório de um profissional else: datatable.append(['Num', 'Data', 'Hora', 'Nome', 'Especialidade']) # De um paciente em específico evolucao.append(['Profissional', 'Anotações']) for con in consultasInt: if l == 't': datatable.append([cont, con.data.strftime("%d/%m/%Y"), con.hora, Paragraph(con.profissional.user.get_full_name(),styles["Left"]) , con.profissional.get_especialidade_display(), Paragraph(con.paciente.nome,styles["Left"])]) else: if pcr == 't': datatable.append([cont, con.data.strftime("%d/%m/%Y"), con.hora, Paragraph(con.paciente.nome, styles["Left"])]) else: datatable.append([cont, con.data.strftime("%d/%m/%Y"), con.hora, Paragraph(con.profissional.user.get_full_name(), styles["Left"]), con.profissional.get_especialidade_display() ]) cont += 1 from reportlab.lib.units import mm if(len(consultasInt) >= 1): if l == 't': t = Table(datatable, colWidths=(10*mm, 22*mm, 20*mm, 50*mm, 50*mm, 50*mm)) else: if pcr == "t": t = Table(datatable, colWidths=(10 * mm, 22 * mm, 20 * mm, 100 * mm)) else: t = Table(datatable, colWidths=(10 * mm, 22 * mm, 20 * mm, 50 * mm, 53 * mm)) # t.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) Story.append(t) else: print("Não há registros de consulta") try: pc = paciente.objects.get(pk=pcr) print("Oi4", pc.nome) evData = Evolucao.objects.all().filter(paciente=pc) print("Oi1") # evolucao.append(['Profissional', 'Anotações']) for ev in evData: text = Paragraph(ev.anotacoes.replace("\n", "<br/>"), styles["Justify"]) esp = Paragraph(ev.profissional.get_especialidade_display()+": "+ev.profissional.user.get_full_name()+" -- dia: "+ev.ultimaatualizacao.strftime("%d/%m/%Y"), styles["Left"]) evolucao.append([esp, text ]) print("Oi2 ", len(evData)) t2 = Table(evolucao, colWidths=((10+22+20) * mm, (50+53) * mm)) print('oi3333') # t2.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) Story.append(Paragraph("<br/><br/>", styles['Left'])) Story.append(t2) except: print('Não há registros de evolução') doc.build(Story) response.write(buff.getvalue()) buff.close() return response def viewFotos(request): return HttpResponse("Olamundo") def home(request): return render(request, 'base2.html') def loginform(request): return render(request, "login/login.html") def sair(request): logout(request) return redirect("/login/") from django.core import serializers @staff_member_required @login_required def pacientecad(request): return render(request, "paciente.html") from .formularios import * @staff_member_required @login_required def cadastrapaciente(request): if request.method == "POST": data = json.loads(request.body.decode("utf-8")) form = PacientForm(data) if form.is_valid(): form.save() return JsonResponse({'resp': 1}) return JsonResponse({'resp': -1}) @login_required def home2(request): return render(request, "base2.html") @staff_member_required @login_required def pacienteman(request): form = PacientForm() pc = paciente() er = None id = "" if request.method == "POST": form = PacientForm(request.POST or None, request.FILES or None) if form.is_valid(): id = request.POST['id'] print("Id passado: ", id) if id == "": form.save() else: pc = form.save(commit=False) pc.id = int(id) pcOld = paciente.objects.get(pk=int(pc.id)) try: foto = request.FILES['foto'] pc.foto = foto except: pc.foto = pcOld.foto print("ID: ", pc.id) pc.save() print("formulario salvo") return redirect("/pacientelist?page=0") else: er = 1 print("Form: ", form.errors) else: pacienteid = request.GET['pacienteid'] if int(pacienteid) != 0: pc = paciente.objects.get(pk=int(pacienteid)) id = pc.id form = PacientForm(instance=pc) else: form = PacientForm() print("Ok form") return render(request, "pacienteman.html", { 'formulario': form, 'foto': pc.foto, 'er': er, 'id': id}) @staff_member_required @login_required def pacienterem(request): idr = request.GET['idr'] pc = paciente.objects.get(pk=idr) pc.delete() return redirect("/pacientelist?page=0") @login_required def pacientelist(request): novaconsulta = 0 try: # novaconsulta = request.GET['novaconsulta'] profid = request.GET['profid'] periodo = request.GET['periodo'] data = request.GET['data'] except: novaconsulta = 0 profid = 0 periodo = 0 data=0 pesquisa = 0 if request.method == "POST": pesquisa = request.POST['pesquisa'] pacientes = paciente.objects.filter(nome__contains=pesquisa) else: pacientes = paciente.objects.all() paginator = Paginator(pacientes, 8) numpages = list(range(1, paginator.num_pages+1)) page = request.GET['page'] print("Página: ", page) atual = 1 try: pcientes = paginator.page(page) atual = int(page) except PageNotAnInteger: # If page is not an integer, deliver first page. pcientes = paginator.page(1) # data = serializers.serialize('json', pcientes) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. pcientes = paginator.page(paginator.num_pages) # data = serializers.serialize('json', pcientes) return render(request, "page.html", { 'pacientes': pcientes, 'numpages': numpages, 'atual': atual, 'fim': paginator.num_pages, 'novaconsulta': novaconsulta, # Só aparece se for para agendar uma nova consulta 'profid': profid, # idem anterior 'periodo': periodo, 'data': data, }) # return JsonResponse(data) # @ @login_required def evolucaopacientes(request): if request.POST: id = request.POST['id'] anotacoes = request.POST['anotacoes'] pc = request.POST['paciente'] anotacaoconsulta = request.POST['anotacaoconsulta'] try: anot = Evolucao.objects.get(pk=id) except: anot = Evolucao() prof = Profissional.objects.get(user=request.user) anot.profissional = prof anot.anotacoes = anotacoes anot.paciente = paciente.objects.get(pk=pc) anot.anotacaoconsulta = Consulta.objects.get(pk=anotacaoconsulta) anot.ultimaatualizacao = datetime.datetime.now() anot.save() evolucaoPage = Evolucao.objects.all().order_by('-ultimaatualizacao') try: pacienteid = request.GET['pacienteid'] pc = paciente.objects.get(pk=pacienteid) evolucaoPage = evolucaoPage.filter(paciente=pc) except: print('Sem paciente id ') paginator = Paginator(evolucaoPage, 8) numpages = list(range(1, paginator.num_pages+1)) # Se nada for fornecido try: page = request.GET['page'] except: page=0 atual = 1 try: evolucaoPage = paginator.page(page) atual = int(page) except PageNotAnInteger: # If page is not an integer, deliver first page. evolucaoPage = paginator.page(1) # data = serializers.serialize('json', pcientes) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. evolucaoPage = paginator.page(paginator.num_pages) return render(request, "evolucaopacientes.html", {'evolucaoanot': evolucaoPage, 'atual': atual, 'fim': paginator.num_pages}) def getAnotacao(consulta): try: evolucao = Evolucao.objects.get(anotacaoconsulta=consulta.id) print('Evoluação: ', evolucao.id) except: # Novo evolucao = {'id': -1, 'profissional': consulta.profissional.id, 'anotacoes':'', 'paciente': consulta.paciente.id, 'anotacaoconsulta': consulta.id, 'ultimaatualizacao': datetime.datetime.now() } return evolucao @login_required def minhasconsultas(request): # configuração e instalação de computadores prof = None # print("Usuário: ", request.user) user = User.objects.get(username=str(request.user)) if not user.is_staff: prof = Profissional.objects.get(user=request.user) if request.POST: id = request.POST['id'] anotacoes = request.POST['anotacoes'] pc = request.POST['paciente'] anotacaoconsulta = request.POST['anotacaoconsulta'] try: anot = Evolucao.objects.get(pk=id) except: anot = Evolucao() anot.profissional = prof anot.anotacoes = anotacoes anot.paciente = paciente.objects.get(pk=pc) anot.anotacaoconsulta = Consulta.objects.get(pk=anotacaoconsulta) anot.ultimaatualizacao = datetime.datetime.now() anot.save() print("Profissional: ", prof.user.get_full_name()) # data = datetime.date.today() # # # Pega todos os gets args e monta o form idpaciente = 0 pacientenome = "" profissional = "" datacad = "" periodo = "" lastid = "" trab = [] # Tenta pegar de uma só data try: datacon = request.GET['data'] try: lastid = request.GET['lastid'] except: lastid = "" # às vezes o algoritmo pode ser ser referenciado sem o ID try: datacadpy = datetime.datetime.strptime(datacon, '%d/%m/%Y') except: datacadpy = datetime.datetime.strptime(datacon, '%Y-%m-%d') consultasList = Consulta.objects.filter(data=datacadpy, profissional=prof) data = datacadpy print("Data: ", datacon) except Exception as e: print("Erro: ", e) consultasList = Consulta.objects.filter(data=data, profissional=prof) print("Quantidade: ", len(consultasList)) p = [] # Verifica se o profissional tem horario na data especificada horario = Horario.objects.filter(profissional=prof).filter( validadeinicio__lte=data).filter(validadefim__gte=data) if (len(horario) > 0): # Pega somente o primeiro hr = horario[0] print("Dia da semana: ", data.isoweekday()) # Segunda manha = 0 tarde = 0 if (data.isoweekday() == 1): if (hr.segundaM == True): manha = 1 if (hr.segundaT == True): tarde = 1 elif (data.isoweekday() == 2): if (hr.tercaM == True): manha = 1 if (hr.tercaT == True): tarde = 1 elif (data.isoweekday() == 3): if (hr.quartaM == True): manha = 1 if (hr.quartaT == True): tarde = 1 elif (data.isoweekday() == 4): if (hr.quintaM == True): manha = 1 if (hr.quintaT == True): tarde = 1 elif (data.isoweekday() == 5): if (hr.sextaM == True): manha = 1 if (hr.sextaT == True): tarde = 1 trab.append( [prof.id, manha, tarde]) # zero não tem espediente e 1 tem -- primeiro é cedo e o outro é de tarde p.append(prof) print("prof nome: ", prof.user.get_full_name()) # Fica so quem tem horario profs = p dictConsultas = [] for c in consultasList: dc = {} dc['cs'] = c # print("Nome: ", c.paciente.nome ) dc['anot'] = getAnotacao(c) dictConsultas.append(dc) print("Tam: ", len(dictConsultas)) return render(request, "minhasconsultas.html", {'profs': profs, 'data': data, 'trab': trab, # Dadoslastid do formulário de cadastro 'idpaciente': idpaciente, 'pacientenome': pacientenome, 'profissional': profissional, 'datacad': datacad, # 'cad': cad, 'consultasList': dictConsultas, 'lastid': lastid, 'periodo': periodo}) # return render(request, "minhasconsultas.html") def logar(request): form = UsuarioForm() erro="" if request.method == "POST": usuario = request.POST['usuario'] senha = request.POST['senha'] user = authenticate(username=usuario, password=<PASSWORD>) if user is not None: login(request, user) return redirect("/") else: erro = "Usuário ou senha estão incorretos" return render(request, "logar.html", { 'form': form, 'erro': erro }) # # @login_required # def userMan(request): # # form = UserForm() # # return render(request, 'criarusuario.html', {'form': form}) # Horário de cada profissional do caps @staff_member_required @login_required def horarioMaker(request): if request.method == "GET": idprof = request.GET['profid'] prof = Profissional.objects.get(pk=int(idprof)) return render(request, "horario.html", {'prof': prof}) # Horário de cada profissional do caps @staff_member_required @login_required def profissionais(request): form = ProfissionalForm() er="" id=0 action="" if request.method == "POST": form = ProfissionalForm(request.POST) if form.is_valid(): id = int(request.POST['id']) if id == 0: print("Opção 1") pc = form.save(commit=False) pc.id = None pc.save() else: pc = form.save(commit=False) pc.id = id print("Opção 2") print("ID: ", pc.id) pc.save() return redirect("/cadprofissionais") else: er = 1 print("Form: ", form.errors) else: try: id = int(request.GET['profid']) if id != 0: prof = Profissional.objects.get(pk=int(id)) action="editar" print("Encontrei o professor: ", prof.nome) form = ProfissionalForm(instance=prof) except: pass return render(request, "profissionais.html", {"form": form, 'er': er, 'id': id, 'action': action }) @staff_member_required @login_required def profissionaislist(request): if request.method =="POST": pesq = request.POST['pesquisa'] profs = Profissional.objects.filter(nome__contains=pesq) else: profs = Profissional.objects.all() return render(request, "profissionaislist.html", {"profs": profs}) @staff_member_required @login_required def remConsulta(request): try: id = request.POST['id'] resp = {} consulta = Consulta.objects.get(pk=int(id)) resp['lastid'] = consulta.profissional_id consulta.delete() return JsonResponse(resp) except: return HttpResponse(-1) @staff_member_required @login_required def newhorario(request): form = HorarioForm() erro = "" prof = "Horário de " hora = Horario() try: idhorario = int(request.GET['idhorario']) except: idhorario=0 try: idprof = int(request.GET['idprof']) p = Profissional.objects.get(pk=idprof) hora.profissional = p except: return HttpResponse("Forneça os parâmetros de maneira correta!!!!<br />") if request.method == "POST": form = HorarioForm(request.POST) if form.is_valid(): #Id do horario id = request.POST['id'] if id is not None and id != "None": hora = form.save(commit=False) validadeinicio = request.POST['validadeinicio'] validadefim = request.POST['validadefim'] validadeinicio = datetime.datetime.strptime(validadeinicio, '%d/%m/%Y') validadefim = datetime.datetime.strptime(validadefim, '%d/%m/%Y') hora.validadeinicio = validadeinicio.date() hora.validadefim = validadefim.date() # print("Data inicio: ", validadeinicio) # print("Data fim: ", validadefim) # print("ID: ", id) hora.id = int(id) # print("Opção 2") # print("ID: ", pc.id) # Valida o salvamento dos itens # Caso jatem retorn uma lista maior que 0, o funcionário já tem um paciente jatem = Horario.objects.filter(profissional_id__exact=hora.profissional.id).filter( validadefim__gte=hora.validadeinicio).filter( validadeinicio__lte=hora.validadeinicio).exclude(id=hora.id) # Não pode estar no intervalo: hora.validadefim <=validadefim and hora.validadeinicio>=validadeinicio>= jatem2 = Horario.objects.filter(profissional_id__exact=hora.profissional.id).filter( validadefim__gte=hora.validadefim).filter( validadeinicio__lte=hora.validadefim).exclude(id=hora.id) # print("Hora fim: ", hora.validadefim) # print("Hora inicio query: ", jatem2[0].validadeinicio) print("jatem1: ", len(jatem)) print("jatem2: ", len(jatem2)) if len(jatem) == 0 and len(jatem2) == 0 and hora.validadefim >= hora.validadeinicio: hora.save() else: erro = "Atenção, já um horário no período especificado. " if hora.validadefim < hora.validadeinicio: erro += " A data de fim deve ser superior ao do início. " else: hora = form.save(commit=False) validadeinicio = request.POST['validadeinicio'] validadefim = request.POST['validadefim'] hora.id = None # # print("Data inicio Passado: ", validadeinicio) # print("Data inicio Passado: ", validadefim) hora.validadeinicio = datetime.datetime.strptime(validadeinicio, '%d/%m/%Y').date() hora.validadefim = datetime.datetime.strptime(validadefim, '%d/%m/%Y').date() # print("Data inicio Passado2: ", pc.validadeinicio) # print("Data inicio Passado2: ", pc.validadefim) # Não pode estar no intervalo: hora.validadeinicio <=validadefim and validadeinicio>=hora.validadeinicio jatem = Horario.objects.filter(profissional_id__exact=hora.profissional.id).filter( validadefim__gte=hora.validadeinicio).filter( validadeinicio__lte=hora.validadeinicio).exclude(id=hora.id) # Não pode estar no intervalo: hora.validadefim <=validadefim and hora.validadeinicio>=validadeinicio>= jatem2 = Horario.objects.filter(profissional_id__exact=hora.profissional.id).filter( validadefim__gte=hora.validadefim).filter( validadeinicio__lte=hora.validadefim).exclude(id=hora.id) # print("Hora fim: ", hora.validadefim) # print("Hora inicio query: ", jatem2[0].validadeinicio) print("jatem1: ", len(jatem)) print("jatem2: ", len(jatem2)) if len(jatem) == 0 and len(jatem2) == 0 and hora.validadefim >= hora.validadeinicio: hora.save() else: erro = "Atenção, já um horário no período especificado." if hora.validadefim <= hora.validadeinicio: erro += " A data de fim deve ser superior ao do início." # if hora.horainicioM > hora.horafimM: # erro += " Hora início matutino é maior que a hora fim." # # if hora.horainicioT > hora.horafimT: # erro += " Hora início da tarde é maior que a hora fim." # else: erro="Erro diversos" print("Dados não válidos", form.errors) if erro == "": print("idprof: ", idprof) return redirect("/horariolist?idprof="+str(idprof)) else: prof += hora.profissional.user.get_full_name() if idhorario ==0: prof += " - Novo" if idhorario > 0 and erro == "": hora = Horario.objects.get(pk=idhorario) form = HorarioForm(instance=hora) prof += hora.profissional.user.get_full_name() if idhorario==0 and erro == "": p = Profissional.objects.get(pk=idprof) p.nome = "" prof += p.user.get_full_name() + " - Novo" return render(request, "newhorario.html", {'form': form, 'hora': hora, 'prof': prof, 'profid': idprof, 'erro': erro } ) # return render(request, 'testeform.html', {'form': form}) @staff_member_required @login_required def horariolist(request): try: idprof = int(request.GET['idprof']) p = Profissional.objects.get(pk=idprof) horarios = Horario.objects.filter(profissional=p).order_by("-validadefim") except: # todos os profissionais return HttpResponse("Forneça idprof como parâmetro") return render(request, "horariolist.html", {'horarios': horarios, 'idprof': idprof, 'prof': p}) @staff_member_required def teste(request): form = HorarioForm() return render(request, "teste.html", {'form': form }) @staff_member_required @login_required def jsont(request): import random data = datetime.datetime.today() inf = {} inf['data'] = data inf['id'] = random.randint(0, 1000) return JsonResponse(inf) @staff_member_required @login_required def consultas(request): # configuração e instalação de computadores profs = Profissional.objects.all() data = datetime.date.today() # Pega todos os gets args e monta o form idpaciente = 0 pacientenome = "" profissional = "" datacad = "" periodo = "" lastid = "" trab = [] # Tenta pegar os argumentos acima try: idpaciente = request.GET['pacienteid'] pacientenome = paciente.objects.get(pk=idpaciente) periodo = request.GET['periodo'] datacad = request.GET['data'] profid = request.GET['profid'] profissional = Profissional.objects.get(pk=profid) cad = '1' except: print("Ocorreu um erro!!!") cad='0' try: datacon = request.GET['data'] try: lastid = request.GET['lastid'] except: lastid = "" # às vezes o algoritmo pode ser ser referenciado sem o ID try: datacadpy = datetime.datetime.strptime(datacon, '%d/%m/%Y') except: datacadpy = datetime.datetime.strptime(datacon, '%Y-%m-%d') consultasList = Consulta.objects.filter(data=datacadpy) data = datacadpy print("Data: ", datacon) except Exception as e: print("Erro: ", e) consultasList = Consulta.objects.filter(data=data) p = [] for pf in profs: # Verifica se o profissional tem horario na data especificada horario = Horario.objects.filter(profissional=pf).filter( validadeinicio__lte=data).filter(validadefim__gte=data) if ( len(horario)>0 ): # Pega somente o primeiro hr = horario[0] print("Dia da semana: ", data.isoweekday()) # Segunda manha = 0 tarde = 0 if (data.isoweekday() == 1): if (hr.segundaM == True): manha = 1 if (hr.segundaT == True): tarde = 1 elif (data.isoweekday() == 2): if (hr.tercaM== True): manha = 1 if (hr.tercaT == True): tarde = 1 elif (data.isoweekday() == 3): if (hr.quartaM == True): manha = 1 if (hr.quartaT == True): tarde = 1 elif (data.isoweekday() == 4): if (hr.quintaM == True): manha = 1 if (hr.quintaT == True): tarde = 1 elif (data.isoweekday() == 5): if (hr.sextaM == True): manha = 1 if (hr.sextaT == True): tarde = 1 else: # não se trabalha no sábado e no domingo break trab.append( [pf.id, manha, tarde]) # zero não tem espediente e 1 tem -- primeiro é cedo e o outro é de tarde p.append(pf) print("prof nome: ", pf.nome) # Fica so quem tem horario profs = p return render(request, "consultalist.html", {'profs': profs, 'data': data, 'trab': trab, # Dadoslastid do formulário de cadastro 'idpaciente': idpaciente, 'pacientenome': pacientenome, 'profissional': profissional, 'datacad': datacad, 'cad': cad, 'consultasList': consultasList, 'lastid': lastid, 'periodo': periodo}) @staff_member_required @login_required def marcarconsulta(request): # Recebe um submit do formulário em aJax # Caso esteja Ok o sistema atualiza a página # Caso contrário, o sistema irá mostrar o erro try: datacad = request.POST['datacad'] idprofissional = request.POST['idprofissional'] idpaciente = request.POST['idpaciente'] horariocad = request.POST['horariocad'] periodo = request.POST['periodo'] # Parse datacad do formato dd/mm/YY datacadpy = datetime.datetime.strptime(datacad, '%d/%m/%Y') consulta = Consulta() consulta.data = datacadpy consulta.hora = horariocad consulta.profissional = Profissional.objects.get(pk=int(idprofissional)) consulta.paciente = paciente.objects.get(pk=int(idpaciente)) consulta.periodo = periodo consulta.status = "pend" # Situação da atividade # Associar um horário a consulta # Fica mais fácil de identificar try: horario = Horario.objects.filter(profissional=consulta.profissional).order_by("-validadefim").filter( validadeinicio__lte=consulta.data).filter(validadefim__gte=consulta.data) print("Eu encontrei um horário para esta consulta?") print("Tam: ", len(horario) ) horario = horario[0] consulta.horario = horario # Avalia de acordo com a quantidade máxima configurada no banco de dados consultasPeriodo = Consulta.objects.filter(profissional=consulta.profissional)\ .filter(data=consulta.data)\ .filter(periodo=consulta.periodo).exclude(status='des').exclude(status='falt').exclude(status='rem') if (len(consultasPeriodo)>= consulta.profissional.quantmaxconsulta): return HttpResponse(-2) # quantidade máxima excedida except: print("Erro do pesquisar por horarios") # Não pode marcar uma consulta para alguém que não tem uma return HttpResponse(-1) consulta.save() print("Salvo com sucesso!!!!") resp = {} resp['lastid'] = consulta.profissional.id resp['data'] = datacad return JsonResponse(resp) except Exception as e: print("Erro:") print(e) # Erro return HttpResponse(-1) @staff_member_required @login_required def changeStatus(request): if request.method=="POST": try: id = request.POST['idconsulta'] status = request.POST['status'] anotacao = request.POST['anotacao'] con = Consulta.objects.get(pk=int(id)) con.status = status con.anotacoes = anotacao con.save() print("Salvo com sucesso!!!") return HttpResponse(1) except: print("Erro") return HttpResponse(-1) else: return HttpResponse(-1) @staff_member_required @login_required def disponibilidade(request): if request.method == "GET": idprof = request.GET['idprof'] prof = Profissional.objects.get(pk=int(idprof)) print("Idprof: ", idprof) print("Idprof: ", prof.nome) return HttpResponse("Executei a bagaça!!!!!!!!!") # @staff_member_required @login_required def diasDisponiveis(request): data = datetime.date.today() nome="" dias = [] horario="" try: # Quem usa isto é o staff idprof = request.GET['idprof'] prof = Profissional.objects.get(pk=int(idprof)) except: prof = Profissional.objects.get(user=request.user) nome = prof.user.get_full_name() consultasprof = Consulta.objects.filter(profissional=prof).order_by('-data') data = datetime.date.today() horario = Horario.objects.filter(profissional=prof).filter( validadeinicio__lte=data).filter(validadefim__gte=data) try: horario = horario[0] except: return HttpResponse("<h1>Defina um horário para este profissional</h1>") diff = horario.validadefim - data # DIAS QUE TRABALHA diastrab = [] if horario.segundaM or horario.segundaT: diastrab.append(1) if horario.tercaM or horario.tercaT: diastrab.append(2) if horario.quartaM or horario.quartaT: diastrab.append(3) if horario.quintaM or horario.quintaT: diastrab.append(4) if horario.sextaM or horario.sextaT: diastrab.append(5) # DIAS MATUTINO diasmat = [] if horario.segundaM: diasmat.append(1) if horario.tercaM: diasmat.append(2) if horario.quartaM: diasmat.append(3) if horario.quintaM: diasmat.append(4) if horario.sextaM: diasmat.append(5) # DIAS VESPERTINO # DIAS QUE TRABALHA diasvesp = [] if horario.segundaT: diasvesp.append(1) if horario.tercaT: diasvesp.append(2) if horario.quartaT: diasvesp.append(3) if horario.quintaT: diasvesp.append(4) if horario.sextaT: diasvesp.append(5) for i in range(diff.days + 1): dia = data + timedelta(days=i) # Tira o sábado e o domingo if dia.isoweekday() > 5 : continue # Se tiver um dia que o profissional não trabalha ... então este dia não estará nos dias disponíveis if dia.isoweekday() not in diastrab: continue qmat = [] qvesp = [] # Contar somente os concluídos e pendentes # CONSULTA = ( # ('pend', 'Pendente'), # ('des', 'Desistir'), # ('rem', 'Remarcar'), # ('falt', 'Faltou'), # ('conc', 'Concluído'), # ) if dia.isoweekday() in diasmat: qmat = Consulta.objects.filter(profissional=prof).order_by('-data').filter(data=dia).filter(periodo='mat').filter(Q(status='conc')| Q(status='pend')) if dia.isoweekday() in diasvesp: qvesp = Consulta.objects.filter(profissional=prof).order_by('-data').filter(data=dia).filter( periodo='ves').filter(Q(status='conc')| Q(status='pend')) consultasprof = Consulta.objects.filter(profissional=prof).order_by('-data').filter(data=dia).filter(Q(status='conc')| Q(status='pend')) d = {} d['dia'] = dia d['quant'] = len(consultasprof) try: quant=prof.quantmaxconsulta+1 except: prof.quantmaxconsulta=0 if dia.isoweekday() in diasmat: d['quantm'] = len(qmat) d['dispm'] = prof.quantmaxconsulta - len(qmat) else: d['dispm'] = '' d['quantm'] = '' if dia.isoweekday() in diasvesp: d['quantv'] = len(qvesp) d['dispv'] = prof.quantmaxconsulta - len(qvesp) else: d['dispv'] = '' d['quantv'] = '' d['profid'] = prof.id print("Quantidade: ", d['quant']) dias.append(d) # Para cada dia, pesquisa-se return render(request, "diaslivres.html", {'profissional': "profissional", 'datainicial': data, 'datafinal': horario.validadefim, 'nome': nome, 'dias': dias}) @staff_member_required @login_required def cadconsulta(request): form = ConsultaForm() return render(request, "consultacad.html", {'form': form}) @staff_member_required @login_required def teste2(request): form = ConsultaForm() # t = input("Digite um valor") return render(request, "logar.html", {'form': form}) @staff_member_required @login_required def paci(request): paci = PacientForm() return render(request, {'form': paci}) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-25 17:36 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('caps', '0031_paciente_nprontuario'), ] operations = [ migrations.RemoveField( model_name='paciente', name='psicoterapeuta', ), migrations.RemoveField( model_name='paciente', name='terapeutaocupacional', ), ] <file_sep>/** * Created by geekaia on 19/03/17. */ var app = angular.module('capsapp', ['ngMaterial', 'ngRoute', 'ngMessages']); app.controller('login', function($scope, $http) { $scope.usuario= ""; $scope.senha= ""; $scope.url = '/login/'; $scope.logar = function() { $scope.data = { 'usuario' : $scope.usuario, 'senha': $scope.senha, }; // CSRFTOKEN $http.defaults.xsrfCookieName = 'csrftoken'; $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http({ method: "POST", url: $scope.url, data: $scope.data }).then(function getRespOk(resp) { if (resp.data.resp ==1 ){ alert("Tudo ocorreu OK") } else { alert("Ocorreu um erro na authenticação!"); } }, function getRespErro(resp) { alert("Ocorreu um erro na conexão!!!"); }); } }); app.controller('pacientectl', function($scope, $http) { $scope.pc = {}; $scope.data = $scope.pc; $scope.url = '/cadastrapaciente/'; $scope.pccad = function() { // CSRFTOKEN $http.defaults.xsrfCookieName = 'csrftoken'; $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http({ method: "POST", url: $scope.url, data: $scope.data }).then(function getRespOk(resp) { if (resp.data.resp ==1 ){ alert("Tudo ocorreu OK") } else { alert("Ocorreu um erro na authenticação!"); } }, function getRespErro(resp) { alert("Ocorreu um erro na conexão!!!"); }); } }); app.config(function($routeProvider) { $routeProvider // .when("/", { // templateUrl: "/" // }) .when("/loginform", { templateUrl: "loginform.htm" }) .when("/pacientecad", { templateUrl: "pacientecad.htm" }); }); app.controller('AppCtrl', function ($scope, $timeout, $mdSidenav) { $scope.toggleLeft = buildToggler('left'); $scope.toggleRight = buildToggler('right'); function buildToggler(componentId) { return function() { $mdSidenav(componentId).toggle(); }; } }); <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11b1 on 2017-03-12 19:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0002_auto_20170312_1618'), ] operations = [ migrations.CreateModel( name='Teste', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fone', models.CharField(max_length=255)), ], ), migrations.AlterField( model_name='paciente', name='rgorgemissor', field=models.CharField(choices=[('SSP', 'Secretaria de Segurança Pública'), ('PM', 'Polícia Militar'), ('PC', 'Policia Civil'), ('CNT', 'Carteira Nacional de Habilitação'), ('DIC', 'Diretoria de Identificação Civil'), ('CTPS', 'Carteira de Trabaho e Previdência Social'), ('FGTS', 'Fundo de Garantia do Tempo de Serviço'), ('IFP', 'Instituto Félix Pacheco'), ('IPF', 'Instituto Pereira Faustino'), ('IML', 'Instituto Médico-Legal'), ('MTE', 'Ministério do Trabalho e Emprego'), ('MMA', 'Ministério da Marinha'), ('MAE', 'Ministério da Aeronáutica'), ('MEX', 'Ministério do Exército'), ('POF', 'Polícia Federal'), ('POM', 'Polícia Militar'), ('SES', 'Carteira de Estrangeiro'), ('SJS', 'Secretaria da Justiça e Segurança'), ('SJTS', 'Secretaria da Justiça do Trabalho e Segurança'), ('ZZZ', 'Outros (inclusive exterior')], max_length=255), ), migrations.AlterField( model_name='paciente', name='rguf', field=models.CharField(choices=[('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins')], max_length=2), ), ] <file_sep>from django.contrib import admin from django import forms # Register your models here. from caps.models import * from input_mask.widgets import InputMask from django.http import HttpResponse from django.core import serializers # # class Telefone(InputMask): # mask = { # 'mask': '(99) 99999-9999', # } # class Cpf(InputMask): mask = { 'mask': '999.999.999-99', } from django import forms #from input_mask.contrib.localflavor.br.widgets import BRPhoneNumberInput #from localflavor.br.forms import BRPhoneNumberField from reportlab.pdfgen import canvas def teste(modeladmin, request, queryset): c = canvas.Canvas("hello.pdf") step=750 for qs in queryset: c.drawString(30, step, qs.nome) step -= 100 c.save() <file_sep>"""capsdjango URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from material.frontend import urls as frontend_urls from caps.views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include(frontend_urls)), url(r'^gerarFicha/(?P<id>[0-9]+)/$', gerarFicha), url(r"^$", home, name="index.htm"), url(r"^sair/", sair, name="sair"), url(r"^loginform.htm", loginform, name="loginform.htm"), url(r"^pacientecad.htm", pacientecad, name="pacientecad"), url(r"^cadastrapaciente", cadastrapaciente, name="cadastrapaciente"), # Material Design url(r"^home2", home2, name="home2"), url(r"^pacienteman", pacienteman, name="pacienteman"), url(r"^pacientelist$", pacientelist, name="pacientecad"), # Controle de usuarios url(r"^login/", logar, name="logar"), # Profissionais url(r"^horarioMaker", horarioMaker, name="horarioMaker"), url(r"^newhorario", newhorario, name="newhorario"), url(r"^horariolist", horariolist, name="horariolist"), url(r"^cadprofissionais", profissionaislist, name="cadprofissionais"), url(r"^profissionais", profissionais, name="profissionais"), # Consulta dos profissionais url(r"^consultas", consultas, name="consultas"), url(r"^cadconsulta", cadconsulta, name="cadconsulta"), url(r"^marcarconsulta", marcarconsulta, name="marcarconsulta"), url(r"^remConsulta", remConsulta, name="remConsulta"), # Visão dos profissionais url(r"^minhasconsultas", minhasconsultas, name="minhasconsultas"), # Evolução dos pacientes url(r"^evolucaopacientes", evolucaopacientes, name="evolucaopacientes"), url(r"^relatorio", gerarRelatorio, name="relatorio"), url(r"^teste", teste, name="teste"), url(r"^jsont", jsont, name="jsont"), url(r"^login/", logar, name="logar"), # url(r"^userMan/", userMan, name="userMan"), url(r"^paci/", paci, name="paci"), # Dias disponíveis de um profissional url(r"^diasDisponiveis/", diasDisponiveis, name="diasDisponiveis"), # Muda o status da consulta url(r"^changeStatus", changeStatus, name="changeStatus"), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-01 17:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0027_auto_20170410_1121'), ] operations = [ migrations.AddField( model_name='consulta', name='status', field=models.CharField(blank=True, choices=[('des', 'Desistir'), ('rem', 'Remarcar'), ('falt', 'Faltou'), ('conc', 'Concluído')], max_length=50, null=True), ), migrations.AlterField( model_name='profissional', name='especialidade', field=models.CharField(choices=[('psiq', 'Psiquiatra'), ('psic', 'Psicólogo(a)'), ('enferm', 'Enfermeiro(a)'), ('psicoterap', 'Psicoterapeuta'), ('assissoc', 'Assistente social'), ('fisioterap', 'Fisioterapeuta'), ('terapocup', 'Terapeuta ocupacional'), ('clinico', 'Clínico Geral')], max_length=255), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-21 22:27 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caps', '0020_auto_20170321_2221'), ] operations = [ migrations.AddField( model_name='horario', name='validadefim', field=models.DateField(default=datetime.date.today), ), migrations.AddField( model_name='horario', name='validadeinicio', field=models.DateField(default=datetime.date.today), ), ]
406feeb29d266be9ec672354b4a1f5793adce7ec
[ "JavaScript", "Python", "Text", "HTML" ]
32
Python
geekaia/capsdjango
265c9dcf5db3d278c985c2dffb97420abf36607a
d4ceb26556fee37aba53af083134ffb1440f7c18
refs/heads/master
<repo_name>rameshu08/shopping-api<file_sep>/models/userSchema.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const modelName = 'Users'; const userSchema = new Schema({ userName:{ type: String, required: true }, email:{ type: String, required: true }, mobile:{ type: String, required: true }, password:{ type: String, required: true }, cart:[ { productId:{ type: mongoose.Schema.Types.ObjectId, ref:'Products' }, qty: Number } ] }); userSchema.statics.findUser = function (findBy, value) { return this.model(modelName).findOne({ [findBy]: value }); }; module.exports = mongoose.model(modelName, userSchema); <file_sep>/services/user-service.js const userDAO = require('../dao/user-dao'); const constant = require('../utils/constant'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const _ = require('lodash'); const res = require('../utils/response'); const UserService = { saltRounds:10, async createUser(userDetail) { try{ if(userDetail == null){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.UNAUTHORIZED,'UserDetail shouldnot be null')); } const userExists = await userDAO.findByCondition({'email':userDetail.email}); if(userExists){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR, 'User Already Exists')); } const mobileNoExists = await userDAO.findByCondition({'mobile': userDetail.mobile}); if(mobileNoExists){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR, 'Mobile Number already exists')); } else if(userDetail.password){ const hashedPassword = await bcrypt.hash(userDetail.password,this.saltRounds); userDetail.password = <PASSWORD>; } const result = await userDAO.create(userDetail); return result; } catch(error){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR, error.message)); } }, async getUser(userDetail) { try{ if(userDetail == null){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.UNAUTHORIZED, 'Invalid User Data.')); } const userData = await userDAO.getUser(userDetail.email); if(!userData){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'Invalid User')); } if(!userData.password){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'Enter Password')); } const isCorrectPassword = await bcrypt.compare(userDetail.password,userData.password); if(!isCorrectPassword){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.UNAUTHORIZED, 'Invalid Password')); } const token = jwt.sign(_.pick(userData, ['_id', 'userName', 'mobile', 'email']), constant.APP_SECRETE, { expiresIn: constant.TOKEN_TIMEOUT }); return { token, Username: userData.userName, mobile: userData.mobile, email: userData.email, _id: userData._id }; } catch(error){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR, error.message)); } }, //CART// async addToCart(user,cartDetail){ try{ let updateFields = {}; if(cartDetail == null){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'Enter the credentials')); } const condition = {}; condition._id = user.id; condition['cart.productId'] = cartDetail[0].productId; let productExists = await userDAO.getCartItems(condition); if(productExists) { // const condition={}; // condition._id = user.id; // condition['cart.productId'] = cartDetail[0].productId; const inCount = cartDetail[0].qty + productExists.cart[0].qty; if(inCount < 1){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'Enter the credentials')); } else{ updateFields = { $inc:{ 'cart.$.qty': cartDetail[0].qty} //if want reduce : -1 or value } } } else{ const condition = {}; condition._id = user.id; updateFields = { $push: {cart : cartDetail} } } // condition['cart.product'] = cartDetail[0].productId; const result = await userDAO.addToCart(condition,updateFields); return result; } catch(error) { return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR, error.message)); } }, async getAllCartItems(userId) { try{ if(userId == null){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'Enter the credentials')); } const result = await userDAO.getAllCartItems({_id:userId.id}); if(!result){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'No products added')); } let cart = result[0].cart; let cartResult = _.groupBy(cart); let totalPrice = 0; let expectedResult = []; for(let i in cartResult){ let normalObj = {}; cartResult[i].forEach(product => { product.amount = Math.round(((product.productId.price - (product.productId.price * product.productId.discount / 100)) * product.qty) * 100) / 100; totalPrice += product.amount; }) normalObj.products = cartResult[i]; expectedResult.push(normalObj); } totalPrice = Math.round(totalPrice * 100)/100; return ({cartItems: expectedResult, TotalPrice: totalPrice}) }catch(error) { return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR, error.message)); } } }; module.exports = UserService;<file_sep>/services/product-service.js const productDAO = require('../dao/product-dao'); const constant = require('../utils/constant'); const res = require('../utils/response'); const productService = { async addProduct(productDetail, user){ try{ if(productDetail == null){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'Please enter The credentials')); } const result = await productDAO.create(productDetail); return result; } catch(error) { return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR), error.message); } }, async getProductById(productDetail){ try{ if(productDetail == null){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA, 'Please pass the credentials')); } const result = await productDAO.findById({'_id': productDetail.id}); return result; } catch(error){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR), error.message); } }, async updateProduct(productId, productDetail){ try{ const objId = await productDAO.findById({'_id': productId.id}); if(!objId){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA,'Invalid Details')); } const result = await productDAO.update(productId.id, productDetail); return result; } catch(error){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR), error.message); } }, async deleteProduct(productId){ try{ const objId = await productDAO.findById({'_id': productId.id}); if(!objId){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INVALID_DATA,'Invalid Details')); } const result = await productDAO.deleteProduct({'_id': productId.id}); return result; } catch(error){ return Promise.reject(res.error(constant.HTML_STATUS_CODE.INTERNAL_ERROR), error.message); } } } module.exports = productService;<file_sep>/index.js const mongoose = require('mongoose'); const app = require("./server"); const http = require('http'); const server = http.createServer(app); // var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/shopping',{ useNewUrlParser: true }); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("MongoDB connected Successfully"); }); server.listen(3000); console.log('Server running on port 3000');
7220f24657804e461709c2ee4dd714524c6584d6
[ "JavaScript" ]
4
JavaScript
rameshu08/shopping-api
a4e8bc47749954cfcba4e8db884b63f7c7b86e54
b1ac7ad6b04def4abb60ab52c0ec0bddff13baa8
refs/heads/master
<repo_name>Tehees/count_letters<file_sep>/count_letters.rb # def count_letters(my_string) # h = {} # my_string.split(//) # end # count_letters("lighthouse") def count_letters(my_string) h = Hash.new word = my_string.split(//) word.each_with_index do |x,index| if h[x] == nil h[x] = [index] else h[x] << index end end return h end puts count_letters("lighthouse in the house...")
10b91661d44a8669749e302949bd19f487411ed4
[ "Ruby" ]
1
Ruby
Tehees/count_letters
6c35e2e31eb4fcef276d479f0a0ed09a4afecdde
bc1672dd2c562c0942ed80dfbac0ecceb5356952
refs/heads/master
<repo_name>OneBrokenPixel/breakout<file_sep>/Assets/Scripts/Ball_Controller.cs using UnityEngine; using System.Collections; using Darkhexxa.SimplePool.Components; [RequireComponent ( typeof ( Rigidbody2D ) )] public class Ball_Controller : BasePoolComponent { [System.Serializable] public class Ball_State { public float MinSpeed = 4.0f; public float MaxSpeed = 8.0f; public float RandomReboundTollerance = 0.999f; } BoxCollider2D _boxCollider; Rigidbody2D _rigidbody2D; //Camera _mainCamera; GameScript _gameScript; Vector3 _vel = new Vector3(); public Vector3 Vel { get { return _vel; } } //public Vector2 SpeedRange = new Vector2(2,8); public static int ActiveBalls = 0; //public float reboundTollerance = 0.9f; public Ball_State state;// = new Ball_State(); void Awake() { _rigidbody2D = GetComponent<Rigidbody2D> (); _gameScript = GameScript.Instance; } // Use this for initialization void Start () { // get the reference to the global ball state state = GameScript.Instance.ballState; } // Update is called once per frame void Update () { } void FixedUpdate() { if ( transform.parent == null ) { _vel = _rigidbody2D.velocity; float currentSpeed = _vel.magnitude; if ( currentSpeed < state.MinSpeed) { _rigidbody2D.AddForce ( _vel * ( state.MinSpeed - currentSpeed ) ); } else if ( currentSpeed > state.MaxSpeed ) { _rigidbody2D.AddForce ( _vel * ( state.MaxSpeed - currentSpeed ) ); } } } void OnCollisionEnter2D ( Collision2D coll ) { if ( isFree == true ) { _vel = Vector2.zero; int count = 0; foreach ( var contact in coll.contacts ) { float dot = Vector2.Dot ( _rigidbody2D.velocity.normalized, Vector2.right ); if ( dot <= -state.RandomReboundTollerance || dot >= state.RandomReboundTollerance ) { count++; _vel += Quaternion.Euler ( 0, 0, Random.Range ( -15, 15f ) ) * _rigidbody2D.velocity; } } if ( count != 0 ) { _rigidbody2D.velocity = _vel * 1f / count; } } } void OnCollisionExit2D ( Collision2D coll ) { } /* void OnTriggerEnter2D ( Collider2D other ) { if ( other.GetType () == typeof ( EdgeCollider2D ) ) { Debug.Log ( gameObject + " has entered" ); } } */ void OnTriggerExit2D ( Collider2D other ) { if ( other.tag == "MainCamera" && other.GetType () == typeof ( BoxCollider2D ) ) { pool.Despawn ( gameObject ); } } public void Launch(Vector2 direction) { _vel = direction * state.MinSpeed; rigidbody2D.velocity = _vel; isFree = true; } public override void OnSpawn () { ActiveBalls++; //_vel = UnityEngine.Random.insideUnitCircle.normalized * SpeedRange.x; //rigidbody2D.velocity = _vel; } public override void OnDespawn () { ActiveBalls--; _vel = Vector2.zero; rigidbody2D.velocity = Vector2.zero; } public bool isFree { get; set; } } <file_sep>/Assets/Scripts/GameScript.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using Darkhexxa.SimplePool; public class GameScript : MonoBehaviour { #region GameScript Singleton static GameScript _instance; static bool applicationIsQuitting = false; private static object _lock = new object (); public static GameScript Instance { get { if ( applicationIsQuitting ) { Debug.LogWarning ( "[Singleton] Instance '" + typeof ( GameScript ) + "' already destroyed on application quit." + " Won't create again - returning null." ); return null; } lock ( _lock ) { if ( _instance == null ) { _instance = (GameScript)FindObjectOfType ( typeof ( GameScript ) ); if ( FindObjectsOfType ( typeof ( GameScript ) ).Length > 1 ) { Debug.LogError ( "[Singleton] Something went really wrong " + " - there should never be more than 1 singleton!" + " Reopenning the scene might fix it." ); return _instance; } if ( _instance == null ) { GameObject singleton = new GameObject (); _instance = singleton.AddComponent<GameScript> (); singleton.name = "(singleton) " + typeof ( GameScript ).ToString (); DontDestroyOnLoad ( singleton ); Debug.Log ( "[Singleton] An instance of " + typeof ( GameScript ) + " is needed in the scene, so '" + singleton + "' was created with DontDestroyOnLoad." ); } else { Debug.Log ( "[Singleton] Using instance already created: " + _instance.gameObject.name ); } } return _instance; } } } #endregion SimplePool _ballPool; SimplePool _dropPool; public SimplePool DropPool { get { return _dropPool; } } Paddle_Controller[] paddels; public Texture lifeImagae; public int StartingLives = 3; public Bounds PlayArea {get;set;} public int Lives { get; set;} public int Score { get; set; } public float DropChance = 0.25f; public Paddle_Controller.Paddle_State paddleState = new Paddle_Controller.Paddle_State(); public Ball_Controller.Ball_State ballState = new Ball_Controller.Ball_State (); public void OnDestroy () { applicationIsQuitting = true; } void Awake() { paddels = FindObjectsOfType<Paddle_Controller> (); } // Use this for initialization void Start () { applicationIsQuitting = false; Transform t = transform.FindChild ( "BallPool" ); _ballPool = t.GetComponent<SimplePool> (); t = transform.FindChild ( "DropPool" ); _dropPool = t.GetComponent<SimplePool> (); Ball_Controller.ActiveBalls = 0; Lives = StartingLives; } void OnGUI() { GUILayout.BeginArea ( new Rect ( 10, 10, 100, 100 ) ); { GUILayout.Box ( "Score: " + Score ); } GUILayout.EndArea (); GUILayout.BeginArea ( new Rect ( 10, Screen.height-40, 100, 30 ) ); { GUILayout.BeginHorizontal (); { GUILayout.Box ( lifeImagae ); GUILayout.Label ( " x" + Lives ); } GUILayout.EndHorizontal (); } GUILayout.EndArea (); } // Update is called once per frame void Update () { if ( Ball_Controller.ActiveBalls == 0 ) { GameObject ball = _ballPool.Spawn ( Vector3.zero, Quaternion.identity ); Ball_Controller ballctrl = ball.GetComponent<Ball_Controller> (); if ( paddels.Length != 0 ) { paddels [0].LaunchBall = ballctrl; } Lives--; } if( Lives <= 0) { Debug.Log ( "GameOver!" ); } if( Brick_Controller.ActiveBricks == 0 ) { Debug.Log ( "You Win GameOver!" ); } } }<file_sep>/Assets/Darkhexxa/SimplePool/Components/CullFinishedParticlesSystems.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Darkhexxa { namespace SimplePool { using Core; namespace Components { /** * @brief A base pool component that despawns the attached object when it goes off screen. */ [AddComponentMenu ( "DarkHexxa/SimplePool/Components/Cull Finshed Particle Systems" )] public class CullFinishedParticlesSystems : BasePoolComponent { ParticleSystem _particles; #region implemented abstract members of BasePoolComponent public override void OnSpawn () { } public override void OnDespawn () { if( _particles != null ) { _particles.Stop(); _particles.Clear(); } } #endregion void Awake() { _particles = particleSystem; } void Update() { if( _particles != null && _particles.isStopped ) { pool.Despawn (this.gameObject); } } } } } } <file_sep>/README.md breakout ======== breakout Clone <file_sep>/Assets/Scripts/DropPowers/Drop_LifeUp.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Drop_LifeUp : Drop_PowerBase { public override void ApplyPower () { GameScript.Instance.Lives++; } } <file_sep>/Assets/Scripts/Drop_PowerBase.cs using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; public abstract class Drop_PowerBase : MonoBehaviour { private static List<Drop_PowerBase> _powers = new List<Drop_PowerBase>(); public static List<Drop_PowerBase> Powers { get { return _powers; } } public static float DropChance = 0.25f; public Sprite Sprite; public static void CreateDrop( Transform t) { if ( _powers.Count != 0 && Random.Range ( 0f, 1f ) < DropChance ) { Drop_Container drop = GameScript.Instance.DropPool.Spawn ( t.position, Quaternion.identity ).GetComponent<Drop_Container> (); int droptype = Random.Range ( 0, _powers.Count ); drop.Effect = _powers [droptype]; } } protected void Awake() { print ( "adding Effect" ); _powers.Add ( this ); } public virtual void InitaliseContainer ( Drop_Container contriner ) { if ( Sprite != null ) { SpriteRenderer sr = contriner.GetComponent<SpriteRenderer> (); if ( sr != null ) { sr.sprite = Sprite; } } } public abstract void ApplyPower (); } <file_sep>/Assets/Scripts/Paddle_Controller.cs using UnityEngine; using System.Collections; [RequireComponent(typeof(BoxCollider2D))] public class Paddle_Controller : MonoBehaviour { [System.Serializable] enum Edge { LEFT, RIGHT, NONE } [System.Serializable] public class Paddle_State { public float Speed = 8.0f; public float Size = 1.0f; } private BoxCollider2D _box; private Vector2 cp = new Vector2 (); private Ball_Controller _lanchBall; public Ball_Controller LaunchBall { get { return _lanchBall; } set { _lanchBall = value; if ( _lanchBall != null ) { _ballJoint.connectedBody = value.rigidbody2D; _ballJoint.enabled = true; _lanchBall.isFree = false; } else { _ballJoint.enabled = false; } } } public Paddle_State state;// = new Paddle_State(); private Vector2 _currentSize = new Vector3 ( 1.0f, 1.0f ); public float CurrentSize { get { return _currentSize.x; } set { _currentSize.x = value; Vector2 boxSize = _box.size; boxSize.x = value+0.5f; _box.size = boxSize; Vector2 halfSize = new Vector2(0.5f * value,0); _left.transform.localPosition = -halfSize; _right.transform.localPosition = halfSize; Vector2 scaleFactor = new Vector2 (value / 0.5f,1.0f); _center.localScale = scaleFactor; } } private Transform _left; private Transform _right; private Transform _center; Edge _edge = Edge.NONE; Vector2 _vel = new Vector2 (); float height = 0f; public AnimationCurve bump; private float bumpTime = float.PositiveInfinity; private HingeJoint2D _ballJoint; void Awake () { _box = GetComponent<BoxCollider2D> (); _ballJoint = GetComponent<HingeJoint2D> (); _ballJoint.enabled = false; _left = transform.FindChild ( "Left" ); _right = transform.FindChild ( "Right" ); _center = transform.FindChild ( "Center" ); } // Use this for initialization void Start () { height = transform.position.y; state = GameScript.Instance.paddleState; CurrentSize = state.Size; } // Update is called once per frame void FixedUpdate () { cp = transform.position; _vel = Input.GetAxis ( "Horizontal" ) * Vector2.right * state.Speed; switch(_edge) { case Edge.LEFT: _vel.x = Mathf.Clamp ( _vel.x, 0, state.Speed ); break; case Edge.RIGHT: _vel.x = Mathf.Clamp ( _vel.x, -state.Speed, 0 ); break; default: break; } rigidbody2D.velocity = _vel; if ( Input.GetButtonDown ( "Fire1" ) ) { if ( LaunchBall != null ) { LaunchBall.Launch ( Vector2.up ); LaunchBall = null; } bumpTime = Time.deltaTime; } float this_height = height; if( bumpTime <= 1.0f ) { this_height += bump.Evaluate ( bumpTime ); bumpTime += Time.deltaTime; } Vector3 pos = transform.position; pos.y = this_height; transform.position = pos; if( CurrentSize != state.Size ) { CurrentSize = state.Size; } } /* void OnCollisionEnter2D ( Collision2D coll ) { if ( coll.gameObject.tag == "Ball" ) { cp = transform.position; Ball_Controller ballScript = coll.gameObject.GetComponent ( typeof ( Ball_Controller ) ) as Ball_Controller; foreach( var contact in coll.contacts) { float ballVel = coll.rigidbody.velocity.magnitude; Vector2 dist = contact.point - cp; coll.rigidbody.velocity += dist * coll.rigidbody.mass * 5; coll.rigidbody.velocity = coll.rigidbody.velocity.normalized * ballVel; } _vel = rigidbody2D.velocity; _vel.y = 0.0f; rigidbody2D.velocity = _vel; } } */ void OnCollisionEnter2D ( Collision2D coll ) { if ( coll.gameObject.tag == "Ball" ) { cp = transform.position; float halfSize = 0.5f * _currentSize.x; Ball_Controller ballScript = coll.gameObject.GetComponent ( typeof ( Ball_Controller ) ) as Ball_Controller; float ballVel = coll.rigidbody.velocity.magnitude; Vector2 point = new Vector2 (); foreach( var contact in coll.contacts) { point += 0.5f * contact.point; } Debug.DrawRay ( point, Vector2.up, Color.white, 1f ); float x = ( point - cp ).x / halfSize; coll.rigidbody.velocity += Vector2.right * x * coll.rigidbody.mass * 10f; coll.rigidbody.velocity += rigidbody2D.velocity * 0.5f; coll.rigidbody.velocity = coll.rigidbody.velocity.normalized * ballVel; } } void OnTriggerEnter2D ( Collider2D other ) { Debug.Log ( "Using: " + other.gameObject ); if(other.tag == "Paddle") { Vector2 direction = (other.transform.position - this.transform.position).normalized; if( Vector2.Dot(Vector2.right, direction) > 0 ) { _edge = Edge.LEFT; } else if ( Vector2.Dot ( Vector2.right, direction ) < 0 ) { _edge = Edge.RIGHT; } else { _edge = Edge.NONE; } } } void OnTriggerExit2D ( Collider2D other ) { if ( other.tag == "Paddle" ) { _edge = Edge.NONE; } } } <file_sep>/Assets/Scripts/CameraCollisionScript.cs using UnityEngine; using System.Collections; [RequireComponent(typeof(EdgeCollider2D),typeof(BoxCollider2D))] public class CameraCollisionScript : MonoBehaviour { EdgeCollider2D _edge; BoxCollider2D _box; Camera _camera; Vector3 _screenWidth = new Vector3 (); float lastCameraSize = 0; Vector2[] _points = new Vector2 [4]; BoxCollider2D[] _paddleEdgeBoxes; void Awake () { _edge = GetComponent<EdgeCollider2D> (); _box = GetComponent<BoxCollider2D> (); _camera = camera; Transform paddleEdge = transform.FindChild ( "PaddelEdge" ); _paddleEdgeBoxes = paddleEdge.GetComponents<BoxCollider2D> (); //lastCameraSize = _camera.orthographicSize; } void UpdateCameraColliders() { if(lastCameraSize != _camera.orthographicSize) { _screenWidth.Set ( Screen.width, Screen.height, 0 ); Vector2 max = _camera.ScreenToWorldPoint ( _screenWidth ); Vector2 min = _camera.ScreenToWorldPoint ( Vector3.zero ); GameScript.Instance.PlayArea.SetMinMax ( min, max ); _box.size = max - min; _points[0].Set( min.x, min.y); _points[1].Set( min.x, max.y); _points[2].Set( max.x, max.y); _points[3].Set( max.x, min.y); _edge.points = _points; _paddleEdgeBoxes [0].size = new Vector2( 0.2f, max.y - min.y ); _paddleEdgeBoxes [0].center = new Vector2 ( min.x, 0f ); _paddleEdgeBoxes [1].size = _paddleEdgeBoxes [0].size; _paddleEdgeBoxes [1].center = new Vector2( max.x, 0f ); lastCameraSize = _camera.orthographicSize; } } // Use this for initialization void Start () { UpdateCameraColliders (); } // Update is called once per frame void Update () { UpdateCameraColliders (); } } <file_sep>/Assets/Scripts/DropPowers/Drop_PaddleSize.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; public class Drop_PaddleSize : Drop_PowerBase { public float sizeModifyer = 0; public override void ApplyPower () { GameScript.Instance.paddleState.Size += sizeModifyer; } } <file_sep>/Assets/Scripts/Drop_Container.cs using UnityEngine; using System.Collections; using Darkhexxa.SimplePool.Components; [RequireComponent(typeof(Rigidbody2D))] public class Drop_Container : BasePoolComponent { public float DropGravity = 2; Rigidbody2D _rigidbody2d; private Drop_PowerBase _effect; public Drop_PowerBase Effect { get { return _effect; } set { _effect = value; _effect.InitaliseContainer ( this ); } } void Awake() { _rigidbody2d = rigidbody2D; } void OnTriggerEnter2D ( Collider2D other ) { if ( other.tag == "Paddle" ) { Effect.ApplyPower(); pool.Despawn ( gameObject ); } } void OnTriggerExit2D ( Collider2D other ) { if ( other.tag == "MainCamera" && other.GetType () == typeof ( BoxCollider2D ) ) { pool.Despawn ( gameObject ); } } public override void OnSpawn () { _rigidbody2d.velocity = Vector2.up * -DropGravity; } public override void OnDespawn () { } } <file_sep>/Assets/Scripts/Brick_Controller.cs using UnityEngine; using System.Collections; using Darkhexxa.SimplePool; [RequireComponent(typeof(SpriteRenderer))] public class Brick_Controller : MonoBehaviour { public bool Immortal = false; public int Life = 1; public Sprite[] SpriteSequence; public Sprite SpriteImmortal; public AnimationCurve ImpactAnimation; private SimplePool particlePool; Transform spriteTransform; SpriteRenderer spriteRenderer; public static int ActiveBricks = 0; void Awake() { spriteTransform = transform.FindChild ( "Sprite" ); spriteRenderer = spriteTransform.GetComponent<SpriteRenderer> (); GameObject go = GameObject.Find ( "DeathParticlesPool" ); //print ( go ); particlePool = go.GetComponent<SimplePool> (); Life = Mathf.Clamp ( Life, 0, (SpriteSequence.Length - 1) ); } // Use this for initialization void Start () { if ( Immortal ) { spriteRenderer.sprite = SpriteImmortal; } else { spriteRenderer.sprite = SpriteSequence [Life]; } ActiveBricks++; } // Update is called once per frame void Update () { if ( _impactTime < 1.0f ) { float dist = ImpactAnimation.Evaluate ( _impactTime ) * 0.1f; Vector3 offset = _impactNormal * dist; spriteTransform.position = transform.position + offset; _impactTime += Time.deltaTime; } } void KillBrick ( ) { GameScript.Instance.Score += 10; ParticleSystem particles = particlePool.Spawn ( transform.position, transform.rotation ).particleSystem; particles.Play (); //GameScript.Instance.BrickDestroyedAt ( transform ); Drop_PowerBase.CreateDrop ( this.transform ); Destroy ( gameObject ); ActiveBricks--; } Vector2 _impactNormal = new Vector2 (); float _impactTime = 2.0f; void FixedUpdate() { } void OnCollisionExit2D ( Collision2D coll ) { if( !Immortal ) { Life--; if ( Life < 0 ) { KillBrick (); } else { spriteRenderer.sprite = SpriteSequence [Life]; _impactNormal = coll.contacts [0].normal; _impactTime = Time.deltaTime; } } } } <file_sep>/Assets/Darkhexxa/SimplePool/SimplePool.cs  using System; using System.Collections; using UnityEngine; namespace Darkhexxa { namespace SimplePool { using Components; using Core; /** * Simple Pool Component * give it a game object and it will spawn clones. */ [AddComponentMenu("DarkHexxa/SimplePool/Pool")] public class SimplePool : MonoBehaviour { /** * @brief Data for the pool */ [Serializable] public class PoolData { public GameObject prefab; ///> game object to clone public int maxCount = 0; ///> max number of clones public int batchCreateCount = 5; ///> number of clones to create when new objects are needed. public bool cullInactive = false; ///> if culling of incactive objects is desired. public float cullInterval = 10f; ///> the interval for the calling process. /** * Constructor for PoolData * * @param GameObject to be cloned */ public PoolData(GameObject prefab) { this.prefab = prefab; this.maxCount = 0; this.batchCreateCount = 5; this.cullInactive = false; this.cullInterval = 10f; } /** * Constructor for PoolData * * @param GameObject to be cloned * @param int maxCount clone * @param int batchCreateCount to clone when new objects are required * @param bool cull inactive objects * @param float the cull interval */ public PoolData(GameObject prefab, int maxCount, int batchCreateCount, bool cullInactive, float cullInterval) { this.prefab = prefab; this.maxCount = maxCount; this.batchCreateCount = batchCreateCount; this.cullInactive = cullInactive; this.cullInterval = cullInterval; } /** * is equal to operator * * @param first PoolData object * @param Second PoolData object * @return true if objects are equal. */ public static bool operator == ( PoolData data1, PoolData data2 ) { // If both are null, or both are same instance, return true. if (System.Object.ReferenceEquals(data1, data2)) { return true; } // If one is null, but not both, return false. if (((object)data1 == null) || ((object)data2 == null)) { return false; } return ( data1.prefab.Equals(data2.prefab) && data1.maxCount == data2.maxCount && data1.cullInactive == data2.cullInactive ); } /** * Equals override * * @param PoolData object * @return true if objects are equal. */ public override bool Equals(object obj) { if (obj == null) { return false; } PoolData p = obj as PoolData; if ((System.Object)p == null) { return false; } return (this.prefab.Equals(p.prefab) && this.maxCount == p.maxCount && this.cullInactive == p.cullInactive); } /** * is not equal to operator * * @param first PoolData object * @param Second PoolData object * @return true if objects are equal. */ public static bool operator !=(PoolData data1, PoolData data2) { return (!data1.prefab.Equals(data2.prefab) && data1.maxCount != data2.maxCount && data1.cullInactive != data2.cullInactive); } /** * generate hash code * * @return int hashcode. */ public override int GetHashCode() { return base.GetHashCode(); } } public PoolData data = new PoolData(null); ///< Pool data object for this pool. private int _count = 0; //< number of objects. /** * Full attrubute. * * @return returns true if the pool is not full */ private bool isFull { get { return (_count < data.maxCount || data.maxCount == 0); } } ComponentList _inactive = null; ///< list of inactive objects created; ComponentList _active = null; ///< list of active objects spawned. ComponentList _despawn = null; ///< list off active objects to be despawned; /** * @brief Coroutine for culling inactive objects */ IEnumerator CullRoutine() { while (data.cullInactive) { yield return new WaitForSeconds(data.cullInterval); //Debug.Log("Culling"); int cullCount = _inactive.Count - data.batchCreateCount; if (cullCount >0) { RemoveGameObjects(_inactive, cullCount); } } } /** * @brief Coroutine for safly Despawning objects at the end of the frame. */ IEnumerator BackgroundProcess() { float t = 0; while(true) { yield return new WaitForEndOfFrame (); t += Time.deltaTime; for ( int i = 0; !_despawn.isEmpty; i++ ) { GameObject obj = _despawn.RemoveTailGO (); obj.SetActive ( false ); BasePoolComponent cmp = obj.GetComponent<BasePoolComponent> (); if ( cmp != null ) { cmp.OnDespawn (); } _inactive.InsertAtTail ( ref obj ); } if( data.cullInactive && t >= data.cullInterval ) { t = 0f; int cullCount = _inactive.Count - data.batchCreateCount; print ( t + cullCount ); if ( cullCount > 0 ) { RemoveGameObjects ( _inactive, cullCount ); } } } } /** * @brief generates new game objects. */ private void AddNewGameObjects() { if (data.prefab != null) { //Debug.Log ("Adding New Game Objects to " + prefab.name + " pool"); for (int i = 0; i < data.batchCreateCount && isFull; i++) { //Debug.Log(i); GameObject obj = GameObject.Instantiate(data.prefab) as GameObject; obj.SetActive(false); obj.transform.parent = transform; BasePoolComponent bhv = obj.GetComponent<BasePoolComponent>(); if(bhv != null) bhv.OnCreatedByPool(this); _inactive.InsertAtTail(ref obj); _count++; } } } /** * @brief removes game objects from a given list. */ void RemoveGameObjects(ComponentList list, int count) { for (int i = 0; i< count && !list.isEmpty; i++) { GameObject obj = list.RemoveTailGO(); GameObject.Destroy(obj); _count--; } } /** * @brief spawns a prfab with the spawners position and rotation */ public GameObject Spawn() { return Spawn (transform.position, transform.rotation); } /** * @brief spawns a clone at a given position and rotation * @param position Vector3 position to spawn at * @param rotation Quaternion rotation to set the new object to. * @return Spawned Game Object; */ public GameObject Spawn( Vector3 position, Quaternion rotation ) { if ( data.prefab == null) { return null; } if( _inactive.isEmpty && isFull) { AddNewGameObjects(); } if(!_inactive.isEmpty) { GameObject obj = _inactive.RemoveHeadGO(); if( obj != null ) { obj.transform.position = position; obj.transform.rotation = rotation; if( rigidbody != null ) { rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; } if( rigidbody2D != null ) { rigidbody2D.velocity = Vector2.zero; rigidbody2D.angularVelocity = 0f; } obj.SetActive(true); BasePoolComponent cmp = obj.GetComponent<BasePoolComponent>(); if( cmp != null ) { cmp.OnSpawn(); } _active.InsertAtTail(ref obj); return obj; } } return null; } /** * @brief despawns on object * @param GameObject game objects to remove from the active scene. */ public void Despawn(GameObject obj) { PoolListableComponent listable = obj.GetComponent<PoolListableComponent>(); if( listable != null && listable.list.Equals(_active)) { _active.Remove(obj); _despawn.InsertAtTail(ref obj); } } /** * @brief unity start function * * Sets the object pool and prefab up for use with the pool. */ void Start () { //StartCoroutine ( CullRoutine () ); StartCoroutine ( BackgroundProcess () ); /* for(int i = 0; i < 6; i++) Spawn(); */ } /** * @brief set up active and inactive lists before start. * * Sets the object pool and prefab up for use with the pool. */ void Awake() { if ( data.prefab != null ) { PoolListableComponent listable = data.prefab.GetComponent<PoolListableComponent> (); if ( listable == null ) { data.prefab.AddComponent<PoolListableComponent> (); ///< adds a listable component to the prefab objects so the clones can be listed. } } _inactive = new ComponentList (); _active = new ComponentList (); _despawn = new ComponentList (); AddNewGameObjects (); } /** * @brief static find function * * Seaches though all pools in the scene for one that generates the prefab. * @param GameObject the prefab of the pool you wish to find * @return a matching pool or null; */ public static SimplePool FindPoolFor(GameObject prefab) { foreach (SimplePool pool in FindObjectsOfType<SimplePool>()) { if (pool.data.prefab.Equals(prefab)) { return pool; } } return null; } /** * @brief static find function * * Seaches though all pools in the scene for one that generates the prefab. * @param GameObject the prefab of the pool you wish to find * @return IEnumerable<SimplePool> yielding all matching pools; */ public static System.Collections.Generic.IEnumerable<SimplePool> FindAllPoolsFor(GameObject prefab) { foreach (SimplePool pool in FindObjectsOfType<SimplePool>()) { if (pool.data.prefab.Equals(prefab)) { yield return pool; } } yield break; } /** * @brief static find function * * Seaches though all pools in the scene for one that has a similar PoolData block * @param GameObject the prefab of the pool you wish to find * @return a matching pool or null; */ public static SimplePool FindPoolFor(PoolData data) { foreach (SimplePool pool in FindObjectsOfType<SimplePool>()) { if ( pool.data == data ) { return pool; } } return null; } /** * @brief static find function * * Seaches though all pools in the scene for one that has a similar PoolData block * @param GameObject the prefab of the pool you wish to find * @return IEnumerable<SimplePool> yielding all matching pools; */ public static System.Collections.Generic.IEnumerable<SimplePool> FindAllPoolsFor(PoolData data) { foreach (SimplePool pool in FindObjectsOfType<SimplePool>()) { if (pool.data == data) { yield return pool; } } yield break; } /** * @brief static create pool function * * searches for a similar pool if non is found it will create one. * @param GameObject the prefab of the pool you wish to find/create * @return a matching pool or a new pool; */ public static SimplePool CreatePool(GameObject prefab) { PoolData data = new PoolData(prefab); return CreatePool(data); } /** * @brief static create pool function * * searches for a similar pool if non is found it will create one. * @param GameObject the prefab of the pool you wish to find/create * @param int maxium number of objects to clone * @param int the number of objects to create when new objects are needed. * @param bool cull the inactive objects on a set interval * @param float the interval of the cull events. * @return a matching pool or a new pool; */ public static SimplePool CreatePool(GameObject prefab, int maxCount, int batchCreateCount, bool cullInactive, float cullInterval) { PoolData data = new PoolData(prefab, maxCount, batchCreateCount, cullInactive, cullInterval); return CreatePool(data); } /** * @brief static create pool function * * searches for a similar pool if non is found it will create one. * @param string name of the GameObject the pool component is attached to * @param GameObject the prefab of the pool you wish to find/create * @return a matching pool or a new pool; */ public static SimplePool CreatePool(string gameObjectName, GameObject prefab) { PoolData data = new PoolData(prefab); return CreatePool(gameObjectName, data); } /** * @brief static create pool function * * searches for a similar pool if non is found it will create one. * @param string name of the GameObject the pool component is attached to * @param GameObject the prefab of the pool you wish to find/create * @param int maxium number of objects to clone * @param int the number of objects to create when new objects are needed. * @param bool cull the inactive objects on a set interval * @param float the interval of the cull events. * @return a matching pool or a new pool; */ public static SimplePool CreatePool(string gameObjectName, GameObject prefab, int maxCount, int batchCreateCount, bool cullInactive, float cullInterval) { PoolData data = new PoolData(prefab, maxCount, batchCreateCount, cullInactive, cullInterval); return CreatePool(gameObjectName, data); } /** * @brief static create pool function * * searches for a similar pool if non is found it will create one. * @param PoolData object that is used to create the pool component. * @return a matching pool or a new pool; */ public static SimplePool CreatePool(PoolData data) { if (data == null || data.prefab == null) return null; return CreatePool(data.prefab.name + "_pool",data); } /** * @brief static create pool function * * searches for a similar pool if non is found it will create one. * @param string name of the GameObject the pool component is attached to * @param PoolData object that is used to create the pool component. * @return a matching pool or a new pool; */ public static SimplePool CreatePool(string gameObjectName, PoolData data) { if (data == null || data.prefab == null) return null; SimplePool pool = FindPoolFor(data); if (pool == null) { GameObject obj = new GameObject(data.prefab.name + "_pool"); pool = obj.AddComponent<SimplePool>(); pool.data = data; } return pool; } } } }
919e8616792741dab85b7591aa92e8cf0186ace2
[ "Markdown", "C#" ]
12
C#
OneBrokenPixel/breakout
a33f5b0cd2defeddbf8b4f88865d5e9568244bb7
9284fdbb25b7dadb06f02ab4d92ff395f936604e
refs/heads/master
<file_sep># .bashrc printf '===========================\nTop 5 CPU processes (col 3)\n===========================\n' ps aux | sort -rk 3,3 | head -n 6 printf '\n==============================\nTop 5 memory processes (col 4)\n==============================\n' ps aux | sort -rk 4,4 | head -n 6 # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi # User specific aliases and functions # Custom prompts 1 & 2 export PS1="\n\e[0;32m[\u@\h]\$\n\w \e[m" export PS2="\n\e[0;33m[>] \e\m" # Show all files function l() { ls -a -l --block-size=\'1 --color=auto } # Change dir and l function c() { cd "$@" && l } # Easier navigation: cd to .., ..., .... ~ & http dir, all with lsa alias ..="c .." alias ...="c ../.." alias ....="c ../../.." alias ~="c ~" alias http="c /srv/http" alias tree="tree -a -C" # Save us from killing root alias rm="rm --preserve-root" # Reload the shell (i.e. invoke as a login shell with .bash_profile, which likely this file) # switch -l to -i if you just want to reload this file alias rebash="exec $SHELL -l" # Nano this file, .inputrc or .nanorc alias profile="sudo nano ~/.bashrc" alias input="sudo nano ~/.inputrc" alias nanorc="sudo nano ~/.nanorc" # Display memory info totals alias meminfo="free -m -l -t" # Reload Nginx or PHP FPM alias nginxt="sudo nginx -t" alias nginxr="sudo service nginx reload" alias phpr="sudo service php-fpm restart" # Go to nginx or php-fpm dirs alias gonginx="c /etc/nginx/conf.d/" alias gophp="c /etc/php-fpm.d/" # List of users alias userslist='cat /etc/passwd |grep "/bin/bash" |grep "[5-9][0-9][0-9]" |cut -d: -f1' # List of all users with UID function userslistall() { awk -F":" '{ print "username: " $1 "\t\tuid:" $3 }' /etc/passwd } # Create a new dir and enter it function mkd() { mkdir -p "$@" && cd "$@" } # Sudo nano a file function edit() { sudo nano "$@" } # Remove a dir and everything inside function killdir() { sudo rm -rf "$@" } # Zip this dir recursively function zipthis() { thisdir=${PWD##*/} sudo zip -r $thisdir.zip . } # Get a file following to end point, from sites such as mailbigfile.com # argument must be within double quotes when called function getzip() { curl -o file.zip -L "$@" } # List the sub dir sizes in human readable format as a summary function dirsizes() { sudo du -h -s * }
0d1025ce08352b3d6c44e53c32bd76b6b4ae3a18
[ "Shell" ]
1
Shell
interbiznw/dotfiles
56f18c8187ae261fc7f3a2fa25b5e332ece4833b
4505069f17654f89f77f712454e24b866c9d7cf8
refs/heads/main
<file_sep># football this is a football restful API ## Before Use Run This : "npm i" OR "npm install" <file_sep>const express= require("express"); const app = express(); const router = express.Router(); require("dotenv").config(); const fetch =require('node-fetch'); //--------------------- this to get teams , logo and player in it --------------------------// router.get("/getteams",async(req,res)=>{ const url =`https://apiv3.apifootball.com/?action=get_teams&league_id=302&APIkey=${process.env.API_KEY}`; try{ await fetch(url) .then(res=>res.json()) .then((data)=>{ for(var i in data){ if(data[i]=="<NAME>"){ console.log(data[i]); } } res.json(data) }) }catch (err){ console.log(err) } }); //--------------------- Search with players name --------------------------// router.get("/getplayer/:name",async(req,res)=>{ const name =req.params.name; const url =`https://apiv3.apifootball.com/?action=get_players&player_name=${name}&APIkey=${process.env.API_KEY}`; try{ await fetch(url) .then(res=>res.json()) .then((data)=>{ res.json(data) }) }catch (err){ console.log(err) } }); // -------------- get countries id ,Logo , Name ----------------------- // router.get("/getcountryid",async(req,res)=>{ const url =`https://apiv3.apifootball.com/?action=get_countries&APIkey=${process.env.API_KEY}`; try{ await fetch(url) .then(res=>res.json()) .then((data)=>{ res.json(data) }) }catch (err){ console.log(err) } }); //https://apiv3.apifootball.com/?action=get_countries app.use(router); app.listen(process.env.PORT,()=>console.log(`server run on ${process.env.PORT}`))
0a2f9f9375363400ed68ebb7d09c84cf94099ea2
[ "Markdown", "JavaScript" ]
2
Markdown
ahmedsolimanpts/football
53861962d24098faa1c537109f9a83dcd2f3d07c
1b486b6b0a8815e6eb2c3dd65174dd0acc102071
refs/heads/master
<repo_name>dscusnets/dscusnets<file_sep>/src/test/java/com/qaprosoft/carina/core/demo/NativeSeleniumTest.java /* * Copyright 2013 QAPROSOFT (http://qaprosoft.com/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qaprosoft.carina.core.demo; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class NativeSeleniumTest { private Logger LOG = Logger.getLogger(NativeSeleniumTest.class); private WebDriver driver; @BeforeTest public void init() { driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @AfterTest public void finilize() { driver.quit(); } @Test @Parameters({"email", "password"}) public void testGoogleLogin(String email, String password) throws Exception { driver.get("https://mail.google.com/"); LOG.info("URL 'https://mail.google.com/' is opened"); ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).createNewFile(); driver.findElement(By.id("Email")).sendKeys(email); LOG.info(email + " keys are sent to emailTextField"); driver.findElement(By.id("Passwd")).sendKeys(<PASSWORD>); LOG.info(email + " keys are sent to emailTextField"); driver.findElement(By.id("signIn")).click(); LOG.info("signInButton is clicked"); driver.get("https://mail.google.com/mail/u/0/#inbox"); LOG.info("URL 'https://mail.google.com/mail/u/0/#inbox' is opened"); ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).createNewFile(); Assert.assertEquals(driver.findElement(By.id("gbgs4dn")).getText(), email); } }<file_sep>/README.md # dscusnets Discovery Communications US Nets Sites Test Automation Suite ...Update Test.... <file_sep>/soap/geoip/Config.properties endpoint=http://www.webservicex.net/geoipservice.asmx<file_sep>/src/main/java/com/discovery/qa/main/sites/DS_HomePagePerf.java package com.discovery.qa.main.sites; import com.qaprosoft.carina.core.foundation.performance.*; import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement; import com.qaprosoft.carina.core.gui.AbstractPage; import com.thoughtworks.selenium.Selenium; import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium; import org.apache.log4j.Logger; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.testng.Assert; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.File; import java.util.Hashtable; import java.util.List; @SuppressWarnings("deprecation") public class DS_HomePagePerf extends AbstractPage { private static final Logger logger = Logger.getLogger(DS_HomePage.class); public DS_HomePagePerf(WebDriver driver) { super(driver); setPageAbsoluteURL("http://www.discovery.com"); open(); } private static final String hostName = "http://www.discovery.com"; //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ LOGIN OBJECTS ************// @FindBy(id = "user_login") private ExtendedWebElement fieldUsername; @FindBy(id = "user_pass") private ExtendedWebElement fieldUserPassword; @FindBy(id = "wp-submit") private ExtendedWebElement btnLogIn; @FindBy(xpath = "//a[@class='ab-item'][@aria-haspopup='true']") private ExtendedWebElement statusAuthenticated; @FindBy(xpath = "//a[@class='whoKnowsWhoCares'][@aria-haspopup='thisIsMeantToFail']") private ExtendedWebElement statusNonExistingItem; @FindBy(xpath = "//div[@id='page-ad-container-bannerFlexOne']") private ExtendedWebElement statusVisibleBanner; //************ LOGIN OBJECTS ************// //************ TITLE BAR OBJECTS ************// @FindBy(xpath = "//a[@class='ab-item'][contains(text(), 'Discovery')]") private ExtendedWebElement btnTitleBarDiscovery; @FindBy(xpath = "//a[@class='ab-item'][@aria-haspopup='true']") private ExtendedWebElement statusHowdy; //************ TITLE BAR OBJECTS ************// //************ MENU BAR OBJECTS ************// @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Dashboard')]") private ExtendedWebElement btnMenuBarDashboard; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Facts')]") private ExtendedWebElement btnMenuBarFacts; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Page Templates')]") private ExtendedWebElement btnMenuBarPageTemplates; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Featured Links')]") private ExtendedWebElement btnMenuBarFeaturedLinks; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Authors')]") private ExtendedWebElement btnMenuBarAuthors; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Media')]") private ExtendedWebElement btnMenuBarMedia; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Blogs')]") private ExtendedWebElement btnMenuBarBlogs; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Lists')]") private ExtendedWebElement btnMenuBarLists; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'TV Listings')]") private ExtendedWebElement btnMenuBarTVListings; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Video')]") private ExtendedWebElement btnMenuBarVideo; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Photo Galleries')]") private ExtendedWebElement btnMenuBarPhotoGalleries; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Pages')]") private ExtendedWebElement btnMenuBarPages; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Taxonomy')]") private ExtendedWebElement btnMenuBarTaxonomy; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'URL Redirects')]") private ExtendedWebElement btnMenuBarURLRedirects; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Appearance')]") private ExtendedWebElement btnMenuBarAppearance; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Plugins')]") private ExtendedWebElement btnMenuBarPlugins; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Access')]") private ExtendedWebElement btnMenuBarAccess; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Tools')]") private ExtendedWebElement btnMenuBarTools; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Settings')]") private ExtendedWebElement btnMenuBarSettings; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Ad Management')]") private ExtendedWebElement btnMenuBarAdManagement; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Migration')]") private ExtendedWebElement btnMenuBarMigration; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Job Manager')]") private ExtendedWebElement btnMenuBarJobManager; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Optimizely')]") private ExtendedWebElement btnMenuBarOptimizely; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Site Settings')]") private ExtendedWebElement btnMenuBarSiteSettings; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Collapse Menu')]") private ExtendedWebElement btnMenuBarCollapseMenu; //************ MENU BAR OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// public void getMythbustersPagePreReFactor() { driver.get("about:blank"); long discoverySitesPerformanceTestDSC001MythbustersPreRefactorStart = System.currentTimeMillis(); driver.get(hostName + "/tv-shows/mythbusters/?optimizely_disable=true"); if (isElementPresent(statusVisibleBanner)) { long discoverySitesPerformanceTestDSC001MythbustersPreRefactorStop = System.currentTimeMillis(); long MythbustersPreRefactorRoundTripTime = (discoverySitesPerformanceTestDSC001MythbustersPreRefactorStop - discoverySitesPerformanceTestDSC001MythbustersPreRefactorStart); logger.info("Mythbusters Pre-Refactor Time (ms): " + MythbustersPreRefactorRoundTripTime); } } public void getMythbustersPagePostReFactor() { driver.get("about:blank"); long discoverySitesPerformanceTestDSC001MythbustersPostRefactorStart = System.currentTimeMillis(); driver.get(hostName + "/tv-shows/mythbusters/?rfc=1"); if (isElementPresent(statusVisibleBanner)) { long discoverySitesPerformanceTestDSC001MythbustersPostRefactorStop = System.currentTimeMillis(); long MythbustersPostRefactorRoundTripTime = (discoverySitesPerformanceTestDSC001MythbustersPostRefactorStop - discoverySitesPerformanceTestDSC001MythbustersPostRefactorStart); logger.info("Mythbusters Post-Refactor Time (ms): " + MythbustersPostRefactorRoundTripTime); } } public void getGoldRushPagePreReFactor() { driver.get("about:blank"); long discoverySitesPerformanceTestDSC001GoldRushPreRefactorStart = System.currentTimeMillis(); driver.get(hostName + "/tv-shows/gold-rush/?optimizely_disable=true"); if (isElementPresent(statusVisibleBanner)) { long discoverySitesPerformanceTestDSC001GoldRushPreRefactorStop = System.currentTimeMillis(); long GoldRushPreRefactorRoundTripTime = (discoverySitesPerformanceTestDSC001GoldRushPreRefactorStop - discoverySitesPerformanceTestDSC001GoldRushPreRefactorStart); logger.info("Gold Rush Pre-Refactor Time (ms): " + GoldRushPreRefactorRoundTripTime); } } public void getGoldRushPagePostReFactor() { long discoverySitesPerformanceTestDSC001GoldRushPostRefactorStart = System.currentTimeMillis(); driver.get(hostName + "/tv-shows/gold-rush/?rfc=1"); if (isElementPresent(statusVisibleBanner)) { long discoverySitesPerformanceTestDSC001GoldRushPostRefactorStop = System.currentTimeMillis(); long GoldRushPostRefactorRoundTripTime = (discoverySitesPerformanceTestDSC001GoldRushPostRefactorStop - discoverySitesPerformanceTestDSC001GoldRushPostRefactorStart); logger.info("Gold Rush Post-Refactor Time (ms): " + GoldRushPostRefactorRoundTripTime); } } public void getDeadliestCatchPagePreReFactor() { driver.get("about:blank"); long discoverySitesPerformanceTestDSC001DeadliestCatchPreRefactorStart = System.currentTimeMillis(); driver.get(hostName + "/tv-shows/deadliest-catch/?optimizely_disable=true"); if (isElementPresent(statusVisibleBanner)) { long discoverySitesPerformanceTestDSC001DeadliestCatchPreRefactorStop = System.currentTimeMillis(); long DeadliestCatchPreRefactorRoundTripTime = (discoverySitesPerformanceTestDSC001DeadliestCatchPreRefactorStop - discoverySitesPerformanceTestDSC001DeadliestCatchPreRefactorStart); logger.info("Deadliest Catch Pre-Refactor Time (ms): " + DeadliestCatchPreRefactorRoundTripTime); } } public void getDeadliestCatchPagePostReFactor() { driver.get("about:blank"); long discoverySitesPerformanceTestDSC001DeadliestCatchPostRefactorStart = System.currentTimeMillis(); driver.get(hostName + "/tv-shows/deadliest-catch/?rfc=1"); if (isElementPresent(statusVisibleBanner)) { long discoverySitesPerformanceTestDSC001DeadliestCatchPostRefactorStop = System.currentTimeMillis(); long DeadliestCatchPostRefactorRoundTripTime = (discoverySitesPerformanceTestDSC001DeadliestCatchPostRefactorStop - discoverySitesPerformanceTestDSC001DeadliestCatchPostRefactorStart); logger.info("Deadliest Catch Post-Refactor Time (ms): " + DeadliestCatchPostRefactorRoundTripTime); } } public void searchForItemThatDoesNotExist() { if (isElementPresent(statusAuthenticated)) { Assert.assertTrue(isElementPresent(statusNonExistingItem, 60),"Failure Has Been Forced!"); // Assert.assertEquals(profile, headerLabel.getText().toLowerCase(),"Profile name is not match!"); } } } <file_sep>/soap/geoip/Temp.properties ip=192.168.3.11 country_code=BLR country_name=Belarus<file_sep>/src/main/java/com/discovery/qa/main/sites/DS_HomePage.java package com.discovery.qa.main.sites; import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement; import com.qaprosoft.carina.core.gui.AbstractPage; import com.thoughtworks.selenium.Selenium; import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium; import org.apache.log4j.Logger; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.testng.Assert; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.File; import java.util.Hashtable; import java.util.List; @SuppressWarnings("deprecation") public class DS_HomePage extends AbstractPage { private static final Logger logger = Logger.getLogger(DS_HomePage.class); public DS_HomePage(WebDriver driver) { super(driver); setPageAbsoluteURL("https://fusion.www.discovery.com.qa-9.i.dsc.tv/wp-admin"); open(); } private static final String hostName = "https://fusion.www.discovery.com.qa-9.i.dsc.tv/wp-admin"; //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ LOGIN OBJECTS ************// @FindBy(id = "user_login") private ExtendedWebElement fieldUsername; @FindBy(id = "user_pass") private ExtendedWebElement fieldUserPassword; @FindBy(id = "wp-submit") private ExtendedWebElement btnLogIn; @FindBy(xpath = "//a[@class='ab-item'][@aria-haspopup='true']") private ExtendedWebElement statusAuthenticated; @FindBy(xpath = "//a[@class='whoKnowsWhoCares'][@aria-haspopup='thisIsMeantToFail']") private ExtendedWebElement statusNonExistingItem; private ExtendedWebElement statusHello; //************ LOGIN OBJECTS ************// //************ TITLE BAR OBJECTS ************// @FindBy(xpath = "//a[@class='ab-item'][contains(text(), 'Discovery')]") private ExtendedWebElement btnTitleBarDiscovery; @FindBy(xpath = "//a[@class='ab-item'][@aria-haspopup='true']") private ExtendedWebElement statusHowdy; //************ TITLE BAR OBJECTS ************// //************ MENU BAR OBJECTS ************// @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Dashboard')]") private ExtendedWebElement btnMenuBarDashboard; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Facts')]") private ExtendedWebElement btnMenuBarFacts; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Page Templates')]") private ExtendedWebElement btnMenuBarPageTemplates; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Featured Links')]") private ExtendedWebElement btnMenuBarFeaturedLinks; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Authors')]") private ExtendedWebElement btnMenuBarAuthors; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Media')]") private ExtendedWebElement btnMenuBarMedia; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Blogs')]") private ExtendedWebElement btnMenuBarBlogs; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Lists')]") private ExtendedWebElement btnMenuBarLists; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'TV Listings')]") private ExtendedWebElement btnMenuBarTVListings; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Video')]") private ExtendedWebElement btnMenuBarVideo; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Photo Galleries')]") private ExtendedWebElement btnMenuBarPhotoGalleries; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Pages')]") private ExtendedWebElement btnMenuBarPages; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Taxonomy')]") private ExtendedWebElement btnMenuBarTaxonomy; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'URL Redirects')]") private ExtendedWebElement btnMenuBarURLRedirects; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Appearance')]") private ExtendedWebElement btnMenuBarAppearance; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Plugins')]") private ExtendedWebElement btnMenuBarPlugins; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Access')]") private ExtendedWebElement btnMenuBarAccess; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Tools')]") private ExtendedWebElement btnMenuBarTools; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Settings')]") private ExtendedWebElement btnMenuBarSettings; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Ad Management')]") private ExtendedWebElement btnMenuBarAdManagement; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Migration')]") private ExtendedWebElement btnMenuBarMigration; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Job Manager')]") private ExtendedWebElement btnMenuBarJobManager; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Optimizely')]") private ExtendedWebElement btnMenuBarOptimizely; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Site Settings')]") private ExtendedWebElement btnMenuBarSiteSettings; @FindBy(xpath = "//div[@class='wp-menu-name'][contains(text(), 'Collapse Menu')]") private ExtendedWebElement btnMenuBarCollapseMenu; //************ MENU BAR OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ IDENTIFIER OBJECTS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// //************ BEGIN FUNCTIONS ************// public void login(String username, String password) { if (isElementPresent(fieldUsername)) { type(fieldUsername, username); type(fieldUserPassword, password); click(btnLogIn); /* if (isElementPresent(selProfile)) { select(selProfile, profile); click(btnSubmitProfile); } */ Assert.assertTrue(isElementPresent(statusAuthenticated, 60),"Login operation is not successful!"); // Assert.assertEquals(profile, headerLabel.getText().toLowerCase(),"Profile name is not match!"); } } public void getMythbustersPagePreReFactor() { driver.get(hostName + "/tv-shows/mythbusters/"); } public void getMythbustersPagePostReFactor() { driver.get(hostName + "/tv-shows/mythbusters/?rfc=1"); } public void getGoldRushPagePreReFactor() { driver.get(hostName + "/tv-shows/gold-rush/"); } public void getGoldRushPagePostReFactor() { driver.get(hostName + "/tv-shows/gold-rush/?rfc=1"); } public void getDeadliestCatchPagePreReFactor() { driver.get(hostName + "/tv-shows/deadliest-catch/"); } public void getDeadliestCatchPagePostReFactor() { driver.get(hostName + "/tv-shows/deadliest-catch/?rfc=1"); } public void searchForItemThatDoesNotExist() { if (isElementPresent(statusAuthenticated)) { Assert.assertTrue(isElementPresent(statusNonExistingItem, 60),"Failure Has Been Forced!"); // Assert.assertEquals(profile, headerLabel.getText().toLowerCase(),"Profile name is not match!"); } } } <file_sep>/src/test/java/com/discovery/qa/tests/web/sites/DiscoveryPerformanceTestSuite.java package com.discovery.qa.tests.web.sites; import com.discovery.qa.main.sites.DS_HomePagePerf; import com.qaprosoft.carina.core.foundation.UITest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class DiscoveryPerformanceTestSuite extends UITest { //************ TEXT FIELD VALUES ************// //************ TEXT FIELD VALUES ************// //************ TEXT FIELD VALUES ************// //************ TEXT FIELD VALUES ************// //************ TEXT FIELD VALUES ************// //************ TEXT FIELD VALUES ************// //************ MAJOR LEAGUE TESTS ************// //************ MAJOR LEAGUE TESTS ************// //************ MAJOR LEAGUE TESTS ************// private DS_HomePagePerf basePart(){ DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); // homePage.oldUIToNewUI(majorLeagueSiteSelection); return homePage; } // @Parameters({"month","day","year"}) // @Test // public void discoverySitesTestDSC000TestFunction() { // DS_HomePagePerf homePage = basePart(); // homePage.probablesGameContentAddPlayers(month,day,year); // homePage.probablesGameContentDeletePlayers(month,day,year); // } @Test public void discoverySitesPerformanceTestDSC001MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC002MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC003GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC004GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC005DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC006DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC011MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC012MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC013GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC014GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC015DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC016DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC021MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC022MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC023GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC024GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC025DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC026DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC031MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC032MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC033GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC034GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC035DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC036DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC041MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC042MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC043GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC044GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC045DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC046DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC051MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC052MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC053GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC054GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC055DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC056DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC061MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC062MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC063GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC064GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC065DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC066DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC071MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC072MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC073GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC074GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC075DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC076DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC081MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC082MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC083GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC084GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC085DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC086DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC091MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC092MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC093GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC094GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC095DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC096DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC101MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC102MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC103GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC104GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC105DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC106DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC111MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC112MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC113GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC114GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC115DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC116DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC121MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC122MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC123GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC124GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC125DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC126DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC131MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC132MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC133GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC134GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC135DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC136DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC141MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC142MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC143GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC144GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC145DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC146DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC151MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC152MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC153GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC154GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC155DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC156DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC161MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC162MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC163GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC164GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC165DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC166DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC171MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC172MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC173GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC174GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC175DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC176DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC181MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC182MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC183GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC184GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC185DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC186DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC191MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC192MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC193GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC194GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC195DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC196DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC201MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC202MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC203GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC204GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC205DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC206DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC211MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC212MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC213GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC214GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC215DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC216DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC221MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC222MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC223GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC224GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC225DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC226DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC231MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC232MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC233GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC234GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC235DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC236DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC241MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC242MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC243GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC244GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC245DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC246DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC251MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC252MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC253GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC254GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC255DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC256DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC261MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC262MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC263GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC264GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC265DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC266DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC271MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC272MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC273GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC274GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC275DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC276DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC281MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC282MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC283GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC284GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC285DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC286DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC291MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC292MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC293GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC294GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC295DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC296DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC301MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC302MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC303GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC304GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC305DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC306DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC311MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC312MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC313GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC314GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC315DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC316DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC321MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC322MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC323GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC324GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC325DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC326DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC331MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC332MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC333GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC334GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC335DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC336DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC341MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC342MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC343GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC344GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC345DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC346DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC351MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC352MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC353GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC354GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC355DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC356DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC361MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC362MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC363GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC364GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC365DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC366DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC371MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC372MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC373GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC374GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC375DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC376DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC381MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC382MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC383GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC384GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC385DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC386DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC391MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC392MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC393GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC394GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC395DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC396DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC401MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC402MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC403GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC404GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC405DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC406DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC411MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC412MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC413GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC414GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC415DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC416DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC421MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC422MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC423GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC424GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC425DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC426DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC431MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC432MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC433GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC434GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC435DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC436DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC441MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC442MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC443GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC444GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC445DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC446DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC451MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC452MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC453GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC454GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC455DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC456DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC461MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC462MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC463GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC464GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC465DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC466DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC471MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC472MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC473GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC474GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC475DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC476DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC481MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC482MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC483GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC484GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC485DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC486DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC491MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC492MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC493GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC494GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC495DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC496DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC501MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC502MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC503GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC504GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC505DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC506DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC511MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC512MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC513GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC514GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC515DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC516DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC521MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC522MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC523GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC524GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC525DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC526DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC531MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC532MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC533GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC534GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC535DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC536DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC541MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC542MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC543GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC544GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC545DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC546DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC551MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC552MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC553GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC554GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC555DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC556DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC561MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC562MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC563GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC564GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC565DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC566DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC571MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC572MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC573GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC574GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC575DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC576DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC581MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC582MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC583GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC584GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC585DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC586DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC591MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC592MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC593GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC594GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC595DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC596DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC601MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC602MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC603GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC604GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC605DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC606DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC611MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC612MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC613GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC614GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC615DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC616DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC621MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC622MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC623GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC624GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC625DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC626DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC631MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC632MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC633GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC634GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC635DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC636DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC641MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC642MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC643GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC644GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC645DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC646DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC651MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC652MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC653GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC654GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC655DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC656DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC661MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC662MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC663GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC664GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC665DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC666DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC671MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC672MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC673GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC674GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC675DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC676DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC681MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC682MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC683GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC684GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC685DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC686DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC691MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC692MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC693GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC694GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC695DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC696DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC701MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC702MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC703GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC704GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC705DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC706DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC711MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC712MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC713GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC714GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC715DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC716DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC721MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC722MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC723GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC724GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC725DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC726DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC731MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC732MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC733GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC734GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC735DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC736DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC741MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC742MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC743GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC744GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC745DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC746DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC751MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC752MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC753GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC754GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC755DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC756DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC761MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC762MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC763GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC764GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC765DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC766DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC771MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC772MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC773GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC774GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC775DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC776DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC781MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC782MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC783GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC784GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC785DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC786DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC791MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC792MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC793GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC794GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC795DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC796DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC801MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC802MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC803GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC804GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC805DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC806DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC811MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC812MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC813GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC814GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC815DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC816DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC821MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC822MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC823GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC824GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC825DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC826DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC831MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC832MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC833GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC834GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC835DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC836DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC841MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC842MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC843GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC844GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC845DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC846DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC851MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC852MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC853GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC854GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC855DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC856DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC861MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC862MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC863GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC864GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC865DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC866DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC871MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC872MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC873GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC874GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC875DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC876DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC881MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC882MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC883GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC884GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC885DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC886DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC891MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC892MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC893GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC894GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC895DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC896DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC901MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC902MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC903GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC904GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC905DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC906DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC911MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC912MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC913GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC914GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC915DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC916DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC921MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC922MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC923GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC924GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC925DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC926DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC931MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC932MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC933GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC934GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC935DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC936DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC941MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC942MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC943GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC944GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC945DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC946DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC951MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC952MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC953GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC954GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC955DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC956DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC961MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC962MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC963GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC964GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC965DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC966DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC971MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC972MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC973GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC974GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC975DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC976DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC981MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC982MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC983GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC984GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC985DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC986DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC991MythbustersPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC992MythbustersPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getMythbustersPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC993GoldRushPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC994GoldRushPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getGoldRushPagePostReFactor(); } @Test public void discoverySitesPerformanceTestDSC995DeadliestCatchPreRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePreReFactor(); } @Test public void discoverySitesPerformanceTestDSC996DeadliestCatchPostRefactor() { DS_HomePagePerf homePage = new DS_HomePagePerf(getDriver()); homePage.getDeadliestCatchPagePostReFactor(); } } <file_sep>/src/main/java/com/qaprosoft/carina/core/demo/util/CustomJiraUpdater.java package com.qaprosoft.carina.core.demo.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import net.rcarz.jiraclient.Field; import net.rcarz.jiraclient.Issue; import net.rcarz.jiraclient.JiraClient; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.testng.ITestResult; import com.qaprosoft.carina.core.foundation.jira.IJiraUpdater; import com.qaprosoft.carina.core.foundation.report.TestResultItem; import com.qaprosoft.carina.core.foundation.utils.Configuration; import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter; public class CustomJiraUpdater implements IJiraUpdater { protected static final Logger LOG = Logger.getLogger(CustomJiraUpdater.class); @Override public void updateAfterTest(JiraClient jira, ITestResult result) { try { String description = result.getMethod().getDescription(); // Check if test description has JIRA id if(!StringUtils.isEmpty(description) && description.contains("JIRA#")) { String id = description.split("#")[1]; // Retrieve Jira issue using client Issue issue = jira.getIssue(id); if("Done".equals(issue.getStatus().getName())) { // Reopen issue issue.transition().execute("Reopen and start progress"); } String date = new SimpleDateFormat(Configuration.get(Parameter.DATE_FORMAT)).format(new Date()); // PASS if(result.getStatus() == 1) { // If test passed - press done, and add comment issue.transition().execute("Done"); issue.addComment("PASSED at " + date); } // FAIL else { // If test failed - populated description with details and add comment issue.update().field(Field.DESCRIPTION, result.getThrowable().getMessage()).execute(); issue.addComment("FAILED at " + date); } } } catch(Exception e) { LOG.error("Jira status not updated: " + e.getMessage()); } } @Override public void updateAfterSuite(JiraClient jira, List<TestResultItem> results) throws Exception { // Do nothing after test suite } }
365a4acb41facf2c545404263453bfaa1f7afa36
[ "Markdown", "Java", "INI" ]
8
Java
dscusnets/dscusnets
094875ef474de9e31cdcc0e72eba04921b27de0b
62a04aff97ec285d9675fcd0009b3d81ce105616
refs/heads/master
<file_sep>var express = require('express'); var router = express.Router(); var pieces = require('../server/models/pieces'); /* GET random piece */ router.get('/pieces/random', function(req, res, next) { console.log('enter random router'); pieces.getRandom(function(err, piece) { console.log(err); console.log(piece); if (err) return next(err); res.json(piece); }); }); module.exports = router;<file_sep>var dbHelper = {}; var MongoClient = require('mongodb').MongoClient; // Connection URL var url = 'mongodb://localhost:27017/autoplay'; // Use connect method to connect to the Server dbHelper.connect = function(callback) { MongoClient.connect(url, callback); } dbHelper.findDocument = function(db, collectionName, cirteria, callback) { var collection = db.collection(collectionName); // Find some documents // operator see: http://docs.mongodb.org/manual/reference/operator/ collection.findOne(cirteria, callback); } module.exports = dbHelper;<file_sep>(function() { angular.module('RootApp').service('PlayerService', ['$rootScope', 'DataService', 'BasePlayer', 'YoukuPlayer', 'YoutubePlayer', function($rootScope, DataService, BasePlayer, YoukuPlayer, YoutubePlayer) { var service = {}; //the piece field service._piece = null; /** * Getter for piece */ service.getPiece = function() { return service._piece; } /** * Setter for piece */ service.setPiece = function(piece) { service._piece = piece; } //the player field service._player = null; /** * Getter for player */ service.getPlayer = function() { return service._player; } /** * Setter for player */ service.setPlayer = function(player) { service._player = player; } //the dataAvailablePromise field service._dataAvailablePromise = null; /** * Getter for dataAvailablePromise */ service.getDataAvailablePromise = function() { return service._dataAvailablePromise; } /** * Setter for dataAvailablePromise */ service.setDataAvailablePromise = function(dataAvailablePromise) { service._dataAvailablePromise = dataAvailablePromise; } //the pieceDataAvailablePromise field service._pieceDataAvailablePromise = null; /** * Getter for pieceDataAvailablePromise */ service.getPieceDataAvailablePromise = function() { return service._pieceDataAvailablePromise; } /** * Setter for pieceDataAvailablePromise */ service.setPieceDataAvailablePromise = function(pieceDataAvailablePromise) { service._pieceDataAvailablePromise = pieceDataAvailablePromise; } //the youtubeJsAvailablePromise field service._youtubeJsAvailablePromise = null; /** * Getter for youtubeJsAvailablePromise */ service.getYoutubeJsAvailablePromise = function() { return service._youtubeJsAvailablePromise; } /** * Setter for youtubeJsAvailablePromise */ service.setYoutubeJsAvailablePromise = function(youtubeJsAvailablePromise) { service._youtubeJsAvailablePromise = youtubeJsAvailablePromise; } //the youkuJsAvailablePromise field service._youkuJsAvailablePromise = null; /** * Getter for youkuJsAvailablePromise */ service.getYoukuJsAvailablePromise = function() { return service._youkuJsAvailablePromise; } /** * Setter for youkuJsAvailablePromise */ service.setYoukuJsAvailablePromise = function(youkuJsAvailablePromise) { service._youkuJsAvailablePromise = youkuJsAvailablePromise; } service.playNextPiece = function playNextPiece() { service.setDataAvailablePromise(DataService.getNextPiece()); service.playPiece(); }; service.playPiece = function playPiece() { service.getDataAvailablePromise().then(function(piece) { if (!piece.videos || !piece.videos[0]) { service.playNextPiece(); return; } service.setPiece(piece); $rootScope.$broadcast('piece-info-available'); switch (piece.videos[0].id.kind) { case 'youku': service.getYoukuJsAvailablePromise().then(function() { if (service.getPlayer()) { if (service.getPlayer() instanceof YoukuPlayer) { //reuse } else { service.getPlayer().destory(); } } else { //first player service.setPlayer(new YoukuPlayer()); } service.getPlayer().playPiece(service.getPiece()); }, function(err) { console.log(err); service.playNextPiece(); }); break; case 'youtube': service.getYoutubeJsAvailablePromise().then(function() { if (service.getPlayer()) { if (service.getPlayer() instanceof YoutubePlayer) { //reuse } else { service.getPlayer().destory(); } } else { //first player service.setPlayer(new YoutubePlayer()); } service.getPlayer().playPiece(service.getPiece()); }, function(err) { console.log(err); service.playNextPiece(); }); break; default: alert('Unknown player type.') } }) } service.loopPiece = function loopPiece() { service.getPlayer().loopPiece(); }; service.unloopPiece = function unloopPiece() { service.getPlayer().unloopPiece(); }; return service; } ]) })();<file_sep>fs = require('fs'); // process the pdf file with qpdf first. fs.readFile('uncompressed.pdf', 'utf8', function(err, data) { if (err) { console.log(err); } // console.log(data); allLinks = data.match(/\(https?:\/\/.*\)/g); // console.log(allLinks); var outFilePath = "./links.txt"; fs.unlinkSync(outFilePath); for (var i = allLinks.length - 1; i >= 0; i--) { var link = allLinks[i].replace(/\((.*)\)/, '$1\n'); fs.appendFile(outFilePath, link, "utf8", function(err) { if (err) { return console.log(err); } }); }; }); <file_sep>(function() { /** * Module * * Description */ angular.module('RootApp', ['restangular']) .value('YOUKU_CLIENT_ID', 'efc2c05958f9cc14') .value('VIEWPORT_ID', 'autoplayer') .value('outOfGWF', true) .config(['$httpProvider', function($httpProvider) { /* * Enable CORS * http://stackoverflow.com/questions/17289195/angularjs-post-data-to-external-rest-api */ $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; }]); })();<file_sep>var fs = require('fs'); Util = {}; Util.writeFile = writeFile; Util.appendFile = appendFile; Util.readFile = readFile; /** * write js object to file system in json format. * @param {String} outFilePath file path * @param {Object} data javascript object data to write. */ function writeFile(outFilePath, data) { fs.writeFile(outFilePath, JSON.stringify(data), function(err) { if (err) { return console.log(err); } }); } function readFile(filePath, callback) { fs.readFile(filePath, function(err, data) { if (err) { callback(err); } else { object = JSON.parse(data); callback(null, object); } }); } function appendFile(outFilePath, data) { fs.appendFile(outFilePath, JSON.stringify(data), function(err) { if (err) { return console.log(err); } }); } module.exports = Util;<file_sep>var bcrypt = require('bcrypt'); var MongoClient = require('mongodb').MongoClient; var ObjectId = require('mongodb').ObjectID; var User = {}; User.findOne = function(criteria, callback) { connect(function(err, db) { if (err) { callback(err); } else { findUser(db, criteria, callback); } }); } User.findById = function(id, callback) { connect(function(err, db) { if (err) { callback(err); } else { findUser(db, { //http://stackoverflow.com/a/14551362/1494097 _id: new ObjectId(id) }, callback); } }) } function connect(callback) { // Connection URL var url = 'mongodb://localhost:27017/autoplay'; // Use connect method to connect to the Server MongoClient.connect(url, function(err, db) { if (err) { // Handle the error. callback(err); } else { //console.log("Connected correctly to server"); callback(null, db); } }); } var findUser = function(db, criteria, callback) { // Get the User collection var collection = db.collection('User'); // Find some documents // operator see: http://docs.mongodb.org/manual/reference/operator/ collection.find(criteria).toArray(function(err, docs) { if (err) { // Handle the error. // callback(err); callback(err); } else { //console.log("Found the following records"); callback(null, processUser(docs[0])); db.close(); } }); } var processUser = function(user) { if (user) { //Rename fields user.id = user._id; delete user._id; user.validPassword = function(plaintext) { console.log(plaintext); console.log(user.password); return bcrypt.compareSync(plaintext, user.password); } } return user; } module.exports = User;<file_sep>(function() { angular.module('RootApp').factory('BasePlayer', ['VIEWPORT_ID', function(VIEWPORT_ID) { return function BasePlayer() { var service = this; service._viewportId = VIEWPORT_ID; service.setViewPortID = function setViewPortID(id) { service.viewportId = id; } service.getViewPortID = function getViewPortID() { return service._viewportId; } //the loop field service._loop = false; /** * Getter for loop */ service.getLoop = function() { return service._loop; } /** * Setter for loop */ service.setLoop = function(loop) { service._loop = loop; } service.loopPiece = function() { service.setLoop(true); } service.unloopPiece = function() { service.setLoop(false); } return service; }; }]); })();<file_sep>var dbHelper = {}; var MongoClient = require('mongodb').MongoClient; // Connection URL var url = 'mongodb://localhost:27017/autoplay'; // Use connect method to connect to the Server dbHelper.connect = function(callback) { MongoClient.connect(url, callback); } module.exports = dbHelper;<file_sep>var http = require('http'); var parseString = require('xml2js').parseString; var _ = require('underscore'); var fs = require('fs'); run(); /** * The entry point */ function run() { var index = 1; var data = []; getOnePage(index, function callback(dataPerPage) { if (!dataPerPage || !dataPerPage.length) { console.log('no result any more. write data.'); data.sort(function(a, b){ return a.id - b.id; }) writeFile('./data.json', data); console.log('data writed.'); } else { data.push.apply(data, dataPerPage); //console.log(dataPerPage); console.log('retrieve ' + dataPerPage.length + ' results in page ' + index + '. Handle next page now...'); getOnePage(++index, callback); } }); } /** * write js object to file system in json format. * @param {String} outFilePath file path * @param {Object} data javascript object data to write. */ function writeFile(outFilePath, data) { fs.writeFile(outFilePath, JSON.stringify(data), "utf8", function(err) { if (err) { return console.log(err); } }); } /** * Retrieve one page data * @param {Number} pageIndex the page index * @param {Function} callback a single argument, the data, * array is expected. */ function getOnePage(pageIndex, callback) { var data = []; var options = { host: 'www.guitarburst.com', path: '/service_advanced_search.php?title=&composer=&keyword=&min_difficulty=1&max_difficulty=20&min_reading=1&max_reading=10&position=15&source=&publisher=&sort=title&custom_sort=undefined&page=' + pageIndex }; cb = function(response) { var responseParts = []; response.setEncoding('utf8'); response.on('data', function(chunk) { // console.log(chunk); responseParts.push(chunk); }); response.on('end', function() { var str = responseParts.join(''); // console.log(str); var tbodyRetriever = /<tbody[^>]*?>[\w\W]*?<\/tbody>/m; var columnInfoTdRemover = /<td[^>]*?column_info[^>]*?>[\w\W]*?<\/td>/gm; tbodyResults = str.match(tbodyRetriever); if (!tbodyResults) { callback(null); } else { str = tbodyResults[0].replace(columnInfoTdRemover, ''); str = str.replace(/[\n\r]/g, '\\n') .replace(/&/g, "&amp;") .replace(/-/g, "&#45;"); // console.log(str); parser(str, callback); } }); } var req = http.request(options, cb); req.end(); } /** * parse the response, which is html code and hence also xml code. * @param {String} xml the xml data. * @param {Function} callback a single argument, the data, * array is expected. */ function parser(xml, callback) { parseString(xml, function(err, result) { if (err) { console.log(err); } // console.log(result); var pieces = []; _.each(result.tbody.tr, function(data) { var piece = {}; var id = data.$.id.replace(/display_row_(.*)/, '$1'); piece['id'] = parseInt(id); _.each(data.td, function(element, index) { var fieldname = element.$.class.replace(/column_(.*)/, '$1'); piece[fieldname] = element._; }); pieces.push(piece); // console.log(piece); }); // console.log(pieces); callback(pieces); }); }<file_sep>var bcrypt = require('bcrypt'); var prompt = require('prompt'); prompt.start(); prompt.get(['password'], function(err, result) { if (err) { return onErr(err); } console.log('Command-line input received:'); console.log(' password: ' + result.password); console.log(' encrypted password: ' + bcrypt.hashSync(result.password, 8)); }); function onErr(err) { console.log(err); return 1; }<file_sep>/** * This script add some video links to data using youtube search api. */ var google = require('googleapis'); var youtube = google.youtube('v3'); var fs = require('fs'); var Util = require('./Util'); var _ = require('underscore'); var async = require('async'); var API_KEY = '<KEY>'; // specify your API key here run(); function run() { var pieces; var piecesWithVideo; async.parallel([ function(callback) { fs.readFile('data.json', function(err, data) { if (err) { callback(err); } else { pieces = JSON.parse(data); callback(null); } }); }, function(callback) { fs.readFile('data-with-video.json', function(err, data) { if (err) { callback(err); } else { piecesWithVideo = JSON.parse(data); callback(null); } }); } ], function(err) { if (err) { console.log(err); } else { dowork(pieces, piecesWithVideo); } } ); } function dowork(pieces, piecesWithVideo) { var count = 1; var changed = false; async.each(pieces, function(piece, callback) { if (contain(piecesWithVideo, piece)) { callback(null); } else { handle(piece, function(err, pieceWithVideo) { if (err) { callback(err); } else { changed = true; piecesWithVideo.push(pieceWithVideo); count++; if (count % 100 == 0) { Util.writeFile('./data-with-video.json', piecesWithVideo); } console.log('We have ' + piecesWithVideo.length + ' already processed. Done with ' + piece.title + ' by ' + piece.composer); callback(null); } }); } }, function(err) { if (err) console.log(err); else { if (changed) { Util.writeFile('./data-with-video.json', piecesWithVideo); } console.log('Done with all files'); } }); } function contain(pieces, piece) { var ids = _.map(pieces, function(piece) { return piece.id; }); return _.contains(ids, piece.id); } function handle(piece, callback) { var q = piece.title + piece.composer; queryYoutube(q, function(err, video) { if (err) { callback(err); } else { if (!piece.videos) { piece.videos = []; } piece.videos.push(video); callback(null, piece); } }); } function queryYoutube(query, callback) { youtube.search.list({ auth: API_KEY, q: query, part: 'snippet', maxResults: 1 }, function(err, results) { if (err) { callback(err); } else { callback(null, results.items[0]); } }); }<file_sep># autoplay classical music recommender It is aimed to be a music recommender, a music autoplay, a music like & unlike (manually selector). <file_sep>(function() { angular.module('RootApp').factory('YoukuPlayer', ['BasePlayer', '$rootScope', 'YOUKU_CLIENT_ID', function(BasePlayer, $rootScope, YOUKU_CLIENT_ID) { YoukuPlayer.prototype = new BasePlayer(); return YoukuPlayer; function YoukuPlayer() { var player = this; var innerPlayer = null; player.playPiece = function(piece) { if (innerPlayer) { innerPlayer.playVideoById(piece.videos[0].id.videoId); } else { var viewport = document.getElementById(player.getViewPortID()); if (viewport.className.indexOf('videoWrapper') == -1){ viewport.className = viewport.className + " videoWrapper"; } innerPlayer = new YKU.Player(player.getViewPortID(), { styleid: '0', client_id: YOUKU_CLIENT_ID, vid: piece.videos[0].id.videoId, autoplay: true, events: { onPlayEnd: onPlayEnd, onPlayerReady: function() { //innerPlayer.hideControls(); } } }); } } function onPlayEnd() { if (player.getLoop()) { innerPlayer.seekTo(0); innerPlayer.playVideo(); } else { $rootScope.$broadcast('next-piece'); } } player.destory = function() { var viewport = document.getElementById(player.getViewPortID()); while (viewport.firstChild) { viewport.removeChild(viewport.firstChild); } } return player; } }]); })();<file_sep>(function() { angular.module('RootApp').controller('RootCtrl', ['PlayerService', '$scope', '$window', '$q', 'outOfGWF', function(PlayerService, $scope, $window, $q, outOfGWF) { //console.log('controller'); var ctrl = this; ctrl.loop = false; ctrl.infoAvaliable = false; ctrl.playNextPiece = function() { PlayerService.playNextPiece(); } $scope.$watch('RootCtrl.loop', function(isLoop) { if (PlayerService.getPlayer()) { if (isLoop) PlayerService.loopPiece(); else PlayerService.unloopPiece(); } }); $scope.$on('piece-info-available', function() { ctrl.piece = PlayerService.getPiece(); /** * @todo not so good way. consider to rewrite it. */ ctrl.infoAvaliable = true; }); $scope.$on('next-piece', function() { PlayerService.playNextPiece(); }); setPlayerPromises(); /** * Player's entry point */ PlayerService.playNextPiece(); function setPlayerPromises() { if (outOfGWF) { /** * @todo How to write fail to load case. E.g. Common China users * can't access Youtube. */ var youtubePromise = $q(function(resolve, reject) { loadScriptAsync('https://www.youtube.com/iframe_api', undefined, function() { reject('Unable to load youtube api js code.'); }); $window.onYouTubeIframeAPIReady = function() { resolve('Youtube api js is ready!'); } }); PlayerService.setYoutubeJsAvailablePromise(youtubePromise); } else { var youkuPromise = $q(function(resolve, reject) { loadScriptAsync('http://player.youku.com/jsapi', function() { // loadScriptAsync('/javascripts/libs/youku-api.js', function() { resolve('Youku api js is ready!'); }, function() { reject('Unable to load youku api js code.'); }); }); PlayerService.setYoukuJsAvailablePromise(youkuPromise); } } /** * This code loads the Player API js code asynchronously. * @param {String} script the script to load * @param {Function} onload Optional onload function * @param {Function} onerror Optional onerror function */ function loadScriptAsync(script, onload, onerror) { var tag = document.createElement('script'); if (onload) { tag.onload = onload; } if (onerror) { tag.onerror = onerror; } tag.src = script; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); } } ]); })();
92990f7b8968862eaf80c59742e3c1cdf114c530
[ "JavaScript", "Markdown" ]
15
JavaScript
wangzhihao/autoplay
4f931e428dd72ce9d328379db38b10a8dd41a0ab
b9a2fdc554e4dd07a4f3c8e9c25b19467c957244
refs/heads/master
<file_sep>from __future__ import absolute_import, print_function, unicode_literals import json import boto3 def lambda_handler(event, context): purge_old_lambda_versions() return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } def convertIntoInteger(version): if version != '$LATEST': return int(version) else : return -99; def findMaxVersion(versions): max_v = -99999; for version in versions: int_version = convertIntoInteger(version['Version']); if int_version > max_v : max_v = int_version; return max_v; def purge_old_lambda_versions(marker = ''): version_to_retain = 4; client = boto3.client('lambda') if marker == '': functions = client.list_functions() else: functions = client.list_functions(Marker=marker) print('functions = {}: with marker = {}'.format(functions, marker)) number_of_functions = 0; for function in functions['Functions']: number_of_functions+= 1 versions = client.list_versions_by_function(FunctionName=function['FunctionArn'])['Versions'] max_version = findMaxVersion(versions); print('max_version={} for function = {}'.format(max_version, function)) if len(versions) == 1: print('{}: No purging is required'.format(function['FunctionName'])) continue # print('function={})'.format(function)) # print('versions={})'.format(versions)) # print('function_version={})'.format(function['Version'])) for version in versions: if version['Version'] != function['Version'] and (max_version - convertIntoInteger(version['Version'])) > version_to_retain: arn = version['FunctionArn'] print('delete_function(FunctionName={})'.format(arn)) client.delete_function(FunctionName=arn) print('{}: Purging is done'.format(function['FunctionName'])) print('Number of functions : {}'.format(number_of_functions)) <file_sep># LambdaPurger Script to parse all the AWS lambdas and purge all Lambda's older versions ## How to Use this script? The default behavior of this lambda is that it will clean all the old versions except latest 5 versions. You can change this by changing version_to_retain variable in purge_old_lambda_versions method. - Create the lambda using the python script. Use Python version 3.7 - Create a Role to execute the lambda - Use the policy.json as the policy for this role - Use any payload. Sample ``` {"key1":"value1","key2":"value2","key3":"value3"}``` - The lambda will return ``` {"statusCode":200,"body":"\"Hello from Lambda!\""} ``` ## Point If you don't have space even to create this lambda then go to any lambda detail page and click "Qualifier" and click version and select oldest version. Then click "Action" and "Delete Function". Now create the purger lambda and execute it.
67f6477a9aed715cb604e580f7b230f60ed5b478
[ "Markdown", "Python" ]
2
Python
khillibob/LambdaPurger
06bb842648a0c6ec7bee567789167b0586eb6bd8
4f81abb4a2023a82bc5c31a61bae6ff78bc03ffe
refs/heads/master
<repo_name>rodrigoaguerra/nodejs<file_sep>/src/server.js import bodyParser from 'body-parser'; import express from 'express'; import fileLoader from 'app/controllers/'; const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); fileLoader(app); app.listen(3047); <file_sep>/src/app/controllers/authRouter.js import express from 'express'; import register from './auth/register'; import authenticate from './auth/authenticate'; const router = express.Router(); router.post('/register', register); router.post('/authenticate', authenticate); export default app => app.use('/auth', router); <file_sep>/README.md # nodejs ### teste importar o arquivo do Insomnia na pasta raiz, no Insomnia mudar a váriavel de ambiente base_url para a porta da aplicação que você definir.<file_sep>/src/app/controllers/auth/authenticate/index.js import bcrypt from 'bcryptjs'; import User from 'app/models/user'; import { generateToken } from '../_helpers'; export default async (req, res) => { const { email, password } = req.body; const user = await User.findOne({ email }).select('+password'); // usuário não encontrado if (!user) { return res.status(400).send({ error: 'Usuário não encontrado.' }); } // verifica senha if (!await bcrypt.compare(password, user.password)) { return res.status(401).send({ error: 'Senha inválida' }); } // remove o password do usuário para o retorno da requisição user.password = <PASSWORD>; res.send({ user, // definindo o token para o usuário token: generateToken({ id: user.id }), }); }; <file_sep>/src/app/controllers/auth/register/index.js import User from 'app/models/user'; import { generateToken, validEmail } from '../_helpers'; export default async (req, res) => { const { name, email, password, password2, } = req.body; try { // verifica se tem nome if (name === undefined) { return res.status(400).send({ error: 'Usuário sem nome' }); } // verifica se o e-mail é valido if (validEmail(email)) { return res.status(400).send({ error: 'Endereço de e-mail invalido' }); } // verifica se e-mail o email já foi cadastrado if (await User.findOne({ email })) { return res.status(400).send({ error: 'E-mail já cadastrado' }); } // confirma a senha if (password === undefined || password2 === undefined || password !== <PASSWORD>) { return res.status(401).send({ error: 'A senha não foi confirmada' }); } const user = await User.create(req.body); // remove o password do usuário para o retorno da requisição user.password = <PASSWORD>; return res.send({ user, // definindo o token para o usuário token: generateToken({ id: user.id }), }); } catch (err) { return res.status(400).send({ error: 'Falha no registro.' }); } }; <file_sep>/src/app/controllers/auth/_helpers.js import jwt from 'jsonwebtoken'; // gera token cadastro de usuário export const generateToken = (parms = {}) => ( jwt.sign(parms, process.env.SECRET_API, { expiresIn: 86400, }) ); // valida email por regex const emailRegexp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; export const validEmail = email => ( !emailRegexp.test(email) ); <file_sep>/src/app/controllers/index.js import fs from 'fs'; /** * Lê todos os arquivos .js de um diretorio, * ignorando o index.js e subdiretorios * @param {*} app */ const fileLoader = (app) => { fs.readdirSync(__dirname) .filter(file => file.indexOf('.') !== 0 && file.indexOf(".js") > -1 && file !== 'index.js') .forEach(async function(file) { const importedModule = await import(__dirname + "/" + file); importedModule.default(app); }); }; export default fileLoader;
0c5a31fbb20c545571c3dc20df147f74b004a882
[ "JavaScript", "Markdown" ]
7
JavaScript
rodrigoaguerra/nodejs
35cda099f7f6667796e6b5929d8b2237fe8a261f
592f12b18ec3b29a49cee438d8e4ba4dadff6510
refs/heads/master
<repo_name>musharrafleo95/AST-git-assignment<file_sep>/README.md # AST Assignment \#1: Git and Github. ## Team members: * 9040658 (<NAME>) * 9041759 (<NAME>) Git assignment for Advanced Software Technology. <file_sep>/report.md # Report ## Team members: * 9040658 (<NAME>) * 9041759 (<NAME>) ### (Part 6) Changes * Musharraf modified all of the Ekansh functions which were the last 4. Some prints were also added in the last part of program * Musharraf modifeied at 2020-11-16 10:41:43 am * The commid id is 26560930 * The message is "Ekansh functions modified and output shown" * The difference is the musharraf modified the variable name "list" to "list1" in all of the Ekansh functions. Furthermore he also printed the output of the top functions. ### (Part 9) * Both team member decide to modify function "sum_of_all" * First Ekansh pushed in the remote repository and no error occured * Then when Musharraf tried to push then the operation failed and it suggested to first integerate the changes before pushing again * So Musharraf pull first and then after that git showed that conflict has occured in "list_manager.py" and auto merging failed. * Musharraf then resolved the conflict by modifying the "list_manager.py" file, then commit the changes and pushed it in the remote repository. ### (Part 10) ![git_log_screenshot](https://github.com/musharrafleo95/AST-git-assignment/blob/master/git_log_graph.png) <file_sep>/list_manager.py # List manager import random import statistics import numpy as np def random_order(list1): '''returns the list with random order''' random.shuffle(list1) return list1 def order_by_increasing_value(list1): '''returns the list ordered by increasing value''' list1.sort() return list1 def order_by_decreasing_value(list1): '''returns the list ordered by decreasing value''' list1.sort(reverse = True) return list1 def reverse_order(list1): '''returns the list in reverse order''' return list1[::-1] def stringfy_list(list1): '''returns a list with all elements turned into strings''' list_1 = ' '.join([str(elem) for elem in list1]) return list_1 def multiply_list(list1, multiple): '''returns the list with all elements multipled by the value multiple''' list_1 = [ i*multiple for i in list1] return list_1 def get_highest_value(list1): return max(list1) def get_lowest_value(list1): return min(list1) def mean(list1): return statistics.mean(list1) def median(list1): return statistics.median(list1) def std_deviation(list1): return statistics.stdev(list1) def unique_item(list1): unique_one = np.array(list1) return np.unique(unique_one) def most_common(list1): common = np.array(list1) return np.bincount(common).argmax() def sum_of_all(list1): sum_ofall = np.array(list1) return np.sum(sum_ofall) if __name__ == "__main__": list_1 = [1, 1, 2, 2, 3, 3, 3, 4] print(stringfy_list(list_1)) print(multiply_list(list_1,5)) print(get_highest_value(list_1)) print(get_lowest_value(list_1)) print(random_order(list_1)) print(order_by_increasing_value(list_1)) print(order_by_decreasing_value(list_1)) print(reverse_order(list_1)) print(mean(list_1)) print(median(list_1)) print(std_deviation(list_1))
806dcbbb2a6315bd7a6498ca2255e0672494ea95
[ "Markdown", "Python" ]
3
Markdown
musharrafleo95/AST-git-assignment
1215e6b016a35d2d579f52b5a87f8418c80ec661
6d31510ce0a55e3d15a5fd2566cb5525233a34cc
refs/heads/master
<file_sep>source 'https://github.com/CocoaPods/Specs.git' pod 'AWSSNS', '~> 2.1.0' <file_sep>source 'https://github.com/CocoaPods/Specs.git' pod 'AWSS3', '~> 2.1.0' pod 'ELCImagePickerController' pod 'JTSImageViewController'
c7ee1f006c6ae1ea3dc7bf12bfb3f8389c1ebdee
[ "Ruby" ]
2
Ruby
sujalBandhara/aws-sdk-ios-samples
2f754e0e643f445e86cd6ff8a2b0e6929ba77107
97c2ffda7cae67c26f192ef57e692770a0f9b940
refs/heads/master
<repo_name>fernandezfelicio24/Machine_Learning-Python_Neural_Networks<file_sep>/neural_network_1.py #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ########################################################## ##For calculation off nuerons output we use, weights W(i).ip(i)=w1.ip1+w2.ip2+w3.ip3; ##we use sigmod function 1/1=exp(-w(i).ip(i)) function for output calculation #and later on for optimizing weights by calculating the error between the training output and th neuronal network output, based on this we adjust this weights, we do this for 100000 iteration sof continusly updating the weights so that we achiceve the optimal output. ###Adjust weight by =error.input.SigmodCurveGradient(output)=error.input.output(1-output) ## now we select the random weights from numpy import exp, array, random, dot training_inputs=array([[4,0,2],[3,0,0],[9,4,0],[12,0,10]]) training_outputs=array([[4,3,9,12]]).T random.seed(1); ##You are seeding the random number so that everytime it start generating the same numbers sample_weights=40 * random.random((3,1)) - 20#3 ip connectio , 1 output, 3x1 matrix with values range -1 to1, actually random.random() generates from 0 to 1 with mean 0.5, so i order to make the mean as 0 weprint 1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights)))) use 2*random.random()-1 ranging from -1 to 1 with mean 0; for iteration in xrange(10000): outputs=1/(1+exp(-(dot(training_inputs,sample_weights)))) # nueral o/p cal using inputs sigmod function sample_weights+=dot(training_inputs.T,(training_outputs-outputs)*outputs*(1-outputs)) print 1/(1 + exp(-(dot(array([9,10,10]), sample_weights)))) <file_sep>/README.md # Machine_Learning-Python_Neural_Networks Neural Networks Implementation using Python. These are based on Sigmod function (https://en.wikipedia.org/wiki/Sigmoid_function) and Backpropogation Algorithm (https://en.wikipedia.org/wiki/Backpropagation) In Machine Learning - Neural Networks ============================================================================================== 1.Single Layer Neural Networks, File Name: neural_network_1.py . 2.Two Layer Neural Network, With Slight modifications while adapted form https://github.com/miloharper/multi-layer-neural-network/blob/master/LICENSE.md . File Name: neural_network_multilayer_Layers_2.py. 3.Three Layer Neural Network, File Name: neural_network_multilayer_Layers_3.py =============================================================================================== Notes: Machine Learning[original(size>20MB):1 | Compressed(size<10MB) :2] and Kalman filter[original(<2MB):3] notes have been added here as PDF format under Creative Commons Attribution 4.0 International License. File Name(s): 1. praveen_machine_learning_notes_full_cc.pdf (original;size>20MB) 2. praveen_machine_learning_notes_full_cc_compressed.pdf (compressed; size<10MB) Pages 1 to 5 are not in good understandable format. Pages 6 to 43 are in good understandable format, with colors representations. File Name(s): 3. praveen_kalman_filter_notes_cc.pdf (original; size<2MB) ============================================================================================== Contributor : <NAME>
94c5ccac4fe3ed60a71bf2c41ef51b974753e83e
[ "Markdown", "Python" ]
2
Python
fernandezfelicio24/Machine_Learning-Python_Neural_Networks
7c64684ebcae30669c3c43a4245bf848fa45371b
6de6fceabd5e42776b24921e9e475356cc3a2df2
refs/heads/master
<file_sep>#include<iostream> #include<stdlib.h> using namespace std; struct SLL { int prn; char name[20]; struct SLL *next; }; typedef struct SLL sll; class Pinnacle_Club { private : sll *President; sll *Secretary; public : Pinnacle_Club(); sll * get_President(); void Add_Member(); void display_members(); void Delete_Member(); void compute_total_members(); void display_list_reverse_order(sll *temp); void concatinate_list(Pinnacle_Club & B); }; sll * Pinnacle_Club :: get_President() { return President; } Pinnacle_Club :: Pinnacle_Club() { President = NULL; Secretary = NULL; } void Pinnacle_Club :: Add_Member() { char ans; int ch; sll *Member,*temp,*node; Member = new sll; cout<<"\nEnter the PRN of the member : "; cin>>Member->prn; cout<<"\nEnter the Name of the member : "; cin>>Member->name; Member->next = NULL; if(President == NULL) { President = Member; cout<<"\nPresident added successfully\n"; } else { if(Secretary == NULL || President->next == NULL) { Secretary = Member; President->next = Secretary; cout<<"\nSecretary added successfully\n"; } else { temp = President; while(temp->next != Secretary) temp = temp->next; temp->next = Member; Member->next = Secretary; cout<<"\nNew Member add successfully\n"; } } } void Pinnacle_Club :: Delete_Member() { char ans; int ch,prn; sll *Member,*temp,*pnode=NULL; cout<<"\nEnter the prn of the member to be deleted : "; cin>>prn; for(temp = President; temp != NULL; temp = temp->next) { if(temp->prn == prn) break; pnode = temp; } if(temp == NULL ) { cout<<"\nMember to be deleted not found in the Club \n"; } else { if(temp == President) { President = President->next; if(President == NULL) Secretary = NULL; cout<<"\nCurrent President deleted from the Club\n"; } else { if(temp->next == NULL) { pnode->next = NULL; Secretary = pnode; cout<<"\nCurrent Secretary deleted from the Club\n"; } else { pnode->next = temp->next; cout<<"\nMember deleted from the Club\n"; } } delete temp; } } void Pinnacle_Club :: display_members() { int i = 1; sll *temp; cout<<"\nOrganization of Pinnacle Club \n"; for(temp = President; temp != NULL; temp= temp->next) { cout<<"\n\t\t"<<i++<<" : "<<temp->name<<" "<<temp->prn; if(temp == President) cout<<" (President) "; if(temp->next == NULL) cout<<" (Secretary)"; } } void Pinnacle_Club :: display_list_reverse_order(sll *temp) { if(temp != NULL) { display_list_reverse_order(temp->next); cout<<"\n\t\t"<<temp->name<<" "<<temp->prn; if(temp == President) cout<<" (President) "; if(temp->next == NULL) cout<<" (Secretary)"; } } void Pinnacle_Club :: compute_total_members() { int i = 0; sll *temp; for(temp = President; temp != NULL; temp= temp->next) { i++; } cout<<"\nTotal members of Pinnacle Club = "<<i; } void Pinnacle_Club :: concatinate_list(Pinnacle_Club & B) { Secretary->next = B.President; Secretary = B.Secretary; B.President = NULL; B.Secretary = NULL; cout<<"\nList concatinated successfully"; } int main() { int ch; Pinnacle_Club A,B; char ans; system("clear"); do { cout<<"\n\t\t\t1 : Add Members"; cout<<"\n\t\t\t2 : Display Members"; cout<<"\n\t\t\t3 : Delete Members"; cout<<"\n\t\t\t4 : Compute Total Members"; cout<<"\n\t\t\t5 : Display list in reverse order using recursion"; cout<<"\n\t\t\t6 : Concatinate two lists"; cout<<"\n\t\t\t7 : Exit"; cout<<"\n\nEnter ur choice : "; cin>>ch; switch(ch) { case 1 : A.Add_Member(); break; case 2 : A.display_members(); break; case 3 : A.Delete_Member(); break; case 4 : A.compute_total_members(); break; case 5 : A.display_list_reverse_order(A.get_President()); break; case 6 : cout<<"\nAdd the members of B Division"; do { B.Add_Member(); cout<<"\nDo u want to add more : "; cin>>ans; }while(ans == 'y'); cout<<"\nDivision A"; A.display_members(); cout<<"\nDivision B"; B.display_members(); A.concatinate_list(B); cout<<"\nConcatinated list :"; A.display_members(); break; case 7 : cout<<"\nEnd of Program\n"; break; default: cout<<"\nInvalid choice !! Try again\n\n"; } }while(ch != 7); return 0; }
0de767b08ecc88be33345b62f5973e724d6e39e3
[ "C++" ]
1
C++
akshayauti/linked-list
a47366d00563294aa2cdefcf1c609a57e6697ca6
b2733851f322f6bbc86013e1e267035f76fc150f
refs/heads/master
<file_sep>package path.navmesh; import math.Vec2; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import path.finder.a_star.Node; /** * Face class. * * @author <NAME> (<EMAIL>) */ public class Face { private final NavMesh2D navMesh; private final List<Vec2> points = new ArrayList<>(); private final Vec2 pointInsideFace = new Vec2(0, 0); private final List<Vec2> edgePoints = new ArrayList<>(); private Node<Vec2> nodeInsideFace; private final List<Node<Vec2>> edgeNodes = new ArrayList<>(); private final Polygon polygonTmp = new Polygon(); public Face(NavMesh2D navMesh, List<Vec2> ps) { this.navMesh = navMesh; points.addAll(ps); create(); } private void create() { updatePointInsideFaceToBarycenter(); nodeInsideFace = new Node<>(pointInsideFace); for (int i = 0; i < points.size(); i++) { Vec2 a = points.get(i); Vec2 b = points.get((i + 1) % points.size()); Node<Vec2> nodeEdge = navMesh.getEdge(a, b); Vec2 pointEdge = nodeEdge.getObj(); edgeNodes.add(nodeEdge); edgePoints.add(pointEdge); pointEdge.x = a.x / 2 + b.x / 2; pointEdge.y = a.y / 2 + b.y / 2; } } public List<Vec2> getPoints() { return points; } public Vec2 getPointInsideFace() { return pointInsideFace; } public List<Vec2> getEdgePoints() { return edgePoints; } public Node<Vec2> getNodeInsideFace() { return nodeInsideFace; } public List<Node<Vec2>> getEdgeNodes() { return edgeNodes; } public void updatePointInsideFaceToBarycenter() { pointInsideFace.x = 0; pointInsideFace.y = 0; for (int i = 0; i < points.size(); i++) { Vec2 vertex = points.get(i); pointInsideFace.x += vertex.x / points.size(); pointInsideFace.y += vertex.y / points.size(); } } public boolean isInside(double x, double y) { polygonTmp.reset(); for (Vec2 point : points) { polygonTmp.addPoint((int) point.x, (int) point.y); } return polygonTmp.contains(x, y); } @Override public String toString() { return "Face{" + "navMesh=" + navMesh + ", points=" + points + ", pointInsideFace=" + pointInsideFace + ", edgePoints=" + edgePoints + ", nodeInsideFace=" + nodeInsideFace + ", edgeNodes=" + edgeNodes + ", polygonTmp=" + polygonTmp + '}'; } }
9bba90e6bd6c6e55d5eb0840110bcc1adfca0001
[ "Java" ]
1
Java
CRY-D/Java2DNavMesh
378fedc81ea6b3675d3eb4cd508fc5cac1f9da35
8deb3def3e46209b771f0d7cb56d12458c9770de
refs/heads/master
<repo_name>scemino/DoomFire<file_sep>/extlibs/imgui/examples/libs/gl3w/GL/glcorearb.h #ifndef __glcorearb_h_ #define __glcorearb_h_ #ifdef __cplusplus extern "C" { #endif /* ** Copyright (c) 2007-2012 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the ** "Materials"), to deal in the Materials without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Materials, and to ** permit persons to whom the Materials are furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be included ** in all copies or substantial portions of the Materials. ** ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ /* glcorearb.h replaces gl3.h. It is for use with OpenGL core * profile implementations. * * glcorearb.h last updated on $Date: 2012-09-19 19:02:24 -0700 (Wed, 19 Sep * 2012) $ * * RELEASE NOTES - 2012/09/19 * * glcorearb.h should be placed in the same directory as gl.h and * included as * '<GL/glcorearb.h>'. * * glcorearb.h includes only APIs in the latest OpenGL core profile * implementation together with APIs in newer ARB extensions which can be * can be supported by the core profile. It does not, and never will * include functionality removed from the core profile, such as * fixed-function vertex and fragment processing. * * It is not possible to #include both <GL/glcorearb.h> and either of * <GL/gl.h> or <GL/glext.h> in the same source file. * * Feedback can be given by registering for the Khronos Bugzilla * (www.khronos.org/bugzilla) and filing issues there under product * "OpenGL", category "Registry". */ /* Function declaration macros - to move into glplatform.h */ #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && \ !defined(__SCITECH_SNAP__) #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #endif #ifndef APIENTRY #define APIENTRY #endif #ifndef APIENTRYP #define APIENTRYP APIENTRY* #endif #ifndef GLAPI #define GLAPI extern #endif /* Base GL types */ typedef unsigned int GLenum; typedef unsigned char GLboolean; typedef unsigned int GLbitfield; typedef signed char GLbyte; typedef short GLshort; typedef int GLint; typedef int GLsizei; typedef unsigned char GLubyte; typedef unsigned short GLushort; typedef unsigned int GLuint; typedef unsigned short GLhalf; typedef float GLfloat; typedef float GLclampf; typedef double GLdouble; typedef double GLclampd; typedef void GLvoid; /*************************************************************/ #ifndef GL_VERSION_1_1 /* AttribMask */ #define GL_DEPTH_BUFFER_BIT 0x00000100 #define GL_STENCIL_BUFFER_BIT 0x00000400 #define GL_COLOR_BUFFER_BIT 0x00004000 /* Boolean */ #define GL_FALSE 0 #define GL_TRUE 1 /* BeginMode */ #define GL_POINTS 0x0000 #define GL_LINES 0x0001 #define GL_LINE_LOOP 0x0002 #define GL_LINE_STRIP 0x0003 #define GL_TRIANGLES 0x0004 #define GL_TRIANGLE_STRIP 0x0005 #define GL_TRIANGLE_FAN 0x0006 #define GL_QUADS 0x0007 /* AlphaFunction */ #define GL_NEVER 0x0200 #define GL_LESS 0x0201 #define GL_EQUAL 0x0202 #define GL_LEQUAL 0x0203 #define GL_GREATER 0x0204 #define GL_NOTEQUAL 0x0205 #define GL_GEQUAL 0x0206 #define GL_ALWAYS 0x0207 /* BlendingFactorDest */ #define GL_ZERO 0 #define GL_ONE 1 #define GL_SRC_COLOR 0x0300 #define GL_ONE_MINUS_SRC_COLOR 0x0301 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 #define GL_DST_ALPHA 0x0304 #define GL_ONE_MINUS_DST_ALPHA 0x0305 /* BlendingFactorSrc */ #define GL_DST_COLOR 0x0306 #define GL_ONE_MINUS_DST_COLOR 0x0307 #define GL_SRC_ALPHA_SATURATE 0x0308 /* DrawBufferMode */ #define GL_NONE 0 #define GL_FRONT_LEFT 0x0400 #define GL_FRONT_RIGHT 0x0401 #define GL_BACK_LEFT 0x0402 #define GL_BACK_RIGHT 0x0403 #define GL_FRONT 0x0404 #define GL_BACK 0x0405 #define GL_LEFT 0x0406 #define GL_RIGHT 0x0407 #define GL_FRONT_AND_BACK 0x0408 /* ErrorCode */ #define GL_NO_ERROR 0 #define GL_INVALID_ENUM 0x0500 #define GL_INVALID_VALUE 0x0501 #define GL_INVALID_OPERATION 0x0502 #define GL_OUT_OF_MEMORY 0x0505 /* FrontFaceDirection */ #define GL_CW 0x0900 #define GL_CCW 0x0901 /* GetPName */ #define GL_POINT_SIZE 0x0B11 #define GL_POINT_SIZE_RANGE 0x0B12 #define GL_POINT_SIZE_GRANULARITY 0x0B13 #define GL_LINE_SMOOTH 0x0B20 #define GL_LINE_WIDTH 0x0B21 #define GL_LINE_WIDTH_RANGE 0x0B22 #define GL_LINE_WIDTH_GRANULARITY 0x0B23 #define GL_POLYGON_MODE 0x0B40 #define GL_POLYGON_SMOOTH 0x0B41 #define GL_CULL_FACE 0x0B44 #define GL_CULL_FACE_MODE 0x0B45 #define GL_FRONT_FACE 0x0B46 #define GL_DEPTH_RANGE 0x0B70 #define GL_DEPTH_TEST 0x0B71 #define GL_DEPTH_WRITEMASK 0x0B72 #define GL_DEPTH_CLEAR_VALUE 0x0B73 #define GL_DEPTH_FUNC 0x0B74 #define GL_STENCIL_TEST 0x0B90 #define GL_STENCIL_CLEAR_VALUE 0x0B91 #define GL_STENCIL_FUNC 0x0B92 #define GL_STENCIL_VALUE_MASK 0x0B93 #define GL_STENCIL_FAIL 0x0B94 #define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 #define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 #define GL_STENCIL_REF 0x0B97 #define GL_STENCIL_WRITEMASK 0x0B98 #define GL_VIEWPORT 0x0BA2 #define GL_DITHER 0x0BD0 #define GL_BLEND_DST 0x0BE0 #define GL_BLEND_SRC 0x0BE1 #define GL_BLEND 0x0BE2 #define GL_LOGIC_OP_MODE 0x0BF0 #define GL_COLOR_LOGIC_OP 0x0BF2 #define GL_DRAW_BUFFER 0x0C01 #define GL_READ_BUFFER 0x0C02 #define GL_SCISSOR_BOX 0x0C10 #define GL_SCISSOR_TEST 0x0C11 #define GL_COLOR_CLEAR_VALUE 0x0C22 #define GL_COLOR_WRITEMASK 0x0C23 #define GL_DOUBLEBUFFER 0x0C32 #define GL_STEREO 0x0C33 #define GL_LINE_SMOOTH_HINT 0x0C52 #define GL_POLYGON_SMOOTH_HINT 0x0C53 #define GL_UNPACK_SWAP_BYTES 0x0CF0 #define GL_UNPACK_LSB_FIRST 0x0CF1 #define GL_UNPACK_ROW_LENGTH 0x0CF2 #define GL_UNPACK_SKIP_ROWS 0x0CF3 #define GL_UNPACK_SKIP_PIXELS 0x0CF4 #define GL_UNPACK_ALIGNMENT 0x0CF5 #define GL_PACK_SWAP_BYTES 0x0D00 #define GL_PACK_LSB_FIRST 0x0D01 #define GL_PACK_ROW_LENGTH 0x0D02 #define GL_PACK_SKIP_ROWS 0x0D03 #define GL_PACK_SKIP_PIXELS 0x0D04 #define GL_PACK_ALIGNMENT 0x0D05 #define GL_MAX_TEXTURE_SIZE 0x0D33 #define GL_MAX_VIEWPORT_DIMS 0x0D3A #define GL_SUBPIXEL_BITS 0x0D50 #define GL_TEXTURE_1D 0x0DE0 #define GL_TEXTURE_2D 0x0DE1 #define GL_POLYGON_OFFSET_UNITS 0x2A00 #define GL_POLYGON_OFFSET_POINT 0x2A01 #define GL_POLYGON_OFFSET_LINE 0x2A02 #define GL_POLYGON_OFFSET_FILL 0x8037 #define GL_POLYGON_OFFSET_FACTOR 0x8038 #define GL_TEXTURE_BINDING_1D 0x8068 #define GL_TEXTURE_BINDING_2D 0x8069 /* GetTextureParameter */ #define GL_TEXTURE_WIDTH 0x1000 #define GL_TEXTURE_HEIGHT 0x1001 #define GL_TEXTURE_INTERNAL_FORMAT 0x1003 #define GL_TEXTURE_BORDER_COLOR 0x1004 #define GL_TEXTURE_RED_SIZE 0x805C #define GL_TEXTURE_GREEN_SIZE 0x805D #define GL_TEXTURE_BLUE_SIZE 0x805E #define GL_TEXTURE_ALPHA_SIZE 0x805F /* HintMode */ #define GL_DONT_CARE 0x1100 #define GL_FASTEST 0x1101 #define GL_NICEST 0x1102 /* DataType */ #define GL_BYTE 0x1400 #define GL_UNSIGNED_BYTE 0x1401 #define GL_SHORT 0x1402 #define GL_UNSIGNED_SHORT 0x1403 #define GL_INT 0x1404 #define GL_UNSIGNED_INT 0x1405 #define GL_FLOAT 0x1406 #define GL_DOUBLE 0x140A /* ErrorCode */ #define GL_STACK_OVERFLOW 0x0503 #define GL_STACK_UNDERFLOW 0x0504 /* LogicOp */ #define GL_CLEAR 0x1500 #define GL_AND 0x1501 #define GL_AND_REVERSE 0x1502 #define GL_COPY 0x1503 #define GL_AND_INVERTED 0x1504 #define GL_NOOP 0x1505 #define GL_XOR 0x1506 #define GL_OR 0x1507 #define GL_NOR 0x1508 #define GL_EQUIV 0x1509 #define GL_INVERT 0x150A #define GL_OR_REVERSE 0x150B #define GL_COPY_INVERTED 0x150C #define GL_OR_INVERTED 0x150D #define GL_NAND 0x150E #define GL_SET 0x150F /* MatrixMode (for gl3.h, FBO attachment type) */ #define GL_TEXTURE 0x1702 /* PixelCopyType */ #define GL_COLOR 0x1800 #define GL_DEPTH 0x1801 #define GL_STENCIL 0x1802 /* PixelFormat */ #define GL_STENCIL_INDEX 0x1901 #define GL_DEPTH_COMPONENT 0x1902 #define GL_RED 0x1903 #define GL_GREEN 0x1904 #define GL_BLUE 0x1905 #define GL_ALPHA 0x1906 #define GL_RGB 0x1907 #define GL_RGBA 0x1908 /* PolygonMode */ #define GL_POINT 0x1B00 #define GL_LINE 0x1B01 #define GL_FILL 0x1B02 /* StencilOp */ #define GL_KEEP 0x1E00 #define GL_REPLACE 0x1E01 #define GL_INCR 0x1E02 #define GL_DECR 0x1E03 /* StringName */ #define GL_VENDOR 0x1F00 #define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 /* TextureMagFilter */ #define GL_NEAREST 0x2600 #define GL_LINEAR 0x2601 /* TextureMinFilter */ #define GL_NEAREST_MIPMAP_NEAREST 0x2700 #define GL_LINEAR_MIPMAP_NEAREST 0x2701 #define GL_NEAREST_MIPMAP_LINEAR 0x2702 #define GL_LINEAR_MIPMAP_LINEAR 0x2703 /* TextureParameterName */ #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 #define GL_TEXTURE_WRAP_S 0x2802 #define GL_TEXTURE_WRAP_T 0x2803 /* TextureTarget */ #define GL_PROXY_TEXTURE_1D 0x8063 #define GL_PROXY_TEXTURE_2D 0x8064 /* TextureWrapMode */ #define GL_REPEAT 0x2901 /* PixelInternalFormat */ #define GL_R3_G3_B2 0x2A10 #define GL_RGB4 0x804F #define GL_RGB5 0x8050 #define GL_RGB8 0x8051 #define GL_RGB10 0x8052 #define GL_RGB12 0x8053 #define GL_RGB16 0x8054 #define GL_RGBA2 0x8055 #define GL_RGBA4 0x8056 #define GL_RGB5_A1 0x8057 #define GL_RGBA8 0x8058 #define GL_RGB10_A2 0x8059 #define GL_RGBA12 0x805A #define GL_RGBA16 0x805B #endif #ifndef GL_VERSION_1_2 #define GL_UNSIGNED_BYTE_3_3_2 0x8032 #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 #define GL_UNSIGNED_INT_8_8_8_8 0x8035 #define GL_UNSIGNED_INT_10_10_10_2 0x8036 #define GL_TEXTURE_BINDING_3D 0x806A #define GL_PACK_SKIP_IMAGES 0x806B #define GL_PACK_IMAGE_HEIGHT 0x806C #define GL_UNPACK_SKIP_IMAGES 0x806D #define GL_UNPACK_IMAGE_HEIGHT 0x806E #define GL_TEXTURE_3D 0x806F #define GL_PROXY_TEXTURE_3D 0x8070 #define GL_TEXTURE_DEPTH 0x8071 #define GL_TEXTURE_WRAP_R 0x8072 #define GL_MAX_3D_TEXTURE_SIZE 0x8073 #define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 #define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 #define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 #define GL_BGR 0x80E0 #define GL_BGRA 0x80E1 #define GL_MAX_ELEMENTS_VERTICES 0x80E8 #define GL_MAX_ELEMENTS_INDICES 0x80E9 #define GL_CLAMP_TO_EDGE 0x812F #define GL_TEXTURE_MIN_LOD 0x813A #define GL_TEXTURE_MAX_LOD 0x813B #define GL_TEXTURE_BASE_LEVEL 0x813C #define GL_TEXTURE_MAX_LEVEL 0x813D #define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 #define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 #define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 #define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 #define GL_ALIASED_LINE_WIDTH_RANGE 0x846E #endif #ifndef GL_ARB_imaging #define GL_CONSTANT_COLOR 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 #define GL_CONSTANT_ALPHA 0x8003 #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 #define GL_BLEND_COLOR 0x8005 #define GL_FUNC_ADD 0x8006 #define GL_MIN 0x8007 #define GL_MAX 0x8008 #define GL_BLEND_EQUATION 0x8009 #define GL_FUNC_SUBTRACT 0x800A #define GL_FUNC_REVERSE_SUBTRACT 0x800B #endif #ifndef GL_VERSION_1_3 #define GL_TEXTURE0 0x84C0 #define GL_TEXTURE1 0x84C1 #define GL_TEXTURE2 0x84C2 #define GL_TEXTURE3 0x84C3 #define GL_TEXTURE4 0x84C4 #define GL_TEXTURE5 0x84C5 #define GL_TEXTURE6 0x84C6 #define GL_TEXTURE7 0x84C7 #define GL_TEXTURE8 0x84C8 #define GL_TEXTURE9 0x84C9 #define GL_TEXTURE10 0x84CA #define GL_TEXTURE11 0x84CB #define GL_TEXTURE12 0x84CC #define GL_TEXTURE13 0x84CD #define GL_TEXTURE14 0x84CE #define GL_TEXTURE15 0x84CF #define GL_TEXTURE16 0x84D0 #define GL_TEXTURE17 0x84D1 #define GL_TEXTURE18 0x84D2 #define GL_TEXTURE19 0x84D3 #define GL_TEXTURE20 0x84D4 #define GL_TEXTURE21 0x84D5 #define GL_TEXTURE22 0x84D6 #define GL_TEXTURE23 0x84D7 #define GL_TEXTURE24 0x84D8 #define GL_TEXTURE25 0x84D9 #define GL_TEXTURE26 0x84DA #define GL_TEXTURE27 0x84DB #define GL_TEXTURE28 0x84DC #define GL_TEXTURE29 0x84DD #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF #define GL_ACTIVE_TEXTURE 0x84E0 #define GL_MULTISAMPLE 0x809D #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E #define GL_SAMPLE_ALPHA_TO_ONE 0x809F #define GL_SAMPLE_COVERAGE 0x80A0 #define GL_SAMPLE_BUFFERS 0x80A8 #define GL_SAMPLES 0x80A9 #define GL_SAMPLE_COVERAGE_VALUE 0x80AA #define GL_SAMPLE_COVERAGE_INVERT 0x80AB #define GL_TEXTURE_CUBE_MAP 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A #define GL_PROXY_TEXTURE_CUBE_MAP 0x851B #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C #define GL_COMPRESSED_RGB 0x84ED #define GL_COMPRESSED_RGBA 0x84EE #define GL_TEXTURE_COMPRESSION_HINT 0x84EF #define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 #define GL_TEXTURE_COMPRESSED 0x86A1 #define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 #define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 #define GL_CLAMP_TO_BORDER 0x812D #endif #ifndef GL_VERSION_1_4 #define GL_BLEND_DST_RGB 0x80C8 #define GL_BLEND_SRC_RGB 0x80C9 #define GL_BLEND_DST_ALPHA 0x80CA #define GL_BLEND_SRC_ALPHA 0x80CB #define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_DEPTH_COMPONENT24 0x81A6 #define GL_DEPTH_COMPONENT32 0x81A7 #define GL_MIRRORED_REPEAT 0x8370 #define GL_MAX_TEXTURE_LOD_BIAS 0x84FD #define GL_TEXTURE_LOD_BIAS 0x8501 #define GL_INCR_WRAP 0x8507 #define GL_DECR_WRAP 0x8508 #define GL_TEXTURE_DEPTH_SIZE 0x884A #define GL_TEXTURE_COMPARE_MODE 0x884C #define GL_TEXTURE_COMPARE_FUNC 0x884D #endif #ifndef GL_VERSION_1_5 #define GL_BUFFER_SIZE 0x8764 #define GL_BUFFER_USAGE 0x8765 #define GL_QUERY_COUNTER_BITS 0x8864 #define GL_CURRENT_QUERY 0x8865 #define GL_QUERY_RESULT 0x8866 #define GL_QUERY_RESULT_AVAILABLE 0x8867 #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F #define GL_READ_ONLY 0x88B8 #define GL_WRITE_ONLY 0x88B9 #define GL_READ_WRITE 0x88BA #define GL_BUFFER_ACCESS 0x88BB #define GL_BUFFER_MAPPED 0x88BC #define GL_BUFFER_MAP_POINTER 0x88BD #define GL_STREAM_DRAW 0x88E0 #define GL_STREAM_READ 0x88E1 #define GL_STREAM_COPY 0x88E2 #define GL_STATIC_DRAW 0x88E4 #define GL_STATIC_READ 0x88E5 #define GL_STATIC_COPY 0x88E6 #define GL_DYNAMIC_DRAW 0x88E8 #define GL_DYNAMIC_READ 0x88E9 #define GL_DYNAMIC_COPY 0x88EA #define GL_SAMPLES_PASSED 0x8914 #define GL_SRC1_ALPHA 0x8589 #endif #ifndef GL_VERSION_2_0 #define GL_BLEND_EQUATION_RGB 0x8009 #define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 #define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 #define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 #define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 #define GL_CURRENT_VERTEX_ATTRIB 0x8626 #define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_STENCIL_BACK_FUNC 0x8800 #define GL_STENCIL_BACK_FAIL 0x8801 #define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 #define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 #define GL_MAX_DRAW_BUFFERS 0x8824 #define GL_DRAW_BUFFER0 0x8825 #define GL_DRAW_BUFFER1 0x8826 #define GL_DRAW_BUFFER2 0x8827 #define GL_DRAW_BUFFER3 0x8828 #define GL_DRAW_BUFFER4 0x8829 #define GL_DRAW_BUFFER5 0x882A #define GL_DRAW_BUFFER6 0x882B #define GL_DRAW_BUFFER7 0x882C #define GL_DRAW_BUFFER8 0x882D #define GL_DRAW_BUFFER9 0x882E #define GL_DRAW_BUFFER10 0x882F #define GL_DRAW_BUFFER11 0x8830 #define GL_DRAW_BUFFER12 0x8831 #define GL_DRAW_BUFFER13 0x8832 #define GL_DRAW_BUFFER14 0x8833 #define GL_DRAW_BUFFER15 0x8834 #define GL_BLEND_EQUATION_ALPHA 0x883D #define GL_MAX_VERTEX_ATTRIBS 0x8869 #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A #define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A #define GL_MAX_VARYING_FLOATS 0x8B4B #define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D #define GL_SHADER_TYPE 0x8B4F #define GL_FLOAT_VEC2 0x8B50 #define GL_FLOAT_VEC3 0x8B51 #define GL_FLOAT_VEC4 0x8B52 #define GL_INT_VEC2 0x8B53 #define GL_INT_VEC3 0x8B54 #define GL_INT_VEC4 0x8B55 #define GL_BOOL 0x8B56 #define GL_BOOL_VEC2 0x8B57 #define GL_BOOL_VEC3 0x8B58 #define GL_BOOL_VEC4 0x8B59 #define GL_FLOAT_MAT2 0x8B5A #define GL_FLOAT_MAT3 0x8B5B #define GL_FLOAT_MAT4 0x8B5C #define GL_SAMPLER_1D 0x8B5D #define GL_SAMPLER_2D 0x8B5E #define GL_SAMPLER_3D 0x8B5F #define GL_SAMPLER_CUBE 0x8B60 #define GL_SAMPLER_1D_SHADOW 0x8B61 #define GL_SAMPLER_2D_SHADOW 0x8B62 #define GL_DELETE_STATUS 0x8B80 #define GL_COMPILE_STATUS 0x8B81 #define GL_LINK_STATUS 0x8B82 #define GL_VALIDATE_STATUS 0x8B83 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_ATTACHED_SHADERS 0x8B85 #define GL_ACTIVE_UNIFORMS 0x8B86 #define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 #define GL_SHADER_SOURCE_LENGTH 0x8B88 #define GL_ACTIVE_ATTRIBUTES 0x8B89 #define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A #define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B #define GL_SHADING_LANGUAGE_VERSION 0x8B8C #define GL_CURRENT_PROGRAM 0x8B8D #define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 #define GL_LOWER_LEFT 0x8CA1 #define GL_UPPER_LEFT 0x8CA2 #define GL_STENCIL_BACK_REF 0x8CA3 #define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 #define GL_STENCIL_BACK_WRITEMASK 0x8CA5 #endif #ifndef GL_VERSION_2_1 #define GL_PIXEL_PACK_BUFFER 0x88EB #define GL_PIXEL_UNPACK_BUFFER 0x88EC #define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED #define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF #define GL_FLOAT_MAT2x3 0x8B65 #define GL_FLOAT_MAT2x4 0x8B66 #define GL_FLOAT_MAT3x2 0x8B67 #define GL_FLOAT_MAT3x4 0x8B68 #define GL_FLOAT_MAT4x2 0x8B69 #define GL_FLOAT_MAT4x3 0x8B6A #define GL_SRGB 0x8C40 #define GL_SRGB8 0x8C41 #define GL_SRGB_ALPHA 0x8C42 #define GL_SRGB8_ALPHA8 0x8C43 #define GL_COMPRESSED_SRGB 0x8C48 #define GL_COMPRESSED_SRGB_ALPHA 0x8C49 #endif #ifndef GL_VERSION_3_0 #define GL_COMPARE_REF_TO_TEXTURE 0x884E #define GL_CLIP_DISTANCE0 0x3000 #define GL_CLIP_DISTANCE1 0x3001 #define GL_CLIP_DISTANCE2 0x3002 #define GL_CLIP_DISTANCE3 0x3003 #define GL_CLIP_DISTANCE4 0x3004 #define GL_CLIP_DISTANCE5 0x3005 #define GL_CLIP_DISTANCE6 0x3006 #define GL_CLIP_DISTANCE7 0x3007 #define GL_MAX_CLIP_DISTANCES 0x0D32 #define GL_MAJOR_VERSION 0x821B #define GL_MINOR_VERSION 0x821C #define GL_NUM_EXTENSIONS 0x821D #define GL_CONTEXT_FLAGS 0x821E #define GL_COMPRESSED_RED 0x8225 #define GL_COMPRESSED_RG 0x8226 #define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x0001 #define GL_RGBA32F 0x8814 #define GL_RGB32F 0x8815 #define GL_RGBA16F 0x881A #define GL_RGB16F 0x881B #define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF #define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 #define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 #define GL_CLAMP_READ_COLOR 0x891C #define GL_FIXED_ONLY 0x891D #define GL_MAX_VARYING_COMPONENTS 0x8B4B #define GL_TEXTURE_1D_ARRAY 0x8C18 #define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 #define GL_TEXTURE_2D_ARRAY 0x8C1A #define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B #define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C #define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D #define GL_R11F_G11F_B10F 0x8C3A #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B #define GL_RGB9_E5 0x8C3D #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E #define GL_TEXTURE_SHARED_SIZE 0x8C3F #define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 #define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 #define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 #define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 #define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 #define GL_PRIMITIVES_GENERATED 0x8C87 #define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 #define GL_RASTERIZER_DISCARD 0x8C89 #define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B #define GL_INTERLEAVED_ATTRIBS 0x8C8C #define GL_SEPARATE_ATTRIBS 0x8C8D #define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E #define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F #define GL_RGBA32UI 0x8D70 #define GL_RGB32UI 0x8D71 #define GL_RGBA16UI 0x8D76 #define GL_RGB16UI 0x8D77 #define GL_RGBA8UI 0x8D7C #define GL_RGB8UI 0x8D7D #define GL_RGBA32I 0x8D82 #define GL_RGB32I 0x8D83 #define GL_RGBA16I 0x8D88 #define GL_RGB16I 0x8D89 #define GL_RGBA8I 0x8D8E #define GL_RGB8I 0x8D8F #define GL_RED_INTEGER 0x8D94 #define GL_GREEN_INTEGER 0x8D95 #define GL_BLUE_INTEGER 0x8D96 #define GL_RGB_INTEGER 0x8D98 #define GL_RGBA_INTEGER 0x8D99 #define GL_BGR_INTEGER 0x8D9A #define GL_BGRA_INTEGER 0x8D9B #define GL_SAMPLER_1D_ARRAY 0x8DC0 #define GL_SAMPLER_2D_ARRAY 0x8DC1 #define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 #define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 #define GL_SAMPLER_CUBE_SHADOW 0x8DC5 #define GL_UNSIGNED_INT_VEC2 0x8DC6 #define GL_UNSIGNED_INT_VEC3 0x8DC7 #define GL_UNSIGNED_INT_VEC4 0x8DC8 #define GL_INT_SAMPLER_1D 0x8DC9 #define GL_INT_SAMPLER_2D 0x8DCA #define GL_INT_SAMPLER_3D 0x8DCB #define GL_INT_SAMPLER_CUBE 0x8DCC #define GL_INT_SAMPLER_1D_ARRAY 0x8DCE #define GL_INT_SAMPLER_2D_ARRAY 0x8DCF #define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 #define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 #define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 #define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 #define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 #define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 #define GL_QUERY_WAIT 0x8E13 #define GL_QUERY_NO_WAIT 0x8E14 #define GL_QUERY_BY_REGION_WAIT 0x8E15 #define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 #define GL_BUFFER_ACCESS_FLAGS 0x911F #define GL_BUFFER_MAP_LENGTH 0x9120 #define GL_BUFFER_MAP_OFFSET 0x9121 /* Reuse tokens from ARB_depth_buffer_float */ /* reuse GL_DEPTH_COMPONENT32F */ /* reuse GL_DEPTH32F_STENCIL8 */ /* reuse GL_FLOAT_32_UNSIGNED_INT_24_8_REV */ /* Reuse tokens from ARB_framebuffer_object */ /* reuse GL_INVALID_FRAMEBUFFER_OPERATION */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE */ /* reuse GL_FRAMEBUFFER_DEFAULT */ /* reuse GL_FRAMEBUFFER_UNDEFINED */ /* reuse GL_DEPTH_STENCIL_ATTACHMENT */ /* reuse GL_INDEX */ /* reuse GL_MAX_RENDERBUFFER_SIZE */ /* reuse GL_DEPTH_STENCIL */ /* reuse GL_UNSIGNED_INT_24_8 */ /* reuse GL_DEPTH24_STENCIL8 */ /* reuse GL_TEXTURE_STENCIL_SIZE */ /* reuse GL_TEXTURE_RED_TYPE */ /* reuse GL_TEXTURE_GREEN_TYPE */ /* reuse GL_TEXTURE_BLUE_TYPE */ /* reuse GL_TEXTURE_ALPHA_TYPE */ /* reuse GL_TEXTURE_DEPTH_TYPE */ /* reuse GL_UNSIGNED_NORMALIZED */ /* reuse GL_FRAMEBUFFER_BINDING */ /* reuse GL_DRAW_FRAMEBUFFER_BINDING */ /* reuse GL_RENDERBUFFER_BINDING */ /* reuse GL_READ_FRAMEBUFFER */ /* reuse GL_DRAW_FRAMEBUFFER */ /* reuse GL_READ_FRAMEBUFFER_BINDING */ /* reuse GL_RENDERBUFFER_SAMPLES */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */ /* reuse GL_FRAMEBUFFER_COMPLETE */ /* reuse GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT */ /* reuse GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT */ /* reuse GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER */ /* reuse GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER */ /* reuse GL_FRAMEBUFFER_UNSUPPORTED */ /* reuse GL_MAX_COLOR_ATTACHMENTS */ /* reuse GL_COLOR_ATTACHMENT0 */ /* reuse GL_COLOR_ATTACHMENT1 */ /* reuse GL_COLOR_ATTACHMENT2 */ /* reuse GL_COLOR_ATTACHMENT3 */ /* reuse GL_COLOR_ATTACHMENT4 */ /* reuse GL_COLOR_ATTACHMENT5 */ /* reuse GL_COLOR_ATTACHMENT6 */ /* reuse GL_COLOR_ATTACHMENT7 */ /* reuse GL_COLOR_ATTACHMENT8 */ /* reuse GL_COLOR_ATTACHMENT9 */ /* reuse GL_COLOR_ATTACHMENT10 */ /* reuse GL_COLOR_ATTACHMENT11 */ /* reuse GL_COLOR_ATTACHMENT12 */ /* reuse GL_COLOR_ATTACHMENT13 */ /* reuse GL_COLOR_ATTACHMENT14 */ /* reuse GL_COLOR_ATTACHMENT15 */ /* reuse GL_DEPTH_ATTACHMENT */ /* reuse GL_STENCIL_ATTACHMENT */ /* reuse GL_FRAMEBUFFER */ /* reuse GL_RENDERBUFFER */ /* reuse GL_RENDERBUFFER_WIDTH */ /* reuse GL_RENDERBUFFER_HEIGHT */ /* reuse GL_RENDERBUFFER_INTERNAL_FORMAT */ /* reuse GL_STENCIL_INDEX1 */ /* reuse GL_STENCIL_INDEX4 */ /* reuse GL_STENCIL_INDEX8 */ /* reuse GL_STENCIL_INDEX16 */ /* reuse GL_RENDERBUFFER_RED_SIZE */ /* reuse GL_RENDERBUFFER_GREEN_SIZE */ /* reuse GL_RENDERBUFFER_BLUE_SIZE */ /* reuse GL_RENDERBUFFER_ALPHA_SIZE */ /* reuse GL_RENDERBUFFER_DEPTH_SIZE */ /* reuse GL_RENDERBUFFER_STENCIL_SIZE */ /* reuse GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE */ /* reuse GL_MAX_SAMPLES */ /* Reuse tokens from ARB_framebuffer_sRGB */ /* reuse GL_FRAMEBUFFER_SRGB */ /* Reuse tokens from ARB_half_float_vertex */ /* reuse GL_HALF_FLOAT */ /* Reuse tokens from ARB_map_buffer_range */ /* reuse GL_MAP_READ_BIT */ /* reuse GL_MAP_WRITE_BIT */ /* reuse GL_MAP_INVALIDATE_RANGE_BIT */ /* reuse GL_MAP_INVALIDATE_BUFFER_BIT */ /* reuse GL_MAP_FLUSH_EXPLICIT_BIT */ /* reuse GL_MAP_UNSYNCHRONIZED_BIT */ /* Reuse tokens from ARB_texture_compression_rgtc */ /* reuse GL_COMPRESSED_RED_RGTC1 */ /* reuse GL_COMPRESSED_SIGNED_RED_RGTC1 */ /* reuse GL_COMPRESSED_RG_RGTC2 */ /* reuse GL_COMPRESSED_SIGNED_RG_RGTC2 */ /* Reuse tokens from ARB_texture_rg */ /* reuse GL_RG */ /* reuse GL_RG_INTEGER */ /* reuse GL_R8 */ /* reuse GL_R16 */ /* reuse GL_RG8 */ /* reuse GL_RG16 */ /* reuse GL_R16F */ /* reuse GL_R32F */ /* reuse GL_RG16F */ /* reuse GL_RG32F */ /* reuse GL_R8I */ /* reuse GL_R8UI */ /* reuse GL_R16I */ /* reuse GL_R16UI */ /* reuse GL_R32I */ /* reuse GL_R32UI */ /* reuse GL_RG8I */ /* reuse GL_RG8UI */ /* reuse GL_RG16I */ /* reuse GL_RG16UI */ /* reuse GL_RG32I */ /* reuse GL_RG32UI */ /* Reuse tokens from ARB_vertex_array_object */ /* reuse GL_VERTEX_ARRAY_BINDING */ #endif #ifndef GL_VERSION_3_1 #define GL_SAMPLER_2D_RECT 0x8B63 #define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 #define GL_SAMPLER_BUFFER 0x8DC2 #define GL_INT_SAMPLER_2D_RECT 0x8DCD #define GL_INT_SAMPLER_BUFFER 0x8DD0 #define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 #define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 #define GL_TEXTURE_BUFFER 0x8C2A #define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B #define GL_TEXTURE_BINDING_BUFFER 0x8C2C #define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D #define GL_TEXTURE_RECTANGLE 0x84F5 #define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 #define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 #define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 #define GL_RED_SNORM 0x8F90 #define GL_RG_SNORM 0x8F91 #define GL_RGB_SNORM 0x8F92 #define GL_RGBA_SNORM 0x8F93 #define GL_R8_SNORM 0x8F94 #define GL_RG8_SNORM 0x8F95 #define GL_RGB8_SNORM 0x8F96 #define GL_RGBA8_SNORM 0x8F97 #define GL_R16_SNORM 0x8F98 #define GL_RG16_SNORM 0x8F99 #define GL_RGB16_SNORM 0x8F9A #define GL_RGBA16_SNORM 0x8F9B #define GL_SIGNED_NORMALIZED 0x8F9C #define GL_PRIMITIVE_RESTART 0x8F9D #define GL_PRIMITIVE_RESTART_INDEX 0x8F9E /* Reuse tokens from ARB_copy_buffer */ /* reuse GL_COPY_READ_BUFFER */ /* reuse GL_COPY_WRITE_BUFFER */ /* Reuse tokens from ARB_draw_instanced (none) */ /* Reuse tokens from ARB_uniform_buffer_object */ /* reuse GL_UNIFORM_BUFFER */ /* reuse GL_UNIFORM_BUFFER_BINDING */ /* reuse GL_UNIFORM_BUFFER_START */ /* reuse GL_UNIFORM_BUFFER_SIZE */ /* reuse GL_MAX_VERTEX_UNIFORM_BLOCKS */ /* reuse GL_MAX_FRAGMENT_UNIFORM_BLOCKS */ /* reuse GL_MAX_COMBINED_UNIFORM_BLOCKS */ /* reuse GL_MAX_UNIFORM_BUFFER_BINDINGS */ /* reuse GL_MAX_UNIFORM_BLOCK_SIZE */ /* reuse GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS */ /* reuse GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS */ /* reuse GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT */ /* reuse GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH */ /* reuse GL_ACTIVE_UNIFORM_BLOCKS */ /* reuse GL_UNIFORM_TYPE */ /* reuse GL_UNIFORM_SIZE */ /* reuse GL_UNIFORM_NAME_LENGTH */ /* reuse GL_UNIFORM_BLOCK_INDEX */ /* reuse GL_UNIFORM_OFFSET */ /* reuse GL_UNIFORM_ARRAY_STRIDE */ /* reuse GL_UNIFORM_MATRIX_STRIDE */ /* reuse GL_UNIFORM_IS_ROW_MAJOR */ /* reuse GL_UNIFORM_BLOCK_BINDING */ /* reuse GL_UNIFORM_BLOCK_DATA_SIZE */ /* reuse GL_UNIFORM_BLOCK_NAME_LENGTH */ /* reuse GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS */ /* reuse GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES */ /* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER */ /* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER */ /* reuse GL_INVALID_INDEX */ #endif #ifndef GL_VERSION_3_2 #define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 #define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 #define GL_LINES_ADJACENCY 0x000A #define GL_LINE_STRIP_ADJACENCY 0x000B #define GL_TRIANGLES_ADJACENCY 0x000C #define GL_TRIANGLE_STRIP_ADJACENCY 0x000D #define GL_PROGRAM_POINT_SIZE 0x8642 #define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 #define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 #define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 #define GL_GEOMETRY_SHADER 0x8DD9 #define GL_GEOMETRY_VERTICES_OUT 0x8916 #define GL_GEOMETRY_INPUT_TYPE 0x8917 #define GL_GEOMETRY_OUTPUT_TYPE 0x8918 #define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF #define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 #define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 #define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 #define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 #define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 #define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 #define GL_CONTEXT_PROFILE_MASK 0x9126 /* reuse GL_MAX_VARYING_COMPONENTS */ /* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */ /* Reuse tokens from ARB_depth_clamp */ /* reuse GL_DEPTH_CLAMP */ /* Reuse tokens from ARB_draw_elements_base_vertex (none) */ /* Reuse tokens from ARB_fragment_coord_conventions (none) */ /* Reuse tokens from ARB_provoking_vertex */ /* reuse GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION */ /* reuse GL_FIRST_VERTEX_CONVENTION */ /* reuse GL_LAST_VERTEX_CONVENTION */ /* reuse GL_PROVOKING_VERTEX */ /* Reuse tokens from ARB_seamless_cube_map */ /* reuse GL_TEXTURE_CUBE_MAP_SEAMLESS */ /* Reuse tokens from ARB_sync */ /* reuse GL_MAX_SERVER_WAIT_TIMEOUT */ /* reuse GL_OBJECT_TYPE */ /* reuse GL_SYNC_CONDITION */ /* reuse GL_SYNC_STATUS */ /* reuse GL_SYNC_FLAGS */ /* reuse GL_SYNC_FENCE */ /* reuse GL_SYNC_GPU_COMMANDS_COMPLETE */ /* reuse GL_UNSIGNALED */ /* reuse GL_SIGNALED */ /* reuse GL_ALREADY_SIGNALED */ /* reuse GL_TIMEOUT_EXPIRED */ /* reuse GL_CONDITION_SATISFIED */ /* reuse GL_WAIT_FAILED */ /* reuse GL_TIMEOUT_IGNORED */ /* reuse GL_SYNC_FLUSH_COMMANDS_BIT */ /* reuse GL_TIMEOUT_IGNORED */ /* Reuse tokens from ARB_texture_multisample */ /* reuse GL_SAMPLE_POSITION */ /* reuse GL_SAMPLE_MASK */ /* reuse GL_SAMPLE_MASK_VALUE */ /* reuse GL_MAX_SAMPLE_MASK_WORDS */ /* reuse GL_TEXTURE_2D_MULTISAMPLE */ /* reuse GL_PROXY_TEXTURE_2D_MULTISAMPLE */ /* reuse GL_TEXTURE_2D_MULTISAMPLE_ARRAY */ /* reuse GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY */ /* reuse GL_TEXTURE_BINDING_2D_MULTISAMPLE */ /* reuse GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY */ /* reuse GL_TEXTURE_SAMPLES */ /* reuse GL_TEXTURE_FIXED_SAMPLE_LOCATIONS */ /* reuse GL_SAMPLER_2D_MULTISAMPLE */ /* reuse GL_INT_SAMPLER_2D_MULTISAMPLE */ /* reuse GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE */ /* reuse GL_SAMPLER_2D_MULTISAMPLE_ARRAY */ /* reuse GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY */ /* reuse GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY */ /* reuse GL_MAX_COLOR_TEXTURE_SAMPLES */ /* reuse GL_MAX_DEPTH_TEXTURE_SAMPLES */ /* reuse GL_MAX_INTEGER_SAMPLES */ /* Don't need to reuse tokens from ARB_vertex_array_bgra since they're already * in 1.2 core */ #endif #ifndef GL_VERSION_3_3 #define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE /* Reuse tokens from ARB_blend_func_extended */ /* reuse GL_SRC1_COLOR */ /* reuse GL_ONE_MINUS_SRC1_COLOR */ /* reuse GL_ONE_MINUS_SRC1_ALPHA */ /* reuse GL_MAX_DUAL_SOURCE_DRAW_BUFFERS */ /* Reuse tokens from ARB_explicit_attrib_location (none) */ /* Reuse tokens from ARB_occlusion_query2 */ /* reuse GL_ANY_SAMPLES_PASSED */ /* Reuse tokens from ARB_sampler_objects */ /* reuse GL_SAMPLER_BINDING */ /* Reuse tokens from ARB_shader_bit_encoding (none) */ /* Reuse tokens from ARB_texture_rgb10_a2ui */ /* reuse GL_RGB10_A2UI */ /* Reuse tokens from ARB_texture_swizzle */ /* reuse GL_TEXTURE_SWIZZLE_R */ /* reuse GL_TEXTURE_SWIZZLE_G */ /* reuse GL_TEXTURE_SWIZZLE_B */ /* reuse GL_TEXTURE_SWIZZLE_A */ /* reuse GL_TEXTURE_SWIZZLE_RGBA */ /* Reuse tokens from ARB_timer_query */ /* reuse GL_TIME_ELAPSED */ /* reuse GL_TIMESTAMP */ /* Reuse tokens from ARB_vertex_type_2_10_10_10_rev */ /* reuse GL_INT_2_10_10_10_REV */ #endif #ifndef GL_VERSION_4_0 #define GL_SAMPLE_SHADING 0x8C36 #define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 #define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E #define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F #define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 #define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A #define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B #define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C #define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D #define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E #define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F /* Reuse tokens from ARB_texture_query_lod (none) */ /* Reuse tokens from ARB_draw_buffers_blend (none) */ /* Reuse tokens from ARB_draw_indirect */ /* reuse GL_DRAW_INDIRECT_BUFFER */ /* reuse GL_DRAW_INDIRECT_BUFFER_BINDING */ /* Reuse tokens from ARB_gpu_shader5 */ /* reuse GL_GEOMETRY_SHADER_INVOCATIONS */ /* reuse GL_MAX_GEOMETRY_SHADER_INVOCATIONS */ /* reuse GL_MIN_FRAGMENT_INTERPOLATION_OFFSET */ /* reuse GL_MAX_FRAGMENT_INTERPOLATION_OFFSET */ /* reuse GL_FRAGMENT_INTERPOLATION_OFFSET_BITS */ /* reuse GL_MAX_VERTEX_STREAMS */ /* Reuse tokens from ARB_gpu_shader_fp64 */ /* reuse GL_DOUBLE_VEC2 */ /* reuse GL_DOUBLE_VEC3 */ /* reuse GL_DOUBLE_VEC4 */ /* reuse GL_DOUBLE_MAT2 */ /* reuse GL_DOUBLE_MAT3 */ /* reuse GL_DOUBLE_MAT4 */ /* reuse GL_DOUBLE_MAT2x3 */ /* reuse GL_DOUBLE_MAT2x4 */ /* reuse GL_DOUBLE_MAT3x2 */ /* reuse GL_DOUBLE_MAT3x4 */ /* reuse GL_DOUBLE_MAT4x2 */ /* reuse GL_DOUBLE_MAT4x3 */ /* Reuse tokens from ARB_shader_subroutine */ /* reuse GL_ACTIVE_SUBROUTINES */ /* reuse GL_ACTIVE_SUBROUTINE_UNIFORMS */ /* reuse GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS */ /* reuse GL_ACTIVE_SUBROUTINE_MAX_LENGTH */ /* reuse GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH */ /* reuse GL_MAX_SUBROUTINES */ /* reuse GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS */ /* reuse GL_NUM_COMPATIBLE_SUBROUTINES */ /* reuse GL_COMPATIBLE_SUBROUTINES */ /* Reuse tokens from ARB_tessellation_shader */ /* reuse GL_PATCHES */ /* reuse GL_PATCH_VERTICES */ /* reuse GL_PATCH_DEFAULT_INNER_LEVEL */ /* reuse GL_PATCH_DEFAULT_OUTER_LEVEL */ /* reuse GL_TESS_CONTROL_OUTPUT_VERTICES */ /* reuse GL_TESS_GEN_MODE */ /* reuse GL_TESS_GEN_SPACING */ /* reuse GL_TESS_GEN_VERTEX_ORDER */ /* reuse GL_TESS_GEN_POINT_MODE */ /* reuse GL_ISOLINES */ /* reuse GL_FRACTIONAL_ODD */ /* reuse GL_FRACTIONAL_EVEN */ /* reuse GL_MAX_PATCH_VERTICES */ /* reuse GL_MAX_TESS_GEN_LEVEL */ /* reuse GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS */ /* reuse GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS */ /* reuse GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS */ /* reuse GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS */ /* reuse GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS */ /* reuse GL_MAX_TESS_PATCH_COMPONENTS */ /* reuse GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS */ /* reuse GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS */ /* reuse GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS */ /* reuse GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS */ /* reuse GL_MAX_TESS_CONTROL_INPUT_COMPONENTS */ /* reuse GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS */ /* reuse GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS */ /* reuse GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS */ /* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER */ /* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER */ /* reuse GL_TESS_EVALUATION_SHADER */ /* reuse GL_TESS_CONTROL_SHADER */ /* Reuse tokens from ARB_texture_buffer_object_rgb32 (none) */ /* Reuse tokens from ARB_transform_feedback2 */ /* reuse GL_TRANSFORM_FEEDBACK */ /* reuse GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED */ /* reuse GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE */ /* reuse GL_TRANSFORM_FEEDBACK_BINDING */ /* Reuse tokens from ARB_transform_feedback3 */ /* reuse GL_MAX_TRANSFORM_FEEDBACK_BUFFERS */ /* reuse GL_MAX_VERTEX_STREAMS */ #endif #ifndef GL_VERSION_4_1 /* Reuse tokens from ARB_ES2_compatibility */ /* reuse GL_FIXED */ /* reuse GL_IMPLEMENTATION_COLOR_READ_TYPE */ /* reuse GL_IMPLEMENTATION_COLOR_READ_FORMAT */ /* reuse GL_LOW_FLOAT */ /* reuse GL_MEDIUM_FLOAT */ /* reuse GL_HIGH_FLOAT */ /* reuse GL_LOW_INT */ /* reuse GL_MEDIUM_INT */ /* reuse GL_HIGH_INT */ /* reuse GL_SHADER_COMPILER */ /* reuse GL_SHADER_BINARY_FORMATS */ /* reuse GL_NUM_SHADER_BINARY_FORMATS */ /* reuse GL_MAX_VERTEX_UNIFORM_VECTORS */ /* reuse GL_MAX_VARYING_VECTORS */ /* reuse GL_MAX_FRAGMENT_UNIFORM_VECTORS */ /* reuse GL_RGB565 */ /* Reuse tokens from ARB_get_program_binary */ /* reuse GL_PROGRAM_BINARY_RETRIEVABLE_HINT */ /* reuse GL_PROGRAM_BINARY_LENGTH */ /* reuse GL_NUM_PROGRAM_BINARY_FORMATS */ /* reuse GL_PROGRAM_BINARY_FORMATS */ /* Reuse tokens from ARB_separate_shader_objects */ /* reuse GL_VERTEX_SHADER_BIT */ /* reuse GL_FRAGMENT_SHADER_BIT */ /* reuse GL_GEOMETRY_SHADER_BIT */ /* reuse GL_TESS_CONTROL_SHADER_BIT */ /* reuse GL_TESS_EVALUATION_SHADER_BIT */ /* reuse GL_ALL_SHADER_BITS */ /* reuse GL_PROGRAM_SEPARABLE */ /* reuse GL_ACTIVE_PROGRAM */ /* reuse GL_PROGRAM_PIPELINE_BINDING */ /* Reuse tokens from ARB_shader_precision (none) */ /* Reuse tokens from ARB_vertex_attrib_64bit - all are in GL 3.0 and 4.0 already */ /* Reuse tokens from ARB_viewport_array - some are in GL 1.1 and * ARB_provoking_vertex already */ /* reuse GL_MAX_VIEWPORTS */ /* reuse GL_VIEWPORT_SUBPIXEL_BITS */ /* reuse GL_VIEWPORT_BOUNDS_RANGE */ /* reuse GL_LAYER_PROVOKING_VERTEX */ /* reuse GL_VIEWPORT_INDEX_PROVOKING_VERTEX */ /* reuse GL_UNDEFINED_VERTEX */ #endif #ifndef GL_VERSION_4_2 /* Reuse tokens from ARB_base_instance (none) */ /* Reuse tokens from ARB_shading_language_420pack (none) */ /* Reuse tokens from ARB_transform_feedback_instanced (none) */ /* Reuse tokens from ARB_compressed_texture_pixel_storage */ /* reuse GL_UNPACK_COMPRESSED_BLOCK_WIDTH */ /* reuse GL_UNPACK_COMPRESSED_BLOCK_HEIGHT */ /* reuse GL_UNPACK_COMPRESSED_BLOCK_DEPTH */ /* reuse GL_UNPACK_COMPRESSED_BLOCK_SIZE */ /* reuse GL_PACK_COMPRESSED_BLOCK_WIDTH */ /* reuse GL_PACK_COMPRESSED_BLOCK_HEIGHT */ /* reuse GL_PACK_COMPRESSED_BLOCK_DEPTH */ /* reuse GL_PACK_COMPRESSED_BLOCK_SIZE */ /* Reuse tokens from ARB_conservative_depth (none) */ /* Reuse tokens from ARB_internalformat_query */ /* reuse GL_NUM_SAMPLE_COUNTS */ /* Reuse tokens from ARB_map_buffer_alignment */ /* reuse GL_MIN_MAP_BUFFER_ALIGNMENT */ /* Reuse tokens from ARB_shader_atomic_counters */ /* reuse GL_ATOMIC_COUNTER_BUFFER */ /* reuse GL_ATOMIC_COUNTER_BUFFER_BINDING */ /* reuse GL_ATOMIC_COUNTER_BUFFER_START */ /* reuse GL_ATOMIC_COUNTER_BUFFER_SIZE */ /* reuse GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE */ /* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS */ /* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES */ /* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER */ /* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER */ /* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER */ /* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER */ /* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER */ /* reuse GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_MAX_VERTEX_ATOMIC_COUNTERS */ /* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS */ /* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS */ /* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTERS */ /* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTERS */ /* reuse GL_MAX_COMBINED_ATOMIC_COUNTERS */ /* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE */ /* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS */ /* reuse GL_ACTIVE_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX */ /* reuse GL_UNSIGNED_INT_ATOMIC_COUNTER */ /* Reuse tokens from ARB_shader_image_load_store */ /* reuse GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT */ /* reuse GL_ELEMENT_ARRAY_BARRIER_BIT */ /* reuse GL_UNIFORM_BARRIER_BIT */ /* reuse GL_TEXTURE_FETCH_BARRIER_BIT */ /* reuse GL_SHADER_IMAGE_ACCESS_BARRIER_BIT */ /* reuse GL_COMMAND_BARRIER_BIT */ /* reuse GL_PIXEL_BUFFER_BARRIER_BIT */ /* reuse GL_TEXTURE_UPDATE_BARRIER_BIT */ /* reuse GL_BUFFER_UPDATE_BARRIER_BIT */ /* reuse GL_FRAMEBUFFER_BARRIER_BIT */ /* reuse GL_TRANSFORM_FEEDBACK_BARRIER_BIT */ /* reuse GL_ATOMIC_COUNTER_BARRIER_BIT */ /* reuse GL_ALL_BARRIER_BITS */ /* reuse GL_MAX_IMAGE_UNITS */ /* reuse GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS */ /* reuse GL_IMAGE_BINDING_NAME */ /* reuse GL_IMAGE_BINDING_LEVEL */ /* reuse GL_IMAGE_BINDING_LAYERED */ /* reuse GL_IMAGE_BINDING_LAYER */ /* reuse GL_IMAGE_BINDING_ACCESS */ /* reuse GL_IMAGE_1D */ /* reuse GL_IMAGE_2D */ /* reuse GL_IMAGE_3D */ /* reuse GL_IMAGE_2D_RECT */ /* reuse GL_IMAGE_CUBE */ /* reuse GL_IMAGE_BUFFER */ /* reuse GL_IMAGE_1D_ARRAY */ /* reuse GL_IMAGE_2D_ARRAY */ /* reuse GL_IMAGE_CUBE_MAP_ARRAY */ /* reuse GL_IMAGE_2D_MULTISAMPLE */ /* reuse GL_IMAGE_2D_MULTISAMPLE_ARRAY */ /* reuse GL_INT_IMAGE_1D */ /* reuse GL_INT_IMAGE_2D */ /* reuse GL_INT_IMAGE_3D */ /* reuse GL_INT_IMAGE_2D_RECT */ /* reuse GL_INT_IMAGE_CUBE */ /* reuse GL_INT_IMAGE_BUFFER */ /* reuse GL_INT_IMAGE_1D_ARRAY */ /* reuse GL_INT_IMAGE_2D_ARRAY */ /* reuse GL_INT_IMAGE_CUBE_MAP_ARRAY */ /* reuse GL_INT_IMAGE_2D_MULTISAMPLE */ /* reuse GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY */ /* reuse GL_UNSIGNED_INT_IMAGE_1D */ /* reuse GL_UNSIGNED_INT_IMAGE_2D */ /* reuse GL_UNSIGNED_INT_IMAGE_3D */ /* reuse GL_UNSIGNED_INT_IMAGE_2D_RECT */ /* reuse GL_UNSIGNED_INT_IMAGE_CUBE */ /* reuse GL_UNSIGNED_INT_IMAGE_BUFFER */ /* reuse GL_UNSIGNED_INT_IMAGE_1D_ARRAY */ /* reuse GL_UNSIGNED_INT_IMAGE_2D_ARRAY */ /* reuse GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY */ /* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE */ /* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY */ /* reuse GL_MAX_IMAGE_SAMPLES */ /* reuse GL_IMAGE_BINDING_FORMAT */ /* reuse GL_IMAGE_FORMAT_COMPATIBILITY_TYPE */ /* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE */ /* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS */ /* reuse GL_MAX_VERTEX_IMAGE_UNIFORMS */ /* reuse GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS */ /* reuse GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS */ /* reuse GL_MAX_GEOMETRY_IMAGE_UNIFORMS */ /* reuse GL_MAX_FRAGMENT_IMAGE_UNIFORMS */ /* reuse GL_MAX_COMBINED_IMAGE_UNIFORMS */ /* Reuse tokens from ARB_shading_language_packing (none) */ /* Reuse tokens from ARB_texture_storage */ /* reuse GL_TEXTURE_IMMUTABLE_FORMAT */ #endif #ifndef GL_VERSION_4_3 #define GL_NUM_SHADING_LANGUAGE_VERSIONS 0x82E9 #define GL_VERTEX_ATTRIB_ARRAY_LONG 0x874E /* Reuse tokens from ARB_arrays_of_arrays (none, GLSL only) */ /* Reuse tokens from ARB_fragment_layer_viewport (none, GLSL only) */ /* Reuse tokens from ARB_shader_image_size (none, GLSL only) */ /* Reuse tokens from ARB_ES3_compatibility */ /* reuse GL_COMPRESSED_RGB8_ETC2 */ /* reuse GL_COMPRESSED_SRGB8_ETC2 */ /* reuse GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 */ /* reuse GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 */ /* reuse GL_COMPRESSED_RGBA8_ETC2_EAC */ /* reuse GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC */ /* reuse GL_COMPRESSED_R11_EAC */ /* reuse GL_COMPRESSED_SIGNED_R11_EAC */ /* reuse GL_COMPRESSED_RG11_EAC */ /* reuse GL_COMPRESSED_SIGNED_RG11_EAC */ /* reuse GL_PRIMITIVE_RESTART_FIXED_INDEX */ /* reuse GL_ANY_SAMPLES_PASSED_CONSERVATIVE */ /* reuse GL_MAX_ELEMENT_INDEX */ /* Reuse tokens from ARB_clear_buffer_object (none) */ /* Reuse tokens from ARB_compute_shader */ /* reuse GL_COMPUTE_SHADER */ /* reuse GL_MAX_COMPUTE_UNIFORM_BLOCKS */ /* reuse GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS */ /* reuse GL_MAX_COMPUTE_IMAGE_UNIFORMS */ /* reuse GL_MAX_COMPUTE_SHARED_MEMORY_SIZE */ /* reuse GL_MAX_COMPUTE_UNIFORM_COMPONENTS */ /* reuse GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS */ /* reuse GL_MAX_COMPUTE_ATOMIC_COUNTERS */ /* reuse GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS */ /* reuse GL_MAX_COMPUTE_LOCAL_INVOCATIONS */ /* reuse GL_MAX_COMPUTE_WORK_GROUP_COUNT */ /* reuse GL_MAX_COMPUTE_WORK_GROUP_SIZE */ /* reuse GL_COMPUTE_LOCAL_WORK_SIZE */ /* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER */ /* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER */ /* reuse GL_DISPATCH_INDIRECT_BUFFER */ /* reuse GL_DISPATCH_INDIRECT_BUFFER_BINDING */ /* Reuse tokens from ARB_copy_image (none) */ /* Reuse tokens from KHR_debug */ /* reuse GL_DEBUG_OUTPUT_SYNCHRONOUS */ /* reuse GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH */ /* reuse GL_DEBUG_CALLBACK_FUNCTION */ /* reuse GL_DEBUG_CALLBACK_USER_PARAM */ /* reuse GL_DEBUG_SOURCE_API */ /* reuse GL_DEBUG_SOURCE_WINDOW_SYSTEM */ /* reuse GL_DEBUG_SOURCE_SHADER_COMPILER */ /* reuse GL_DEBUG_SOURCE_THIRD_PARTY */ /* reuse GL_DEBUG_SOURCE_APPLICATION */ /* reuse GL_DEBUG_SOURCE_OTHER */ /* reuse GL_DEBUG_TYPE_ERROR */ /* reuse GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR */ /* reuse GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR */ /* reuse GL_DEBUG_TYPE_PORTABILITY */ /* reuse GL_DEBUG_TYPE_PERFORMANCE */ /* reuse GL_DEBUG_TYPE_OTHER */ /* reuse GL_MAX_DEBUG_MESSAGE_LENGTH */ /* reuse GL_MAX_DEBUG_LOGGED_MESSAGES */ /* reuse GL_DEBUG_LOGGED_MESSAGES */ /* reuse GL_DEBUG_SEVERITY_HIGH */ /* reuse GL_DEBUG_SEVERITY_MEDIUM */ /* reuse GL_DEBUG_SEVERITY_LOW */ /* reuse GL_DEBUG_TYPE_MARKER */ /* reuse GL_DEBUG_TYPE_PUSH_GROUP */ /* reuse GL_DEBUG_TYPE_POP_GROUP */ /* reuse GL_DEBUG_SEVERITY_NOTIFICATION */ /* reuse GL_MAX_DEBUG_GROUP_STACK_DEPTH */ /* reuse GL_DEBUG_GROUP_STACK_DEPTH */ /* reuse GL_BUFFER */ /* reuse GL_SHADER */ /* reuse GL_PROGRAM */ /* reuse GL_QUERY */ /* reuse GL_PROGRAM_PIPELINE */ /* reuse GL_SAMPLER */ /* reuse GL_DISPLAY_LIST */ /* reuse GL_MAX_LABEL_LENGTH */ /* reuse GL_DEBUG_OUTPUT */ /* reuse GL_CONTEXT_FLAG_DEBUG_BIT */ /* reuse GL_STACK_UNDERFLOW */ /* reuse GL_STACK_OVERFLOW */ /* Reuse tokens from ARB_explicit_uniform_location */ /* reuse GL_MAX_UNIFORM_LOCATIONS */ /* Reuse tokens from ARB_framebuffer_no_attachments */ /* reuse GL_FRAMEBUFFER_DEFAULT_WIDTH */ /* reuse GL_FRAMEBUFFER_DEFAULT_HEIGHT */ /* reuse GL_FRAMEBUFFER_DEFAULT_LAYERS */ /* reuse GL_FRAMEBUFFER_DEFAULT_SAMPLES */ /* reuse GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS */ /* reuse GL_MAX_FRAMEBUFFER_WIDTH */ /* reuse GL_MAX_FRAMEBUFFER_HEIGHT */ /* reuse GL_MAX_FRAMEBUFFER_LAYERS */ /* reuse GL_MAX_FRAMEBUFFER_SAMPLES */ /* Reuse tokens from ARB_internalformat_query2 */ /* reuse GL_INTERNALFORMAT_SUPPORTED */ /* reuse GL_INTERNALFORMAT_PREFERRED */ /* reuse GL_INTERNALFORMAT_RED_SIZE */ /* reuse GL_INTERNALFORMAT_GREEN_SIZE */ /* reuse GL_INTERNALFORMAT_BLUE_SIZE */ /* reuse GL_INTERNALFORMAT_ALPHA_SIZE */ /* reuse GL_INTERNALFORMAT_DEPTH_SIZE */ /* reuse GL_INTERNALFORMAT_STENCIL_SIZE */ /* reuse GL_INTERNALFORMAT_SHARED_SIZE */ /* reuse GL_INTERNALFORMAT_RED_TYPE */ /* reuse GL_INTERNALFORMAT_GREEN_TYPE */ /* reuse GL_INTERNALFORMAT_BLUE_TYPE */ /* reuse GL_INTERNALFORMAT_ALPHA_TYPE */ /* reuse GL_INTERNALFORMAT_DEPTH_TYPE */ /* reuse GL_INTERNALFORMAT_STENCIL_TYPE */ /* reuse GL_MAX_WIDTH */ /* reuse GL_MAX_HEIGHT */ /* reuse GL_MAX_DEPTH */ /* reuse GL_MAX_LAYERS */ /* reuse GL_MAX_COMBINED_DIMENSIONS */ /* reuse GL_COLOR_COMPONENTS */ /* reuse GL_DEPTH_COMPONENTS */ /* reuse GL_STENCIL_COMPONENTS */ /* reuse GL_COLOR_RENDERABLE */ /* reuse GL_DEPTH_RENDERABLE */ /* reuse GL_STENCIL_RENDERABLE */ /* reuse GL_FRAMEBUFFER_RENDERABLE */ /* reuse GL_FRAMEBUFFER_RENDERABLE_LAYERED */ /* reuse GL_FRAMEBUFFER_BLEND */ /* reuse GL_READ_PIXELS */ /* reuse GL_READ_PIXELS_FORMAT */ /* reuse GL_READ_PIXELS_TYPE */ /* reuse GL_TEXTURE_IMAGE_FORMAT */ /* reuse GL_TEXTURE_IMAGE_TYPE */ /* reuse GL_GET_TEXTURE_IMAGE_FORMAT */ /* reuse GL_GET_TEXTURE_IMAGE_TYPE */ /* reuse GL_MIPMAP */ /* reuse GL_MANUAL_GENERATE_MIPMAP */ /* reuse GL_AUTO_GENERATE_MIPMAP */ /* reuse GL_COLOR_ENCODING */ /* reuse GL_SRGB_READ */ /* reuse GL_SRGB_WRITE */ /* reuse GL_FILTER */ /* reuse GL_VERTEX_TEXTURE */ /* reuse GL_TESS_CONTROL_TEXTURE */ /* reuse GL_TESS_EVALUATION_TEXTURE */ /* reuse GL_GEOMETRY_TEXTURE */ /* reuse GL_FRAGMENT_TEXTURE */ /* reuse GL_COMPUTE_TEXTURE */ /* reuse GL_TEXTURE_SHADOW */ /* reuse GL_TEXTURE_GATHER */ /* reuse GL_TEXTURE_GATHER_SHADOW */ /* reuse GL_SHADER_IMAGE_LOAD */ /* reuse GL_SHADER_IMAGE_STORE */ /* reuse GL_SHADER_IMAGE_ATOMIC */ /* reuse GL_IMAGE_TEXEL_SIZE */ /* reuse GL_IMAGE_COMPATIBILITY_CLASS */ /* reuse GL_IMAGE_PIXEL_FORMAT */ /* reuse GL_IMAGE_PIXEL_TYPE */ /* reuse GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST */ /* reuse GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST */ /* reuse GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE */ /* reuse GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE */ /* reuse GL_TEXTURE_COMPRESSED_BLOCK_WIDTH */ /* reuse GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT */ /* reuse GL_TEXTURE_COMPRESSED_BLOCK_SIZE */ /* reuse GL_CLEAR_BUFFER */ /* reuse GL_TEXTURE_VIEW */ /* reuse GL_VIEW_COMPATIBILITY_CLASS */ /* reuse GL_FULL_SUPPORT */ /* reuse GL_CAVEAT_SUPPORT */ /* reuse GL_IMAGE_CLASS_4_X_32 */ /* reuse GL_IMAGE_CLASS_2_X_32 */ /* reuse GL_IMAGE_CLASS_1_X_32 */ /* reuse GL_IMAGE_CLASS_4_X_16 */ /* reuse GL_IMAGE_CLASS_2_X_16 */ /* reuse GL_IMAGE_CLASS_1_X_16 */ /* reuse GL_IMAGE_CLASS_4_X_8 */ /* reuse GL_IMAGE_CLASS_2_X_8 */ /* reuse GL_IMAGE_CLASS_1_X_8 */ /* reuse GL_IMAGE_CLASS_11_11_10 */ /* reuse GL_IMAGE_CLASS_10_10_10_2 */ /* reuse GL_VIEW_CLASS_128_BITS */ /* reuse GL_VIEW_CLASS_96_BITS */ /* reuse GL_VIEW_CLASS_64_BITS */ /* reuse GL_VIEW_CLASS_48_BITS */ /* reuse GL_VIEW_CLASS_32_BITS */ /* reuse GL_VIEW_CLASS_24_BITS */ /* reuse GL_VIEW_CLASS_16_BITS */ /* reuse GL_VIEW_CLASS_8_BITS */ /* reuse GL_VIEW_CLASS_S3TC_DXT1_RGB */ /* reuse GL_VIEW_CLASS_S3TC_DXT1_RGBA */ /* reuse GL_VIEW_CLASS_S3TC_DXT3_RGBA */ /* reuse GL_VIEW_CLASS_S3TC_DXT5_RGBA */ /* reuse GL_VIEW_CLASS_RGTC1_RED */ /* reuse GL_VIEW_CLASS_RGTC2_RG */ /* reuse GL_VIEW_CLASS_BPTC_UNORM */ /* reuse GL_VIEW_CLASS_BPTC_FLOAT */ /* Reuse tokens from ARB_invalidate_subdata (none) */ /* Reuse tokens from ARB_multi_draw_indirect (none) */ /* Reuse tokens from ARB_program_interface_query */ /* reuse GL_UNIFORM */ /* reuse GL_UNIFORM_BLOCK */ /* reuse GL_PROGRAM_INPUT */ /* reuse GL_PROGRAM_OUTPUT */ /* reuse GL_BUFFER_VARIABLE */ /* reuse GL_SHADER_STORAGE_BLOCK */ /* reuse GL_VERTEX_SUBROUTINE */ /* reuse GL_TESS_CONTROL_SUBROUTINE */ /* reuse GL_TESS_EVALUATION_SUBROUTINE */ /* reuse GL_GEOMETRY_SUBROUTINE */ /* reuse GL_FRAGMENT_SUBROUTINE */ /* reuse GL_COMPUTE_SUBROUTINE */ /* reuse GL_VERTEX_SUBROUTINE_UNIFORM */ /* reuse GL_TESS_CONTROL_SUBROUTINE_UNIFORM */ /* reuse GL_TESS_EVALUATION_SUBROUTINE_UNIFORM */ /* reuse GL_GEOMETRY_SUBROUTINE_UNIFORM */ /* reuse GL_FRAGMENT_SUBROUTINE_UNIFORM */ /* reuse GL_COMPUTE_SUBROUTINE_UNIFORM */ /* reuse GL_TRANSFORM_FEEDBACK_VARYING */ /* reuse GL_ACTIVE_RESOURCES */ /* reuse GL_MAX_NAME_LENGTH */ /* reuse GL_MAX_NUM_ACTIVE_VARIABLES */ /* reuse GL_MAX_NUM_COMPATIBLE_SUBROUTINES */ /* reuse GL_NAME_LENGTH */ /* reuse GL_TYPE */ /* reuse GL_ARRAY_SIZE */ /* reuse GL_OFFSET */ /* reuse GL_BLOCK_INDEX */ /* reuse GL_ARRAY_STRIDE */ /* reuse GL_MATRIX_STRIDE */ /* reuse GL_IS_ROW_MAJOR */ /* reuse GL_ATOMIC_COUNTER_BUFFER_INDEX */ /* reuse GL_BUFFER_BINDING */ /* reuse GL_BUFFER_DATA_SIZE */ /* reuse GL_NUM_ACTIVE_VARIABLES */ /* reuse GL_ACTIVE_VARIABLES */ /* reuse GL_REFERENCED_BY_VERTEX_SHADER */ /* reuse GL_REFERENCED_BY_TESS_CONTROL_SHADER */ /* reuse GL_REFERENCED_BY_TESS_EVALUATION_SHADER */ /* reuse GL_REFERENCED_BY_GEOMETRY_SHADER */ /* reuse GL_REFERENCED_BY_FRAGMENT_SHADER */ /* reuse GL_REFERENCED_BY_COMPUTE_SHADER */ /* reuse GL_TOP_LEVEL_ARRAY_SIZE */ /* reuse GL_TOP_LEVEL_ARRAY_STRIDE */ /* reuse GL_LOCATION */ /* reuse GL_LOCATION_INDEX */ /* reuse GL_IS_PER_PATCH */ /* Reuse tokens from ARB_robust_buffer_access_behavior (none) */ /* Reuse tokens from ARB_shader_storage_buffer_object */ /* reuse GL_SHADER_STORAGE_BUFFER */ /* reuse GL_SHADER_STORAGE_BUFFER_BINDING */ /* reuse GL_SHADER_STORAGE_BUFFER_START */ /* reuse GL_SHADER_STORAGE_BUFFER_SIZE */ /* reuse GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS */ /* reuse GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS */ /* reuse GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS */ /* reuse GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS */ /* reuse GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS */ /* reuse GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS */ /* reuse GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS */ /* reuse GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS */ /* reuse GL_MAX_SHADER_STORAGE_BLOCK_SIZE */ /* reuse GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT */ /* reuse GL_SHADER_STORAGE_BARRIER_BIT */ /* reuse GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES */ /* Reuse tokens from ARB_stencil_texturing */ /* reuse GL_DEPTH_STENCIL_TEXTURE_MODE */ /* Reuse tokens from ARB_texture_buffer_range */ /* reuse GL_TEXTURE_BUFFER_OFFSET */ /* reuse GL_TEXTURE_BUFFER_SIZE */ /* reuse GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT */ /* Reuse tokens from ARB_texture_query_levels (none) */ /* Reuse tokens from ARB_texture_storage_multisample (none) */ /* Reuse tokens from ARB_texture_view */ /* reuse GL_TEXTURE_VIEW_MIN_LEVEL */ /* reuse GL_TEXTURE_VIEW_NUM_LEVELS */ /* reuse GL_TEXTURE_VIEW_MIN_LAYER */ /* reuse GL_TEXTURE_VIEW_NUM_LAYERS */ /* reuse GL_TEXTURE_IMMUTABLE_LEVELS */ /* Reuse tokens from ARB_vertex_attrib_binding */ /* reuse GL_VERTEX_ATTRIB_BINDING */ /* reuse GL_VERTEX_ATTRIB_RELATIVE_OFFSET */ /* reuse GL_VERTEX_BINDING_DIVISOR */ /* reuse GL_VERTEX_BINDING_OFFSET */ /* reuse GL_VERTEX_BINDING_STRIDE */ /* reuse GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET */ /* reuse GL_MAX_VERTEX_ATTRIB_BINDINGS */ #endif #ifndef GL_ARB_depth_buffer_float #define GL_DEPTH_COMPONENT32F 0x8CAC #define GL_DEPTH32F_STENCIL8 0x8CAD #define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD #endif #ifndef GL_ARB_framebuffer_object #define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 #define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 #define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 #define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 #define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 #define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 #define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 #define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 #define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 #define GL_FRAMEBUFFER_DEFAULT 0x8218 #define GL_FRAMEBUFFER_UNDEFINED 0x8219 #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A #define GL_MAX_RENDERBUFFER_SIZE 0x84E8 #define GL_DEPTH_STENCIL 0x84F9 #define GL_UNSIGNED_INT_24_8 0x84FA #define GL_DEPTH24_STENCIL8 0x88F0 #define GL_TEXTURE_STENCIL_SIZE 0x88F1 #define GL_TEXTURE_RED_TYPE 0x8C10 #define GL_TEXTURE_GREEN_TYPE 0x8C11 #define GL_TEXTURE_BLUE_TYPE 0x8C12 #define GL_TEXTURE_ALPHA_TYPE 0x8C13 #define GL_TEXTURE_DEPTH_TYPE 0x8C16 #define GL_UNSIGNED_NORMALIZED 0x8C17 #define GL_FRAMEBUFFER_BINDING 0x8CA6 #define GL_DRAW_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING #define GL_RENDERBUFFER_BINDING 0x8CA7 #define GL_READ_FRAMEBUFFER 0x8CA8 #define GL_DRAW_FRAMEBUFFER 0x8CA9 #define GL_READ_FRAMEBUFFER_BINDING 0x8CAA #define GL_RENDERBUFFER_SAMPLES 0x8CAB #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 #define GL_FRAMEBUFFER_COMPLETE 0x8CD5 #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 #define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB #define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD #define GL_MAX_COLOR_ATTACHMENTS 0x8CDF #define GL_COLOR_ATTACHMENT0 0x8CE0 #define GL_COLOR_ATTACHMENT1 0x8CE1 #define GL_COLOR_ATTACHMENT2 0x8CE2 #define GL_COLOR_ATTACHMENT3 0x8CE3 #define GL_COLOR_ATTACHMENT4 0x8CE4 #define GL_COLOR_ATTACHMENT5 0x8CE5 #define GL_COLOR_ATTACHMENT6 0x8CE6 #define GL_COLOR_ATTACHMENT7 0x8CE7 #define GL_COLOR_ATTACHMENT8 0x8CE8 #define GL_COLOR_ATTACHMENT9 0x8CE9 #define GL_COLOR_ATTACHMENT10 0x8CEA #define GL_COLOR_ATTACHMENT11 0x8CEB #define GL_COLOR_ATTACHMENT12 0x8CEC #define GL_COLOR_ATTACHMENT13 0x8CED #define GL_COLOR_ATTACHMENT14 0x8CEE #define GL_COLOR_ATTACHMENT15 0x8CEF #define GL_DEPTH_ATTACHMENT 0x8D00 #define GL_STENCIL_ATTACHMENT 0x8D20 #define GL_FRAMEBUFFER 0x8D40 #define GL_RENDERBUFFER 0x8D41 #define GL_RENDERBUFFER_WIDTH 0x8D42 #define GL_RENDERBUFFER_HEIGHT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 #define GL_STENCIL_INDEX1 0x8D46 #define GL_STENCIL_INDEX4 0x8D47 #define GL_STENCIL_INDEX8 0x8D48 #define GL_STENCIL_INDEX16 0x8D49 #define GL_RENDERBUFFER_RED_SIZE 0x8D50 #define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 #define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 #define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 #define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 #define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 #define GL_MAX_SAMPLES 0x8D57 #endif #ifndef GL_ARB_framebuffer_sRGB #define GL_FRAMEBUFFER_SRGB 0x8DB9 #endif #ifndef GL_ARB_half_float_vertex #define GL_HALF_FLOAT 0x140B #endif #ifndef GL_ARB_map_buffer_range #define GL_MAP_READ_BIT 0x0001 #define GL_MAP_WRITE_BIT 0x0002 #define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 #define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 #define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 #define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 #endif #ifndef GL_ARB_texture_compression_rgtc #define GL_COMPRESSED_RED_RGTC1 0x8DBB #define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC #define GL_COMPRESSED_RG_RGTC2 0x8DBD #define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE #endif #ifndef GL_ARB_texture_rg #define GL_RG 0x8227 #define GL_RG_INTEGER 0x8228 #define GL_R8 0x8229 #define GL_R16 0x822A #define GL_RG8 0x822B #define GL_RG16 0x822C #define GL_R16F 0x822D #define GL_R32F 0x822E #define GL_RG16F 0x822F #define GL_RG32F 0x8230 #define GL_R8I 0x8231 #define GL_R8UI 0x8232 #define GL_R16I 0x8233 #define GL_R16UI 0x8234 #define GL_R32I 0x8235 #define GL_R32UI 0x8236 #define GL_RG8I 0x8237 #define GL_RG8UI 0x8238 #define GL_RG16I 0x8239 #define GL_RG16UI 0x823A #define GL_RG32I 0x823B #define GL_RG32UI 0x823C #endif #ifndef GL_ARB_vertex_array_object #define GL_VERTEX_ARRAY_BINDING 0x85B5 #endif #ifndef GL_ARB_uniform_buffer_object #define GL_UNIFORM_BUFFER 0x8A11 #define GL_UNIFORM_BUFFER_BINDING 0x8A28 #define GL_UNIFORM_BUFFER_START 0x8A29 #define GL_UNIFORM_BUFFER_SIZE 0x8A2A #define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B #define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C #define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D #define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E #define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F #define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 #define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 #define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 #define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 #define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 #define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 #define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 #define GL_UNIFORM_TYPE 0x8A37 #define GL_UNIFORM_SIZE 0x8A38 #define GL_UNIFORM_NAME_LENGTH 0x8A39 #define GL_UNIFORM_BLOCK_INDEX 0x8A3A #define GL_UNIFORM_OFFSET 0x8A3B #define GL_UNIFORM_ARRAY_STRIDE 0x8A3C #define GL_UNIFORM_MATRIX_STRIDE 0x8A3D #define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E #define GL_UNIFORM_BLOCK_BINDING 0x8A3F #define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 #define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 #define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 #define GL_INVALID_INDEX 0xFFFFFFFFu #endif #ifndef GL_ARB_copy_buffer #define GL_COPY_READ_BUFFER_BINDING 0x8F36 #define GL_COPY_READ_BUFFER GL_COPY_READ_BUFFER_BINDING #define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 #define GL_COPY_WRITE_BUFFER GL_COPY_WRITE_BUFFER_BINDING #endif #ifndef GL_ARB_depth_clamp #define GL_DEPTH_CLAMP 0x864F #endif #ifndef GL_ARB_draw_elements_base_vertex #endif #ifndef GL_ARB_fragment_coord_conventions #endif #ifndef GL_ARB_provoking_vertex #define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C #define GL_FIRST_VERTEX_CONVENTION 0x8E4D #define GL_LAST_VERTEX_CONVENTION 0x8E4E #define GL_PROVOKING_VERTEX 0x8E4F #endif #ifndef GL_ARB_seamless_cube_map #define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F #endif #ifndef GL_ARB_sync #define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 #define GL_OBJECT_TYPE 0x9112 #define GL_SYNC_CONDITION 0x9113 #define GL_SYNC_STATUS 0x9114 #define GL_SYNC_FLAGS 0x9115 #define GL_SYNC_FENCE 0x9116 #define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 #define GL_UNSIGNALED 0x9118 #define GL_SIGNALED 0x9119 #define GL_ALREADY_SIGNALED 0x911A #define GL_TIMEOUT_EXPIRED 0x911B #define GL_CONDITION_SATISFIED 0x911C #define GL_WAIT_FAILED 0x911D #define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 #define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull #endif #ifndef GL_ARB_texture_multisample #define GL_SAMPLE_POSITION 0x8E50 #define GL_SAMPLE_MASK 0x8E51 #define GL_SAMPLE_MASK_VALUE 0x8E52 #define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 #define GL_TEXTURE_2D_MULTISAMPLE 0x9100 #define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 #define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 #define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 #define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 #define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 #define GL_TEXTURE_SAMPLES 0x9106 #define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 #define GL_SAMPLER_2D_MULTISAMPLE 0x9108 #define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 #define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A #define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B #define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C #define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D #define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E #define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F #define GL_MAX_INTEGER_SAMPLES 0x9110 #endif #ifndef GL_ARB_vertex_array_bgra /* reuse GL_BGRA */ #endif #ifndef GL_ARB_draw_buffers_blend #endif #ifndef GL_ARB_sample_shading #define GL_SAMPLE_SHADING_ARB 0x8C36 #define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37 #endif #ifndef GL_ARB_texture_cube_map_array #define GL_TEXTURE_CUBE_MAP_ARRAY_ARB 0x9009 #define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A #define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B #define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C #define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D #define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E #define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F #endif #ifndef GL_ARB_texture_gather #define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E #define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F #define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F #endif #ifndef GL_ARB_texture_query_lod #endif #ifndef GL_ARB_shading_language_include #define GL_SHADER_INCLUDE_ARB 0x8DAE #define GL_NAMED_STRING_LENGTH_ARB 0x8DE9 #define GL_NAMED_STRING_TYPE_ARB 0x8DEA #endif #ifndef GL_ARB_texture_compression_bptc #define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C #define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D #define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E #define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F #endif #ifndef GL_ARB_blend_func_extended #define GL_SRC1_COLOR 0x88F9 /* reuse GL_SRC1_ALPHA */ #define GL_ONE_MINUS_SRC1_COLOR 0x88FA #define GL_ONE_MINUS_SRC1_ALPHA 0x88FB #define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC #endif #ifndef GL_ARB_explicit_attrib_location #endif #ifndef GL_ARB_occlusion_query2 #define GL_ANY_SAMPLES_PASSED 0x8C2F #endif #ifndef GL_ARB_sampler_objects #define GL_SAMPLER_BINDING 0x8919 #endif #ifndef GL_ARB_shader_bit_encoding #endif #ifndef GL_ARB_texture_rgb10_a2ui #define GL_RGB10_A2UI 0x906F #endif #ifndef GL_ARB_texture_swizzle #define GL_TEXTURE_SWIZZLE_R 0x8E42 #define GL_TEXTURE_SWIZZLE_G 0x8E43 #define GL_TEXTURE_SWIZZLE_B 0x8E44 #define GL_TEXTURE_SWIZZLE_A 0x8E45 #define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 #endif #ifndef GL_ARB_timer_query #define GL_TIME_ELAPSED 0x88BF #define GL_TIMESTAMP 0x8E28 #endif #ifndef GL_ARB_vertex_type_2_10_10_10_rev /* reuse GL_UNSIGNED_INT_2_10_10_10_REV */ #define GL_INT_2_10_10_10_REV 0x8D9F #endif #ifndef GL_ARB_draw_indirect #define GL_DRAW_INDIRECT_BUFFER 0x8F3F #define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 #endif #ifndef GL_ARB_gpu_shader5 #define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F #define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A #define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B #define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C #define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D /* reuse GL_MAX_VERTEX_STREAMS */ #endif #ifndef GL_ARB_gpu_shader_fp64 /* reuse GL_DOUBLE */ #define GL_DOUBLE_VEC2 0x8FFC #define GL_DOUBLE_VEC3 0x8FFD #define GL_DOUBLE_VEC4 0x8FFE #define GL_DOUBLE_MAT2 0x8F46 #define GL_DOUBLE_MAT3 0x8F47 #define GL_DOUBLE_MAT4 0x8F48 #define GL_DOUBLE_MAT2x3 0x8F49 #define GL_DOUBLE_MAT2x4 0x8F4A #define GL_DOUBLE_MAT3x2 0x8F4B #define GL_DOUBLE_MAT3x4 0x8F4C #define GL_DOUBLE_MAT4x2 0x8F4D #define GL_DOUBLE_MAT4x3 0x8F4E #endif #ifndef GL_ARB_shader_subroutine #define GL_ACTIVE_SUBROUTINES 0x8DE5 #define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 #define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 #define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 #define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 #define GL_MAX_SUBROUTINES 0x8DE7 #define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 #define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A #define GL_COMPATIBLE_SUBROUTINES 0x8E4B /* reuse GL_UNIFORM_SIZE */ /* reuse GL_UNIFORM_NAME_LENGTH */ #endif #ifndef GL_ARB_tessellation_shader #define GL_PATCHES 0x000E #define GL_PATCH_VERTICES 0x8E72 #define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 #define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 #define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 #define GL_TESS_GEN_MODE 0x8E76 #define GL_TESS_GEN_SPACING 0x8E77 #define GL_TESS_GEN_VERTEX_ORDER 0x8E78 #define GL_TESS_GEN_POINT_MODE 0x8E79 /* reuse GL_TRIANGLES */ /* reuse GL_QUADS */ #define GL_ISOLINES 0x8E7A /* reuse GL_EQUAL */ #define GL_FRACTIONAL_ODD 0x8E7B #define GL_FRACTIONAL_EVEN 0x8E7C /* reuse GL_CCW */ /* reuse GL_CW */ #define GL_MAX_PATCH_VERTICES 0x8E7D #define GL_MAX_TESS_GEN_LEVEL 0x8E7E #define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F #define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 #define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 #define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 #define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 #define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 #define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 #define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 #define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 #define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A #define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C #define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D #define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E #define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F #define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 #define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 #define GL_TESS_EVALUATION_SHADER 0x8E87 #define GL_TESS_CONTROL_SHADER 0x8E88 #endif #ifndef GL_ARB_texture_buffer_object_rgb32 /* reuse GL_RGB32F */ /* reuse GL_RGB32UI */ /* reuse GL_RGB32I */ #endif #ifndef GL_ARB_transform_feedback2 #define GL_TRANSFORM_FEEDBACK 0x8E22 #define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 #define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED GL_TRANSFORM_FEEDBACK_PAUSED #define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 #define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE GL_TRANSFORM_FEEDBACK_ACTIVE #define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 #endif #ifndef GL_ARB_transform_feedback3 #define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 #define GL_MAX_VERTEX_STREAMS 0x8E71 #endif #ifndef GL_ARB_ES2_compatibility #define GL_FIXED 0x140C #define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A #define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B #define GL_LOW_FLOAT 0x8DF0 #define GL_MEDIUM_FLOAT 0x8DF1 #define GL_HIGH_FLOAT 0x8DF2 #define GL_LOW_INT 0x8DF3 #define GL_MEDIUM_INT 0x8DF4 #define GL_HIGH_INT 0x8DF5 #define GL_SHADER_COMPILER 0x8DFA #define GL_SHADER_BINARY_FORMATS 0x8DF8 #define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 #define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB #define GL_MAX_VARYING_VECTORS 0x8DFC #define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD #define GL_RGB565 0x8D62 #endif #ifndef GL_ARB_get_program_binary #define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 #define GL_PROGRAM_BINARY_LENGTH 0x8741 #define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE #define GL_PROGRAM_BINARY_FORMATS 0x87FF #endif #ifndef GL_ARB_separate_shader_objects #define GL_VERTEX_SHADER_BIT 0x00000001 #define GL_FRAGMENT_SHADER_BIT 0x00000002 #define GL_GEOMETRY_SHADER_BIT 0x00000004 #define GL_TESS_CONTROL_SHADER_BIT 0x00000008 #define GL_TESS_EVALUATION_SHADER_BIT 0x00000010 #define GL_ALL_SHADER_BITS 0xFFFFFFFF #define GL_PROGRAM_SEPARABLE 0x8258 #define GL_ACTIVE_PROGRAM 0x8259 #define GL_PROGRAM_PIPELINE_BINDING 0x825A #endif #ifndef GL_ARB_shader_precision #endif #ifndef GL_ARB_vertex_attrib_64bit /* reuse GL_RGB32I */ /* reuse GL_DOUBLE_VEC2 */ /* reuse GL_DOUBLE_VEC3 */ /* reuse GL_DOUBLE_VEC4 */ /* reuse GL_DOUBLE_MAT2 */ /* reuse GL_DOUBLE_MAT3 */ /* reuse GL_DOUBLE_MAT4 */ /* reuse GL_DOUBLE_MAT2x3 */ /* reuse GL_DOUBLE_MAT2x4 */ /* reuse GL_DOUBLE_MAT3x2 */ /* reuse GL_DOUBLE_MAT3x4 */ /* reuse GL_DOUBLE_MAT4x2 */ /* reuse GL_DOUBLE_MAT4x3 */ #endif #ifndef GL_ARB_viewport_array /* reuse GL_SCISSOR_BOX */ /* reuse GL_VIEWPORT */ /* reuse GL_DEPTH_RANGE */ /* reuse GL_SCISSOR_TEST */ #define GL_MAX_VIEWPORTS 0x825B #define GL_VIEWPORT_SUBPIXEL_BITS 0x825C #define GL_VIEWPORT_BOUNDS_RANGE 0x825D #define GL_LAYER_PROVOKING_VERTEX 0x825E #define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F #define GL_UNDEFINED_VERTEX 0x8260 /* reuse GL_FIRST_VERTEX_CONVENTION */ /* reuse GL_LAST_VERTEX_CONVENTION */ /* reuse GL_PROVOKING_VERTEX */ #endif #ifndef GL_ARB_cl_event #define GL_SYNC_CL_EVENT_ARB 0x8240 #define GL_SYNC_CL_EVENT_COMPLETE_ARB 0x8241 #endif #ifndef GL_ARB_debug_output #define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 #define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 #define GL_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 #define GL_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 #define GL_DEBUG_SOURCE_API_ARB 0x8246 #define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 #define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 #define GL_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 #define GL_DEBUG_SOURCE_APPLICATION_ARB 0x824A #define GL_DEBUG_SOURCE_OTHER_ARB 0x824B #define GL_DEBUG_TYPE_ERROR_ARB 0x824C #define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D #define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E #define GL_DEBUG_TYPE_PORTABILITY_ARB 0x824F #define GL_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 #define GL_DEBUG_TYPE_OTHER_ARB 0x8251 #define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 #define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 #define GL_DEBUG_LOGGED_MESSAGES_ARB 0x9145 #define GL_DEBUG_SEVERITY_HIGH_ARB 0x9146 #define GL_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 #define GL_DEBUG_SEVERITY_LOW_ARB 0x9148 #endif #ifndef GL_ARB_robustness /* reuse GL_NO_ERROR */ #define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004 #define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 #define GL_GUILTY_CONTEXT_RESET_ARB 0x8253 #define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254 #define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255 #define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 #define GL_NO_RESET_NOTIFICATION_ARB 0x8261 #endif #ifndef GL_ARB_shader_stencil_export #endif #ifndef GL_ARB_base_instance #endif #ifndef GL_ARB_shading_language_420pack #endif #ifndef GL_ARB_transform_feedback_instanced #endif #ifndef GL_ARB_compressed_texture_pixel_storage #define GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127 #define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128 #define GL_UNPACK_COMPRESSED_BLOCK_DEPTH 0x9129 #define GL_UNPACK_COMPRESSED_BLOCK_SIZE 0x912A #define GL_PACK_COMPRESSED_BLOCK_WIDTH 0x912B #define GL_PACK_COMPRESSED_BLOCK_HEIGHT 0x912C #define GL_PACK_COMPRESSED_BLOCK_DEPTH 0x912D #define GL_PACK_COMPRESSED_BLOCK_SIZE 0x912E #endif #ifndef GL_ARB_conservative_depth #endif #ifndef GL_ARB_internalformat_query #define GL_NUM_SAMPLE_COUNTS 0x9380 #endif #ifndef GL_ARB_map_buffer_alignment #define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC #endif #ifndef GL_ARB_shader_atomic_counters #define GL_ATOMIC_COUNTER_BUFFER 0x92C0 #define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 #define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 #define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 #define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 #define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 #define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB #define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC #define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD #define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE #define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF #define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 #define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 #define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 #define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 #define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 #define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 #define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 #define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 #define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 #define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC #define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 #define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA #define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB #endif #ifndef GL_ARB_shader_image_load_store #define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 #define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 #define GL_UNIFORM_BARRIER_BIT 0x00000004 #define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 #define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 #define GL_COMMAND_BARRIER_BIT 0x00000040 #define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 #define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 #define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 #define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 #define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 #define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 #define GL_ALL_BARRIER_BITS 0xFFFFFFFF #define GL_MAX_IMAGE_UNITS 0x8F38 #define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 #define GL_IMAGE_BINDING_NAME 0x8F3A #define GL_IMAGE_BINDING_LEVEL 0x8F3B #define GL_IMAGE_BINDING_LAYERED 0x8F3C #define GL_IMAGE_BINDING_LAYER 0x8F3D #define GL_IMAGE_BINDING_ACCESS 0x8F3E #define GL_IMAGE_1D 0x904C #define GL_IMAGE_2D 0x904D #define GL_IMAGE_3D 0x904E #define GL_IMAGE_2D_RECT 0x904F #define GL_IMAGE_CUBE 0x9050 #define GL_IMAGE_BUFFER 0x9051 #define GL_IMAGE_1D_ARRAY 0x9052 #define GL_IMAGE_2D_ARRAY 0x9053 #define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 #define GL_IMAGE_2D_MULTISAMPLE 0x9055 #define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 #define GL_INT_IMAGE_1D 0x9057 #define GL_INT_IMAGE_2D 0x9058 #define GL_INT_IMAGE_3D 0x9059 #define GL_INT_IMAGE_2D_RECT 0x905A #define GL_INT_IMAGE_CUBE 0x905B #define GL_INT_IMAGE_BUFFER 0x905C #define GL_INT_IMAGE_1D_ARRAY 0x905D #define GL_INT_IMAGE_2D_ARRAY 0x905E #define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F #define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 #define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 #define GL_UNSIGNED_INT_IMAGE_1D 0x9062 #define GL_UNSIGNED_INT_IMAGE_2D 0x9063 #define GL_UNSIGNED_INT_IMAGE_3D 0x9064 #define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 #define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 #define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 #define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 #define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 #define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A #define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B #define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C #define GL_MAX_IMAGE_SAMPLES 0x906D #define GL_IMAGE_BINDING_FORMAT 0x906E #define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 #define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA #define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB #define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC #define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD #define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE #define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF #endif #ifndef GL_ARB_shading_language_packing #endif #ifndef GL_ARB_texture_storage #define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F #endif #ifndef GL_KHR_texture_compression_astc_ldr #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 #define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 #define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 #define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 #define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 #define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 #define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 #define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 #define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 #define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 #define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA #define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB #define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC #define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD #endif #ifndef GL_KHR_debug #define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 #define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 #define GL_DEBUG_CALLBACK_FUNCTION 0x8244 #define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 #define GL_DEBUG_SOURCE_API 0x8246 #define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 #define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 #define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 #define GL_DEBUG_SOURCE_APPLICATION 0x824A #define GL_DEBUG_SOURCE_OTHER 0x824B #define GL_DEBUG_TYPE_ERROR 0x824C #define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D #define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E #define GL_DEBUG_TYPE_PORTABILITY 0x824F #define GL_DEBUG_TYPE_PERFORMANCE 0x8250 #define GL_DEBUG_TYPE_OTHER 0x8251 #define GL_DEBUG_TYPE_MARKER 0x8268 #define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 #define GL_DEBUG_TYPE_POP_GROUP 0x826A #define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B #define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C #define GL_DEBUG_GROUP_STACK_DEPTH 0x826D #define GL_BUFFER 0x82E0 #define GL_SHADER 0x82E1 #define GL_PROGRAM 0x82E2 #define GL_QUERY 0x82E3 #define GL_PROGRAM_PIPELINE 0x82E4 #define GL_SAMPLER 0x82E6 #define GL_DISPLAY_LIST 0x82E7 /* DISPLAY_LIST used in compatibility profile only */ #define GL_MAX_LABEL_LENGTH 0x82E8 #define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 #define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 #define GL_DEBUG_LOGGED_MESSAGES 0x9145 #define GL_DEBUG_SEVERITY_HIGH 0x9146 #define GL_DEBUG_SEVERITY_MEDIUM 0x9147 #define GL_DEBUG_SEVERITY_LOW 0x9148 #define GL_DEBUG_OUTPUT 0x92E0 #define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 /* reuse GL_STACK_UNDERFLOW */ /* reuse GL_STACK_OVERFLOW */ #endif #ifndef GL_ARB_arrays_of_arrays #endif #ifndef GL_ARB_clear_buffer_object #endif #ifndef GL_ARB_compute_shader #define GL_COMPUTE_SHADER 0x91B9 #define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB #define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC #define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD #define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 #define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 #define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 #define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 #define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 #define GL_MAX_COMPUTE_LOCAL_INVOCATIONS 0x90EB #define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE #define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF #define GL_COMPUTE_LOCAL_WORK_SIZE 0x8267 #define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED #define GL_DISPATCH_INDIRECT_BUFFER 0x90EE #define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF #define GL_COMPUTE_SHADER_BIT 0x00000020 #endif #ifndef GL_ARB_copy_image #endif #ifndef GL_ARB_texture_view #define GL_TEXTURE_VIEW_MIN_LEVEL 0x82DB #define GL_TEXTURE_VIEW_NUM_LEVELS 0x82DC #define GL_TEXTURE_VIEW_MIN_LAYER 0x82DD #define GL_TEXTURE_VIEW_NUM_LAYERS 0x82DE #define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF #endif #ifndef GL_ARB_vertex_attrib_binding #define GL_VERTEX_ATTRIB_BINDING 0x82D4 #define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 #define GL_VERTEX_BINDING_DIVISOR 0x82D6 #define GL_VERTEX_BINDING_OFFSET 0x82D7 #define GL_VERTEX_BINDING_STRIDE 0x82D8 #define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 #define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA #endif #ifndef GL_ARB_robustness_isolation #endif #ifndef GL_ARB_ES3_compatibility #define GL_COMPRESSED_RGB8_ETC2 0x9274 #define GL_COMPRESSED_SRGB8_ETC2 0x9275 #define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 #define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 #define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 #define GL_COMPRESSED_R11_EAC 0x9270 #define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 #define GL_COMPRESSED_RG11_EAC 0x9272 #define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 #define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 #define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A #define GL_MAX_ELEMENT_INDEX 0x8D6B #endif #ifndef GL_ARB_explicit_uniform_location #define GL_MAX_UNIFORM_LOCATIONS 0x826E #endif #ifndef GL_ARB_fragment_layer_viewport #endif #ifndef GL_ARB_framebuffer_no_attachments #define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 #define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 #define GL_FRAMEBUFFER_DEFAULT_LAYERS 0x9312 #define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 #define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 #define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 #define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 #define GL_MAX_FRAMEBUFFER_LAYERS 0x9317 #define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 #endif #ifndef GL_ARB_internalformat_query2 /* reuse GL_IMAGE_FORMAT_COMPATIBILITY_TYPE */ /* reuse GL_NUM_SAMPLE_COUNTS */ /* reuse GL_RENDERBUFFER */ /* reuse GL_SAMPLES */ /* reuse GL_TEXTURE_1D */ /* reuse GL_TEXTURE_1D_ARRAY */ /* reuse GL_TEXTURE_2D */ /* reuse GL_TEXTURE_2D_ARRAY */ /* reuse GL_TEXTURE_3D */ /* reuse GL_TEXTURE_CUBE_MAP */ /* reuse GL_TEXTURE_CUBE_MAP_ARRAY */ /* reuse GL_TEXTURE_RECTANGLE */ /* reuse GL_TEXTURE_BUFFER */ /* reuse GL_TEXTURE_2D_MULTISAMPLE */ /* reuse GL_TEXTURE_2D_MULTISAMPLE_ARRAY */ /* reuse GL_TEXTURE_COMPRESSED */ #define GL_INTERNALFORMAT_SUPPORTED 0x826F #define GL_INTERNALFORMAT_PREFERRED 0x8270 #define GL_INTERNALFORMAT_RED_SIZE 0x8271 #define GL_INTERNALFORMAT_GREEN_SIZE 0x8272 #define GL_INTERNALFORMAT_BLUE_SIZE 0x8273 #define GL_INTERNALFORMAT_ALPHA_SIZE 0x8274 #define GL_INTERNALFORMAT_DEPTH_SIZE 0x8275 #define GL_INTERNALFORMAT_STENCIL_SIZE 0x8276 #define GL_INTERNALFORMAT_SHARED_SIZE 0x8277 #define GL_INTERNALFORMAT_RED_TYPE 0x8278 #define GL_INTERNALFORMAT_GREEN_TYPE 0x8279 #define GL_INTERNALFORMAT_BLUE_TYPE 0x827A #define GL_INTERNALFORMAT_ALPHA_TYPE 0x827B #define GL_INTERNALFORMAT_DEPTH_TYPE 0x827C #define GL_INTERNALFORMAT_STENCIL_TYPE 0x827D #define GL_MAX_WIDTH 0x827E #define GL_MAX_HEIGHT 0x827F #define GL_MAX_DEPTH 0x8280 #define GL_MAX_LAYERS 0x8281 #define GL_MAX_COMBINED_DIMENSIONS 0x8282 #define GL_COLOR_COMPONENTS 0x8283 #define GL_DEPTH_COMPONENTS 0x8284 #define GL_STENCIL_COMPONENTS 0x8285 #define GL_COLOR_RENDERABLE 0x8286 #define GL_DEPTH_RENDERABLE 0x8287 #define GL_STENCIL_RENDERABLE 0x8288 #define GL_FRAMEBUFFER_RENDERABLE 0x8289 #define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A #define GL_FRAMEBUFFER_BLEND 0x828B #define GL_READ_PIXELS 0x828C #define GL_READ_PIXELS_FORMAT 0x828D #define GL_READ_PIXELS_TYPE 0x828E #define GL_TEXTURE_IMAGE_FORMAT 0x828F #define GL_TEXTURE_IMAGE_TYPE 0x8290 #define GL_GET_TEXTURE_IMAGE_FORMAT 0x8291 #define GL_GET_TEXTURE_IMAGE_TYPE 0x8292 #define GL_MIPMAP 0x8293 #define GL_MANUAL_GENERATE_MIPMAP 0x8294 #define GL_AUTO_GENERATE_MIPMAP 0x8295 #define GL_COLOR_ENCODING 0x8296 #define GL_SRGB_READ 0x8297 #define GL_SRGB_WRITE 0x8298 #define GL_SRGB_DECODE_ARB 0x8299 #define GL_FILTER 0x829A #define GL_VERTEX_TEXTURE 0x829B #define GL_TESS_CONTROL_TEXTURE 0x829C #define GL_TESS_EVALUATION_TEXTURE 0x829D #define GL_GEOMETRY_TEXTURE 0x829E #define GL_FRAGMENT_TEXTURE 0x829F #define GL_COMPUTE_TEXTURE 0x82A0 #define GL_TEXTURE_SHADOW 0x82A1 #define GL_TEXTURE_GATHER 0x82A2 #define GL_TEXTURE_GATHER_SHADOW 0x82A3 #define GL_SHADER_IMAGE_LOAD 0x82A4 #define GL_SHADER_IMAGE_STORE 0x82A5 #define GL_SHADER_IMAGE_ATOMIC 0x82A6 #define GL_IMAGE_TEXEL_SIZE 0x82A7 #define GL_IMAGE_COMPATIBILITY_CLASS 0x82A8 #define GL_IMAGE_PIXEL_FORMAT 0x82A9 #define GL_IMAGE_PIXEL_TYPE 0x82AA #define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC #define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD #define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE #define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF #define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1 #define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2 #define GL_TEXTURE_COMPRESSED_BLOCK_SIZE 0x82B3 #define GL_CLEAR_BUFFER 0x82B4 #define GL_TEXTURE_VIEW 0x82B5 #define GL_VIEW_COMPATIBILITY_CLASS 0x82B6 #define GL_FULL_SUPPORT 0x82B7 #define GL_CAVEAT_SUPPORT 0x82B8 #define GL_IMAGE_CLASS_4_X_32 0x82B9 #define GL_IMAGE_CLASS_2_X_32 0x82BA #define GL_IMAGE_CLASS_1_X_32 0x82BB #define GL_IMAGE_CLASS_4_X_16 0x82BC #define GL_IMAGE_CLASS_2_X_16 0x82BD #define GL_IMAGE_CLASS_1_X_16 0x82BE #define GL_IMAGE_CLASS_4_X_8 0x82BF #define GL_IMAGE_CLASS_2_X_8 0x82C0 #define GL_IMAGE_CLASS_1_X_8 0x82C1 #define GL_IMAGE_CLASS_11_11_10 0x82C2 #define GL_IMAGE_CLASS_10_10_10_2 0x82C3 #define GL_VIEW_CLASS_128_BITS 0x82C4 #define GL_VIEW_CLASS_96_BITS 0x82C5 #define GL_VIEW_CLASS_64_BITS 0x82C6 #define GL_VIEW_CLASS_48_BITS 0x82C7 #define GL_VIEW_CLASS_32_BITS 0x82C8 #define GL_VIEW_CLASS_24_BITS 0x82C9 #define GL_VIEW_CLASS_16_BITS 0x82CA #define GL_VIEW_CLASS_8_BITS 0x82CB #define GL_VIEW_CLASS_S3TC_DXT1_RGB 0x82CC #define GL_VIEW_CLASS_S3TC_DXT1_RGBA 0x82CD #define GL_VIEW_CLASS_S3TC_DXT3_RGBA 0x82CE #define GL_VIEW_CLASS_S3TC_DXT5_RGBA 0x82CF #define GL_VIEW_CLASS_RGTC1_RED 0x82D0 #define GL_VIEW_CLASS_RGTC2_RG 0x82D1 #define GL_VIEW_CLASS_BPTC_UNORM 0x82D2 #define GL_VIEW_CLASS_BPTC_FLOAT 0x82D3 #endif #ifndef GL_ARB_invalidate_subdata #endif #ifndef GL_ARB_multi_draw_indirect #endif #ifndef GL_ARB_program_interface_query #define GL_UNIFORM 0x92E1 #define GL_UNIFORM_BLOCK 0x92E2 #define GL_PROGRAM_INPUT 0x92E3 #define GL_PROGRAM_OUTPUT 0x92E4 #define GL_BUFFER_VARIABLE 0x92E5 #define GL_SHADER_STORAGE_BLOCK 0x92E6 /* reuse GL_ATOMIC_COUNTER_BUFFER */ #define GL_VERTEX_SUBROUTINE 0x92E8 #define GL_TESS_CONTROL_SUBROUTINE 0x92E9 #define GL_TESS_EVALUATION_SUBROUTINE 0x92EA #define GL_GEOMETRY_SUBROUTINE 0x92EB #define GL_FRAGMENT_SUBROUTINE 0x92EC #define GL_COMPUTE_SUBROUTINE 0x92ED #define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE #define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF #define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 #define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 #define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 #define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 #define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 #define GL_ACTIVE_RESOURCES 0x92F5 #define GL_MAX_NAME_LENGTH 0x92F6 #define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 #define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 #define GL_NAME_LENGTH 0x92F9 #define GL_TYPE 0x92FA #define GL_ARRAY_SIZE 0x92FB #define GL_OFFSET 0x92FC #define GL_BLOCK_INDEX 0x92FD #define GL_ARRAY_STRIDE 0x92FE #define GL_MATRIX_STRIDE 0x92FF #define GL_IS_ROW_MAJOR 0x9300 #define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 #define GL_BUFFER_BINDING 0x9302 #define GL_BUFFER_DATA_SIZE 0x9303 #define GL_NUM_ACTIVE_VARIABLES 0x9304 #define GL_ACTIVE_VARIABLES 0x9305 #define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 #define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 #define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 #define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 #define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A #define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B #define GL_TOP_LEVEL_ARRAY_SIZE 0x930C #define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D #define GL_LOCATION 0x930E #define GL_LOCATION_INDEX 0x930F #define GL_IS_PER_PATCH 0x92E7 /* reuse GL_NUM_COMPATIBLE_SUBROUTINES */ /* reuse GL_COMPATIBLE_SUBROUTINES */ #endif #ifndef GL_ARB_robust_buffer_access_behavior #endif #ifndef GL_ARB_shader_image_size #endif #ifndef GL_ARB_shader_storage_buffer_object #define GL_SHADER_STORAGE_BUFFER 0x90D2 #define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 #define GL_SHADER_STORAGE_BUFFER_START 0x90D4 #define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 #define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 #define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 #define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 #define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 #define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA #define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB #define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC #define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD #define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE #define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF #define GL_SHADER_STORAGE_BARRIER_BIT 0x2000 #define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES \ GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS /* reuse GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS */ #endif #ifndef GL_ARB_stencil_texturing #define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA #endif #ifndef GL_ARB_texture_buffer_range #define GL_TEXTURE_BUFFER_OFFSET 0x919D #define GL_TEXTURE_BUFFER_SIZE 0x919E #define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F #endif #ifndef GL_ARB_texture_query_levels #endif #ifndef GL_ARB_texture_storage_multisample #endif /*************************************************************/ #include <stddef.h> #ifndef GL_VERSION_2_0 /* GL type for program/shader text */ typedef char GLchar; #endif #ifndef GL_VERSION_1_5 /* GL types for handling large vertex buffer objects */ typedef ptrdiff_t GLintptr; typedef ptrdiff_t GLsizeiptr; #endif #ifndef GL_ARB_vertex_buffer_object /* GL types for handling large vertex buffer objects */ typedef ptrdiff_t GLintptrARB; typedef ptrdiff_t GLsizeiptrARB; #endif #ifndef GL_ARB_shader_objects /* GL types for program/shader text and shader object handles */ typedef char GLcharARB; typedef unsigned int GLhandleARB; #endif /* GL type for "half" precision (s10e5) float data in host memory */ #ifndef GL_ARB_half_float_pixel typedef unsigned short GLhalfARB; #endif #ifndef GL_NV_half_float typedef unsigned short GLhalfNV; #endif #ifndef GLEXT_64_TYPES_DEFINED /* This code block is duplicated in glxext.h, so must be protected */ #define GLEXT_64_TYPES_DEFINED /* Define int32_t, int64_t, and uint64_t types for UST/MSC */ /* (as used in the GL_EXT_timer_query extension). */ #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #include <inttypes.h> #elif defined(__sun__) || defined(__digital__) #include <inttypes.h> #if defined(__STDC__) #if defined(__arch64__) || defined(_LP64) typedef long int int64_t; typedef unsigned long int uint64_t; #else typedef long long int int64_t; typedef unsigned long long int uint64_t; #endif /* __arch64__ */ #endif /* __STDC__ */ #elif defined(__VMS) || defined(__sgi) #include <inttypes.h> #elif defined(__SCO__) || defined(__USLC__) #include <stdint.h> #elif defined(__UNIXOS2__) || defined(__SOL64__) typedef long int int32_t; typedef long long int int64_t; typedef unsigned long long int uint64_t; #elif defined(_WIN32) && defined(__GNUC__) #include <stdint.h> #elif defined(_WIN32) typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else /* Fallback if nothing above works */ #include <inttypes.h> #endif #endif #ifndef GL_EXT_timer_query typedef int64_t GLint64EXT; typedef uint64_t GLuint64EXT; #endif #ifndef GL_ARB_sync typedef int64_t GLint64; typedef uint64_t GLuint64; typedef struct __GLsync* GLsync; #endif #ifndef GL_ARB_cl_event /* These incomplete types let us declare types compatible with OpenCL's * cl_context and cl_event */ struct _cl_context; struct _cl_event; #endif #ifndef GL_ARB_debug_output typedef void(APIENTRY* GLDEBUGPROCARB)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, GLvoid* userParam); #endif #ifndef GL_AMD_debug_output typedef void(APIENTRY* GLDEBUGPROCAMD)(GLuint id, GLenum category, GLenum severity, GLsizei length, const GLchar* message, GLvoid* userParam); #endif #ifndef GL_KHR_debug typedef void(APIENTRY* GLDEBUGPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, GLvoid* userParam); #endif #ifndef GL_NV_vdpau_interop typedef GLintptr GLvdpauSurfaceNV; #endif #ifndef GL_VERSION_1_0 #define GL_VERSION_1_0 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glCullFace(GLenum mode); GLAPI void APIENTRY glFrontFace(GLenum mode); GLAPI void APIENTRY glHint(GLenum target, GLenum mode); GLAPI void APIENTRY glLineWidth(GLfloat width); GLAPI void APIENTRY glPointSize(GLfloat size); GLAPI void APIENTRY glPolygonMode(GLenum face, GLenum mode); GLAPI void APIENTRY glScissor( GLint x, GLint y, GLsizei width, GLsizei height); GLAPI void APIENTRY glTexParameterf( GLenum target, GLenum pname, GLfloat param); GLAPI void APIENTRY glTexParameterfv( GLenum target, GLenum pname, const GLfloat* params); GLAPI void APIENTRY glTexParameteri( GLenum target, GLenum pname, GLint param); GLAPI void APIENTRY glTexParameteriv( GLenum target, GLenum pname, const GLint* params); GLAPI void APIENTRY glTexImage1D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid* pixels); GLAPI void APIENTRY glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels); GLAPI void APIENTRY glDrawBuffer(GLenum mode); GLAPI void APIENTRY glClear(GLbitfield mask); GLAPI void APIENTRY glClearColor( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI void APIENTRY glClearStencil(GLint s); GLAPI void APIENTRY glClearDepth(GLdouble depth); GLAPI void APIENTRY glStencilMask(GLuint mask); GLAPI void APIENTRY glColorMask( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); GLAPI void APIENTRY glDepthMask(GLboolean flag); GLAPI void APIENTRY glDisable(GLenum cap); GLAPI void APIENTRY glEnable(GLenum cap); GLAPI void APIENTRY glFinish(void); GLAPI void APIENTRY glFlush(void); GLAPI void APIENTRY glBlendFunc(GLenum sfactor, GLenum dfactor); GLAPI void APIENTRY glLogicOp(GLenum opcode); GLAPI void APIENTRY glStencilFunc(GLenum func, GLint ref, GLuint mask); GLAPI void APIENTRY glStencilOp(GLenum fail, GLenum zfail, GLenum zpass); GLAPI void APIENTRY glDepthFunc(GLenum func); GLAPI void APIENTRY glPixelStoref(GLenum pname, GLfloat param); GLAPI void APIENTRY glPixelStorei(GLenum pname, GLint param); GLAPI void APIENTRY glReadBuffer(GLenum mode); GLAPI void APIENTRY glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels); GLAPI void APIENTRY glGetBooleanv(GLenum pname, GLboolean* params); GLAPI void APIENTRY glGetDoublev(GLenum pname, GLdouble* params); GLAPI GLenum APIENTRY glGetError(void); GLAPI void APIENTRY glGetFloatv(GLenum pname, GLfloat* params); GLAPI void APIENTRY glGetIntegerv(GLenum pname, GLint* params); GLAPI const GLubyte* APIENTRY glGetString(GLenum name); GLAPI void APIENTRY glGetTexImage( GLenum target, GLint level, GLenum format, GLenum type, GLvoid* pixels); GLAPI void APIENTRY glGetTexParameterfv( GLenum target, GLenum pname, GLfloat* params); GLAPI void APIENTRY glGetTexParameteriv( GLenum target, GLenum pname, GLint* params); GLAPI void APIENTRY glGetTexLevelParameterfv( GLenum target, GLint level, GLenum pname, GLfloat* params); GLAPI void APIENTRY glGetTexLevelParameteriv( GLenum target, GLint level, GLenum pname, GLint* params); GLAPI GLboolean APIENTRY glIsEnabled(GLenum cap); GLAPI void APIENTRY glDepthRange(GLdouble near, GLdouble far); GLAPI void APIENTRY glViewport( GLint x, GLint y, GLsizei width, GLsizei height); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); typedef void(APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); typedef void(APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); typedef void(APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); typedef void(APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); typedef void(APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); typedef void(APIENTRYP PFNGLSCISSORPROC)( GLint x, GLint y, GLsizei width, GLsizei height); typedef void(APIENTRYP PFNGLTEXPARAMETERFPROC)( GLenum target, GLenum pname, GLfloat param); typedef void(APIENTRYP PFNGLTEXPARAMETERFVPROC)( GLenum target, GLenum pname, const GLfloat* params); typedef void(APIENTRYP PFNGLTEXPARAMETERIPROC)( GLenum target, GLenum pname, GLint param); typedef void(APIENTRYP PFNGLTEXPARAMETERIVPROC)( GLenum target, GLenum pname, const GLint* params); typedef void(APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid* pixels); typedef void(APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels); typedef void(APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum mode); typedef void(APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); typedef void(APIENTRYP PFNGLCLEARCOLORPROC)( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); typedef void(APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); typedef void(APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); typedef void(APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); typedef void(APIENTRYP PFNGLCOLORMASKPROC)( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); typedef void(APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); typedef void(APIENTRYP PFNGLDISABLEPROC)(GLenum cap); typedef void(APIENTRYP PFNGLENABLEPROC)(GLenum cap); typedef void(APIENTRYP PFNGLFINISHPROC)(void); typedef void(APIENTRYP PFNGLFLUSHPROC)(void); typedef void(APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); typedef void(APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); typedef void(APIENTRYP PFNGLSTENCILFUNCPROC)( GLenum func, GLint ref, GLuint mask); typedef void(APIENTRYP PFNGLSTENCILOPPROC)( GLenum fail, GLenum zfail, GLenum zpass); typedef void(APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); typedef void(APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); typedef void(APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); typedef void(APIENTRYP PFNGLREADBUFFERPROC)(GLenum mode); typedef void(APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels); typedef void(APIENTRYP PFNGLGETBOOLEANVPROC)( GLenum pname, GLboolean* params); typedef void(APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble* params); typedef GLenum(APIENTRYP PFNGLGETERRORPROC)(void); typedef void(APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat* params); typedef void(APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint* params); typedef const GLubyte*(APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); typedef void(APIENTRYP PFNGLGETTEXIMAGEPROC)( GLenum target, GLint level, GLenum format, GLenum type, GLvoid* pixels); typedef void(APIENTRYP PFNGLGETTEXPARAMETERFVPROC)( GLenum target, GLenum pname, GLfloat* params); typedef void(APIENTRYP PFNGLGETTEXPARAMETERIVPROC)( GLenum target, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)( GLenum target, GLint level, GLenum pname, GLfloat* params); typedef void(APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)( GLenum target, GLint level, GLenum pname, GLint* params); typedef GLboolean(APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); typedef void(APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble near, GLdouble far); typedef void(APIENTRYP PFNGLVIEWPORTPROC)( GLint x, GLint y, GLsizei width, GLsizei height); #endif #ifndef GL_VERSION_1_1 #define GL_VERSION_1_1 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDrawArrays(GLenum mode, GLint first, GLsizei count); GLAPI void APIENTRY glDrawElements( GLenum mode, GLsizei count, GLenum type, const GLvoid* indices); GLAPI void APIENTRY glGetPointerv(GLenum pname, GLvoid** params); GLAPI void APIENTRY glPolygonOffset(GLfloat factor, GLfloat units); GLAPI void APIENTRY glCopyTexImage1D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); GLAPI void APIENTRY glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); GLAPI void APIENTRY glCopyTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); GLAPI void APIENTRY glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI void APIENTRY glTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid* pixels); GLAPI void APIENTRY glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels); GLAPI void APIENTRY glBindTexture(GLenum target, GLuint texture); GLAPI void APIENTRY glDeleteTextures(GLsizei n, const GLuint* textures); GLAPI void APIENTRY glGenTextures(GLsizei n, GLuint* textures); GLAPI GLboolean APIENTRY glIsTexture(GLuint texture); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDRAWARRAYSPROC)( GLenum mode, GLint first, GLsizei count); typedef void(APIENTRYP PFNGLDRAWELEMENTSPROC)( GLenum mode, GLsizei count, GLenum type, const GLvoid* indices); typedef void(APIENTRYP PFNGLGETPOINTERVPROC)(GLenum pname, GLvoid** params); typedef void(APIENTRYP PFNGLPOLYGONOFFSETPROC)( GLfloat factor, GLfloat units); typedef void(APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); typedef void(APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); typedef void(APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid* pixels); typedef void(APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels); typedef void(APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); typedef void(APIENTRYP PFNGLDELETETEXTURESPROC)( GLsizei n, const GLuint* textures); typedef void(APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint* textures); typedef GLboolean(APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); #endif #ifndef GL_VERSION_1_2 #define GL_VERSION_1_2 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBlendColor( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI void APIENTRY glBlendEquation(GLenum mode); GLAPI void APIENTRY glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices); GLAPI void APIENTRY glTexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels); GLAPI void APIENTRY glTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels); GLAPI void APIENTRY glCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBLENDCOLORPROC)( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); typedef void(APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); typedef void(APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices); typedef void(APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels); typedef void(APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels); typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); #endif #ifndef GL_VERSION_1_3 #define GL_VERSION_1_3 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glActiveTexture(GLenum texture); GLAPI void APIENTRY glSampleCoverage(GLfloat value, GLboolean invert); GLAPI void APIENTRY glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data); GLAPI void APIENTRY glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data); GLAPI void APIENTRY glCompressedTexImage1D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid* data); GLAPI void APIENTRY glCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data); GLAPI void APIENTRY glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data); GLAPI void APIENTRY glCompressedTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid* data); GLAPI void APIENTRY glGetCompressedTexImage( GLenum target, GLint level, GLvoid* img); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); typedef void(APIENTRYP PFNGLSAMPLECOVERAGEPROC)( GLfloat value, GLboolean invert); typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data); typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data); typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid* data); typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data); typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data); typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid* data); typedef void(APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)( GLenum target, GLint level, GLvoid* img); #endif #ifndef GL_VERSION_1_4 #define GL_VERSION_1_4 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); GLAPI void APIENTRY glMultiDrawArrays(GLenum mode, const GLint* first, const GLsizei* count, GLsizei drawcount); GLAPI void APIENTRY glMultiDrawElements(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices, GLsizei drawcount); GLAPI void APIENTRY glPointParameterf(GLenum pname, GLfloat param); GLAPI void APIENTRY glPointParameterfv(GLenum pname, const GLfloat* params); GLAPI void APIENTRY glPointParameteri(GLenum pname, GLint param); GLAPI void APIENTRY glPointParameteriv(GLenum pname, const GLint* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); typedef void(APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint* first, const GLsizei* count, GLsizei drawcount); typedef void(APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices, GLsizei drawcount); typedef void(APIENTRYP PFNGLPOINTPARAMETERFPROC)( GLenum pname, GLfloat param); typedef void(APIENTRYP PFNGLPOINTPARAMETERFVPROC)( GLenum pname, const GLfloat* params); typedef void(APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); typedef void(APIENTRYP PFNGLPOINTPARAMETERIVPROC)( GLenum pname, const GLint* params); #endif #ifndef GL_VERSION_1_5 #define GL_VERSION_1_5 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGenQueries(GLsizei n, GLuint* ids); GLAPI void APIENTRY glDeleteQueries(GLsizei n, const GLuint* ids); GLAPI GLboolean APIENTRY glIsQuery(GLuint id); GLAPI void APIENTRY glBeginQuery(GLenum target, GLuint id); GLAPI void APIENTRY glEndQuery(GLenum target); GLAPI void APIENTRY glGetQueryiv( GLenum target, GLenum pname, GLint* params); GLAPI void APIENTRY glGetQueryObjectiv( GLuint id, GLenum pname, GLint* params); GLAPI void APIENTRY glGetQueryObjectuiv( GLuint id, GLenum pname, GLuint* params); GLAPI void APIENTRY glBindBuffer(GLenum target, GLuint buffer); GLAPI void APIENTRY glDeleteBuffers(GLsizei n, const GLuint* buffers); GLAPI void APIENTRY glGenBuffers(GLsizei n, GLuint* buffers); GLAPI GLboolean APIENTRY glIsBuffer(GLuint buffer); GLAPI void APIENTRY glBufferData( GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage); GLAPI void APIENTRY glBufferSubData( GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data); GLAPI void APIENTRY glGetBufferSubData( GLenum target, GLintptr offset, GLsizeiptr size, GLvoid* data); GLAPI GLvoid* APIENTRY glMapBuffer(GLenum target, GLenum access); GLAPI GLboolean APIENTRY glUnmapBuffer(GLenum target); GLAPI void APIENTRY glGetBufferParameteriv( GLenum target, GLenum pname, GLint* params); GLAPI void APIENTRY glGetBufferPointerv( GLenum target, GLenum pname, GLvoid** params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint* ids); typedef void(APIENTRYP PFNGLDELETEQUERIESPROC)( GLsizei n, const GLuint* ids); typedef GLboolean(APIENTRYP PFNGLISQUERYPROC)(GLuint id); typedef void(APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); typedef void(APIENTRYP PFNGLENDQUERYPROC)(GLenum target); typedef void(APIENTRYP PFNGLGETQUERYIVPROC)( GLenum target, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETQUERYOBJECTIVPROC)( GLuint id, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)( GLuint id, GLenum pname, GLuint* params); typedef void(APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); typedef void(APIENTRYP PFNGLDELETEBUFFERSPROC)( GLsizei n, const GLuint* buffers); typedef void(APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint* buffers); typedef GLboolean(APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); typedef void(APIENTRYP PFNGLBUFFERDATAPROC)( GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage); typedef void(APIENTRYP PFNGLBUFFERSUBDATAPROC)( GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data); typedef void(APIENTRYP PFNGLGETBUFFERSUBDATAPROC)( GLenum target, GLintptr offset, GLsizeiptr size, GLvoid* data); typedef GLvoid*(APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); typedef GLboolean(APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); typedef void(APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)( GLenum target, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETBUFFERPOINTERVPROC)( GLenum target, GLenum pname, GLvoid** params); #endif #ifndef GL_VERSION_2_0 #define GL_VERSION_2_0 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBlendEquationSeparate( GLenum modeRGB, GLenum modeAlpha); GLAPI void APIENTRY glDrawBuffers(GLsizei n, const GLenum* bufs); GLAPI void APIENTRY glStencilOpSeparate( GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); GLAPI void APIENTRY glStencilFuncSeparate( GLenum face, GLenum func, GLint ref, GLuint mask); GLAPI void APIENTRY glStencilMaskSeparate(GLenum face, GLuint mask); GLAPI void APIENTRY glAttachShader(GLuint program, GLuint shader); GLAPI void APIENTRY glBindAttribLocation( GLuint program, GLuint index, const GLchar* name); GLAPI void APIENTRY glCompileShader(GLuint shader); GLAPI GLuint APIENTRY glCreateProgram(void); GLAPI GLuint APIENTRY glCreateShader(GLenum type); GLAPI void APIENTRY glDeleteProgram(GLuint program); GLAPI void APIENTRY glDeleteShader(GLuint shader); GLAPI void APIENTRY glDetachShader(GLuint program, GLuint shader); GLAPI void APIENTRY glDisableVertexAttribArray(GLuint index); GLAPI void APIENTRY glEnableVertexAttribArray(GLuint index); GLAPI void APIENTRY glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name); GLAPI void APIENTRY glGetActiveUniform(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name); GLAPI void APIENTRY glGetAttachedShaders( GLuint program, GLsizei maxCount, GLsizei* count, GLuint* obj); GLAPI GLint APIENTRY glGetAttribLocation( GLuint program, const GLchar* name); GLAPI void APIENTRY glGetProgramiv( GLuint program, GLenum pname, GLint* params); GLAPI void APIENTRY glGetProgramInfoLog( GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog); GLAPI void APIENTRY glGetShaderiv( GLuint shader, GLenum pname, GLint* params); GLAPI void APIENTRY glGetShaderInfoLog( GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog); GLAPI void APIENTRY glGetShaderSource( GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source); GLAPI GLint APIENTRY glGetUniformLocation( GLuint program, const GLchar* name); GLAPI void APIENTRY glGetUniformfv( GLuint program, GLint location, GLfloat* params); GLAPI void APIENTRY glGetUniformiv( GLuint program, GLint location, GLint* params); GLAPI void APIENTRY glGetVertexAttribdv( GLuint index, GLenum pname, GLdouble* params); GLAPI void APIENTRY glGetVertexAttribfv( GLuint index, GLenum pname, GLfloat* params); GLAPI void APIENTRY glGetVertexAttribiv( GLuint index, GLenum pname, GLint* params); GLAPI void APIENTRY glGetVertexAttribPointerv( GLuint index, GLenum pname, GLvoid** pointer); GLAPI GLboolean APIENTRY glIsProgram(GLuint program); GLAPI GLboolean APIENTRY glIsShader(GLuint shader); GLAPI void APIENTRY glLinkProgram(GLuint program); GLAPI void APIENTRY glShaderSource(GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length); GLAPI void APIENTRY glUseProgram(GLuint program); GLAPI void APIENTRY glUniform1f(GLint location, GLfloat v0); GLAPI void APIENTRY glUniform2f(GLint location, GLfloat v0, GLfloat v1); GLAPI void APIENTRY glUniform3f( GLint location, GLfloat v0, GLfloat v1, GLfloat v2); GLAPI void APIENTRY glUniform4f( GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); GLAPI void APIENTRY glUniform1i(GLint location, GLint v0); GLAPI void APIENTRY glUniform2i(GLint location, GLint v0, GLint v1); GLAPI void APIENTRY glUniform3i( GLint location, GLint v0, GLint v1, GLint v2); GLAPI void APIENTRY glUniform4i( GLint location, GLint v0, GLint v1, GLint v2, GLint v3); GLAPI void APIENTRY glUniform1fv( GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glUniform2fv( GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glUniform3fv( GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glUniform4fv( GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glUniform1iv( GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glUniform2iv( GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glUniform3iv( GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glUniform4iv( GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glValidateProgram(GLuint program); GLAPI void APIENTRY glVertexAttrib1d(GLuint index, GLdouble x); GLAPI void APIENTRY glVertexAttrib1dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttrib1f(GLuint index, GLfloat x); GLAPI void APIENTRY glVertexAttrib1fv(GLuint index, const GLfloat* v); GLAPI void APIENTRY glVertexAttrib1s(GLuint index, GLshort x); GLAPI void APIENTRY glVertexAttrib1sv(GLuint index, const GLshort* v); GLAPI void APIENTRY glVertexAttrib2d(GLuint index, GLdouble x, GLdouble y); GLAPI void APIENTRY glVertexAttrib2dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttrib2f(GLuint index, GLfloat x, GLfloat y); GLAPI void APIENTRY glVertexAttrib2fv(GLuint index, const GLfloat* v); GLAPI void APIENTRY glVertexAttrib2s(GLuint index, GLshort x, GLshort y); GLAPI void APIENTRY glVertexAttrib2sv(GLuint index, const GLshort* v); GLAPI void APIENTRY glVertexAttrib3d( GLuint index, GLdouble x, GLdouble y, GLdouble z); GLAPI void APIENTRY glVertexAttrib3dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttrib3f( GLuint index, GLfloat x, GLfloat y, GLfloat z); GLAPI void APIENTRY glVertexAttrib3fv(GLuint index, const GLfloat* v); GLAPI void APIENTRY glVertexAttrib3s( GLuint index, GLshort x, GLshort y, GLshort z); GLAPI void APIENTRY glVertexAttrib3sv(GLuint index, const GLshort* v); GLAPI void APIENTRY glVertexAttrib4Nbv(GLuint index, const GLbyte* v); GLAPI void APIENTRY glVertexAttrib4Niv(GLuint index, const GLint* v); GLAPI void APIENTRY glVertexAttrib4Nsv(GLuint index, const GLshort* v); GLAPI void APIENTRY glVertexAttrib4Nub( GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); GLAPI void APIENTRY glVertexAttrib4Nubv(GLuint index, const GLubyte* v); GLAPI void APIENTRY glVertexAttrib4Nuiv(GLuint index, const GLuint* v); GLAPI void APIENTRY glVertexAttrib4Nusv(GLuint index, const GLushort* v); GLAPI void APIENTRY glVertexAttrib4bv(GLuint index, const GLbyte* v); GLAPI void APIENTRY glVertexAttrib4d( GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI void APIENTRY glVertexAttrib4dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttrib4f( GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLAPI void APIENTRY glVertexAttrib4fv(GLuint index, const GLfloat* v); GLAPI void APIENTRY glVertexAttrib4iv(GLuint index, const GLint* v); GLAPI void APIENTRY glVertexAttrib4s( GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); GLAPI void APIENTRY glVertexAttrib4sv(GLuint index, const GLshort* v); GLAPI void APIENTRY glVertexAttrib4ubv(GLuint index, const GLubyte* v); GLAPI void APIENTRY glVertexAttrib4uiv(GLuint index, const GLuint* v); GLAPI void APIENTRY glVertexAttrib4usv(GLuint index, const GLushort* v); GLAPI void APIENTRY glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)( GLenum modeRGB, GLenum modeAlpha); typedef void(APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum* bufs); typedef void(APIENTRYP PFNGLSTENCILOPSEPARATEPROC)( GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); typedef void(APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)( GLenum face, GLenum func, GLint ref, GLuint mask); typedef void(APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)( GLenum face, GLuint mask); typedef void(APIENTRYP PFNGLATTACHSHADERPROC)( GLuint program, GLuint shader); typedef void(APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)( GLuint program, GLuint index, const GLchar* name); typedef void(APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); typedef GLuint(APIENTRYP PFNGLCREATEPROGRAMPROC)(void); typedef GLuint(APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); typedef void(APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); typedef void(APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); typedef void(APIENTRYP PFNGLDETACHSHADERPROC)( GLuint program, GLuint shader); typedef void(APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); typedef void(APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); typedef void(APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name); typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name); typedef void(APIENTRYP PFNGLGETATTACHEDSHADERSPROC)( GLuint program, GLsizei maxCount, GLsizei* count, GLuint* obj); typedef GLint(APIENTRYP PFNGLGETATTRIBLOCATIONPROC)( GLuint program, const GLchar* name); typedef void(APIENTRYP PFNGLGETPROGRAMIVPROC)( GLuint program, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)( GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog); typedef void(APIENTRYP PFNGLGETSHADERIVPROC)( GLuint shader, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETSHADERINFOLOGPROC)( GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog); typedef void(APIENTRYP PFNGLGETSHADERSOURCEPROC)( GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source); typedef GLint(APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)( GLuint program, const GLchar* name); typedef void(APIENTRYP PFNGLGETUNIFORMFVPROC)( GLuint program, GLint location, GLfloat* params); typedef void(APIENTRYP PFNGLGETUNIFORMIVPROC)( GLuint program, GLint location, GLint* params); typedef void(APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)( GLuint index, GLenum pname, GLdouble* params); typedef void(APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)( GLuint index, GLenum pname, GLfloat* params); typedef void(APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)( GLuint index, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)( GLuint index, GLenum pname, GLvoid** pointer); typedef GLboolean(APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); typedef GLboolean(APIENTRYP PFNGLISSHADERPROC)(GLuint shader); typedef void(APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); typedef void(APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length); typedef void(APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); typedef void(APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); typedef void(APIENTRYP PFNGLUNIFORM2FPROC)( GLint location, GLfloat v0, GLfloat v1); typedef void(APIENTRYP PFNGLUNIFORM3FPROC)( GLint location, GLfloat v0, GLfloat v1, GLfloat v2); typedef void(APIENTRYP PFNGLUNIFORM4FPROC)( GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); typedef void(APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); typedef void(APIENTRYP PFNGLUNIFORM2IPROC)( GLint location, GLint v0, GLint v1); typedef void(APIENTRYP PFNGLUNIFORM3IPROC)( GLint location, GLint v0, GLint v1, GLint v2); typedef void(APIENTRYP PFNGLUNIFORM4IPROC)( GLint location, GLint v0, GLint v1, GLint v2, GLint v3); typedef void(APIENTRYP PFNGLUNIFORM1FVPROC)( GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORM2FVPROC)( GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORM3FVPROC)( GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORM4FVPROC)( GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORM1IVPROC)( GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLUNIFORM2IVPROC)( GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLUNIFORM3IVPROC)( GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLUNIFORM4IVPROC)( GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); typedef void(APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); typedef void(APIENTRYP PFNGLVERTEXATTRIB1DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); typedef void(APIENTRYP PFNGLVERTEXATTRIB1FVPROC)( GLuint index, const GLfloat* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); typedef void(APIENTRYP PFNGLVERTEXATTRIB1SVPROC)( GLuint index, const GLshort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB2DPROC)( GLuint index, GLdouble x, GLdouble y); typedef void(APIENTRYP PFNGLVERTEXATTRIB2DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB2FPROC)( GLuint index, GLfloat x, GLfloat y); typedef void(APIENTRYP PFNGLVERTEXATTRIB2FVPROC)( GLuint index, const GLfloat* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB2SPROC)( GLuint index, GLshort x, GLshort y); typedef void(APIENTRYP PFNGLVERTEXATTRIB2SVPROC)( GLuint index, const GLshort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB3DPROC)( GLuint index, GLdouble x, GLdouble y, GLdouble z); typedef void(APIENTRYP PFNGLVERTEXATTRIB3DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB3FPROC)( GLuint index, GLfloat x, GLfloat y, GLfloat z); typedef void(APIENTRYP PFNGLVERTEXATTRIB3FVPROC)( GLuint index, const GLfloat* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB3SPROC)( GLuint index, GLshort x, GLshort y, GLshort z); typedef void(APIENTRYP PFNGLVERTEXATTRIB3SVPROC)( GLuint index, const GLshort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)( GLuint index, const GLbyte* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)( GLuint index, const GLint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)( GLuint index, const GLshort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)( GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); typedef void(APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)( GLuint index, const GLubyte* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)( GLuint index, const GLuint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)( GLuint index, const GLushort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4BVPROC)( GLuint index, const GLbyte* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4DPROC)( GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void(APIENTRYP PFNGLVERTEXATTRIB4DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4FPROC)( GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void(APIENTRYP PFNGLVERTEXATTRIB4FVPROC)( GLuint index, const GLfloat* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4IVPROC)( GLuint index, const GLint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4SPROC)( GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); typedef void(APIENTRYP PFNGLVERTEXATTRIB4SVPROC)( GLuint index, const GLshort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)( GLuint index, const GLubyte* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)( GLuint index, const GLuint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIB4USVPROC)( GLuint index, const GLushort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); #endif #ifndef GL_VERSION_2_1 #define GL_VERSION_2_1 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); #endif #ifndef GL_VERSION_3_0 #define GL_VERSION_3_0 1 /* OpenGL 3.0 also reuses entry points from these extensions: */ /* ARB_framebuffer_object */ /* ARB_map_buffer_range */ /* ARB_vertex_array_object */ #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glColorMaski( GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); GLAPI void APIENTRY glGetBooleani_v( GLenum target, GLuint index, GLboolean* data); GLAPI void APIENTRY glGetIntegeri_v( GLenum target, GLuint index, GLint* data); GLAPI void APIENTRY glEnablei(GLenum target, GLuint index); GLAPI void APIENTRY glDisablei(GLenum target, GLuint index); GLAPI GLboolean APIENTRY glIsEnabledi(GLenum target, GLuint index); GLAPI void APIENTRY glBeginTransformFeedback(GLenum primitiveMode); GLAPI void APIENTRY glEndTransformFeedback(void); GLAPI void APIENTRY glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI void APIENTRY glBindBufferBase( GLenum target, GLuint index, GLuint buffer); GLAPI void APIENTRY glTransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode); GLAPI void APIENTRY glGetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name); GLAPI void APIENTRY glClampColor(GLenum target, GLenum clamp); GLAPI void APIENTRY glBeginConditionalRender(GLuint id, GLenum mode); GLAPI void APIENTRY glEndConditionalRender(void); GLAPI void APIENTRY glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer); GLAPI void APIENTRY glGetVertexAttribIiv( GLuint index, GLenum pname, GLint* params); GLAPI void APIENTRY glGetVertexAttribIuiv( GLuint index, GLenum pname, GLuint* params); GLAPI void APIENTRY glVertexAttribI1i(GLuint index, GLint x); GLAPI void APIENTRY glVertexAttribI2i(GLuint index, GLint x, GLint y); GLAPI void APIENTRY glVertexAttribI3i( GLuint index, GLint x, GLint y, GLint z); GLAPI void APIENTRY glVertexAttribI4i( GLuint index, GLint x, GLint y, GLint z, GLint w); GLAPI void APIENTRY glVertexAttribI1ui(GLuint index, GLuint x); GLAPI void APIENTRY glVertexAttribI2ui(GLuint index, GLuint x, GLuint y); GLAPI void APIENTRY glVertexAttribI3ui( GLuint index, GLuint x, GLuint y, GLuint z); GLAPI void APIENTRY glVertexAttribI4ui( GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); GLAPI void APIENTRY glVertexAttribI1iv(GLuint index, const GLint* v); GLAPI void APIENTRY glVertexAttribI2iv(GLuint index, const GLint* v); GLAPI void APIENTRY glVertexAttribI3iv(GLuint index, const GLint* v); GLAPI void APIENTRY glVertexAttribI4iv(GLuint index, const GLint* v); GLAPI void APIENTRY glVertexAttribI1uiv(GLuint index, const GLuint* v); GLAPI void APIENTRY glVertexAttribI2uiv(GLuint index, const GLuint* v); GLAPI void APIENTRY glVertexAttribI3uiv(GLuint index, const GLuint* v); GLAPI void APIENTRY glVertexAttribI4uiv(GLuint index, const GLuint* v); GLAPI void APIENTRY glVertexAttribI4bv(GLuint index, const GLbyte* v); GLAPI void APIENTRY glVertexAttribI4sv(GLuint index, const GLshort* v); GLAPI void APIENTRY glVertexAttribI4ubv(GLuint index, const GLubyte* v); GLAPI void APIENTRY glVertexAttribI4usv(GLuint index, const GLushort* v); GLAPI void APIENTRY glGetUniformuiv( GLuint program, GLint location, GLuint* params); GLAPI void APIENTRY glBindFragDataLocation( GLuint program, GLuint color, const GLchar* name); GLAPI GLint APIENTRY glGetFragDataLocation( GLuint program, const GLchar* name); GLAPI void APIENTRY glUniform1ui(GLint location, GLuint v0); GLAPI void APIENTRY glUniform2ui(GLint location, GLuint v0, GLuint v1); GLAPI void APIENTRY glUniform3ui( GLint location, GLuint v0, GLuint v1, GLuint v2); GLAPI void APIENTRY glUniform4ui( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); GLAPI void APIENTRY glUniform1uiv( GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glUniform2uiv( GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glUniform3uiv( GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glUniform4uiv( GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glTexParameterIiv( GLenum target, GLenum pname, const GLint* params); GLAPI void APIENTRY glTexParameterIuiv( GLenum target, GLenum pname, const GLuint* params); GLAPI void APIENTRY glGetTexParameterIiv( GLenum target, GLenum pname, GLint* params); GLAPI void APIENTRY glGetTexParameterIuiv( GLenum target, GLenum pname, GLuint* params); GLAPI void APIENTRY glClearBufferiv( GLenum buffer, GLint drawbuffer, const GLint* value); GLAPI void APIENTRY glClearBufferuiv( GLenum buffer, GLint drawbuffer, const GLuint* value); GLAPI void APIENTRY glClearBufferfv( GLenum buffer, GLint drawbuffer, const GLfloat* value); GLAPI void APIENTRY glClearBufferfi( GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); GLAPI const GLubyte* APIENTRY glGetStringi(GLenum name, GLuint index); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLCOLORMASKIPROC)( GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); typedef void(APIENTRYP PFNGLGETBOOLEANI_VPROC)( GLenum target, GLuint index, GLboolean* data); typedef void(APIENTRYP PFNGLGETINTEGERI_VPROC)( GLenum target, GLuint index, GLint* data); typedef void(APIENTRYP PFNGLENABLEIPROC)(GLenum target, GLuint index); typedef void(APIENTRYP PFNGLDISABLEIPROC)(GLenum target, GLuint index); typedef GLboolean(APIENTRYP PFNGLISENABLEDIPROC)( GLenum target, GLuint index); typedef void(APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC)( GLenum primitiveMode); typedef void(APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC)(void); typedef void(APIENTRYP PFNGLBINDBUFFERRANGEPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); typedef void(APIENTRYP PFNGLBINDBUFFERBASEPROC)( GLenum target, GLuint index, GLuint buffer); typedef void(APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode); typedef void(APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name); typedef void(APIENTRYP PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); typedef void(APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC)( GLuint id, GLenum mode); typedef void(APIENTRYP PFNGLENDCONDITIONALRENDERPROC)(void); typedef void(APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer); typedef void(APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC)( GLuint index, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC)( GLuint index, GLenum pname, GLuint* params); typedef void(APIENTRYP PFNGLVERTEXATTRIBI1IPROC)(GLuint index, GLint x); typedef void(APIENTRYP PFNGLVERTEXATTRIBI2IPROC)( GLuint index, GLint x, GLint y); typedef void(APIENTRYP PFNGLVERTEXATTRIBI3IPROC)( GLuint index, GLint x, GLint y, GLint z); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4IPROC)( GLuint index, GLint x, GLint y, GLint z, GLint w); typedef void(APIENTRYP PFNGLVERTEXATTRIBI1UIPROC)(GLuint index, GLuint x); typedef void(APIENTRYP PFNGLVERTEXATTRIBI2UIPROC)( GLuint index, GLuint x, GLuint y); typedef void(APIENTRYP PFNGLVERTEXATTRIBI3UIPROC)( GLuint index, GLuint x, GLuint y, GLuint z); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4UIPROC)( GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); typedef void(APIENTRYP PFNGLVERTEXATTRIBI1IVPROC)( GLuint index, const GLint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI2IVPROC)( GLuint index, const GLint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI3IVPROC)( GLuint index, const GLint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4IVPROC)( GLuint index, const GLint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC)( GLuint index, const GLuint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC)( GLuint index, const GLuint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC)( GLuint index, const GLuint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC)( GLuint index, const GLuint* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4BVPROC)( GLuint index, const GLbyte* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4SVPROC)( GLuint index, const GLshort* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC)( GLuint index, const GLubyte* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBI4USVPROC)( GLuint index, const GLushort* v); typedef void(APIENTRYP PFNGLGETUNIFORMUIVPROC)( GLuint program, GLint location, GLuint* params); typedef void(APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC)( GLuint program, GLuint color, const GLchar* name); typedef GLint(APIENTRYP PFNGLGETFRAGDATALOCATIONPROC)( GLuint program, const GLchar* name); typedef void(APIENTRYP PFNGLUNIFORM1UIPROC)(GLint location, GLuint v0); typedef void(APIENTRYP PFNGLUNIFORM2UIPROC)( GLint location, GLuint v0, GLuint v1); typedef void(APIENTRYP PFNGLUNIFORM3UIPROC)( GLint location, GLuint v0, GLuint v1, GLuint v2); typedef void(APIENTRYP PFNGLUNIFORM4UIPROC)( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); typedef void(APIENTRYP PFNGLUNIFORM1UIVPROC)( GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLUNIFORM2UIVPROC)( GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLUNIFORM3UIVPROC)( GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLUNIFORM4UIVPROC)( GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLTEXPARAMETERIIVPROC)( GLenum target, GLenum pname, const GLint* params); typedef void(APIENTRYP PFNGLTEXPARAMETERIUIVPROC)( GLenum target, GLenum pname, const GLuint* params); typedef void(APIENTRYP PFNGLGETTEXPARAMETERIIVPROC)( GLenum target, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC)( GLenum target, GLenum pname, GLuint* params); typedef void(APIENTRYP PFNGLCLEARBUFFERIVPROC)( GLenum buffer, GLint drawbuffer, const GLint* value); typedef void(APIENTRYP PFNGLCLEARBUFFERUIVPROC)( GLenum buffer, GLint drawbuffer, const GLuint* value); typedef void(APIENTRYP PFNGLCLEARBUFFERFVPROC)( GLenum buffer, GLint drawbuffer, const GLfloat* value); typedef void(APIENTRYP PFNGLCLEARBUFFERFIPROC)( GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); typedef const GLubyte*(APIENTRYP PFNGLGETSTRINGIPROC)( GLenum name, GLuint index); #endif #ifndef GL_VERSION_3_1 #define GL_VERSION_3_1 1 /* OpenGL 3.1 also reuses entry points from these extensions: */ /* ARB_copy_buffer */ /* ARB_uniform_buffer_object */ #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDrawArraysInstanced( GLenum mode, GLint first, GLsizei count, GLsizei instancecount); GLAPI void APIENTRY glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount); GLAPI void APIENTRY glTexBuffer( GLenum target, GLenum internalformat, GLuint buffer); GLAPI void APIENTRY glPrimitiveRestartIndex(GLuint index); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC)( GLenum mode, GLint first, GLsizei count, GLsizei instancecount); typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC)(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount); typedef void(APIENTRYP PFNGLTEXBUFFERPROC)( GLenum target, GLenum internalformat, GLuint buffer); typedef void(APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC)(GLuint index); #endif #ifndef GL_VERSION_3_2 #define GL_VERSION_3_2 1 /* OpenGL 3.2 also reuses entry points from these extensions: */ /* ARB_draw_elements_base_vertex */ /* ARB_provoking_vertex */ /* ARB_sync */ /* ARB_texture_multisample */ #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGetInteger64i_v( GLenum target, GLuint index, GLint64* data); GLAPI void APIENTRY glGetBufferParameteri64v( GLenum target, GLenum pname, GLint64* params); GLAPI void APIENTRY glFramebufferTexture( GLenum target, GLenum attachment, GLuint texture, GLint level); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGETINTEGER64I_VPROC)( GLenum target, GLuint index, GLint64* data); typedef void(APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC)( GLenum target, GLenum pname, GLint64* params); typedef void(APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC)( GLenum target, GLenum attachment, GLuint texture, GLint level); #endif #ifndef GL_VERSION_3_3 #define GL_VERSION_3_3 1 /* OpenGL 3.3 also reuses entry points from these extensions: */ /* ARB_blend_func_extended */ /* ARB_sampler_objects */ /* ARB_explicit_attrib_location, but it has none */ /* ARB_occlusion_query2 (no entry points) */ /* ARB_shader_bit_encoding (no entry points) */ /* ARB_texture_rgb10_a2ui (no entry points) */ /* ARB_texture_swizzle (no entry points) */ /* ARB_timer_query */ /* ARB_vertex_type_2_10_10_10_rev */ #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glVertexAttribDivisor(GLuint index, GLuint divisor); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC)( GLuint index, GLuint divisor); #endif #ifndef GL_VERSION_4_0 #define GL_VERSION_4_0 1 /* OpenGL 4.0 also reuses entry points from these extensions: */ /* ARB_texture_query_lod (no entry points) */ /* ARB_draw_indirect */ /* ARB_gpu_shader5 (no entry points) */ /* ARB_gpu_shader_fp64 */ /* ARB_shader_subroutine */ /* ARB_tessellation_shader */ /* ARB_texture_buffer_object_rgb32 (no entry points) */ /* ARB_texture_cube_map_array (no entry points) */ /* ARB_texture_gather (no entry points) */ /* ARB_transform_feedback2 */ /* ARB_transform_feedback3 */ #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glMinSampleShading(GLfloat value); GLAPI void APIENTRY glBlendEquationi(GLuint buf, GLenum mode); GLAPI void APIENTRY glBlendEquationSeparatei( GLuint buf, GLenum modeRGB, GLenum modeAlpha); GLAPI void APIENTRY glBlendFunci(GLuint buf, GLenum src, GLenum dst); GLAPI void APIENTRY glBlendFuncSeparatei(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLMINSAMPLESHADINGPROC)(GLfloat value); typedef void(APIENTRYP PFNGLBLENDEQUATIONIPROC)(GLuint buf, GLenum mode); typedef void(APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC)( GLuint buf, GLenum modeRGB, GLenum modeAlpha); typedef void(APIENTRYP PFNGLBLENDFUNCIPROC)( GLuint buf, GLenum src, GLenum dst); typedef void(APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC)(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); #endif #ifndef GL_VERSION_4_1 #define GL_VERSION_4_1 1 /* OpenGL 4.1 reuses entry points from these extensions: */ /* ARB_ES2_compatibility */ /* ARB_get_program_binary */ /* ARB_separate_shader_objects */ /* ARB_shader_precision (no entry points) */ /* ARB_vertex_attrib_64bit */ /* ARB_viewport_array */ #endif #ifndef GL_VERSION_4_2 #define GL_VERSION_4_2 1 /* OpenGL 4.2 reuses entry points from these extensions: */ /* ARB_base_instance */ /* ARB_shading_language_420pack (no entry points) */ /* ARB_transform_feedback_instanced */ /* ARB_compressed_texture_pixel_storage (no entry points) */ /* ARB_conservative_depth (no entry points) */ /* ARB_internalformat_query */ /* ARB_map_buffer_alignment (no entry points) */ /* ARB_shader_atomic_counters */ /* ARB_shader_image_load_store */ /* ARB_shading_language_packing (no entry points) */ /* ARB_texture_storage */ #endif #ifndef GL_VERSION_4_3 #define GL_VERSION_4_3 1 /* OpenGL 4.3 reuses entry points from these extensions: */ /* ARB_arrays_of_arrays (no entry points, GLSL only) */ /* ARB_fragment_layer_viewport (no entry points, GLSL only) */ /* ARB_shader_image_size (no entry points, GLSL only) */ /* ARB_ES3_compatibility (no entry points) */ /* ARB_clear_buffer_object */ /* ARB_compute_shader */ /* ARB_copy_image */ /* KHR_debug (includes ARB_debug_output commands promoted to KHR without * suffixes) */ /* ARB_explicit_uniform_location (no entry points) */ /* ARB_framebuffer_no_attachments */ /* ARB_internalformat_query2 */ /* ARB_invalidate_subdata */ /* ARB_multi_draw_indirect */ /* ARB_program_interface_query */ /* ARB_robust_buffer_access_behavior (no entry points) */ /* ARB_shader_storage_buffer_object */ /* ARB_stencil_texturing (no entry points) */ /* ARB_texture_buffer_range */ /* ARB_texture_query_levels (no entry points) */ /* ARB_texture_storage_multisample */ /* ARB_texture_view */ /* ARB_vertex_attrib_binding */ #endif #ifndef GL_ARB_depth_buffer_float #define GL_ARB_depth_buffer_float 1 #endif #ifndef GL_ARB_framebuffer_object #define GL_ARB_framebuffer_object 1 #ifdef GLCOREARB_PROTOTYPES GLAPI GLboolean APIENTRY glIsRenderbuffer(GLuint renderbuffer); GLAPI void APIENTRY glBindRenderbuffer(GLenum target, GLuint renderbuffer); GLAPI void APIENTRY glDeleteRenderbuffers( GLsizei n, const GLuint* renderbuffers); GLAPI void APIENTRY glGenRenderbuffers(GLsizei n, GLuint* renderbuffers); GLAPI void APIENTRY glRenderbufferStorage( GLenum target, GLenum internalformat, GLsizei width, GLsizei height); GLAPI void APIENTRY glGetRenderbufferParameteriv( GLenum target, GLenum pname, GLint* params); GLAPI GLboolean APIENTRY glIsFramebuffer(GLuint framebuffer); GLAPI void APIENTRY glBindFramebuffer(GLenum target, GLuint framebuffer); GLAPI void APIENTRY glDeleteFramebuffers( GLsizei n, const GLuint* framebuffers); GLAPI void APIENTRY glGenFramebuffers(GLsizei n, GLuint* framebuffers); GLAPI GLenum APIENTRY glCheckFramebufferStatus(GLenum target); GLAPI void APIENTRY glFramebufferTexture1D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GLAPI void APIENTRY glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GLAPI void APIENTRY glFramebufferTexture3D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); GLAPI void APIENTRY glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); GLAPI void APIENTRY glGetFramebufferAttachmentParameteriv( GLenum target, GLenum attachment, GLenum pname, GLint* params); GLAPI void APIENTRY glGenerateMipmap(GLenum target); GLAPI void APIENTRY glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GLAPI void APIENTRY glRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); GLAPI void APIENTRY glFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); #endif /* GLCOREARB_PROTOTYPES */ typedef GLboolean(APIENTRYP PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); typedef void(APIENTRYP PFNGLBINDRENDERBUFFERPROC)( GLenum target, GLuint renderbuffer); typedef void(APIENTRYP PFNGLDELETERENDERBUFFERSPROC)( GLsizei n, const GLuint* renderbuffers); typedef void(APIENTRYP PFNGLGENRENDERBUFFERSPROC)( GLsizei n, GLuint* renderbuffers); typedef void(APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC)( GLenum target, GLenum internalformat, GLsizei width, GLsizei height); typedef void(APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC)( GLenum target, GLenum pname, GLint* params); typedef GLboolean(APIENTRYP PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); typedef void(APIENTRYP PFNGLBINDFRAMEBUFFERPROC)( GLenum target, GLuint framebuffer); typedef void(APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC)( GLsizei n, const GLuint* framebuffers); typedef void(APIENTRYP PFNGLGENFRAMEBUFFERSPROC)( GLsizei n, GLuint* framebuffers); typedef GLenum(APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); typedef void(APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); typedef void(APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); typedef void(APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); typedef void(APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); typedef void(APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)( GLenum target, GLenum attachment, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); typedef void(APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); typedef void(APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); typedef void(APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); #endif #ifndef GL_ARB_framebuffer_sRGB #define GL_ARB_framebuffer_sRGB 1 #endif #ifndef GL_ARB_half_float_vertex #define GL_ARB_half_float_vertex 1 #endif #ifndef GL_ARB_map_buffer_range #define GL_ARB_map_buffer_range 1 #ifdef GLCOREARB_PROTOTYPES GLAPI GLvoid* APIENTRY glMapBufferRange( GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); GLAPI void APIENTRY glFlushMappedBufferRange( GLenum target, GLintptr offset, GLsizeiptr length); #endif /* GLCOREARB_PROTOTYPES */ typedef GLvoid*(APIENTRYP PFNGLMAPBUFFERRANGEPROC)( GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); typedef void(APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC)( GLenum target, GLintptr offset, GLsizeiptr length); #endif #ifndef GL_ARB_texture_compression_rgtc #define GL_ARB_texture_compression_rgtc 1 #endif #ifndef GL_ARB_texture_rg #define GL_ARB_texture_rg 1 #endif #ifndef GL_ARB_vertex_array_object #define GL_ARB_vertex_array_object 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBindVertexArray(GLuint array); GLAPI void APIENTRY glDeleteVertexArrays(GLsizei n, const GLuint* arrays); GLAPI void APIENTRY glGenVertexArrays(GLsizei n, GLuint* arrays); GLAPI GLboolean APIENTRY glIsVertexArray(GLuint array); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBINDVERTEXARRAYPROC)(GLuint array); typedef void(APIENTRYP PFNGLDELETEVERTEXARRAYSPROC)( GLsizei n, const GLuint* arrays); typedef void(APIENTRYP PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint* arrays); typedef GLboolean(APIENTRYP PFNGLISVERTEXARRAYPROC)(GLuint array); #endif #ifndef GL_ARB_uniform_buffer_object #define GL_ARB_uniform_buffer_object 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices); GLAPI void APIENTRY glGetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params); GLAPI void APIENTRY glGetActiveUniformName(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformName); GLAPI GLuint APIENTRY glGetUniformBlockIndex( GLuint program, const GLchar* uniformBlockName); GLAPI void APIENTRY glGetActiveUniformBlockiv( GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params); GLAPI void APIENTRY glGetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName); GLAPI void APIENTRY glUniformBlockBinding( GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGETUNIFORMINDICESPROC)(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices); typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC)(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformName); typedef GLuint(APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC)( GLuint program, const GLchar* uniformBlockName); typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC)( GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName); typedef void(APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC)( GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); #endif #ifndef GL_ARB_copy_buffer #define GL_ARB_copy_buffer 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); #endif #ifndef GL_ARB_depth_clamp #define GL_ARB_depth_clamp 1 #endif #ifndef GL_ARB_draw_elements_base_vertex #define GL_ARB_draw_elements_base_vertex 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLint basevertex); GLAPI void APIENTRY glDrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices, GLint basevertex); GLAPI void APIENTRY glDrawElementsInstancedBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount, GLint basevertex); GLAPI void APIENTRY glMultiDrawElementsBaseVertex(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices, GLsizei drawcount, const GLint* basevertex); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLint basevertex); typedef void(APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices, GLint basevertex); typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)( GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount, GLint basevertex); typedef void(APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei* count, GLenum type, const GLvoid* const* indices, GLsizei drawcount, const GLint* basevertex); #endif #ifndef GL_ARB_fragment_coord_conventions #define GL_ARB_fragment_coord_conventions 1 #endif #ifndef GL_ARB_provoking_vertex #define GL_ARB_provoking_vertex 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glProvokingVertex(GLenum mode); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLPROVOKINGVERTEXPROC)(GLenum mode); #endif #ifndef GL_ARB_seamless_cube_map #define GL_ARB_seamless_cube_map 1 #endif #ifndef GL_ARB_sync #define GL_ARB_sync 1 #ifdef GLCOREARB_PROTOTYPES GLAPI GLsync APIENTRY glFenceSync(GLenum condition, GLbitfield flags); GLAPI GLboolean APIENTRY glIsSync(GLsync sync); GLAPI void APIENTRY glDeleteSync(GLsync sync); GLAPI GLenum APIENTRY glClientWaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout); GLAPI void APIENTRY glWaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout); GLAPI void APIENTRY glGetInteger64v(GLenum pname, GLint64* params); GLAPI void APIENTRY glGetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values); #endif /* GLCOREARB_PROTOTYPES */ typedef GLsync(APIENTRYP PFNGLFENCESYNCPROC)( GLenum condition, GLbitfield flags); typedef GLboolean(APIENTRYP PFNGLISSYNCPROC)(GLsync sync); typedef void(APIENTRYP PFNGLDELETESYNCPROC)(GLsync sync); typedef GLenum(APIENTRYP PFNGLCLIENTWAITSYNCPROC)( GLsync sync, GLbitfield flags, GLuint64 timeout); typedef void(APIENTRYP PFNGLWAITSYNCPROC)( GLsync sync, GLbitfield flags, GLuint64 timeout); typedef void(APIENTRYP PFNGLGETINTEGER64VPROC)( GLenum pname, GLint64* params); typedef void(APIENTRYP PFNGLGETSYNCIVPROC)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values); #endif #ifndef GL_ARB_texture_multisample #define GL_ARB_texture_multisample 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glTexImage2DMultisample(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI void APIENTRY glTexImage3DMultisample(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI void APIENTRY glGetMultisamplefv( GLenum pname, GLuint index, GLfloat* val); GLAPI void APIENTRY glSampleMaski(GLuint index, GLbitfield mask); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); typedef void(APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); typedef void(APIENTRYP PFNGLGETMULTISAMPLEFVPROC)( GLenum pname, GLuint index, GLfloat* val); typedef void(APIENTRYP PFNGLSAMPLEMASKIPROC)(GLuint index, GLbitfield mask); #endif #ifndef GL_ARB_vertex_array_bgra #define GL_ARB_vertex_array_bgra 1 #endif #ifndef GL_ARB_draw_buffers_blend #define GL_ARB_draw_buffers_blend 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBlendEquationiARB(GLuint buf, GLenum mode); GLAPI void APIENTRY glBlendEquationSeparateiARB( GLuint buf, GLenum modeRGB, GLenum modeAlpha); GLAPI void APIENTRY glBlendFunciARB(GLuint buf, GLenum src, GLenum dst); GLAPI void APIENTRY glBlendFuncSeparateiARB(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBLENDEQUATIONIARBPROC)(GLuint buf, GLenum mode); typedef void(APIENTRYP PFNGLBLENDEQUATIONSEPARATEIARBPROC)( GLuint buf, GLenum modeRGB, GLenum modeAlpha); typedef void(APIENTRYP PFNGLBLENDFUNCIARBPROC)( GLuint buf, GLenum src, GLenum dst); typedef void(APIENTRYP PFNGLBLENDFUNCSEPARATEIARBPROC)(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); #endif #ifndef GL_ARB_sample_shading #define GL_ARB_sample_shading 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glMinSampleShadingARB(GLfloat value); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLMINSAMPLESHADINGARBPROC)(GLfloat value); #endif #ifndef GL_ARB_texture_cube_map_array #define GL_ARB_texture_cube_map_array 1 #endif #ifndef GL_ARB_texture_gather #define GL_ARB_texture_gather 1 #endif #ifndef GL_ARB_texture_query_lod #define GL_ARB_texture_query_lod 1 #endif #ifndef GL_ARB_shading_language_include #define GL_ARB_shading_language_include 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glNamedStringARB(GLenum type, GLint namelen, const GLchar* name, GLint stringlen, const GLchar* string); GLAPI void APIENTRY glDeleteNamedStringARB( GLint namelen, const GLchar* name); GLAPI void APIENTRY glCompileShaderIncludeARB( GLuint shader, GLsizei count, const GLchar** path, const GLint* length); GLAPI GLboolean APIENTRY glIsNamedStringARB( GLint namelen, const GLchar* name); GLAPI void APIENTRY glGetNamedStringARB(GLint namelen, const GLchar* name, GLsizei bufSize, GLint* stringlen, GLchar* string); GLAPI void APIENTRY glGetNamedStringivARB( GLint namelen, const GLchar* name, GLenum pname, GLint* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLNAMEDSTRINGARBPROC)(GLenum type, GLint namelen, const GLchar* name, GLint stringlen, const GLchar* string); typedef void(APIENTRYP PFNGLDELETENAMEDSTRINGARBPROC)( GLint namelen, const GLchar* name); typedef void(APIENTRYP PFNGLCOMPILESHADERINCLUDEARBPROC)( GLuint shader, GLsizei count, const GLchar** path, const GLint* length); typedef GLboolean(APIENTRYP PFNGLISNAMEDSTRINGARBPROC)( GLint namelen, const GLchar* name); typedef void(APIENTRYP PFNGLGETNAMEDSTRINGARBPROC)(GLint namelen, const GLchar* name, GLsizei bufSize, GLint* stringlen, GLchar* string); typedef void(APIENTRYP PFNGLGETNAMEDSTRINGIVARBPROC)( GLint namelen, const GLchar* name, GLenum pname, GLint* params); #endif #ifndef GL_ARB_texture_compression_bptc #define GL_ARB_texture_compression_bptc 1 #endif #ifndef GL_ARB_blend_func_extended #define GL_ARB_blend_func_extended 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBindFragDataLocationIndexed( GLuint program, GLuint colorNumber, GLuint index, const GLchar* name); GLAPI GLint APIENTRY glGetFragDataIndex(GLuint program, const GLchar* name); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)( GLuint program, GLuint colorNumber, GLuint index, const GLchar* name); typedef GLint(APIENTRYP PFNGLGETFRAGDATAINDEXPROC)( GLuint program, const GLchar* name); #endif #ifndef GL_ARB_explicit_attrib_location #define GL_ARB_explicit_attrib_location 1 #endif #ifndef GL_ARB_occlusion_query2 #define GL_ARB_occlusion_query2 1 #endif #ifndef GL_ARB_sampler_objects #define GL_ARB_sampler_objects 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGenSamplers(GLsizei count, GLuint* samplers); GLAPI void APIENTRY glDeleteSamplers(GLsizei count, const GLuint* samplers); GLAPI GLboolean APIENTRY glIsSampler(GLuint sampler); GLAPI void APIENTRY glBindSampler(GLuint unit, GLuint sampler); GLAPI void APIENTRY glSamplerParameteri( GLuint sampler, GLenum pname, GLint param); GLAPI void APIENTRY glSamplerParameteriv( GLuint sampler, GLenum pname, const GLint* param); GLAPI void APIENTRY glSamplerParameterf( GLuint sampler, GLenum pname, GLfloat param); GLAPI void APIENTRY glSamplerParameterfv( GLuint sampler, GLenum pname, const GLfloat* param); GLAPI void APIENTRY glSamplerParameterIiv( GLuint sampler, GLenum pname, const GLint* param); GLAPI void APIENTRY glSamplerParameterIuiv( GLuint sampler, GLenum pname, const GLuint* param); GLAPI void APIENTRY glGetSamplerParameteriv( GLuint sampler, GLenum pname, GLint* params); GLAPI void APIENTRY glGetSamplerParameterIiv( GLuint sampler, GLenum pname, GLint* params); GLAPI void APIENTRY glGetSamplerParameterfv( GLuint sampler, GLenum pname, GLfloat* params); GLAPI void APIENTRY glGetSamplerParameterIuiv( GLuint sampler, GLenum pname, GLuint* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGENSAMPLERSPROC)( GLsizei count, GLuint* samplers); typedef void(APIENTRYP PFNGLDELETESAMPLERSPROC)( GLsizei count, const GLuint* samplers); typedef GLboolean(APIENTRYP PFNGLISSAMPLERPROC)(GLuint sampler); typedef void(APIENTRYP PFNGLBINDSAMPLERPROC)(GLuint unit, GLuint sampler); typedef void(APIENTRYP PFNGLSAMPLERPARAMETERIPROC)( GLuint sampler, GLenum pname, GLint param); typedef void(APIENTRYP PFNGLSAMPLERPARAMETERIVPROC)( GLuint sampler, GLenum pname, const GLint* param); typedef void(APIENTRYP PFNGLSAMPLERPARAMETERFPROC)( GLuint sampler, GLenum pname, GLfloat param); typedef void(APIENTRYP PFNGLSAMPLERPARAMETERFVPROC)( GLuint sampler, GLenum pname, const GLfloat* param); typedef void(APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC)( GLuint sampler, GLenum pname, const GLint* param); typedef void(APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC)( GLuint sampler, GLenum pname, const GLuint* param); typedef void(APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC)( GLuint sampler, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC)( GLuint sampler, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC)( GLuint sampler, GLenum pname, GLfloat* params); typedef void(APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC)( GLuint sampler, GLenum pname, GLuint* params); #endif #ifndef GL_ARB_shader_bit_encoding #define GL_ARB_shader_bit_encoding 1 #endif #ifndef GL_ARB_texture_rgb10_a2ui #define GL_ARB_texture_rgb10_a2ui 1 #endif #ifndef GL_ARB_texture_swizzle #define GL_ARB_texture_swizzle 1 #endif #ifndef GL_ARB_timer_query #define GL_ARB_timer_query 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glQueryCounter(GLuint id, GLenum target); GLAPI void APIENTRY glGetQueryObjecti64v( GLuint id, GLenum pname, GLint64* params); GLAPI void APIENTRY glGetQueryObjectui64v( GLuint id, GLenum pname, GLuint64* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLQUERYCOUNTERPROC)(GLuint id, GLenum target); typedef void(APIENTRYP PFNGLGETQUERYOBJECTI64VPROC)( GLuint id, GLenum pname, GLint64* params); typedef void(APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC)( GLuint id, GLenum pname, GLuint64* params); #endif #ifndef GL_ARB_vertex_type_2_10_10_10_rev #define GL_ARB_vertex_type_2_10_10_10_rev 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glVertexP2ui(GLenum type, GLuint value); GLAPI void APIENTRY glVertexP2uiv(GLenum type, const GLuint* value); GLAPI void APIENTRY glVertexP3ui(GLenum type, GLuint value); GLAPI void APIENTRY glVertexP3uiv(GLenum type, const GLuint* value); GLAPI void APIENTRY glVertexP4ui(GLenum type, GLuint value); GLAPI void APIENTRY glVertexP4uiv(GLenum type, const GLuint* value); GLAPI void APIENTRY glTexCoordP1ui(GLenum type, GLuint coords); GLAPI void APIENTRY glTexCoordP1uiv(GLenum type, const GLuint* coords); GLAPI void APIENTRY glTexCoordP2ui(GLenum type, GLuint coords); GLAPI void APIENTRY glTexCoordP2uiv(GLenum type, const GLuint* coords); GLAPI void APIENTRY glTexCoordP3ui(GLenum type, GLuint coords); GLAPI void APIENTRY glTexCoordP3uiv(GLenum type, const GLuint* coords); GLAPI void APIENTRY glTexCoordP4ui(GLenum type, GLuint coords); GLAPI void APIENTRY glTexCoordP4uiv(GLenum type, const GLuint* coords); GLAPI void APIENTRY glMultiTexCoordP1ui( GLenum texture, GLenum type, GLuint coords); GLAPI void APIENTRY glMultiTexCoordP1uiv( GLenum texture, GLenum type, const GLuint* coords); GLAPI void APIENTRY glMultiTexCoordP2ui( GLenum texture, GLenum type, GLuint coords); GLAPI void APIENTRY glMultiTexCoordP2uiv( GLenum texture, GLenum type, const GLuint* coords); GLAPI void APIENTRY glMultiTexCoordP3ui( GLenum texture, GLenum type, GLuint coords); GLAPI void APIENTRY glMultiTexCoordP3uiv( GLenum texture, GLenum type, const GLuint* coords); GLAPI void APIENTRY glMultiTexCoordP4ui( GLenum texture, GLenum type, GLuint coords); GLAPI void APIENTRY glMultiTexCoordP4uiv( GLenum texture, GLenum type, const GLuint* coords); GLAPI void APIENTRY glNormalP3ui(GLenum type, GLuint coords); GLAPI void APIENTRY glNormalP3uiv(GLenum type, const GLuint* coords); GLAPI void APIENTRY glColorP3ui(GLenum type, GLuint color); GLAPI void APIENTRY glColorP3uiv(GLenum type, const GLuint* color); GLAPI void APIENTRY glColorP4ui(GLenum type, GLuint color); GLAPI void APIENTRY glColorP4uiv(GLenum type, const GLuint* color); GLAPI void APIENTRY glSecondaryColorP3ui(GLenum type, GLuint color); GLAPI void APIENTRY glSecondaryColorP3uiv(GLenum type, const GLuint* color); GLAPI void APIENTRY glVertexAttribP1ui( GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI void APIENTRY glVertexAttribP1uiv( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); GLAPI void APIENTRY glVertexAttribP2ui( GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI void APIENTRY glVertexAttribP2uiv( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); GLAPI void APIENTRY glVertexAttribP3ui( GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI void APIENTRY glVertexAttribP3uiv( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); GLAPI void APIENTRY glVertexAttribP4ui( GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI void APIENTRY glVertexAttribP4uiv( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLVERTEXP2UIPROC)(GLenum type, GLuint value); typedef void(APIENTRYP PFNGLVERTEXP2UIVPROC)( GLenum type, const GLuint* value); typedef void(APIENTRYP PFNGLVERTEXP3UIPROC)(GLenum type, GLuint value); typedef void(APIENTRYP PFNGLVERTEXP3UIVPROC)( GLenum type, const GLuint* value); typedef void(APIENTRYP PFNGLVERTEXP4UIPROC)(GLenum type, GLuint value); typedef void(APIENTRYP PFNGLVERTEXP4UIVPROC)( GLenum type, const GLuint* value); typedef void(APIENTRYP PFNGLTEXCOORDP1UIPROC)(GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLTEXCOORDP1UIVPROC)( GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLTEXCOORDP2UIPROC)(GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLTEXCOORDP2UIVPROC)( GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLTEXCOORDP3UIPROC)(GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLTEXCOORDP3UIVPROC)( GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLTEXCOORDP4UIPROC)(GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLTEXCOORDP4UIVPROC)( GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP1UIPROC)( GLenum texture, GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC)( GLenum texture, GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP2UIPROC)( GLenum texture, GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC)( GLenum texture, GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP3UIPROC)( GLenum texture, GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC)( GLenum texture, GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP4UIPROC)( GLenum texture, GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC)( GLenum texture, GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLNORMALP3UIPROC)(GLenum type, GLuint coords); typedef void(APIENTRYP PFNGLNORMALP3UIVPROC)( GLenum type, const GLuint* coords); typedef void(APIENTRYP PFNGLCOLORP3UIPROC)(GLenum type, GLuint color); typedef void(APIENTRYP PFNGLCOLORP3UIVPROC)( GLenum type, const GLuint* color); typedef void(APIENTRYP PFNGLCOLORP4UIPROC)(GLenum type, GLuint color); typedef void(APIENTRYP PFNGLCOLORP4UIVPROC)( GLenum type, const GLuint* color); typedef void(APIENTRYP PFNGLSECONDARYCOLORP3UIPROC)( GLenum type, GLuint color); typedef void(APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC)( GLenum type, const GLuint* color); typedef void(APIENTRYP PFNGLVERTEXATTRIBP1UIPROC)( GLuint index, GLenum type, GLboolean normalized, GLuint value); typedef void(APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC)( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); typedef void(APIENTRYP PFNGLVERTEXATTRIBP2UIPROC)( GLuint index, GLenum type, GLboolean normalized, GLuint value); typedef void(APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC)( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); typedef void(APIENTRYP PFNGLVERTEXATTRIBP3UIPROC)( GLuint index, GLenum type, GLboolean normalized, GLuint value); typedef void(APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC)( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); typedef void(APIENTRYP PFNGLVERTEXATTRIBP4UIPROC)( GLuint index, GLenum type, GLboolean normalized, GLuint value); typedef void(APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC)( GLuint index, GLenum type, GLboolean normalized, const GLuint* value); #endif #ifndef GL_ARB_draw_indirect #define GL_ARB_draw_indirect 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDrawArraysIndirect( GLenum mode, const GLvoid* indirect); GLAPI void APIENTRY glDrawElementsIndirect( GLenum mode, GLenum type, const GLvoid* indirect); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC)( GLenum mode, const GLvoid* indirect); typedef void(APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC)( GLenum mode, GLenum type, const GLvoid* indirect); #endif #ifndef GL_ARB_gpu_shader5 #define GL_ARB_gpu_shader5 1 #endif #ifndef GL_ARB_gpu_shader_fp64 #define GL_ARB_gpu_shader_fp64 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glUniform1d(GLint location, GLdouble x); GLAPI void APIENTRY glUniform2d(GLint location, GLdouble x, GLdouble y); GLAPI void APIENTRY glUniform3d( GLint location, GLdouble x, GLdouble y, GLdouble z); GLAPI void APIENTRY glUniform4d( GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI void APIENTRY glUniform1dv( GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glUniform2dv( GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glUniform3dv( GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glUniform4dv( GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix2dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix3dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix4dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix2x3dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix2x4dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix3x2dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix3x4dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix4x2dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glUniformMatrix4x3dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glGetUniformdv( GLuint program, GLint location, GLdouble* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLUNIFORM1DPROC)(GLint location, GLdouble x); typedef void(APIENTRYP PFNGLUNIFORM2DPROC)( GLint location, GLdouble x, GLdouble y); typedef void(APIENTRYP PFNGLUNIFORM3DPROC)( GLint location, GLdouble x, GLdouble y, GLdouble z); typedef void(APIENTRYP PFNGLUNIFORM4DPROC)( GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void(APIENTRYP PFNGLUNIFORM1DVPROC)( GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORM2DVPROC)( GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORM3DVPROC)( GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORM4DVPROC)( GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLGETUNIFORMDVPROC)( GLuint program, GLint location, GLdouble* params); #endif #ifndef GL_ARB_shader_subroutine #define GL_ARB_shader_subroutine 1 #ifdef GLCOREARB_PROTOTYPES GLAPI GLint APIENTRY glGetSubroutineUniformLocation( GLuint program, GLenum shadertype, const GLchar* name); GLAPI GLuint APIENTRY glGetSubroutineIndex( GLuint program, GLenum shadertype, const GLchar* name); GLAPI void APIENTRY glGetActiveSubroutineUniformiv(GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint* values); GLAPI void APIENTRY glGetActiveSubroutineUniformName(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei* length, GLchar* name); GLAPI void APIENTRY glGetActiveSubroutineName(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei* length, GLchar* name); GLAPI void APIENTRY glUniformSubroutinesuiv( GLenum shadertype, GLsizei count, const GLuint* indices); GLAPI void APIENTRY glGetUniformSubroutineuiv( GLenum shadertype, GLint location, GLuint* params); GLAPI void APIENTRY glGetProgramStageiv( GLuint program, GLenum shadertype, GLenum pname, GLint* values); #endif /* GLCOREARB_PROTOTYPES */ typedef GLint(APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)( GLuint program, GLenum shadertype, const GLchar* name); typedef GLuint(APIENTRYP PFNGLGETSUBROUTINEINDEXPROC)( GLuint program, GLenum shadertype, const GLchar* name); typedef void(APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)( GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint* values); typedef void(APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)( GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei* length, GLchar* name); typedef void(APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei* length, GLchar* name); typedef void(APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC)( GLenum shadertype, GLsizei count, const GLuint* indices); typedef void(APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC)( GLenum shadertype, GLint location, GLuint* params); typedef void(APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC)( GLuint program, GLenum shadertype, GLenum pname, GLint* values); #endif #ifndef GL_ARB_tessellation_shader #define GL_ARB_tessellation_shader 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glPatchParameteri(GLenum pname, GLint value); GLAPI void APIENTRY glPatchParameterfv(GLenum pname, const GLfloat* values); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLPATCHPARAMETERIPROC)(GLenum pname, GLint value); typedef void(APIENTRYP PFNGLPATCHPARAMETERFVPROC)( GLenum pname, const GLfloat* values); #endif #ifndef GL_ARB_texture_buffer_object_rgb32 #define GL_ARB_texture_buffer_object_rgb32 1 #endif #ifndef GL_ARB_transform_feedback2 #define GL_ARB_transform_feedback2 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBindTransformFeedback(GLenum target, GLuint id); GLAPI void APIENTRY glDeleteTransformFeedbacks( GLsizei n, const GLuint* ids); GLAPI void APIENTRY glGenTransformFeedbacks(GLsizei n, GLuint* ids); GLAPI GLboolean APIENTRY glIsTransformFeedback(GLuint id); GLAPI void APIENTRY glPauseTransformFeedback(void); GLAPI void APIENTRY glResumeTransformFeedback(void); GLAPI void APIENTRY glDrawTransformFeedback(GLenum mode, GLuint id); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC)( GLenum target, GLuint id); typedef void(APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC)( GLsizei n, const GLuint* ids); typedef void(APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC)( GLsizei n, GLuint* ids); typedef GLboolean(APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC)(GLuint id); typedef void(APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC)(void); typedef void(APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC)(void); typedef void(APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC)( GLenum mode, GLuint id); #endif #ifndef GL_ARB_transform_feedback3 #define GL_ARB_transform_feedback3 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDrawTransformFeedbackStream( GLenum mode, GLuint id, GLuint stream); GLAPI void APIENTRY glBeginQueryIndexed( GLenum target, GLuint index, GLuint id); GLAPI void APIENTRY glEndQueryIndexed(GLenum target, GLuint index); GLAPI void APIENTRY glGetQueryIndexediv( GLenum target, GLuint index, GLenum pname, GLint* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)( GLenum mode, GLuint id, GLuint stream); typedef void(APIENTRYP PFNGLBEGINQUERYINDEXEDPROC)( GLenum target, GLuint index, GLuint id); typedef void(APIENTRYP PFNGLENDQUERYINDEXEDPROC)( GLenum target, GLuint index); typedef void(APIENTRYP PFNGLGETQUERYINDEXEDIVPROC)( GLenum target, GLuint index, GLenum pname, GLint* params); #endif #ifndef GL_ARB_ES2_compatibility #define GL_ARB_ES2_compatibility 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glReleaseShaderCompiler(void); GLAPI void APIENTRY glShaderBinary(GLsizei count, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length); GLAPI void APIENTRY glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision); GLAPI void APIENTRY glDepthRangef(GLfloat n, GLfloat f); GLAPI void APIENTRY glClearDepthf(GLfloat d); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLRELEASESHADERCOMPILERPROC)(void); typedef void(APIENTRYP PFNGLSHADERBINARYPROC)(GLsizei count, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length); typedef void(APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC)(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision); typedef void(APIENTRYP PFNGLDEPTHRANGEFPROC)(GLfloat n, GLfloat f); typedef void(APIENTRYP PFNGLCLEARDEPTHFPROC)(GLfloat d); #endif #ifndef GL_ARB_get_program_binary #define GL_ARB_get_program_binary 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary); GLAPI void APIENTRY glProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length); GLAPI void APIENTRY glProgramParameteri( GLuint program, GLenum pname, GLint value); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGETPROGRAMBINARYPROC)(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary); typedef void(APIENTRYP PFNGLPROGRAMBINARYPROC)(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length); typedef void(APIENTRYP PFNGLPROGRAMPARAMETERIPROC)( GLuint program, GLenum pname, GLint value); #endif #ifndef GL_ARB_separate_shader_objects #define GL_ARB_separate_shader_objects 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glUseProgramStages( GLuint pipeline, GLbitfield stages, GLuint program); GLAPI void APIENTRY glActiveShaderProgram(GLuint pipeline, GLuint program); GLAPI GLuint APIENTRY glCreateShaderProgramv( GLenum type, GLsizei count, const GLchar* const* strings); GLAPI void APIENTRY glBindProgramPipeline(GLuint pipeline); GLAPI void APIENTRY glDeleteProgramPipelines( GLsizei n, const GLuint* pipelines); GLAPI void APIENTRY glGenProgramPipelines(GLsizei n, GLuint* pipelines); GLAPI GLboolean APIENTRY glIsProgramPipeline(GLuint pipeline); GLAPI void APIENTRY glGetProgramPipelineiv( GLuint pipeline, GLenum pname, GLint* params); GLAPI void APIENTRY glProgramUniform1i( GLuint program, GLint location, GLint v0); GLAPI void APIENTRY glProgramUniform1iv( GLuint program, GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glProgramUniform1f( GLuint program, GLint location, GLfloat v0); GLAPI void APIENTRY glProgramUniform1fv( GLuint program, GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glProgramUniform1d( GLuint program, GLint location, GLdouble v0); GLAPI void APIENTRY glProgramUniform1dv( GLuint program, GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glProgramUniform1ui( GLuint program, GLint location, GLuint v0); GLAPI void APIENTRY glProgramUniform1uiv( GLuint program, GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glProgramUniform2i( GLuint program, GLint location, GLint v0, GLint v1); GLAPI void APIENTRY glProgramUniform2iv( GLuint program, GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glProgramUniform2f( GLuint program, GLint location, GLfloat v0, GLfloat v1); GLAPI void APIENTRY glProgramUniform2fv( GLuint program, GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glProgramUniform2d( GLuint program, GLint location, GLdouble v0, GLdouble v1); GLAPI void APIENTRY glProgramUniform2dv( GLuint program, GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glProgramUniform2ui( GLuint program, GLint location, GLuint v0, GLuint v1); GLAPI void APIENTRY glProgramUniform2uiv( GLuint program, GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glProgramUniform3i( GLuint program, GLint location, GLint v0, GLint v1, GLint v2); GLAPI void APIENTRY glProgramUniform3iv( GLuint program, GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glProgramUniform3f( GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); GLAPI void APIENTRY glProgramUniform3fv( GLuint program, GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glProgramUniform3d( GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); GLAPI void APIENTRY glProgramUniform3dv( GLuint program, GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glProgramUniform3ui( GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); GLAPI void APIENTRY glProgramUniform3uiv( GLuint program, GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glProgramUniform4i( GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); GLAPI void APIENTRY glProgramUniform4iv( GLuint program, GLint location, GLsizei count, const GLint* value); GLAPI void APIENTRY glProgramUniform4f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); GLAPI void APIENTRY glProgramUniform4fv( GLuint program, GLint location, GLsizei count, const GLfloat* value); GLAPI void APIENTRY glProgramUniform4d(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); GLAPI void APIENTRY glProgramUniform4dv( GLuint program, GLint location, GLsizei count, const GLdouble* value); GLAPI void APIENTRY glProgramUniform4ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); GLAPI void APIENTRY glProgramUniform4uiv( GLuint program, GLint location, GLsizei count, const GLuint* value); GLAPI void APIENTRY glProgramUniformMatrix2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix2dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix3dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix4dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix2x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix3x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix2x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix4x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix3x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix4x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); GLAPI void APIENTRY glProgramUniformMatrix2x3dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix3x2dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix2x4dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix4x2dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix3x4dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glProgramUniformMatrix4x3dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); GLAPI void APIENTRY glValidateProgramPipeline(GLuint pipeline); GLAPI void APIENTRY glGetProgramPipelineInfoLog( GLuint pipeline, GLsizei bufSize, GLsizei* length, GLchar* infoLog); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLUSEPROGRAMSTAGESPROC)( GLuint pipeline, GLbitfield stages, GLuint program); typedef void(APIENTRYP PFNGLACTIVESHADERPROGRAMPROC)( GLuint pipeline, GLuint program); typedef GLuint(APIENTRYP PFNGLCREATESHADERPROGRAMVPROC)( GLenum type, GLsizei count, const GLchar* const* strings); typedef void(APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC)(GLuint pipeline); typedef void(APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC)( GLsizei n, const GLuint* pipelines); typedef void(APIENTRYP PFNGLGENPROGRAMPIPELINESPROC)( GLsizei n, GLuint* pipelines); typedef GLboolean(APIENTRYP PFNGLISPROGRAMPIPELINEPROC)(GLuint pipeline); typedef void(APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC)( GLuint pipeline, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1IPROC)( GLuint program, GLint location, GLint v0); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC)( GLuint program, GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1FPROC)( GLuint program, GLint location, GLfloat v0); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC)( GLuint program, GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1DPROC)( GLuint program, GLint location, GLdouble v0); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC)( GLuint program, GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC)( GLuint program, GLint location, GLuint v0); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC)( GLuint program, GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2IPROC)( GLuint program, GLint location, GLint v0, GLint v1); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC)( GLuint program, GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2FPROC)( GLuint program, GLint location, GLfloat v0, GLfloat v1); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC)( GLuint program, GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2DPROC)( GLuint program, GLint location, GLdouble v0, GLdouble v1); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC)( GLuint program, GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC)( GLuint program, GLint location, GLuint v0, GLuint v1); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC)( GLuint program, GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3IPROC)( GLuint program, GLint location, GLint v0, GLint v1, GLint v2); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC)( GLuint program, GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3FPROC)( GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC)( GLuint program, GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3DPROC)( GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC)( GLuint program, GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC)( GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC)( GLuint program, GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4IPROC)( GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC)( GLuint program, GLint location, GLsizei count, const GLint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4FPROC)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC)( GLuint program, GLint location, GLsizei count, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4DPROC)(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC)( GLuint program, GLint location, GLsizei count, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); typedef void(APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC)( GLuint program, GLint location, GLsizei count, const GLuint* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value); typedef void(APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC)(GLuint pipeline); typedef void(APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC)( GLuint pipeline, GLsizei bufSize, GLsizei* length, GLchar* infoLog); #endif #ifndef GL_ARB_vertex_attrib_64bit #define GL_ARB_vertex_attrib_64bit 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glVertexAttribL1d(GLuint index, GLdouble x); GLAPI void APIENTRY glVertexAttribL2d(GLuint index, GLdouble x, GLdouble y); GLAPI void APIENTRY glVertexAttribL3d( GLuint index, GLdouble x, GLdouble y, GLdouble z); GLAPI void APIENTRY glVertexAttribL4d( GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI void APIENTRY glVertexAttribL1dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttribL2dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttribL3dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttribL4dv(GLuint index, const GLdouble* v); GLAPI void APIENTRY glVertexAttribLPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer); GLAPI void APIENTRY glGetVertexAttribLdv( GLuint index, GLenum pname, GLdouble* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLVERTEXATTRIBL1DPROC)(GLuint index, GLdouble x); typedef void(APIENTRYP PFNGLVERTEXATTRIBL2DPROC)( GLuint index, GLdouble x, GLdouble y); typedef void(APIENTRYP PFNGLVERTEXATTRIBL3DPROC)( GLuint index, GLdouble x, GLdouble y, GLdouble z); typedef void(APIENTRYP PFNGLVERTEXATTRIBL4DPROC)( GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void(APIENTRYP PFNGLVERTEXATTRIBL1DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBL2DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBL3DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBL4DVPROC)( GLuint index, const GLdouble* v); typedef void(APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer); typedef void(APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC)( GLuint index, GLenum pname, GLdouble* params); #endif #ifndef GL_ARB_viewport_array #define GL_ARB_viewport_array 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glViewportArrayv( GLuint first, GLsizei count, const GLfloat* v); GLAPI void APIENTRY glViewportIndexedf( GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); GLAPI void APIENTRY glViewportIndexedfv(GLuint index, const GLfloat* v); GLAPI void APIENTRY glScissorArrayv( GLuint first, GLsizei count, const GLint* v); GLAPI void APIENTRY glScissorIndexed( GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); GLAPI void APIENTRY glScissorIndexedv(GLuint index, const GLint* v); GLAPI void APIENTRY glDepthRangeArrayv( GLuint first, GLsizei count, const GLdouble* v); GLAPI void APIENTRY glDepthRangeIndexed( GLuint index, GLdouble n, GLdouble f); GLAPI void APIENTRY glGetFloati_v( GLenum target, GLuint index, GLfloat* data); GLAPI void APIENTRY glGetDoublei_v( GLenum target, GLuint index, GLdouble* data); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLVIEWPORTARRAYVPROC)( GLuint first, GLsizei count, const GLfloat* v); typedef void(APIENTRYP PFNGLVIEWPORTINDEXEDFPROC)( GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); typedef void(APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC)( GLuint index, const GLfloat* v); typedef void(APIENTRYP PFNGLSCISSORARRAYVPROC)( GLuint first, GLsizei count, const GLint* v); typedef void(APIENTRYP PFNGLSCISSORINDEXEDPROC)( GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); typedef void(APIENTRYP PFNGLSCISSORINDEXEDVPROC)( GLuint index, const GLint* v); typedef void(APIENTRYP PFNGLDEPTHRANGEARRAYVPROC)( GLuint first, GLsizei count, const GLdouble* v); typedef void(APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC)( GLuint index, GLdouble n, GLdouble f); typedef void(APIENTRYP PFNGLGETFLOATI_VPROC)( GLenum target, GLuint index, GLfloat* data); typedef void(APIENTRYP PFNGLGETDOUBLEI_VPROC)( GLenum target, GLuint index, GLdouble* data); #endif #ifndef GL_ARB_cl_event #define GL_ARB_cl_event 1 #ifdef GLCOREARB_PROTOTYPES GLAPI GLsync APIENTRY glCreateSyncFromCLeventARB( struct _cl_context* context, struct _cl_event* event, GLbitfield flags); #endif /* GLCOREARB_PROTOTYPES */ typedef GLsync(APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC)( struct _cl_context* context, struct _cl_event* event, GLbitfield flags); #endif #ifndef GL_ARB_debug_output #define GL_ARB_debug_output 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDebugMessageControlARB(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled); GLAPI void APIENTRY glDebugMessageInsertARB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* buf); GLAPI void APIENTRY glDebugMessageCallbackARB( GLDEBUGPROCARB callback, const GLvoid* userParam); GLAPI GLuint APIENTRY glGetDebugMessageLogARB(GLuint count, GLsizei bufsize, GLenum* sources, GLenum* types, GLuint* ids, GLenum* severities, GLsizei* lengths, GLchar* messageLog); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled); typedef void(APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* buf); typedef void(APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC)( GLDEBUGPROCARB callback, const GLvoid* userParam); typedef GLuint(APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC)(GLuint count, GLsizei bufsize, GLenum* sources, GLenum* types, GLuint* ids, GLenum* severities, GLsizei* lengths, GLchar* messageLog); #endif #ifndef GL_ARB_robustness #define GL_ARB_robustness 1 #ifdef GLCOREARB_PROTOTYPES GLAPI GLenum APIENTRY glGetGraphicsResetStatusARB(void); GLAPI void APIENTRY glGetnTexImageARB(GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, GLvoid* img); GLAPI void APIENTRY glReadnPixelsARB(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, GLvoid* data); GLAPI void APIENTRY glGetnCompressedTexImageARB( GLenum target, GLint lod, GLsizei bufSize, GLvoid* img); GLAPI void APIENTRY glGetnUniformfvARB( GLuint program, GLint location, GLsizei bufSize, GLfloat* params); GLAPI void APIENTRY glGetnUniformivARB( GLuint program, GLint location, GLsizei bufSize, GLint* params); GLAPI void APIENTRY glGetnUniformuivARB( GLuint program, GLint location, GLsizei bufSize, GLuint* params); GLAPI void APIENTRY glGetnUniformdvARB( GLuint program, GLint location, GLsizei bufSize, GLdouble* params); #endif /* GLCOREARB_PROTOTYPES */ typedef GLenum(APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC)(void); typedef void(APIENTRYP PFNGLGETNTEXIMAGEARBPROC)(GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, GLvoid* img); typedef void(APIENTRYP PFNGLREADNPIXELSARBPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, GLvoid* data); typedef void(APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC)( GLenum target, GLint lod, GLsizei bufSize, GLvoid* img); typedef void(APIENTRYP PFNGLGETNUNIFORMFVARBPROC)( GLuint program, GLint location, GLsizei bufSize, GLfloat* params); typedef void(APIENTRYP PFNGLGETNUNIFORMIVARBPROC)( GLuint program, GLint location, GLsizei bufSize, GLint* params); typedef void(APIENTRYP PFNGLGETNUNIFORMUIVARBPROC)( GLuint program, GLint location, GLsizei bufSize, GLuint* params); typedef void(APIENTRYP PFNGLGETNUNIFORMDVARBPROC)( GLuint program, GLint location, GLsizei bufSize, GLdouble* params); #endif #ifndef GL_ARB_shader_stencil_export #define GL_ARB_shader_stencil_export 1 #endif #ifndef GL_ARB_base_instance #define GL_ARB_base_instance 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDrawArraysInstancedBaseInstance(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); GLAPI void APIENTRY glDrawElementsInstancedBaseInstance(GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount, GLuint baseinstance); GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance( GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)( GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)( GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount, GLuint baseinstance); typedef void( APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)( GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); #endif #ifndef GL_ARB_shading_language_420pack #define GL_ARB_shading_language_420pack 1 #endif #ifndef GL_ARB_transform_feedback_instanced #define GL_ARB_transform_feedback_instanced 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDrawTransformFeedbackInstanced( GLenum mode, GLuint id, GLsizei instancecount); GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced( GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC)( GLenum mode, GLuint id, GLsizei instancecount); typedef void(APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC)( GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); #endif #ifndef GL_ARB_compressed_texture_pixel_storage #define GL_ARB_compressed_texture_pixel_storage 1 #endif #ifndef GL_ARB_conservative_depth #define GL_ARB_conservative_depth 1 #endif #ifndef GL_ARB_internalformat_query #define GL_ARB_internalformat_query 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGETINTERNALFORMATIVPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params); #endif #ifndef GL_ARB_map_buffer_alignment #define GL_ARB_map_buffer_alignment 1 #endif #ifndef GL_ARB_shader_atomic_counters #define GL_ARB_shader_atomic_counters 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv( GLuint program, GLuint bufferIndex, GLenum pname, GLint* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC)( GLuint program, GLuint bufferIndex, GLenum pname, GLint* params); #endif #ifndef GL_ARB_shader_image_load_store #define GL_ARB_shader_image_load_store 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); GLAPI void APIENTRY glMemoryBarrier(GLbitfield barriers); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBINDIMAGETEXTUREPROC)(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); typedef void(APIENTRYP PFNGLMEMORYBARRIERPROC)(GLbitfield barriers); #endif #ifndef GL_ARB_shading_language_packing #define GL_ARB_shading_language_packing 1 #endif #ifndef GL_ARB_texture_storage #define GL_ARB_texture_storage 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glTexStorage1D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); GLAPI void APIENTRY glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); GLAPI void APIENTRY glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); GLAPI void APIENTRY glTextureStorage1DEXT(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); GLAPI void APIENTRY glTextureStorage2DEXT(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); GLAPI void APIENTRY glTextureStorage3DEXT(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLTEXSTORAGE1DPROC)( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); typedef void(APIENTRYP PFNGLTEXSTORAGE2DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); typedef void(APIENTRYP PFNGLTEXSTORAGE3DPROC)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); typedef void(APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC)(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); typedef void(APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC)(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); typedef void(APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC)(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); #endif #ifndef GL_KHR_texture_compression_astc_ldr #define GL_KHR_texture_compression_astc_ldr 1 #endif #ifndef GL_KHR_debug #define GL_KHR_debug 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDebugMessageControl(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled); GLAPI void APIENTRY glDebugMessageInsert(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* buf); GLAPI void APIENTRY glDebugMessageCallback( GLDEBUGPROC callback, const void* userParam); GLAPI GLuint APIENTRY glGetDebugMessageLog(GLuint count, GLsizei bufsize, GLenum* sources, GLenum* types, GLuint* ids, GLenum* severities, GLsizei* lengths, GLchar* messageLog); GLAPI void APIENTRY glPushDebugGroup( GLenum source, GLuint id, GLsizei length, const GLchar* message); GLAPI void APIENTRY glPopDebugGroup(void); GLAPI void APIENTRY glObjectLabel( GLenum identifier, GLuint name, GLsizei length, const GLchar* label); GLAPI void APIENTRY glGetObjectLabel(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei* length, GLchar* label); GLAPI void APIENTRY glObjectPtrLabel( const void* ptr, GLsizei length, const GLchar* label); GLAPI void APIENTRY glGetObjectPtrLabel( const void* ptr, GLsizei bufSize, GLsizei* length, GLchar* label); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled); typedef void(APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* buf); typedef void(APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC)( GLDEBUGPROC callback, const void* userParam); typedef GLuint(APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC)(GLuint count, GLsizei bufsize, GLenum* sources, GLenum* types, GLuint* ids, GLenum* severities, GLsizei* lengths, GLchar* messageLog); typedef void(APIENTRYP PFNGLPUSHDEBUGGROUPPROC)( GLenum source, GLuint id, GLsizei length, const GLchar* message); typedef void(APIENTRYP PFNGLPOPDEBUGGROUPPROC)(void); typedef void(APIENTRYP PFNGLOBJECTLABELPROC)( GLenum identifier, GLuint name, GLsizei length, const GLchar* label); typedef void(APIENTRYP PFNGLGETOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei* length, GLchar* label); typedef void(APIENTRYP PFNGLOBJECTPTRLABELPROC)( const void* ptr, GLsizei length, const GLchar* label); typedef void(APIENTRYP PFNGLGETOBJECTPTRLABELPROC)( const void* ptr, GLsizei bufSize, GLsizei* length, GLchar* label); #endif #ifndef GL_ARB_arrays_of_arrays #define GL_ARB_arrays_of_arrays 1 #endif #ifndef GL_ARB_clear_buffer_object #define GL_ARB_clear_buffer_object 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glClearBufferData(GLenum target, GLenum internalformat, GLenum format, GLenum type, const void* data); GLAPI void APIENTRY glClearBufferSubData(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void* data); GLAPI void APIENTRY glClearNamedBufferDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void* data); GLAPI void APIENTRY glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLsizeiptr offset, GLsizeiptr size, const void* data); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLCLEARBUFFERDATAPROC)(GLenum target, GLenum internalformat, GLenum format, GLenum type, const void* data); typedef void(APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC)(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void* data); typedef void(APIENTRYP PFNGLCLEARNAMEDBUFFERDATAEXTPROC)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void* data); typedef void(APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLsizeiptr offset, GLsizeiptr size, const void* data); #endif #ifndef GL_ARB_compute_shader #define GL_ARB_compute_shader 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glDispatchCompute( GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); GLAPI void APIENTRY glDispatchComputeIndirect(GLintptr indirect); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLDISPATCHCOMPUTEPROC)( GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); typedef void(APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC)(GLintptr indirect); #endif #ifndef GL_ARB_copy_image #define GL_ARB_copy_image 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glCopyImageSubData(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLCOPYIMAGESUBDATAPROC)(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); #endif #ifndef GL_ARB_texture_view #define GL_ARB_texture_view 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glTextureView(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLTEXTUREVIEWPROC)(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); #endif #ifndef GL_ARB_vertex_attrib_binding #define GL_ARB_vertex_attrib_binding 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glBindVertexBuffer( GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); GLAPI void APIENTRY glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); GLAPI void APIENTRY glVertexAttribIFormat( GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI void APIENTRY glVertexAttribLFormat( GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI void APIENTRY glVertexAttribBinding( GLuint attribindex, GLuint bindingindex); GLAPI void APIENTRY glVertexBindingDivisor( GLuint bindingindex, GLuint divisor); GLAPI void APIENTRY glVertexArrayBindVertexBufferEXT(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); GLAPI void APIENTRY glVertexArrayVertexAttribFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); GLAPI void APIENTRY glVertexArrayVertexAttribIFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI void APIENTRY glVertexArrayVertexAttribLFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); GLAPI void APIENTRY glVertexArrayVertexAttribBindingEXT( GLuint vaobj, GLuint attribindex, GLuint bindingindex); GLAPI void APIENTRY glVertexArrayVertexBindingDivisorEXT( GLuint vaobj, GLuint bindingindex, GLuint divisor); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLBINDVERTEXBUFFERPROC)( GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); typedef void(APIENTRYP PFNGLVERTEXATTRIBFORMATPROC)(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); typedef void(APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC)( GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); typedef void(APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC)( GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); typedef void(APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC)( GLuint attribindex, GLuint bindingindex); typedef void(APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC)( GLuint bindingindex, GLuint divisor); typedef void(APIENTRYP PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC)( GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC)( GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC)( GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC)( GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC)( GLuint vaobj, GLuint attribindex, GLuint bindingindex); typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC)( GLuint vaobj, GLuint bindingindex, GLuint divisor); #endif #ifndef GL_ARB_robustness_isolation #define GL_ARB_robustness_isolation 1 #endif #ifndef GL_ARB_ES3_compatibility #define GL_ARB_ES3_compatibility 1 #endif #ifndef GL_ARB_explicit_uniform_location #define GL_ARB_explicit_uniform_location 1 #endif #ifndef GL_ARB_fragment_layer_viewport #define GL_ARB_fragment_layer_viewport 1 #endif #ifndef GL_ARB_framebuffer_no_attachments #define GL_ARB_framebuffer_no_attachments 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glFramebufferParameteri( GLenum target, GLenum pname, GLint param); GLAPI void APIENTRY glGetFramebufferParameteriv( GLenum target, GLenum pname, GLint* params); GLAPI void APIENTRY glNamedFramebufferParameteriEXT( GLuint framebuffer, GLenum pname, GLint param); GLAPI void APIENTRY glGetNamedFramebufferParameterivEXT( GLuint framebuffer, GLenum pname, GLint* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC)( GLenum target, GLenum pname, GLint param); typedef void(APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC)( GLenum target, GLenum pname, GLint* params); typedef void(APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC)( GLuint framebuffer, GLenum pname, GLint param); typedef void(APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC)( GLuint framebuffer, GLenum pname, GLint* params); #endif #ifndef GL_ARB_internalformat_query2 #define GL_ARB_internalformat_query2 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGetInternalformati64v(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64* params); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGETINTERNALFORMATI64VPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64* params); #endif #ifndef GL_ARB_invalidate_subdata #define GL_ARB_invalidate_subdata 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glInvalidateTexSubImage(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); GLAPI void APIENTRY glInvalidateTexImage(GLuint texture, GLint level); GLAPI void APIENTRY glInvalidateBufferSubData( GLuint buffer, GLintptr offset, GLsizeiptr length); GLAPI void APIENTRY glInvalidateBufferData(GLuint buffer); GLAPI void APIENTRY glInvalidateFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments); GLAPI void APIENTRY glInvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); typedef void(APIENTRYP PFNGLINVALIDATETEXIMAGEPROC)( GLuint texture, GLint level); typedef void(APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC)( GLuint buffer, GLintptr offset, GLsizeiptr length); typedef void(APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC)(GLuint buffer); typedef void(APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC)( GLenum target, GLsizei numAttachments, const GLenum* attachments); typedef void(APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC)(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height); #endif #ifndef GL_ARB_multi_draw_indirect #define GL_ARB_multi_draw_indirect 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glMultiDrawArraysIndirect( GLenum mode, const void* indirect, GLsizei drawcount, GLsizei stride); GLAPI void APIENTRY glMultiDrawElementsIndirect(GLenum mode, GLenum type, const void* indirect, GLsizei drawcount, GLsizei stride); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC)( GLenum mode, const void* indirect, GLsizei drawcount, GLsizei stride); typedef void(APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC)(GLenum mode, GLenum type, const void* indirect, GLsizei drawcount, GLsizei stride); #endif #ifndef GL_ARB_program_interface_query #define GL_ARB_program_interface_query 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glGetProgramInterfaceiv( GLuint program, GLenum programInterface, GLenum pname, GLint* params); GLAPI GLuint APIENTRY glGetProgramResourceIndex( GLuint program, GLenum programInterface, const GLchar* name); GLAPI void APIENTRY glGetProgramResourceName(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei* length, GLchar* name); GLAPI void APIENTRY glGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum* props, GLsizei bufSize, GLsizei* length, GLint* params); GLAPI GLint APIENTRY glGetProgramResourceLocation( GLuint program, GLenum programInterface, const GLchar* name); GLAPI GLint APIENTRY glGetProgramResourceLocationIndex( GLuint program, GLenum programInterface, const GLchar* name); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC)( GLuint program, GLenum programInterface, GLenum pname, GLint* params); typedef GLuint(APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC)( GLuint program, GLenum programInterface, const GLchar* name); typedef void(APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei* length, GLchar* name); typedef void(APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum* props, GLsizei bufSize, GLsizei* length, GLint* params); typedef GLint(APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC)( GLuint program, GLenum programInterface, const GLchar* name); typedef GLint(APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC)( GLuint program, GLenum programInterface, const GLchar* name); #endif #ifndef GL_ARB_robust_buffer_access_behavior #define GL_ARB_robust_buffer_access_behavior 1 #endif #ifndef GL_ARB_shader_image_size #define GL_ARB_shader_image_size 1 #endif #ifndef GL_ARB_shader_storage_buffer_object #define GL_ARB_shader_storage_buffer_object 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glShaderStorageBlockBinding( GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC)( GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); #endif #ifndef GL_ARB_stencil_texturing #define GL_ARB_stencil_texturing 1 #endif #ifndef GL_ARB_texture_buffer_range #define GL_ARB_texture_buffer_range 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glTexBufferRange(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI void APIENTRY glTextureBufferRangeEXT(GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLTEXBUFFERRANGEPROC)(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); typedef void(APIENTRYP PFNGLTEXTUREBUFFERRANGEEXTPROC)(GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); #endif #ifndef GL_ARB_texture_query_levels #define GL_ARB_texture_query_levels 1 #endif #ifndef GL_ARB_texture_storage_multisample #define GL_ARB_texture_storage_multisample 1 #ifdef GLCOREARB_PROTOTYPES GLAPI void APIENTRY glTexStorage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI void APIENTRY glTexStorage3DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI void APIENTRY glTextureStorage2DMultisampleEXT(GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI void APIENTRY glTextureStorage3DMultisampleEXT(GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); #endif /* GLCOREARB_PROTOTYPES */ typedef void(APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); typedef void(APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); typedef void(APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC)( GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); typedef void(APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC)( GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); #endif #ifdef __cplusplus } #endif #endif <file_sep>/src/DoomFireApplication.h #pragma once #include <array> #include "Application.h" #include "VertexArray.h" #include "VertexBuffer.h" #include "Texture.h" #include "Shader.h" #include "RenderTarget.h" class DoomFireApplication final : public Application { protected: void onInit() override; void onImGuiRender() override; void onEvent(SDL_Event &event) override; void onRender() override; void onUpdate(const TimeSpan &elapsed) override; void reset(); private: void reshape(int x, int y) const; void spreadFire(int src); void doFire(); private: static constexpr int FIRE_WIDTH = 640; static constexpr int FIRE_HEIGHT = 480; RenderTarget m_target{}; std::array<std::uint8_t, FIRE_WIDTH * FIRE_HEIGHT> m_image{}; std::unique_ptr<Shader> m_shader{}; std::unique_ptr<VertexArray> m_vao{}; std::unique_ptr<VertexBuffer> m_vbo{}; std::unique_ptr<VertexBuffer> m_ebo{}; std::unique_ptr<Texture> m_img_tex{}; std::unique_ptr<Texture> m_pal_tex{}; }; <file_sep>/extlibs/imgui/examples/imgui_impl_dx12.h // dear imgui: Renderer for DirectX12 // This needs to be used along with a Platform Binding (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as // ImTextureID. Read the FAQ about ImTextureID! [X] Renderer: Support for large // meshes (64k+ vertices) with 16-bit indices. // Issues: // [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See // github.com/ocornut/imgui/pull/301 // You can copy and use unmodified imgui_impl_* files in your project. See // main.cpp for an example of using this. If you are new to dear imgui, read // examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui #pragma once #include "imgui.h" // IMGUI_IMPL_API enum DXGI_FORMAT; struct ID3D12Device; struct ID3D12DescriptorHeap; struct ID3D12GraphicsCommandList; struct D3D12_CPU_DESCRIPTOR_HANDLE; struct D3D12_GPU_DESCRIPTOR_HANDLE; // cmd_list is the command list that the implementation will use to render imgui // draw lists. Before calling the render function, caller must prepare cmd_list // by resetting it and setting the appropriate render target and descriptor heap // that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle. // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single // SRV descriptor to use for the internal font texture. IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle); IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData( ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list); // Use if you want to reset your rendering device without losing Dear ImGui // state. IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); <file_sep>/extlibs/imgui/examples/example_sdl_metal/Makefile # #You will need SDL2(http: // www.libsdl.org): #brew install sdl2 # #CXX = g++ #CXX = clang++ EXE = example_sdl_metal SOURCES = main.mm SOURCES += ../ imgui_impl_sdl.cpp../ imgui_impl_metal.mm SOURCES += ../../ imgui.cpp../../ imgui_widgets.cpp../../ imgui_demo.cpp../../ imgui_draw.cpp OBJS = $(addsuffix.o, $(basename $(notdir $(SOURCES)))) LIBS = -framework Metal - framework MetalKit - framework Cocoa - framework IOKit - framework CoreVideo - framework QuartzCore LIBS += `sdl2 - config-- libs` LIBS += -L / usr / local / lib CXXFLAGS = -I../ -I../../ -I / usr / local / include CXXFLAGS += `sdl2 - config-- cflags` CXXFLAGS += -Wall - Wformat CFLAGS = $(CXXFLAGS) %.o : %.cpp $(CXX) $(CXXFLAGS) - c - o $ @$ < %.o :../ %.cpp $(CXX) $(CXXFLAGS) - c - o $ @$ < %.o :../../ %.cpp $(CXX) $(CXXFLAGS) - c - o $ @$ < %.o :../ %.mm $(CXX) $(CXXFLAGS) - ObjC++ - fobjc - weak - fobjc - arc - c - o $ @$ < %.o : %.mm $(CXX) $(CXXFLAGS) - ObjC++ - fobjc - weak - fobjc - arc - c - o $ @$ < all : $(EXE) @echo Build complete $(EXE) : $(OBJS) $(CXX) - o $ @$ ^ $(CXXFLAGS) $(LIBS) clean : rm - f $(EXE) $(OBJS) <file_sep>/src/Debug.h #pragma once #include <cstdio> #include <iostream> #include <GL/glew.h> #ifdef DEBUG #define GL_CHECK(expr) do { (expr); checkGlError(__FILE__, __LINE__, #expr); } while (false) #else #define GL_CHECK(expr) (expr) #endif static void checkGlError(const char* file, unsigned int line, const char* expr){ auto code = glGetError(); if (code == GL_NO_ERROR) return; const char *name; const char *desc; switch (code) { case GL_INVALID_ENUM: name = "GL_INVALID_ENUM"; desc = "An unacceptable value is specified for an enumerated argument."; break; case GL_INVALID_VALUE: name = "GL_INVALID_VALUE"; desc = "A numeric argument is out of range."; break; case GL_INVALID_OPERATION: name = "GL_INVALID_OPERATION"; desc = "The specified operation is not allowed in the current state."; break; case GL_INVALID_FRAMEBUFFER_OPERATION: name = "GL_INVALID_FRAMEBUFFER_OPERATION"; desc = "The command is trying to render to or read from the framebuffer while the currently bound framebuffer is not framebuffer complete."; break; case GL_OUT_OF_MEMORY: name = "GL_OUT_OF_MEMORY"; desc = "There is not enough memory left to execute the command."; break; default: std::cerr << "Error '" << code <<"' at " << file << ':' << line << " for expression '" << expr << "'" << "\n"; return; } std::cerr << "Error '" << name <<"' at " << file << ':' << line << " for expression '" << expr << "': " << desc << "\n"; } <file_sep>/src/Window.h #ifndef COLORCYCLING__WINDOW_H #define COLORCYCLING__WINDOW_H #include <SDL.h> class Window { public: Window(); ~Window(); void init(); void display(); bool pollEvent(SDL_Event &event); SDL_Window *getNativeHandle() { return m_window; } private: SDL_Window *m_window{nullptr}; SDL_GameController *m_gameController{nullptr}; SDL_GLContext m_glContext{nullptr}; }; #endif//COLORCYCLING__WINDOW_H <file_sep>/src/TimeSpan.cpp #include "TimeSpan.h" const TimeSpan TimeSpan::Zero; bool operator==(const TimeSpan &left, const TimeSpan &right) { return left.getTicks() == right.getTicks(); } bool operator!=(const TimeSpan &left, const TimeSpan &right) { return left.getTicks() != right.getTicks(); } bool operator<(const TimeSpan &left, const TimeSpan &right) { return left.getTicks() < right.getTicks(); } bool operator>(const TimeSpan &left, const TimeSpan &right) { return left.getTicks() > right.getTicks(); } bool operator<=(const TimeSpan &left, const TimeSpan &right) { return left.getTicks() <= right.getTicks(); } bool operator>=(const TimeSpan &left, const TimeSpan &right) { return left.getTicks() >= right.getTicks(); } TimeSpan operator+(const TimeSpan &left, const TimeSpan &right) { long result = left.getTicks() + right.getTicks(); // Overflow if signs of operands was identical and result's // sign was opposite. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((left.getTicks() >> 63 == right.getTicks() >> 63) && (left.getTicks() >> 63 != result >> 63)) throw std::overflow_error("TimeSpan overflow"); return TimeSpan{result}; } TimeSpan &operator+=(TimeSpan &left, const TimeSpan &right) { return left = left + right; } TimeSpan operator-(const TimeSpan &left, const TimeSpan &right) { long result = left.getTicks() - right.getTicks(); // Overflow if signs of operands was different and result's // sign was opposite from the first argument's sign. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((left.getTicks() >> 63 != right.getTicks() >> 63) && (left.getTicks() >> 63 != result >> 63)) throw std::overflow_error("TimeSpan overflow"); return TimeSpan{result}; } TimeSpan &operator-=(TimeSpan &left, const TimeSpan &right) { return left = left - right; } <file_sep>/src/Util.cpp #include "Util.h" namespace Util { unsigned int nextPow2(unsigned int x) { --x; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; } void endianSwap(int32_t *value) { unsigned char *chs; unsigned char temp; chs = (unsigned char *) value; temp = chs[0]; chs[0] = chs[3]; chs[3] = temp; temp = chs[1]; chs[1] = chs[2]; chs[2] = temp; } void endianSwap(int16_t *value) { unsigned char *chs; unsigned char temp; chs = (unsigned char *) value; temp = chs[0]; chs[0] = chs[1]; chs[1] = temp; } void endianSwap(uint16_t *value) { endianSwap((int16_t *) value); } }// namespace Util <file_sep>/src/StopWatch.h #ifndef COLORCYCLING__STOPWATCH_H #define COLORCYCLING__STOPWATCH_H class StopWatch { public: StopWatch() : m_startTime(TimeSpan::milliseconds(SDL_GetTicks())) { } [[nodiscard]] TimeSpan getElapsedTime() const { return TimeSpan::milliseconds(SDL_GetTicks()) - m_startTime; } TimeSpan restart() { TimeSpan now = TimeSpan::milliseconds(SDL_GetTicks()); TimeSpan elapsed = now - m_startTime; m_startTime = now; return elapsed; } private: TimeSpan m_startTime; }; #endif//COLORCYCLING__STOPWATCH_H <file_sep>/extlibs/imgui/examples/libs/gl3w/GL/gl3w.c #include <GL/gl3w.h> #ifdef _MSC_VER #pragma warning(disable : 4055) // warning C4055: 'type cast' : from data // pointer 'void *' to function pointer #pragma warning( \ disable : 4152) // warning C4152: nonstandard extension, function/data // pointer conversion in expression #endif #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> static HMODULE libgl; static void open_libgl(void) { libgl = LoadLibraryA("opengl32.dll"); } static void close_libgl(void) { FreeLibrary(libgl); } static void* get_proc(const char* proc) { void* res; res = wglGetProcAddress(proc); if(!res) res = GetProcAddress(libgl, proc); return res; } #elif defined(__APPLE__) || defined(__APPLE_CC__) #include <Carbon/Carbon.h> CFBundleRef bundle; CFURLRef bundleURL; static void open_libgl(void) { bundleURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("/System/Library/Frameworks/OpenGL.framework"), kCFURLPOSIXPathStyle, true); bundle = CFBundleCreate(kCFAllocatorDefault, bundleURL); assert(bundle != NULL); } static void close_libgl(void) { CFRelease(bundle); CFRelease(bundleURL); } static void* get_proc(const char* proc) { void* res; CFStringRef procname = CFStringCreateWithCString( kCFAllocatorDefault, proc, kCFStringEncodingASCII); res = CFBundleGetFunctionPointerForName(bundle, procname); CFRelease(procname); return res; } #else #include <dlfcn.h> #include <GL/glx.h> static void* libgl; static void open_libgl(void) { libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL); } static void close_libgl(void) { dlclose(libgl); } static void* get_proc(const char* proc) { void* res; res = (void*)glXGetProcAddress((const GLubyte*)proc); if(!res) res = dlsym(libgl, proc); return res; } #endif static struct { int major, minor; } version; static int parse_version(void) { if(!glGetIntegerv) return -1; glGetIntegerv(GL_MAJOR_VERSION, &version.major); glGetIntegerv(GL_MINOR_VERSION, &version.minor); if(version.major < 3) return -1; return 0; } static void load_procs(void); int gl3wInit(void) { open_libgl(); load_procs(); close_libgl(); return parse_version(); } int gl3wIsSupported(int major, int minor) { if(major < 3) return 0; if(version.major == major) return version.minor >= minor; return version.major >= major; } void* gl3wGetProcAddress(const char* proc) { return get_proc(proc); } PFNGLCULLFACEPROC gl3wCullFace; PFNGLFRONTFACEPROC gl3wFrontFace; PFNGLHINTPROC gl3wHint; PFNGLLINEWIDTHPROC gl3wLineWidth; PFNGLPOINTSIZEPROC gl3wPointSize; PFNGLPOLYGONMODEPROC gl3wPolygonMode; PFNGLSCISSORPROC gl3wScissor; PFNGLTEXPARAMETERFPROC gl3wTexParameterf; PFNGLTEXPARAMETERFVPROC gl3wTexParameterfv; PFNGLTEXPARAMETERIPROC gl3wTexParameteri; PFNGLTEXPARAMETERIVPROC gl3wTexParameteriv; PFNGLTEXIMAGE1DPROC gl3wTexImage1D; PFNGLTEXIMAGE2DPROC gl3wTexImage2D; PFNGLDRAWBUFFERPROC gl3wDrawBuffer; PFNGLCLEARPROC gl3wClear; PFNGLCLEARCOLORPROC gl3wClearColor; PFNGLCLEARSTENCILPROC gl3wClearStencil; PFNGLCLEARDEPTHPROC gl3wClearDepth; PFNGLSTENCILMASKPROC gl3wStencilMask; PFNGLCOLORMASKPROC gl3wColorMask; PFNGLDEPTHMASKPROC gl3wDepthMask; PFNGLDISABLEPROC gl3wDisable; PFNGLENABLEPROC gl3wEnable; PFNGLFINISHPROC gl3wFinish; PFNGLFLUSHPROC gl3wFlush; PFNGLBLENDFUNCPROC gl3wBlendFunc; PFNGLLOGICOPPROC gl3wLogicOp; PFNGLSTENCILFUNCPROC gl3wStencilFunc; PFNGLSTENCILOPPROC gl3wStencilOp; PFNGLDEPTHFUNCPROC gl3wDepthFunc; PFNGLPIXELSTOREFPROC gl3wPixelStoref; PFNGLPIXELSTOREIPROC gl3wPixelStorei; PFNGLREADBUFFERPROC gl3wReadBuffer; PFNGLREADPIXELSPROC gl3wReadPixels; PFNGLGETBOOLEANVPROC gl3wGetBooleanv; PFNGLGETDOUBLEVPROC gl3wGetDoublev; PFNGLGETERRORPROC gl3wGetError; PFNGLGETFLOATVPROC gl3wGetFloatv; PFNGLGETINTEGERVPROC gl3wGetIntegerv; PFNGLGETSTRINGPROC gl3wGetString; PFNGLGETTEXIMAGEPROC gl3wGetTexImage; PFNGLGETTEXPARAMETERFVPROC gl3wGetTexParameterfv; PFNGLGETTEXPARAMETERIVPROC gl3wGetTexParameteriv; PFNGLGETTEXLEVELPARAMETERFVPROC gl3wGetTexLevelParameterfv; PFNGLGETTEXLEVELPARAMETERIVPROC gl3wGetTexLevelParameteriv; PFNGLISENABLEDPROC gl3wIsEnabled; PFNGLDEPTHRANGEPROC gl3wDepthRange; PFNGLVIEWPORTPROC gl3wViewport; PFNGLDRAWARRAYSPROC gl3wDrawArrays; PFNGLDRAWELEMENTSPROC gl3wDrawElements; PFNGLGETPOINTERVPROC gl3wGetPointerv; PFNGLPOLYGONOFFSETPROC gl3wPolygonOffset; PFNGLCOPYTEXIMAGE1DPROC gl3wCopyTexImage1D; PFNGLCOPYTEXIMAGE2DPROC gl3wCopyTexImage2D; PFNGLCOPYTEXSUBIMAGE1DPROC gl3wCopyTexSubImage1D; PFNGLCOPYTEXSUBIMAGE2DPROC gl3wCopyTexSubImage2D; PFNGLTEXSUBIMAGE1DPROC gl3wTexSubImage1D; PFNGLTEXSUBIMAGE2DPROC gl3wTexSubImage2D; PFNGLBINDTEXTUREPROC gl3wBindTexture; PFNGLDELETETEXTURESPROC gl3wDeleteTextures; PFNGLGENTEXTURESPROC gl3wGenTextures; PFNGLISTEXTUREPROC gl3wIsTexture; PFNGLBLENDCOLORPROC gl3wBlendColor; PFNGLBLENDEQUATIONPROC gl3wBlendEquation; PFNGLDRAWRANGEELEMENTSPROC gl3wDrawRangeElements; PFNGLTEXIMAGE3DPROC gl3wTexImage3D; PFNGLTEXSUBIMAGE3DPROC gl3wTexSubImage3D; PFNGLCOPYTEXSUBIMAGE3DPROC gl3wCopyTexSubImage3D; PFNGLACTIVETEXTUREPROC gl3wActiveTexture; PFNGLSAMPLECOVERAGEPROC gl3wSampleCoverage; PFNGLCOMPRESSEDTEXIMAGE3DPROC gl3wCompressedTexImage3D; PFNGLCOMPRESSEDTEXIMAGE2DPROC gl3wCompressedTexImage2D; PFNGLCOMPRESSEDTEXIMAGE1DPROC gl3wCompressedTexImage1D; PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC gl3wCompressedTexSubImage3D; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC gl3wCompressedTexSubImage2D; PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC gl3wCompressedTexSubImage1D; PFNGLGETCOMPRESSEDTEXIMAGEPROC gl3wGetCompressedTexImage; PFNGLBLENDFUNCSEPARATEPROC gl3wBlendFuncSeparate; PFNGLMULTIDRAWARRAYSPROC gl3wMultiDrawArrays; PFNGLMULTIDRAWELEMENTSPROC gl3wMultiDrawElements; PFNGLPOINTPARAMETERFPROC gl3wPointParameterf; PFNGLPOINTPARAMETERFVPROC gl3wPointParameterfv; PFNGLPOINTPARAMETERIPROC gl3wPointParameteri; PFNGLPOINTPARAMETERIVPROC gl3wPointParameteriv; PFNGLGENQUERIESPROC gl3wGenQueries; PFNGLDELETEQUERIESPROC gl3wDeleteQueries; PFNGLISQUERYPROC gl3wIsQuery; PFNGLBEGINQUERYPROC gl3wBeginQuery; PFNGLENDQUERYPROC gl3wEndQuery; PFNGLGETQUERYIVPROC gl3wGetQueryiv; PFNGLGETQUERYOBJECTIVPROC gl3wGetQueryObjectiv; PFNGLGETQUERYOBJECTUIVPROC gl3wGetQueryObjectuiv; PFNGLBINDBUFFERPROC gl3wBindBuffer; PFNGLDELETEBUFFERSPROC gl3wDeleteBuffers; PFNGLGENBUFFERSPROC gl3wGenBuffers; PFNGLISBUFFERPROC gl3wIsBuffer; PFNGLBUFFERDATAPROC gl3wBufferData; PFNGLBUFFERSUBDATAPROC gl3wBufferSubData; PFNGLGETBUFFERSUBDATAPROC gl3wGetBufferSubData; PFNGLMAPBUFFERPROC gl3wMapBuffer; PFNGLUNMAPBUFFERPROC gl3wUnmapBuffer; PFNGLGETBUFFERPARAMETERIVPROC gl3wGetBufferParameteriv; PFNGLGETBUFFERPOINTERVPROC gl3wGetBufferPointerv; PFNGLBLENDEQUATIONSEPARATEPROC gl3wBlendEquationSeparate; PFNGLDRAWBUFFERSPROC gl3wDrawBuffers; PFNGLSTENCILOPSEPARATEPROC gl3wStencilOpSeparate; PFNGLSTENCILFUNCSEPARATEPROC gl3wStencilFuncSeparate; PFNGLSTENCILMASKSEPARATEPROC gl3wStencilMaskSeparate; PFNGLATTACHSHADERPROC gl3wAttachShader; PFNGLBINDATTRIBLOCATIONPROC gl3wBindAttribLocation; PFNGLCOMPILESHADERPROC gl3wCompileShader; PFNGLCREATEPROGRAMPROC gl3wCreateProgram; PFNGLCREATESHADERPROC gl3wCreateShader; PFNGLDELETEPROGRAMPROC gl3wDeleteProgram; PFNGLDELETESHADERPROC gl3wDeleteShader; PFNGLDETACHSHADERPROC gl3wDetachShader; PFNGLDISABLEVERTEXATTRIBARRAYPROC gl3wDisableVertexAttribArray; PFNGLENABLEVERTEXATTRIBARRAYPROC gl3wEnableVertexAttribArray; PFNGLGETACTIVEATTRIBPROC gl3wGetActiveAttrib; PFNGLGETACTIVEUNIFORMPROC gl3wGetActiveUniform; PFNGLGETATTACHEDSHADERSPROC gl3wGetAttachedShaders; PFNGLGETATTRIBLOCATIONPROC gl3wGetAttribLocation; PFNGLGETPROGRAMIVPROC gl3wGetProgramiv; PFNGLGETPROGRAMINFOLOGPROC gl3wGetProgramInfoLog; PFNGLGETSHADERIVPROC gl3wGetShaderiv; PFNGLGETSHADERINFOLOGPROC gl3wGetShaderInfoLog; PFNGLGETSHADERSOURCEPROC gl3wGetShaderSource; PFNGLGETUNIFORMLOCATIONPROC gl3wGetUniformLocation; PFNGLGETUNIFORMFVPROC gl3wGetUniformfv; PFNGLGETUNIFORMIVPROC gl3wGetUniformiv; PFNGLGETVERTEXATTRIBDVPROC gl3wGetVertexAttribdv; PFNGLGETVERTEXATTRIBFVPROC gl3wGetVertexAttribfv; PFNGLGETVERTEXATTRIBIVPROC gl3wGetVertexAttribiv; PFNGLGETVERTEXATTRIBPOINTERVPROC gl3wGetVertexAttribPointerv; PFNGLISPROGRAMPROC gl3wIsProgram; PFNGLISSHADERPROC gl3wIsShader; PFNGLLINKPROGRAMPROC gl3wLinkProgram; PFNGLSHADERSOURCEPROC gl3wShaderSource; PFNGLUSEPROGRAMPROC gl3wUseProgram; PFNGLUNIFORM1FPROC gl3wUniform1f; PFNGLUNIFORM2FPROC gl3wUniform2f; PFNGLUNIFORM3FPROC gl3wUniform3f; PFNGLUNIFORM4FPROC gl3wUniform4f; PFNGLUNIFORM1IPROC gl3wUniform1i; PFNGLUNIFORM2IPROC gl3wUniform2i; PFNGLUNIFORM3IPROC gl3wUniform3i; PFNGLUNIFORM4IPROC gl3wUniform4i; PFNGLUNIFORM1FVPROC gl3wUniform1fv; PFNGLUNIFORM2FVPROC gl3wUniform2fv; PFNGLUNIFORM3FVPROC gl3wUniform3fv; PFNGLUNIFORM4FVPROC gl3wUniform4fv; PFNGLUNIFORM1IVPROC gl3wUniform1iv; PFNGLUNIFORM2IVPROC gl3wUniform2iv; PFNGLUNIFORM3IVPROC gl3wUniform3iv; PFNGLUNIFORM4IVPROC gl3wUniform4iv; PFNGLUNIFORMMATRIX2FVPROC gl3wUniformMatrix2fv; PFNGLUNIFORMMATRIX3FVPROC gl3wUniformMatrix3fv; PFNGLUNIFORMMATRIX4FVPROC gl3wUniformMatrix4fv; PFNGLVALIDATEPROGRAMPROC gl3wValidateProgram; PFNGLVERTEXATTRIB1DPROC gl3wVertexAttrib1d; PFNGLVERTEXATTRIB1DVPROC gl3wVertexAttrib1dv; PFNGLVERTEXATTRIB1FPROC gl3wVertexAttrib1f; PFNGLVERTEXATTRIB1FVPROC gl3wVertexAttrib1fv; PFNGLVERTEXATTRIB1SPROC gl3wVertexAttrib1s; PFNGLVERTEXATTRIB1SVPROC gl3wVertexAttrib1sv; PFNGLVERTEXATTRIB2DPROC gl3wVertexAttrib2d; PFNGLVERTEXATTRIB2DVPROC gl3wVertexAttrib2dv; PFNGLVERTEXATTRIB2FPROC gl3wVertexAttrib2f; PFNGLVERTEXATTRIB2FVPROC gl3wVertexAttrib2fv; PFNGLVERTEXATTRIB2SPROC gl3wVertexAttrib2s; PFNGLVERTEXATTRIB2SVPROC gl3wVertexAttrib2sv; PFNGLVERTEXATTRIB3DPROC gl3wVertexAttrib3d; PFNGLVERTEXATTRIB3DVPROC gl3wVertexAttrib3dv; PFNGLVERTEXATTRIB3FPROC gl3wVertexAttrib3f; PFNGLVERTEXATTRIB3FVPROC gl3wVertexAttrib3fv; PFNGLVERTEXATTRIB3SPROC gl3wVertexAttrib3s; PFNGLVERTEXATTRIB3SVPROC gl3wVertexAttrib3sv; PFNGLVERTEXATTRIB4NBVPROC gl3wVertexAttrib4Nbv; PFNGLVERTEXATTRIB4NIVPROC gl3wVertexAttrib4Niv; PFNGLVERTEXATTRIB4NSVPROC gl3wVertexAttrib4Nsv; PFNGLVERTEXATTRIB4NUBPROC gl3wVertexAttrib4Nub; PFNGLVERTEXATTRIB4NUBVPROC gl3wVertexAttrib4Nubv; PFNGLVERTEXATTRIB4NUIVPROC gl3wVertexAttrib4Nuiv; PFNGLVERTEXATTRIB4NUSVPROC gl3wVertexAttrib4Nusv; PFNGLVERTEXATTRIB4BVPROC gl3wVertexAttrib4bv; PFNGLVERTEXATTRIB4DPROC gl3wVertexAttrib4d; PFNGLVERTEXATTRIB4DVPROC gl3wVertexAttrib4dv; PFNGLVERTEXATTRIB4FPROC gl3wVertexAttrib4f; PFNGLVERTEXATTRIB4FVPROC gl3wVertexAttrib4fv; PFNGLVERTEXATTRIB4IVPROC gl3wVertexAttrib4iv; PFNGLVERTEXATTRIB4SPROC gl3wVertexAttrib4s; PFNGLVERTEXATTRIB4SVPROC gl3wVertexAttrib4sv; PFNGLVERTEXATTRIB4UBVPROC gl3wVertexAttrib4ubv; PFNGLVERTEXATTRIB4UIVPROC gl3wVertexAttrib4uiv; PFNGLVERTEXATTRIB4USVPROC gl3wVertexAttrib4usv; PFNGLVERTEXATTRIBPOINTERPROC gl3wVertexAttribPointer; PFNGLUNIFORMMATRIX2X3FVPROC gl3wUniformMatrix2x3fv; PFNGLUNIFORMMATRIX3X2FVPROC gl3wUniformMatrix3x2fv; PFNGLUNIFORMMATRIX2X4FVPROC gl3wUniformMatrix2x4fv; PFNGLUNIFORMMATRIX4X2FVPROC gl3wUniformMatrix4x2fv; PFNGLUNIFORMMATRIX3X4FVPROC gl3wUniformMatrix3x4fv; PFNGLUNIFORMMATRIX4X3FVPROC gl3wUniformMatrix4x3fv; PFNGLCOLORMASKIPROC gl3wColorMaski; PFNGLGETBOOLEANI_VPROC gl3wGetBooleani_v; PFNGLGETINTEGERI_VPROC gl3wGetIntegeri_v; PFNGLENABLEIPROC gl3wEnablei; PFNGLDISABLEIPROC gl3wDisablei; PFNGLISENABLEDIPROC gl3wIsEnabledi; PFNGLBEGINTRANSFORMFEEDBACKPROC gl3wBeginTransformFeedback; PFNGLENDTRANSFORMFEEDBACKPROC gl3wEndTransformFeedback; PFNGLBINDBUFFERRANGEPROC gl3wBindBufferRange; PFNGLBINDBUFFERBASEPROC gl3wBindBufferBase; PFNGLTRANSFORMFEEDBACKVARYINGSPROC gl3wTransformFeedbackVaryings; PFNGLGETTRANSFORMFEEDBACKVARYINGPROC gl3wGetTransformFeedbackVarying; PFNGLCLAMPCOLORPROC gl3wClampColor; PFNGLBEGINCONDITIONALRENDERPROC gl3wBeginConditionalRender; PFNGLENDCONDITIONALRENDERPROC gl3wEndConditionalRender; PFNGLVERTEXATTRIBIPOINTERPROC gl3wVertexAttribIPointer; PFNGLGETVERTEXATTRIBIIVPROC gl3wGetVertexAttribIiv; PFNGLGETVERTEXATTRIBIUIVPROC gl3wGetVertexAttribIuiv; PFNGLVERTEXATTRIBI1IPROC gl3wVertexAttribI1i; PFNGLVERTEXATTRIBI2IPROC gl3wVertexAttribI2i; PFNGLVERTEXATTRIBI3IPROC gl3wVertexAttribI3i; PFNGLVERTEXATTRIBI4IPROC gl3wVertexAttribI4i; PFNGLVERTEXATTRIBI1UIPROC gl3wVertexAttribI1ui; PFNGLVERTEXATTRIBI2UIPROC gl3wVertexAttribI2ui; PFNGLVERTEXATTRIBI3UIPROC gl3wVertexAttribI3ui; PFNGLVERTEXATTRIBI4UIPROC gl3wVertexAttribI4ui; PFNGLVERTEXATTRIBI1IVPROC gl3wVertexAttribI1iv; PFNGLVERTEXATTRIBI2IVPROC gl3wVertexAttribI2iv; PFNGLVERTEXATTRIBI3IVPROC gl3wVertexAttribI3iv; PFNGLVERTEXATTRIBI4IVPROC gl3wVertexAttribI4iv; PFNGLVERTEXATTRIBI1UIVPROC gl3wVertexAttribI1uiv; PFNGLVERTEXATTRIBI2UIVPROC gl3wVertexAttribI2uiv; PFNGLVERTEXATTRIBI3UIVPROC gl3wVertexAttribI3uiv; PFNGLVERTEXATTRIBI4UIVPROC gl3wVertexAttribI4uiv; PFNGLVERTEXATTRIBI4BVPROC gl3wVertexAttribI4bv; PFNGLVERTEXATTRIBI4SVPROC gl3wVertexAttribI4sv; PFNGLVERTEXATTRIBI4UBVPROC gl3wVertexAttribI4ubv; PFNGLVERTEXATTRIBI4USVPROC gl3wVertexAttribI4usv; PFNGLGETUNIFORMUIVPROC gl3wGetUniformuiv; PFNGLBINDFRAGDATALOCATIONPROC gl3wBindFragDataLocation; PFNGLGETFRAGDATALOCATIONPROC gl3wGetFragDataLocation; PFNGLUNIFORM1UIPROC gl3wUniform1ui; PFNGLUNIFORM2UIPROC gl3wUniform2ui; PFNGLUNIFORM3UIPROC gl3wUniform3ui; PFNGLUNIFORM4UIPROC gl3wUniform4ui; PFNGLUNIFORM1UIVPROC gl3wUniform1uiv; PFNGLUNIFORM2UIVPROC gl3wUniform2uiv; PFNGLUNIFORM3UIVPROC gl3wUniform3uiv; PFNGLUNIFORM4UIVPROC gl3wUniform4uiv; PFNGLTEXPARAMETERIIVPROC gl3wTexParameterIiv; PFNGLTEXPARAMETERIUIVPROC gl3wTexParameterIuiv; PFNGLGETTEXPARAMETERIIVPROC gl3wGetTexParameterIiv; PFNGLGETTEXPARAMETERIUIVPROC gl3wGetTexParameterIuiv; PFNGLCLEARBUFFERIVPROC gl3wClearBufferiv; PFNGLCLEARBUFFERUIVPROC gl3wClearBufferuiv; PFNGLCLEARBUFFERFVPROC gl3wClearBufferfv; PFNGLCLEARBUFFERFIPROC gl3wClearBufferfi; PFNGLGETSTRINGIPROC gl3wGetStringi; PFNGLDRAWARRAYSINSTANCEDPROC gl3wDrawArraysInstanced; PFNGLDRAWELEMENTSINSTANCEDPROC gl3wDrawElementsInstanced; PFNGLTEXBUFFERPROC gl3wTexBuffer; PFNGLPRIMITIVERESTARTINDEXPROC gl3wPrimitiveRestartIndex; PFNGLGETINTEGER64I_VPROC gl3wGetInteger64i_v; PFNGLGETBUFFERPARAMETERI64VPROC gl3wGetBufferParameteri64v; PFNGLFRAMEBUFFERTEXTUREPROC gl3wFramebufferTexture; PFNGLVERTEXATTRIBDIVISORPROC gl3wVertexAttribDivisor; PFNGLMINSAMPLESHADINGPROC gl3wMinSampleShading; PFNGLBLENDEQUATIONIPROC gl3wBlendEquationi; PFNGLBLENDEQUATIONSEPARATEIPROC gl3wBlendEquationSeparatei; PFNGLBLENDFUNCIPROC gl3wBlendFunci; PFNGLBLENDFUNCSEPARATEIPROC gl3wBlendFuncSeparatei; PFNGLISRENDERBUFFERPROC gl3wIsRenderbuffer; PFNGLBINDRENDERBUFFERPROC gl3wBindRenderbuffer; PFNGLDELETERENDERBUFFERSPROC gl3wDeleteRenderbuffers; PFNGLGENRENDERBUFFERSPROC gl3wGenRenderbuffers; PFNGLRENDERBUFFERSTORAGEPROC gl3wRenderbufferStorage; PFNGLGETRENDERBUFFERPARAMETERIVPROC gl3wGetRenderbufferParameteriv; PFNGLISFRAMEBUFFERPROC gl3wIsFramebuffer; PFNGLBINDFRAMEBUFFERPROC gl3wBindFramebuffer; PFNGLDELETEFRAMEBUFFERSPROC gl3wDeleteFramebuffers; PFNGLGENFRAMEBUFFERSPROC gl3wGenFramebuffers; PFNGLCHECKFRAMEBUFFERSTATUSPROC gl3wCheckFramebufferStatus; PFNGLFRAMEBUFFERTEXTURE1DPROC gl3wFramebufferTexture1D; PFNGLFRAMEBUFFERTEXTURE2DPROC gl3wFramebufferTexture2D; PFNGLFRAMEBUFFERTEXTURE3DPROC gl3wFramebufferTexture3D; PFNGLFRAMEBUFFERRENDERBUFFERPROC gl3wFramebufferRenderbuffer; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC gl3wGetFramebufferAttachmentParameteriv; PFNGLGENERATEMIPMAPPROC gl3wGenerateMipmap; PFNGLBLITFRAMEBUFFERPROC gl3wBlitFramebuffer; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC gl3wRenderbufferStorageMultisample; PFNGLFRAMEBUFFERTEXTURELAYERPROC gl3wFramebufferTextureLayer; PFNGLMAPBUFFERRANGEPROC gl3wMapBufferRange; PFNGLFLUSHMAPPEDBUFFERRANGEPROC gl3wFlushMappedBufferRange; PFNGLBINDVERTEXARRAYPROC gl3wBindVertexArray; PFNGLDELETEVERTEXARRAYSPROC gl3wDeleteVertexArrays; PFNGLGENVERTEXARRAYSPROC gl3wGenVertexArrays; PFNGLISVERTEXARRAYPROC gl3wIsVertexArray; PFNGLGETUNIFORMINDICESPROC gl3wGetUniformIndices; PFNGLGETACTIVEUNIFORMSIVPROC gl3wGetActiveUniformsiv; PFNGLGETACTIVEUNIFORMNAMEPROC gl3wGetActiveUniformName; PFNGLGETUNIFORMBLOCKINDEXPROC gl3wGetUniformBlockIndex; PFNGLGETACTIVEUNIFORMBLOCKIVPROC gl3wGetActiveUniformBlockiv; PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC gl3wGetActiveUniformBlockName; PFNGLUNIFORMBLOCKBINDINGPROC gl3wUniformBlockBinding; PFNGLCOPYBUFFERSUBDATAPROC gl3wCopyBufferSubData; PFNGLDRAWELEMENTSBASEVERTEXPROC gl3wDrawElementsBaseVertex; PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC gl3wDrawRangeElementsBaseVertex; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC gl3wDrawElementsInstancedBaseVertex; PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC gl3wMultiDrawElementsBaseVertex; PFNGLPROVOKINGVERTEXPROC gl3wProvokingVertex; PFNGLFENCESYNCPROC gl3wFenceSync; PFNGLISSYNCPROC gl3wIsSync; PFNGLDELETESYNCPROC gl3wDeleteSync; PFNGLCLIENTWAITSYNCPROC gl3wClientWaitSync; PFNGLWAITSYNCPROC gl3wWaitSync; PFNGLGETINTEGER64VPROC gl3wGetInteger64v; PFNGLGETSYNCIVPROC gl3wGetSynciv; PFNGLTEXIMAGE2DMULTISAMPLEPROC gl3wTexImage2DMultisample; PFNGLTEXIMAGE3DMULTISAMPLEPROC gl3wTexImage3DMultisample; PFNGLGETMULTISAMPLEFVPROC gl3wGetMultisamplefv; PFNGLSAMPLEMASKIPROC gl3wSampleMaski; PFNGLBLENDEQUATIONIARBPROC gl3wBlendEquationiARB; PFNGLBLENDEQUATIONSEPARATEIARBPROC gl3wBlendEquationSeparateiARB; PFNGLBLENDFUNCIARBPROC gl3wBlendFunciARB; PFNGLBLENDFUNCSEPARATEIARBPROC gl3wBlendFuncSeparateiARB; PFNGLMINSAMPLESHADINGARBPROC gl3wMinSampleShadingARB; PFNGLNAMEDSTRINGARBPROC gl3wNamedStringARB; PFNGLDELETENAMEDSTRINGARBPROC gl3wDeleteNamedStringARB; PFNGLCOMPILESHADERINCLUDEARBPROC gl3wCompileShaderIncludeARB; PFNGLISNAMEDSTRINGARBPROC gl3wIsNamedStringARB; PFNGLGETNAMEDSTRINGARBPROC gl3wGetNamedStringARB; PFNGLGETNAMEDSTRINGIVARBPROC gl3wGetNamedStringivARB; PFNGLBINDFRAGDATALOCATIONINDEXEDPROC gl3wBindFragDataLocationIndexed; PFNGLGETFRAGDATAINDEXPROC gl3wGetFragDataIndex; PFNGLGENSAMPLERSPROC gl3wGenSamplers; PFNGLDELETESAMPLERSPROC gl3wDeleteSamplers; PFNGLISSAMPLERPROC gl3wIsSampler; PFNGLBINDSAMPLERPROC gl3wBindSampler; PFNGLSAMPLERPARAMETERIPROC gl3wSamplerParameteri; PFNGLSAMPLERPARAMETERIVPROC gl3wSamplerParameteriv; PFNGLSAMPLERPARAMETERFPROC gl3wSamplerParameterf; PFNGLSAMPLERPARAMETERFVPROC gl3wSamplerParameterfv; PFNGLSAMPLERPARAMETERIIVPROC gl3wSamplerParameterIiv; PFNGLSAMPLERPARAMETERIUIVPROC gl3wSamplerParameterIuiv; PFNGLGETSAMPLERPARAMETERIVPROC gl3wGetSamplerParameteriv; PFNGLGETSAMPLERPARAMETERIIVPROC gl3wGetSamplerParameterIiv; PFNGLGETSAMPLERPARAMETERFVPROC gl3wGetSamplerParameterfv; PFNGLGETSAMPLERPARAMETERIUIVPROC gl3wGetSamplerParameterIuiv; PFNGLQUERYCOUNTERPROC gl3wQueryCounter; PFNGLGETQUERYOBJECTI64VPROC gl3wGetQueryObjecti64v; PFNGLGETQUERYOBJECTUI64VPROC gl3wGetQueryObjectui64v; PFNGLVERTEXP2UIPROC gl3wVertexP2ui; PFNGLVERTEXP2UIVPROC gl3wVertexP2uiv; PFNGLVERTEXP3UIPROC gl3wVertexP3ui; PFNGLVERTEXP3UIVPROC gl3wVertexP3uiv; PFNGLVERTEXP4UIPROC gl3wVertexP4ui; PFNGLVERTEXP4UIVPROC gl3wVertexP4uiv; PFNGLTEXCOORDP1UIPROC gl3wTexCoordP1ui; PFNGLTEXCOORDP1UIVPROC gl3wTexCoordP1uiv; PFNGLTEXCOORDP2UIPROC gl3wTexCoordP2ui; PFNGLTEXCOORDP2UIVPROC gl3wTexCoordP2uiv; PFNGLTEXCOORDP3UIPROC gl3wTexCoordP3ui; PFNGLTEXCOORDP3UIVPROC gl3wTexCoordP3uiv; PFNGLTEXCOORDP4UIPROC gl3wTexCoordP4ui; PFNGLTEXCOORDP4UIVPROC gl3wTexCoordP4uiv; PFNGLMULTITEXCOORDP1UIPROC gl3wMultiTexCoordP1ui; PFNGLMULTITEXCOORDP1UIVPROC gl3wMultiTexCoordP1uiv; PFNGLMULTITEXCOORDP2UIPROC gl3wMultiTexCoordP2ui; PFNGLMULTITEXCOORDP2UIVPROC gl3wMultiTexCoordP2uiv; PFNGLMULTITEXCOORDP3UIPROC gl3wMultiTexCoordP3ui; PFNGLMULTITEXCOORDP3UIVPROC gl3wMultiTexCoordP3uiv; PFNGLMULTITEXCOORDP4UIPROC gl3wMultiTexCoordP4ui; PFNGLMULTITEXCOORDP4UIVPROC gl3wMultiTexCoordP4uiv; PFNGLNORMALP3UIPROC gl3wNormalP3ui; PFNGLNORMALP3UIVPROC gl3wNormalP3uiv; PFNGLCOLORP3UIPROC gl3wColorP3ui; PFNGLCOLORP3UIVPROC gl3wColorP3uiv; PFNGLCOLORP4UIPROC gl3wColorP4ui; PFNGLCOLORP4UIVPROC gl3wColorP4uiv; PFNGLSECONDARYCOLORP3UIPROC gl3wSecondaryColorP3ui; PFNGLSECONDARYCOLORP3UIVPROC gl3wSecondaryColorP3uiv; PFNGLVERTEXATTRIBP1UIPROC gl3wVertexAttribP1ui; PFNGLVERTEXATTRIBP1UIVPROC gl3wVertexAttribP1uiv; PFNGLVERTEXATTRIBP2UIPROC gl3wVertexAttribP2ui; PFNGLVERTEXATTRIBP2UIVPROC gl3wVertexAttribP2uiv; PFNGLVERTEXATTRIBP3UIPROC gl3wVertexAttribP3ui; PFNGLVERTEXATTRIBP3UIVPROC gl3wVertexAttribP3uiv; PFNGLVERTEXATTRIBP4UIPROC gl3wVertexAttribP4ui; PFNGLVERTEXATTRIBP4UIVPROC gl3wVertexAttribP4uiv; PFNGLDRAWARRAYSINDIRECTPROC gl3wDrawArraysIndirect; PFNGLDRAWELEMENTSINDIRECTPROC gl3wDrawElementsIndirect; PFNGLUNIFORM1DPROC gl3wUniform1d; PFNGLUNIFORM2DPROC gl3wUniform2d; PFNGLUNIFORM3DPROC gl3wUniform3d; PFNGLUNIFORM4DPROC gl3wUniform4d; PFNGLUNIFORM1DVPROC gl3wUniform1dv; PFNGLUNIFORM2DVPROC gl3wUniform2dv; PFNGLUNIFORM3DVPROC gl3wUniform3dv; PFNGLUNIFORM4DVPROC gl3wUniform4dv; PFNGLUNIFORMMATRIX2DVPROC gl3wUniformMatrix2dv; PFNGLUNIFORMMATRIX3DVPROC gl3wUniformMatrix3dv; PFNGLUNIFORMMATRIX4DVPROC gl3wUniformMatrix4dv; PFNGLUNIFORMMATRIX2X3DVPROC gl3wUniformMatrix2x3dv; PFNGLUNIFORMMATRIX2X4DVPROC gl3wUniformMatrix2x4dv; PFNGLUNIFORMMATRIX3X2DVPROC gl3wUniformMatrix3x2dv; PFNGLUNIFORMMATRIX3X4DVPROC gl3wUniformMatrix3x4dv; PFNGLUNIFORMMATRIX4X2DVPROC gl3wUniformMatrix4x2dv; PFNGLUNIFORMMATRIX4X3DVPROC gl3wUniformMatrix4x3dv; PFNGLGETUNIFORMDVPROC gl3wGetUniformdv; PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC gl3wGetSubroutineUniformLocation; PFNGLGETSUBROUTINEINDEXPROC gl3wGetSubroutineIndex; PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC gl3wGetActiveSubroutineUniformiv; PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC gl3wGetActiveSubroutineUniformName; PFNGLGETACTIVESUBROUTINENAMEPROC gl3wGetActiveSubroutineName; PFNGLUNIFORMSUBROUTINESUIVPROC gl3wUniformSubroutinesuiv; PFNGLGETUNIFORMSUBROUTINEUIVPROC gl3wGetUniformSubroutineuiv; PFNGLGETPROGRAMSTAGEIVPROC gl3wGetProgramStageiv; PFNGLPATCHPARAMETERIPROC gl3wPatchParameteri; PFNGLPATCHPARAMETERFVPROC gl3wPatchParameterfv; PFNGLBINDTRANSFORMFEEDBACKPROC gl3wBindTransformFeedback; PFNGLDELETETRANSFORMFEEDBACKSPROC gl3wDeleteTransformFeedbacks; PFNGLGENTRANSFORMFEEDBACKSPROC gl3wGenTransformFeedbacks; PFNGLISTRANSFORMFEEDBACKPROC gl3wIsTransformFeedback; PFNGLPAUSETRANSFORMFEEDBACKPROC gl3wPauseTransformFeedback; PFNGLRESUMETRANSFORMFEEDBACKPROC gl3wResumeTransformFeedback; PFNGLDRAWTRANSFORMFEEDBACKPROC gl3wDrawTransformFeedback; PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC gl3wDrawTransformFeedbackStream; PFNGLBEGINQUERYINDEXEDPROC gl3wBeginQueryIndexed; PFNGLENDQUERYINDEXEDPROC gl3wEndQueryIndexed; PFNGLGETQUERYINDEXEDIVPROC gl3wGetQueryIndexediv; PFNGLRELEASESHADERCOMPILERPROC gl3wReleaseShaderCompiler; PFNGLSHADERBINARYPROC gl3wShaderBinary; PFNGLGETSHADERPRECISIONFORMATPROC gl3wGetShaderPrecisionFormat; PFNGLDEPTHRANGEFPROC gl3wDepthRangef; PFNGLCLEARDEPTHFPROC gl3wClearDepthf; PFNGLGETPROGRAMBINARYPROC gl3wGetProgramBinary; PFNGLPROGRAMBINARYPROC gl3wProgramBinary; PFNGLPROGRAMPARAMETERIPROC gl3wProgramParameteri; PFNGLUSEPROGRAMSTAGESPROC gl3wUseProgramStages; PFNGLACTIVESHADERPROGRAMPROC gl3wActiveShaderProgram; PFNGLCREATESHADERPROGRAMVPROC gl3wCreateShaderProgramv; PFNGLBINDPROGRAMPIPELINEPROC gl3wBindProgramPipeline; PFNGLDELETEPROGRAMPIPELINESPROC gl3wDeleteProgramPipelines; PFNGLGENPROGRAMPIPELINESPROC gl3wGenProgramPipelines; PFNGLISPROGRAMPIPELINEPROC gl3wIsProgramPipeline; PFNGLGETPROGRAMPIPELINEIVPROC gl3wGetProgramPipelineiv; PFNGLPROGRAMUNIFORM1IPROC gl3wProgramUniform1i; PFNGLPROGRAMUNIFORM1IVPROC gl3wProgramUniform1iv; PFNGLPROGRAMUNIFORM1FPROC gl3wProgramUniform1f; PFNGLPROGRAMUNIFORM1FVPROC gl3wProgramUniform1fv; PFNGLPROGRAMUNIFORM1DPROC gl3wProgramUniform1d; PFNGLPROGRAMUNIFORM1DVPROC gl3wProgramUniform1dv; PFNGLPROGRAMUNIFORM1UIPROC gl3wProgramUniform1ui; PFNGLPROGRAMUNIFORM1UIVPROC gl3wProgramUniform1uiv; PFNGLPROGRAMUNIFORM2IPROC gl3wProgramUniform2i; PFNGLPROGRAMUNIFORM2IVPROC gl3wProgramUniform2iv; PFNGLPROGRAMUNIFORM2FPROC gl3wProgramUniform2f; PFNGLPROGRAMUNIFORM2FVPROC gl3wProgramUniform2fv; PFNGLPROGRAMUNIFORM2DPROC gl3wProgramUniform2d; PFNGLPROGRAMUNIFORM2DVPROC gl3wProgramUniform2dv; PFNGLPROGRAMUNIFORM2UIPROC gl3wProgramUniform2ui; PFNGLPROGRAMUNIFORM2UIVPROC gl3wProgramUniform2uiv; PFNGLPROGRAMUNIFORM3IPROC gl3wProgramUniform3i; PFNGLPROGRAMUNIFORM3IVPROC gl3wProgramUniform3iv; PFNGLPROGRAMUNIFORM3FPROC gl3wProgramUniform3f; PFNGLPROGRAMUNIFORM3FVPROC gl3wProgramUniform3fv; PFNGLPROGRAMUNIFORM3DPROC gl3wProgramUniform3d; PFNGLPROGRAMUNIFORM3DVPROC gl3wProgramUniform3dv; PFNGLPROGRAMUNIFORM3UIPROC gl3wProgramUniform3ui; PFNGLPROGRAMUNIFORM3UIVPROC gl3wProgramUniform3uiv; PFNGLPROGRAMUNIFORM4IPROC gl3wProgramUniform4i; PFNGLPROGRAMUNIFORM4IVPROC gl3wProgramUniform4iv; PFNGLPROGRAMUNIFORM4FPROC gl3wProgramUniform4f; PFNGLPROGRAMUNIFORM4FVPROC gl3wProgramUniform4fv; PFNGLPROGRAMUNIFORM4DPROC gl3wProgramUniform4d; PFNGLPROGRAMUNIFORM4DVPROC gl3wProgramUniform4dv; PFNGLPROGRAMUNIFORM4UIPROC gl3wProgramUniform4ui; PFNGLPROGRAMUNIFORM4UIVPROC gl3wProgramUniform4uiv; PFNGLPROGRAMUNIFORMMATRIX2FVPROC gl3wProgramUniformMatrix2fv; PFNGLPROGRAMUNIFORMMATRIX3FVPROC gl3wProgramUniformMatrix3fv; PFNGLPROGRAMUNIFORMMATRIX4FVPROC gl3wProgramUniformMatrix4fv; PFNGLPROGRAMUNIFORMMATRIX2DVPROC gl3wProgramUniformMatrix2dv; PFNGLPROGRAMUNIFORMMATRIX3DVPROC gl3wProgramUniformMatrix3dv; PFNGLPROGRAMUNIFORMMATRIX4DVPROC gl3wProgramUniformMatrix4dv; PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC gl3wProgramUniformMatrix2x3fv; PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC gl3wProgramUniformMatrix3x2fv; PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC gl3wProgramUniformMatrix2x4fv; PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC gl3wProgramUniformMatrix4x2fv; PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC gl3wProgramUniformMatrix3x4fv; PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC gl3wProgramUniformMatrix4x3fv; PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC gl3wProgramUniformMatrix2x3dv; PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC gl3wProgramUniformMatrix3x2dv; PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC gl3wProgramUniformMatrix2x4dv; PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC gl3wProgramUniformMatrix4x2dv; PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC gl3wProgramUniformMatrix3x4dv; PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC gl3wProgramUniformMatrix4x3dv; PFNGLVALIDATEPROGRAMPIPELINEPROC gl3wValidateProgramPipeline; PFNGLGETPROGRAMPIPELINEINFOLOGPROC gl3wGetProgramPipelineInfoLog; PFNGLVERTEXATTRIBL1DPROC gl3wVertexAttribL1d; PFNGLVERTEXATTRIBL2DPROC gl3wVertexAttribL2d; PFNGLVERTEXATTRIBL3DPROC gl3wVertexAttribL3d; PFNGLVERTEXATTRIBL4DPROC gl3wVertexAttribL4d; PFNGLVERTEXATTRIBL1DVPROC gl3wVertexAttribL1dv; PFNGLVERTEXATTRIBL2DVPROC gl3wVertexAttribL2dv; PFNGLVERTEXATTRIBL3DVPROC gl3wVertexAttribL3dv; PFNGLVERTEXATTRIBL4DVPROC gl3wVertexAttribL4dv; PFNGLVERTEXATTRIBLPOINTERPROC gl3wVertexAttribLPointer; PFNGLGETVERTEXATTRIBLDVPROC gl3wGetVertexAttribLdv; PFNGLVIEWPORTARRAYVPROC gl3wViewportArrayv; PFNGLVIEWPORTINDEXEDFPROC gl3wViewportIndexedf; PFNGLVIEWPORTINDEXEDFVPROC gl3wViewportIndexedfv; PFNGLSCISSORARRAYVPROC gl3wScissorArrayv; PFNGLSCISSORINDEXEDPROC gl3wScissorIndexed; PFNGLSCISSORINDEXEDVPROC gl3wScissorIndexedv; PFNGLDEPTHRANGEARRAYVPROC gl3wDepthRangeArrayv; PFNGLDEPTHRANGEINDEXEDPROC gl3wDepthRangeIndexed; PFNGLGETFLOATI_VPROC gl3wGetFloati_v; PFNGLGETDOUBLEI_VPROC gl3wGetDoublei_v; PFNGLCREATESYNCFROMCLEVENTARBPROC gl3wCreateSyncFromCLeventARB; PFNGLDEBUGMESSAGECONTROLARBPROC gl3wDebugMessageControlARB; PFNGLDEBUGMESSAGEINSERTARBPROC gl3wDebugMessageInsertARB; PFNGLDEBUGMESSAGECALLBACKARBPROC gl3wDebugMessageCallbackARB; PFNGLGETDEBUGMESSAGELOGARBPROC gl3wGetDebugMessageLogARB; PFNGLGETGRAPHICSRESETSTATUSARBPROC gl3wGetGraphicsResetStatusARB; PFNGLGETNTEXIMAGEARBPROC gl3wGetnTexImageARB; PFNGLREADNPIXELSARBPROC gl3wReadnPixelsARB; PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC gl3wGetnCompressedTexImageARB; PFNGLGETNUNIFORMFVARBPROC gl3wGetnUniformfvARB; PFNGLGETNUNIFORMIVARBPROC gl3wGetnUniformivARB; PFNGLGETNUNIFORMUIVARBPROC gl3wGetnUniformuivARB; PFNGLGETNUNIFORMDVARBPROC gl3wGetnUniformdvARB; PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC gl3wDrawArraysInstancedBaseInstance; PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC gl3wDrawElementsInstancedBaseInstance; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC gl3wDrawElementsInstancedBaseVertexBaseInstance; PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC gl3wDrawTransformFeedbackInstanced; PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC gl3wDrawTransformFeedbackStreamInstanced; PFNGLGETINTERNALFORMATIVPROC gl3wGetInternalformativ; PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC gl3wGetActiveAtomicCounterBufferiv; PFNGLBINDIMAGETEXTUREPROC gl3wBindImageTexture; PFNGLMEMORYBARRIERPROC gl3wMemoryBarrier; PFNGLTEXSTORAGE1DPROC gl3wTexStorage1D; PFNGLTEXSTORAGE2DPROC gl3wTexStorage2D; PFNGLTEXSTORAGE3DPROC gl3wTexStorage3D; PFNGLTEXTURESTORAGE1DEXTPROC gl3wTextureStorage1DEXT; PFNGLTEXTURESTORAGE2DEXTPROC gl3wTextureStorage2DEXT; PFNGLTEXTURESTORAGE3DEXTPROC gl3wTextureStorage3DEXT; PFNGLDEBUGMESSAGECONTROLPROC gl3wDebugMessageControl; PFNGLDEBUGMESSAGEINSERTPROC gl3wDebugMessageInsert; PFNGLDEBUGMESSAGECALLBACKPROC gl3wDebugMessageCallback; PFNGLGETDEBUGMESSAGELOGPROC gl3wGetDebugMessageLog; PFNGLPUSHDEBUGGROUPPROC gl3wPushDebugGroup; PFNGLPOPDEBUGGROUPPROC gl3wPopDebugGroup; PFNGLOBJECTLABELPROC gl3wObjectLabel; PFNGLGETOBJECTLABELPROC gl3wGetObjectLabel; PFNGLOBJECTPTRLABELPROC gl3wObjectPtrLabel; PFNGLGETOBJECTPTRLABELPROC gl3wGetObjectPtrLabel; PFNGLCLEARBUFFERDATAPROC gl3wClearBufferData; PFNGLCLEARBUFFERSUBDATAPROC gl3wClearBufferSubData; PFNGLCLEARNAMEDBUFFERDATAEXTPROC gl3wClearNamedBufferDataEXT; PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC gl3wClearNamedBufferSubDataEXT; PFNGLDISPATCHCOMPUTEPROC gl3wDispatchCompute; PFNGLDISPATCHCOMPUTEINDIRECTPROC gl3wDispatchComputeIndirect; PFNGLCOPYIMAGESUBDATAPROC gl3wCopyImageSubData; PFNGLTEXTUREVIEWPROC gl3wTextureView; PFNGLBINDVERTEXBUFFERPROC gl3wBindVertexBuffer; PFNGLVERTEXATTRIBFORMATPROC gl3wVertexAttribFormat; PFNGLVERTEXATTRIBIFORMATPROC gl3wVertexAttribIFormat; PFNGLVERTEXATTRIBLFORMATPROC gl3wVertexAttribLFormat; PFNGLVERTEXATTRIBBINDINGPROC gl3wVertexAttribBinding; PFNGLVERTEXBINDINGDIVISORPROC gl3wVertexBindingDivisor; PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC gl3wVertexArrayBindVertexBufferEXT; PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC gl3wVertexArrayVertexAttribFormatEXT; PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC gl3wVertexArrayVertexAttribIFormatEXT; PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC gl3wVertexArrayVertexAttribLFormatEXT; PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC gl3wVertexArrayVertexAttribBindingEXT; PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC gl3wVertexArrayVertexBindingDivisorEXT; PFNGLFRAMEBUFFERPARAMETERIPROC gl3wFramebufferParameteri; PFNGLGETFRAMEBUFFERPARAMETERIVPROC gl3wGetFramebufferParameteriv; PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC gl3wNamedFramebufferParameteriEXT; PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC gl3wGetNamedFramebufferParameterivEXT; PFNGLGETINTERNALFORMATI64VPROC gl3wGetInternalformati64v; PFNGLINVALIDATETEXSUBIMAGEPROC gl3wInvalidateTexSubImage; PFNGLINVALIDATETEXIMAGEPROC gl3wInvalidateTexImage; PFNGLINVALIDATEBUFFERSUBDATAPROC gl3wInvalidateBufferSubData; PFNGLINVALIDATEBUFFERDATAPROC gl3wInvalidateBufferData; PFNGLINVALIDATEFRAMEBUFFERPROC gl3wInvalidateFramebuffer; PFNGLINVALIDATESUBFRAMEBUFFERPROC gl3wInvalidateSubFramebuffer; PFNGLMULTIDRAWARRAYSINDIRECTPROC gl3wMultiDrawArraysIndirect; PFNGLMULTIDRAWELEMENTSINDIRECTPROC gl3wMultiDrawElementsIndirect; PFNGLGETPROGRAMINTERFACEIVPROC gl3wGetProgramInterfaceiv; PFNGLGETPROGRAMRESOURCEINDEXPROC gl3wGetProgramResourceIndex; PFNGLGETPROGRAMRESOURCENAMEPROC gl3wGetProgramResourceName; PFNGLGETPROGRAMRESOURCEIVPROC gl3wGetProgramResourceiv; PFNGLGETPROGRAMRESOURCELOCATIONPROC gl3wGetProgramResourceLocation; PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC gl3wGetProgramResourceLocationIndex; PFNGLSHADERSTORAGEBLOCKBINDINGPROC gl3wShaderStorageBlockBinding; PFNGLTEXBUFFERRANGEPROC gl3wTexBufferRange; PFNGLTEXTUREBUFFERRANGEEXTPROC gl3wTextureBufferRangeEXT; PFNGLTEXSTORAGE2DMULTISAMPLEPROC gl3wTexStorage2DMultisample; PFNGLTEXSTORAGE3DMULTISAMPLEPROC gl3wTexStorage3DMultisample; PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC gl3wTextureStorage2DMultisampleEXT; PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC gl3wTextureStorage3DMultisampleEXT; static void load_procs(void) { gl3wCullFace = (PFNGLCULLFACEPROC)get_proc("glCullFace"); gl3wFrontFace = (PFNGLFRONTFACEPROC)get_proc("glFrontFace"); gl3wHint = (PFNGLHINTPROC)get_proc("glHint"); gl3wLineWidth = (PFNGLLINEWIDTHPROC)get_proc("glLineWidth"); gl3wPointSize = (PFNGLPOINTSIZEPROC)get_proc("glPointSize"); gl3wPolygonMode = (PFNGLPOLYGONMODEPROC)get_proc("glPolygonMode"); gl3wScissor = (PFNGLSCISSORPROC)get_proc("glScissor"); gl3wTexParameterf = (PFNGLTEXPARAMETERFPROC)get_proc("glTexParameterf"); gl3wTexParameterfv = (PFNGLTEXPARAMETERFVPROC)get_proc("glTexParameterfv"); gl3wTexParameteri = (PFNGLTEXPARAMETERIPROC)get_proc("glTexParameteri"); gl3wTexParameteriv = (PFNGLTEXPARAMETERIVPROC)get_proc("glTexParameteriv"); gl3wTexImage1D = (PFNGLTEXIMAGE1DPROC)get_proc("glTexImage1D"); gl3wTexImage2D = (PFNGLTEXIMAGE2DPROC)get_proc("glTexImage2D"); gl3wDrawBuffer = (PFNGLDRAWBUFFERPROC)get_proc("glDrawBuffer"); gl3wClear = (PFNGLCLEARPROC)get_proc("glClear"); gl3wClearColor = (PFNGLCLEARCOLORPROC)get_proc("glClearColor"); gl3wClearStencil = (PFNGLCLEARSTENCILPROC)get_proc("glClearStencil"); gl3wClearDepth = (PFNGLCLEARDEPTHPROC)get_proc("glClearDepth"); gl3wStencilMask = (PFNGLSTENCILMASKPROC)get_proc("glStencilMask"); gl3wColorMask = (PFNGLCOLORMASKPROC)get_proc("glColorMask"); gl3wDepthMask = (PFNGLDEPTHMASKPROC)get_proc("glDepthMask"); gl3wDisable = (PFNGLDISABLEPROC)get_proc("glDisable"); gl3wEnable = (PFNGLENABLEPROC)get_proc("glEnable"); gl3wFinish = (PFNGLFINISHPROC)get_proc("glFinish"); gl3wFlush = (PFNGLFLUSHPROC)get_proc("glFlush"); gl3wBlendFunc = (PFNGLBLENDFUNCPROC)get_proc("glBlendFunc"); gl3wLogicOp = (PFNGLLOGICOPPROC)get_proc("glLogicOp"); gl3wStencilFunc = (PFNGLSTENCILFUNCPROC)get_proc("glStencilFunc"); gl3wStencilOp = (PFNGLSTENCILOPPROC)get_proc("glStencilOp"); gl3wDepthFunc = (PFNGLDEPTHFUNCPROC)get_proc("glDepthFunc"); gl3wPixelStoref = (PFNGLPIXELSTOREFPROC)get_proc("glPixelStoref"); gl3wPixelStorei = (PFNGLPIXELSTOREIPROC)get_proc("glPixelStorei"); gl3wReadBuffer = (PFNGLREADBUFFERPROC)get_proc("glReadBuffer"); gl3wReadPixels = (PFNGLREADPIXELSPROC)get_proc("glReadPixels"); gl3wGetBooleanv = (PFNGLGETBOOLEANVPROC)get_proc("glGetBooleanv"); gl3wGetDoublev = (PFNGLGETDOUBLEVPROC)get_proc("glGetDoublev"); gl3wGetError = (PFNGLGETERRORPROC)get_proc("glGetError"); gl3wGetFloatv = (PFNGLGETFLOATVPROC)get_proc("glGetFloatv"); gl3wGetIntegerv = (PFNGLGETINTEGERVPROC)get_proc("glGetIntegerv"); gl3wGetString = (PFNGLGETSTRINGPROC)get_proc("glGetString"); gl3wGetTexImage = (PFNGLGETTEXIMAGEPROC)get_proc("glGetTexImage"); gl3wGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)get_proc("glGetTexParameterfv"); gl3wGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)get_proc("glGetTexParameteriv"); gl3wGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)get_proc("glGetTexLevelParameterfv"); gl3wGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)get_proc("glGetTexLevelParameteriv"); gl3wIsEnabled = (PFNGLISENABLEDPROC)get_proc("glIsEnabled"); gl3wDepthRange = (PFNGLDEPTHRANGEPROC)get_proc("glDepthRange"); gl3wViewport = (PFNGLVIEWPORTPROC)get_proc("glViewport"); gl3wDrawArrays = (PFNGLDRAWARRAYSPROC)get_proc("glDrawArrays"); gl3wDrawElements = (PFNGLDRAWELEMENTSPROC)get_proc("glDrawElements"); gl3wGetPointerv = (PFNGLGETPOINTERVPROC)get_proc("glGetPointerv"); gl3wPolygonOffset = (PFNGLPOLYGONOFFSETPROC)get_proc("glPolygonOffset"); gl3wCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)get_proc("glCopyTexImage1D"); gl3wCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)get_proc("glCopyTexImage2D"); gl3wCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)get_proc("glCopyTexSubImage1D"); gl3wCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)get_proc("glCopyTexSubImage2D"); gl3wTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)get_proc("glTexSubImage1D"); gl3wTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)get_proc("glTexSubImage2D"); gl3wBindTexture = (PFNGLBINDTEXTUREPROC)get_proc("glBindTexture"); gl3wDeleteTextures = (PFNGLDELETETEXTURESPROC)get_proc("glDeleteTextures"); gl3wGenTextures = (PFNGLGENTEXTURESPROC)get_proc("glGenTextures"); gl3wIsTexture = (PFNGLISTEXTUREPROC)get_proc("glIsTexture"); gl3wBlendColor = (PFNGLBLENDCOLORPROC)get_proc("glBlendColor"); gl3wBlendEquation = (PFNGLBLENDEQUATIONPROC)get_proc("glBlendEquation"); gl3wDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)get_proc("glDrawRangeElements"); gl3wTexImage3D = (PFNGLTEXIMAGE3DPROC)get_proc("glTexImage3D"); gl3wTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)get_proc("glTexSubImage3D"); gl3wCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)get_proc("glCopyTexSubImage3D"); gl3wActiveTexture = (PFNGLACTIVETEXTUREPROC)get_proc("glActiveTexture"); gl3wSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)get_proc("glSampleCoverage"); gl3wCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)get_proc("glCompressedTexImage3D"); gl3wCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)get_proc("glCompressedTexImage2D"); gl3wCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)get_proc("glCompressedTexImage1D"); gl3wCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)get_proc("glCompressedTexSubImage3D"); gl3wCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)get_proc("glCompressedTexSubImage2D"); gl3wCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)get_proc("glCompressedTexSubImage1D"); gl3wGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)get_proc("glGetCompressedTexImage"); gl3wBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)get_proc("glBlendFuncSeparate"); gl3wMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)get_proc("glMultiDrawArrays"); gl3wMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)get_proc("glMultiDrawElements"); gl3wPointParameterf = (PFNGLPOINTPARAMETERFPROC)get_proc("glPointParameterf"); gl3wPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)get_proc("glPointParameterfv"); gl3wPointParameteri = (PFNGLPOINTPARAMETERIPROC)get_proc("glPointParameteri"); gl3wPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)get_proc("glPointParameteriv"); gl3wGenQueries = (PFNGLGENQUERIESPROC)get_proc("glGenQueries"); gl3wDeleteQueries = (PFNGLDELETEQUERIESPROC)get_proc("glDeleteQueries"); gl3wIsQuery = (PFNGLISQUERYPROC)get_proc("glIsQuery"); gl3wBeginQuery = (PFNGLBEGINQUERYPROC)get_proc("glBeginQuery"); gl3wEndQuery = (PFNGLENDQUERYPROC)get_proc("glEndQuery"); gl3wGetQueryiv = (PFNGLGETQUERYIVPROC)get_proc("glGetQueryiv"); gl3wGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)get_proc("glGetQueryObjectiv"); gl3wGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)get_proc("glGetQueryObjectuiv"); gl3wBindBuffer = (PFNGLBINDBUFFERPROC)get_proc("glBindBuffer"); gl3wDeleteBuffers = (PFNGLDELETEBUFFERSPROC)get_proc("glDeleteBuffers"); gl3wGenBuffers = (PFNGLGENBUFFERSPROC)get_proc("glGenBuffers"); gl3wIsBuffer = (PFNGLISBUFFERPROC)get_proc("glIsBuffer"); gl3wBufferData = (PFNGLBUFFERDATAPROC)get_proc("glBufferData"); gl3wBufferSubData = (PFNGLBUFFERSUBDATAPROC)get_proc("glBufferSubData"); gl3wGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)get_proc("glGetBufferSubData"); gl3wMapBuffer = (PFNGLMAPBUFFERPROC)get_proc("glMapBuffer"); gl3wUnmapBuffer = (PFNGLUNMAPBUFFERPROC)get_proc("glUnmapBuffer"); gl3wGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)get_proc("glGetBufferParameteriv"); gl3wGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)get_proc("glGetBufferPointerv"); gl3wBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)get_proc("glBlendEquationSeparate"); gl3wDrawBuffers = (PFNGLDRAWBUFFERSPROC)get_proc("glDrawBuffers"); gl3wStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)get_proc("glStencilOpSeparate"); gl3wStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)get_proc("glStencilFuncSeparate"); gl3wStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)get_proc("glStencilMaskSeparate"); gl3wAttachShader = (PFNGLATTACHSHADERPROC)get_proc("glAttachShader"); gl3wBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)get_proc("glBindAttribLocation"); gl3wCompileShader = (PFNGLCOMPILESHADERPROC)get_proc("glCompileShader"); gl3wCreateProgram = (PFNGLCREATEPROGRAMPROC)get_proc("glCreateProgram"); gl3wCreateShader = (PFNGLCREATESHADERPROC)get_proc("glCreateShader"); gl3wDeleteProgram = (PFNGLDELETEPROGRAMPROC)get_proc("glDeleteProgram"); gl3wDeleteShader = (PFNGLDELETESHADERPROC)get_proc("glDeleteShader"); gl3wDetachShader = (PFNGLDETACHSHADERPROC)get_proc("glDetachShader"); gl3wDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)get_proc( "glDisableVertexAttribArray"); gl3wEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)get_proc("glEnableVertexAttribArray"); gl3wGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)get_proc("glGetActiveAttrib"); gl3wGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)get_proc("glGetActiveUniform"); gl3wGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)get_proc("glGetAttachedShaders"); gl3wGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)get_proc("glGetAttribLocation"); gl3wGetProgramiv = (PFNGLGETPROGRAMIVPROC)get_proc("glGetProgramiv"); gl3wGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)get_proc("glGetProgramInfoLog"); gl3wGetShaderiv = (PFNGLGETSHADERIVPROC)get_proc("glGetShaderiv"); gl3wGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)get_proc("glGetShaderInfoLog"); gl3wGetShaderSource = (PFNGLGETSHADERSOURCEPROC)get_proc("glGetShaderSource"); gl3wGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)get_proc("glGetUniformLocation"); gl3wGetUniformfv = (PFNGLGETUNIFORMFVPROC)get_proc("glGetUniformfv"); gl3wGetUniformiv = (PFNGLGETUNIFORMIVPROC)get_proc("glGetUniformiv"); gl3wGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)get_proc("glGetVertexAttribdv"); gl3wGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)get_proc("glGetVertexAttribfv"); gl3wGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)get_proc("glGetVertexAttribiv"); gl3wGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)get_proc("glGetVertexAttribPointerv"); gl3wIsProgram = (PFNGLISPROGRAMPROC)get_proc("glIsProgram"); gl3wIsShader = (PFNGLISSHADERPROC)get_proc("glIsShader"); gl3wLinkProgram = (PFNGLLINKPROGRAMPROC)get_proc("glLinkProgram"); gl3wShaderSource = (PFNGLSHADERSOURCEPROC)get_proc("glShaderSource"); gl3wUseProgram = (PFNGLUSEPROGRAMPROC)get_proc("glUseProgram"); gl3wUniform1f = (PFNGLUNIFORM1FPROC)get_proc("glUniform1f"); gl3wUniform2f = (PFNGLUNIFORM2FPROC)get_proc("glUniform2f"); gl3wUniform3f = (PFNGLUNIFORM3FPROC)get_proc("glUniform3f"); gl3wUniform4f = (PFNGLUNIFORM4FPROC)get_proc("glUniform4f"); gl3wUniform1i = (PFNGLUNIFORM1IPROC)get_proc("glUniform1i"); gl3wUniform2i = (PFNGLUNIFORM2IPROC)get_proc("glUniform2i"); gl3wUniform3i = (PFNGLUNIFORM3IPROC)get_proc("glUniform3i"); gl3wUniform4i = (PFNGLUNIFORM4IPROC)get_proc("glUniform4i"); gl3wUniform1fv = (PFNGLUNIFORM1FVPROC)get_proc("glUniform1fv"); gl3wUniform2fv = (PFNGLUNIFORM2FVPROC)get_proc("glUniform2fv"); gl3wUniform3fv = (PFNGLUNIFORM3FVPROC)get_proc("glUniform3fv"); gl3wUniform4fv = (PFNGLUNIFORM4FVPROC)get_proc("glUniform4fv"); gl3wUniform1iv = (PFNGLUNIFORM1IVPROC)get_proc("glUniform1iv"); gl3wUniform2iv = (PFNGLUNIFORM2IVPROC)get_proc("glUniform2iv"); gl3wUniform3iv = (PFNGLUNIFORM3IVPROC)get_proc("glUniform3iv"); gl3wUniform4iv = (PFNGLUNIFORM4IVPROC)get_proc("glUniform4iv"); gl3wUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)get_proc("glUniformMatrix2fv"); gl3wUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)get_proc("glUniformMatrix3fv"); gl3wUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)get_proc("glUniformMatrix4fv"); gl3wValidateProgram = (PFNGLVALIDATEPROGRAMPROC)get_proc("glValidateProgram"); gl3wVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)get_proc("glVertexAttrib1d"); gl3wVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)get_proc("glVertexAttrib1dv"); gl3wVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)get_proc("glVertexAttrib1f"); gl3wVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)get_proc("glVertexAttrib1fv"); gl3wVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)get_proc("glVertexAttrib1s"); gl3wVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)get_proc("glVertexAttrib1sv"); gl3wVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)get_proc("glVertexAttrib2d"); gl3wVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)get_proc("glVertexAttrib2dv"); gl3wVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)get_proc("glVertexAttrib2f"); gl3wVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)get_proc("glVertexAttrib2fv"); gl3wVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)get_proc("glVertexAttrib2s"); gl3wVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)get_proc("glVertexAttrib2sv"); gl3wVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)get_proc("glVertexAttrib3d"); gl3wVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)get_proc("glVertexAttrib3dv"); gl3wVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)get_proc("glVertexAttrib3f"); gl3wVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)get_proc("glVertexAttrib3fv"); gl3wVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)get_proc("glVertexAttrib3s"); gl3wVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)get_proc("glVertexAttrib3sv"); gl3wVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)get_proc("glVertexAttrib4Nbv"); gl3wVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)get_proc("glVertexAttrib4Niv"); gl3wVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)get_proc("glVertexAttrib4Nsv"); gl3wVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)get_proc("glVertexAttrib4Nub"); gl3wVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)get_proc("glVertexAttrib4Nubv"); gl3wVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)get_proc("glVertexAttrib4Nuiv"); gl3wVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)get_proc("glVertexAttrib4Nusv"); gl3wVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)get_proc("glVertexAttrib4bv"); gl3wVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)get_proc("glVertexAttrib4d"); gl3wVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)get_proc("glVertexAttrib4dv"); gl3wVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)get_proc("glVertexAttrib4f"); gl3wVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)get_proc("glVertexAttrib4fv"); gl3wVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)get_proc("glVertexAttrib4iv"); gl3wVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)get_proc("glVertexAttrib4s"); gl3wVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)get_proc("glVertexAttrib4sv"); gl3wVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)get_proc("glVertexAttrib4ubv"); gl3wVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)get_proc("glVertexAttrib4uiv"); gl3wVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)get_proc("glVertexAttrib4usv"); gl3wVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)get_proc("glVertexAttribPointer"); gl3wUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)get_proc("glUniformMatrix2x3fv"); gl3wUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)get_proc("glUniformMatrix3x2fv"); gl3wUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)get_proc("glUniformMatrix2x4fv"); gl3wUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)get_proc("glUniformMatrix4x2fv"); gl3wUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)get_proc("glUniformMatrix3x4fv"); gl3wUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)get_proc("glUniformMatrix4x3fv"); gl3wColorMaski = (PFNGLCOLORMASKIPROC)get_proc("glColorMaski"); gl3wGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)get_proc("glGetBooleani_v"); gl3wGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)get_proc("glGetIntegeri_v"); gl3wEnablei = (PFNGLENABLEIPROC)get_proc("glEnablei"); gl3wDisablei = (PFNGLDISABLEIPROC)get_proc("glDisablei"); gl3wIsEnabledi = (PFNGLISENABLEDIPROC)get_proc("glIsEnabledi"); gl3wBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)get_proc("glBeginTransformFeedback"); gl3wEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)get_proc("glEndTransformFeedback"); gl3wBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)get_proc("glBindBufferRange"); gl3wBindBufferBase = (PFNGLBINDBUFFERBASEPROC)get_proc("glBindBufferBase"); gl3wTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)get_proc( "glTransformFeedbackVaryings"); gl3wGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)get_proc( "glGetTransformFeedbackVarying"); gl3wClampColor = (PFNGLCLAMPCOLORPROC)get_proc("glClampColor"); gl3wBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)get_proc("glBeginConditionalRender"); gl3wEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)get_proc("glEndConditionalRender"); gl3wVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)get_proc("glVertexAttribIPointer"); gl3wGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)get_proc("glGetVertexAttribIiv"); gl3wGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)get_proc("glGetVertexAttribIuiv"); gl3wVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)get_proc("glVertexAttribI1i"); gl3wVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)get_proc("glVertexAttribI2i"); gl3wVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)get_proc("glVertexAttribI3i"); gl3wVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)get_proc("glVertexAttribI4i"); gl3wVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)get_proc("glVertexAttribI1ui"); gl3wVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)get_proc("glVertexAttribI2ui"); gl3wVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)get_proc("glVertexAttribI3ui"); gl3wVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)get_proc("glVertexAttribI4ui"); gl3wVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)get_proc("glVertexAttribI1iv"); gl3wVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)get_proc("glVertexAttribI2iv"); gl3wVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)get_proc("glVertexAttribI3iv"); gl3wVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)get_proc("glVertexAttribI4iv"); gl3wVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)get_proc("glVertexAttribI1uiv"); gl3wVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)get_proc("glVertexAttribI2uiv"); gl3wVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)get_proc("glVertexAttribI3uiv"); gl3wVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)get_proc("glVertexAttribI4uiv"); gl3wVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)get_proc("glVertexAttribI4bv"); gl3wVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)get_proc("glVertexAttribI4sv"); gl3wVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)get_proc("glVertexAttribI4ubv"); gl3wVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)get_proc("glVertexAttribI4usv"); gl3wGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)get_proc("glGetUniformuiv"); gl3wBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)get_proc("glBindFragDataLocation"); gl3wGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)get_proc("glGetFragDataLocation"); gl3wUniform1ui = (PFNGLUNIFORM1UIPROC)get_proc("glUniform1ui"); gl3wUniform2ui = (PFNGLUNIFORM2UIPROC)get_proc("glUniform2ui"); gl3wUniform3ui = (PFNGLUNIFORM3UIPROC)get_proc("glUniform3ui"); gl3wUniform4ui = (PFNGLUNIFORM4UIPROC)get_proc("glUniform4ui"); gl3wUniform1uiv = (PFNGLUNIFORM1UIVPROC)get_proc("glUniform1uiv"); gl3wUniform2uiv = (PFNGLUNIFORM2UIVPROC)get_proc("glUniform2uiv"); gl3wUniform3uiv = (PFNGLUNIFORM3UIVPROC)get_proc("glUniform3uiv"); gl3wUniform4uiv = (PFNGLUNIFORM4UIVPROC)get_proc("glUniform4uiv"); gl3wTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)get_proc("glTexParameterIiv"); gl3wTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)get_proc("glTexParameterIuiv"); gl3wGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)get_proc("glGetTexParameterIiv"); gl3wGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)get_proc("glGetTexParameterIuiv"); gl3wClearBufferiv = (PFNGLCLEARBUFFERIVPROC)get_proc("glClearBufferiv"); gl3wClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)get_proc("glClearBufferuiv"); gl3wClearBufferfv = (PFNGLCLEARBUFFERFVPROC)get_proc("glClearBufferfv"); gl3wClearBufferfi = (PFNGLCLEARBUFFERFIPROC)get_proc("glClearBufferfi"); gl3wGetStringi = (PFNGLGETSTRINGIPROC)get_proc("glGetStringi"); gl3wDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)get_proc("glDrawArraysInstanced"); gl3wDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)get_proc("glDrawElementsInstanced"); gl3wTexBuffer = (PFNGLTEXBUFFERPROC)get_proc("glTexBuffer"); gl3wPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)get_proc("glPrimitiveRestartIndex"); gl3wGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)get_proc("glGetInteger64i_v"); gl3wGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)get_proc("glGetBufferParameteri64v"); gl3wFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)get_proc("glFramebufferTexture"); gl3wVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)get_proc("glVertexAttribDivisor"); gl3wMinSampleShading = (PFNGLMINSAMPLESHADINGPROC)get_proc("glMinSampleShading"); gl3wBlendEquationi = (PFNGLBLENDEQUATIONIPROC)get_proc("glBlendEquationi"); gl3wBlendEquationSeparatei = (PFNGLBLENDEQUATIONSEPARATEIPROC)get_proc("glBlendEquationSeparatei"); gl3wBlendFunci = (PFNGLBLENDFUNCIPROC)get_proc("glBlendFunci"); gl3wBlendFuncSeparatei = (PFNGLBLENDFUNCSEPARATEIPROC)get_proc("glBlendFuncSeparatei"); gl3wIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)get_proc("glIsRenderbuffer"); gl3wBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)get_proc("glBindRenderbuffer"); gl3wDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)get_proc("glDeleteRenderbuffers"); gl3wGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)get_proc("glGenRenderbuffers"); gl3wRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)get_proc("glRenderbufferStorage"); gl3wGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)get_proc( "glGetRenderbufferParameteriv"); gl3wIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)get_proc("glIsFramebuffer"); gl3wBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)get_proc("glBindFramebuffer"); gl3wDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)get_proc("glDeleteFramebuffers"); gl3wGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)get_proc("glGenFramebuffers"); gl3wCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)get_proc("glCheckFramebufferStatus"); gl3wFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)get_proc("glFramebufferTexture1D"); gl3wFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)get_proc("glFramebufferTexture2D"); gl3wFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)get_proc("glFramebufferTexture3D"); gl3wFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)get_proc("glFramebufferRenderbuffer"); gl3wGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)get_proc( "glGetFramebufferAttachmentParameteriv"); gl3wGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)get_proc("glGenerateMipmap"); gl3wBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)get_proc("glBlitFramebuffer"); gl3wRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)get_proc( "glRenderbufferStorageMultisample"); gl3wFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)get_proc("glFramebufferTextureLayer"); gl3wMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)get_proc("glMapBufferRange"); gl3wFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)get_proc("glFlushMappedBufferRange"); gl3wBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)get_proc("glBindVertexArray"); gl3wDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)get_proc("glDeleteVertexArrays"); gl3wGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)get_proc("glGenVertexArrays"); gl3wIsVertexArray = (PFNGLISVERTEXARRAYPROC)get_proc("glIsVertexArray"); gl3wGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)get_proc("glGetUniformIndices"); gl3wGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)get_proc("glGetActiveUniformsiv"); gl3wGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)get_proc("glGetActiveUniformName"); gl3wGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)get_proc("glGetUniformBlockIndex"); gl3wGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)get_proc("glGetActiveUniformBlockiv"); gl3wGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)get_proc( "glGetActiveUniformBlockName"); gl3wUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)get_proc("glUniformBlockBinding"); gl3wCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)get_proc("glCopyBufferSubData"); gl3wDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)get_proc("glDrawElementsBaseVertex"); gl3wDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)get_proc( "glDrawRangeElementsBaseVertex"); gl3wDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)get_proc( "glDrawElementsInstancedBaseVertex"); gl3wMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)get_proc( "glMultiDrawElementsBaseVertex"); gl3wProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)get_proc("glProvokingVertex"); gl3wFenceSync = (PFNGLFENCESYNCPROC)get_proc("glFenceSync"); gl3wIsSync = (PFNGLISSYNCPROC)get_proc("glIsSync"); gl3wDeleteSync = (PFNGLDELETESYNCPROC)get_proc("glDeleteSync"); gl3wClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)get_proc("glClientWaitSync"); gl3wWaitSync = (PFNGLWAITSYNCPROC)get_proc("glWaitSync"); gl3wGetInteger64v = (PFNGLGETINTEGER64VPROC)get_proc("glGetInteger64v"); gl3wGetSynciv = (PFNGLGETSYNCIVPROC)get_proc("glGetSynciv"); gl3wTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)get_proc("glTexImage2DMultisample"); gl3wTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)get_proc("glTexImage3DMultisample"); gl3wGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)get_proc("glGetMultisamplefv"); gl3wSampleMaski = (PFNGLSAMPLEMASKIPROC)get_proc("glSampleMaski"); gl3wBlendEquationiARB = (PFNGLBLENDEQUATIONIARBPROC)get_proc("glBlendEquationiARB"); gl3wBlendEquationSeparateiARB = (PFNGLBLENDEQUATIONSEPARATEIARBPROC)get_proc( "glBlendEquationSeparateiARB"); gl3wBlendFunciARB = (PFNGLBLENDFUNCIARBPROC)get_proc("glBlendFunciARB"); gl3wBlendFuncSeparateiARB = (PFNGLBLENDFUNCSEPARATEIARBPROC)get_proc("glBlendFuncSeparateiARB"); gl3wMinSampleShadingARB = (PFNGLMINSAMPLESHADINGARBPROC)get_proc("glMinSampleShadingARB"); gl3wNamedStringARB = (PFNGLNAMEDSTRINGARBPROC)get_proc("glNamedStringARB"); gl3wDeleteNamedStringARB = (PFNGLDELETENAMEDSTRINGARBPROC)get_proc("glDeleteNamedStringARB"); gl3wCompileShaderIncludeARB = (PFNGLCOMPILESHADERINCLUDEARBPROC)get_proc("glCompileShaderIncludeARB"); gl3wIsNamedStringARB = (PFNGLISNAMEDSTRINGARBPROC)get_proc("glIsNamedStringARB"); gl3wGetNamedStringARB = (PFNGLGETNAMEDSTRINGARBPROC)get_proc("glGetNamedStringARB"); gl3wGetNamedStringivARB = (PFNGLGETNAMEDSTRINGIVARBPROC)get_proc("glGetNamedStringivARB"); gl3wBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)get_proc( "glBindFragDataLocationIndexed"); gl3wGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)get_proc("glGetFragDataIndex"); gl3wGenSamplers = (PFNGLGENSAMPLERSPROC)get_proc("glGenSamplers"); gl3wDeleteSamplers = (PFNGLDELETESAMPLERSPROC)get_proc("glDeleteSamplers"); gl3wIsSampler = (PFNGLISSAMPLERPROC)get_proc("glIsSampler"); gl3wBindSampler = (PFNGLBINDSAMPLERPROC)get_proc("glBindSampler"); gl3wSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)get_proc("glSamplerParameteri"); gl3wSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)get_proc("glSamplerParameteriv"); gl3wSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)get_proc("glSamplerParameterf"); gl3wSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)get_proc("glSamplerParameterfv"); gl3wSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)get_proc("glSamplerParameterIiv"); gl3wSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)get_proc("glSamplerParameterIuiv"); gl3wGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)get_proc("glGetSamplerParameteriv"); gl3wGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)get_proc("glGetSamplerParameterIiv"); gl3wGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)get_proc("glGetSamplerParameterfv"); gl3wGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)get_proc("glGetSamplerParameterIuiv"); gl3wQueryCounter = (PFNGLQUERYCOUNTERPROC)get_proc("glQueryCounter"); gl3wGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)get_proc("glGetQueryObjecti64v"); gl3wGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)get_proc("glGetQueryObjectui64v"); gl3wVertexP2ui = (PFNGLVERTEXP2UIPROC)get_proc("glVertexP2ui"); gl3wVertexP2uiv = (PFNGLVERTEXP2UIVPROC)get_proc("glVertexP2uiv"); gl3wVertexP3ui = (PFNGLVERTEXP3UIPROC)get_proc("glVertexP3ui"); gl3wVertexP3uiv = (PFNGLVERTEXP3UIVPROC)get_proc("glVertexP3uiv"); gl3wVertexP4ui = (PFNGLVERTEXP4UIPROC)get_proc("glVertexP4ui"); gl3wVertexP4uiv = (PFNGLVERTEXP4UIVPROC)get_proc("glVertexP4uiv"); gl3wTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)get_proc("glTexCoordP1ui"); gl3wTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)get_proc("glTexCoordP1uiv"); gl3wTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)get_proc("glTexCoordP2ui"); gl3wTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)get_proc("glTexCoordP2uiv"); gl3wTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)get_proc("glTexCoordP3ui"); gl3wTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)get_proc("glTexCoordP3uiv"); gl3wTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)get_proc("glTexCoordP4ui"); gl3wTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)get_proc("glTexCoordP4uiv"); gl3wMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)get_proc("glMultiTexCoordP1ui"); gl3wMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)get_proc("glMultiTexCoordP1uiv"); gl3wMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)get_proc("glMultiTexCoordP2ui"); gl3wMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)get_proc("glMultiTexCoordP2uiv"); gl3wMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)get_proc("glMultiTexCoordP3ui"); gl3wMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)get_proc("glMultiTexCoordP3uiv"); gl3wMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)get_proc("glMultiTexCoordP4ui"); gl3wMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)get_proc("glMultiTexCoordP4uiv"); gl3wNormalP3ui = (PFNGLNORMALP3UIPROC)get_proc("glNormalP3ui"); gl3wNormalP3uiv = (PFNGLNORMALP3UIVPROC)get_proc("glNormalP3uiv"); gl3wColorP3ui = (PFNGLCOLORP3UIPROC)get_proc("glColorP3ui"); gl3wColorP3uiv = (PFNGLCOLORP3UIVPROC)get_proc("glColorP3uiv"); gl3wColorP4ui = (PFNGLCOLORP4UIPROC)get_proc("glColorP4ui"); gl3wColorP4uiv = (PFNGLCOLORP4UIVPROC)get_proc("glColorP4uiv"); gl3wSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)get_proc("glSecondaryColorP3ui"); gl3wSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)get_proc("glSecondaryColorP3uiv"); gl3wVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)get_proc("glVertexAttribP1ui"); gl3wVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)get_proc("glVertexAttribP1uiv"); gl3wVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)get_proc("glVertexAttribP2ui"); gl3wVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)get_proc("glVertexAttribP2uiv"); gl3wVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)get_proc("glVertexAttribP3ui"); gl3wVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)get_proc("glVertexAttribP3uiv"); gl3wVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)get_proc("glVertexAttribP4ui"); gl3wVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)get_proc("glVertexAttribP4uiv"); gl3wDrawArraysIndirect = (PFNGLDRAWARRAYSINDIRECTPROC)get_proc("glDrawArraysIndirect"); gl3wDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC)get_proc("glDrawElementsIndirect"); gl3wUniform1d = (PFNGLUNIFORM1DPROC)get_proc("glUniform1d"); gl3wUniform2d = (PFNGLUNIFORM2DPROC)get_proc("glUniform2d"); gl3wUniform3d = (PFNGLUNIFORM3DPROC)get_proc("glUniform3d"); gl3wUniform4d = (PFNGLUNIFORM4DPROC)get_proc("glUniform4d"); gl3wUniform1dv = (PFNGLUNIFORM1DVPROC)get_proc("glUniform1dv"); gl3wUniform2dv = (PFNGLUNIFORM2DVPROC)get_proc("glUniform2dv"); gl3wUniform3dv = (PFNGLUNIFORM3DVPROC)get_proc("glUniform3dv"); gl3wUniform4dv = (PFNGLUNIFORM4DVPROC)get_proc("glUniform4dv"); gl3wUniformMatrix2dv = (PFNGLUNIFORMMATRIX2DVPROC)get_proc("glUniformMatrix2dv"); gl3wUniformMatrix3dv = (PFNGLUNIFORMMATRIX3DVPROC)get_proc("glUniformMatrix3dv"); gl3wUniformMatrix4dv = (PFNGLUNIFORMMATRIX4DVPROC)get_proc("glUniformMatrix4dv"); gl3wUniformMatrix2x3dv = (PFNGLUNIFORMMATRIX2X3DVPROC)get_proc("glUniformMatrix2x3dv"); gl3wUniformMatrix2x4dv = (PFNGLUNIFORMMATRIX2X4DVPROC)get_proc("glUniformMatrix2x4dv"); gl3wUniformMatrix3x2dv = (PFNGLUNIFORMMATRIX3X2DVPROC)get_proc("glUniformMatrix3x2dv"); gl3wUniformMatrix3x4dv = (PFNGLUNIFORMMATRIX3X4DVPROC)get_proc("glUniformMatrix3x4dv"); gl3wUniformMatrix4x2dv = (PFNGLUNIFORMMATRIX4X2DVPROC)get_proc("glUniformMatrix4x2dv"); gl3wUniformMatrix4x3dv = (PFNGLUNIFORMMATRIX4X3DVPROC)get_proc("glUniformMatrix4x3dv"); gl3wGetUniformdv = (PFNGLGETUNIFORMDVPROC)get_proc("glGetUniformdv"); gl3wGetSubroutineUniformLocation = (PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)get_proc( "glGetSubroutineUniformLocation"); gl3wGetSubroutineIndex = (PFNGLGETSUBROUTINEINDEXPROC)get_proc("glGetSubroutineIndex"); gl3wGetActiveSubroutineUniformiv = (PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)get_proc( "glGetActiveSubroutineUniformiv"); gl3wGetActiveSubroutineUniformName = (PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)get_proc( "glGetActiveSubroutineUniformName"); gl3wGetActiveSubroutineName = (PFNGLGETACTIVESUBROUTINENAMEPROC)get_proc("glGetActiveSubroutineName"); gl3wUniformSubroutinesuiv = (PFNGLUNIFORMSUBROUTINESUIVPROC)get_proc("glUniformSubroutinesuiv"); gl3wGetUniformSubroutineuiv = (PFNGLGETUNIFORMSUBROUTINEUIVPROC)get_proc("glGetUniformSubroutineuiv"); gl3wGetProgramStageiv = (PFNGLGETPROGRAMSTAGEIVPROC)get_proc("glGetProgramStageiv"); gl3wPatchParameteri = (PFNGLPATCHPARAMETERIPROC)get_proc("glPatchParameteri"); gl3wPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)get_proc("glPatchParameterfv"); gl3wBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)get_proc("glBindTransformFeedback"); gl3wDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)get_proc( "glDeleteTransformFeedbacks"); gl3wGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)get_proc("glGenTransformFeedbacks"); gl3wIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)get_proc("glIsTransformFeedback"); gl3wPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)get_proc("glPauseTransformFeedback"); gl3wResumeTransformFeedback = (PFNGLRESUMETRANSFORMFEEDBACKPROC)get_proc("glResumeTransformFeedback"); gl3wDrawTransformFeedback = (PFNGLDRAWTRANSFORMFEEDBACKPROC)get_proc("glDrawTransformFeedback"); gl3wDrawTransformFeedbackStream = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)get_proc( "glDrawTransformFeedbackStream"); gl3wBeginQueryIndexed = (PFNGLBEGINQUERYINDEXEDPROC)get_proc("glBeginQueryIndexed"); gl3wEndQueryIndexed = (PFNGLENDQUERYINDEXEDPROC)get_proc("glEndQueryIndexed"); gl3wGetQueryIndexediv = (PFNGLGETQUERYINDEXEDIVPROC)get_proc("glGetQueryIndexediv"); gl3wReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)get_proc("glReleaseShaderCompiler"); gl3wShaderBinary = (PFNGLSHADERBINARYPROC)get_proc("glShaderBinary"); gl3wGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)get_proc( "glGetShaderPrecisionFormat"); gl3wDepthRangef = (PFNGLDEPTHRANGEFPROC)get_proc("glDepthRangef"); gl3wClearDepthf = (PFNGLCLEARDEPTHFPROC)get_proc("glClearDepthf"); gl3wGetProgramBinary = (PFNGLGETPROGRAMBINARYPROC)get_proc("glGetProgramBinary"); gl3wProgramBinary = (PFNGLPROGRAMBINARYPROC)get_proc("glProgramBinary"); gl3wProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)get_proc("glProgramParameteri"); gl3wUseProgramStages = (PFNGLUSEPROGRAMSTAGESPROC)get_proc("glUseProgramStages"); gl3wActiveShaderProgram = (PFNGLACTIVESHADERPROGRAMPROC)get_proc("glActiveShaderProgram"); gl3wCreateShaderProgramv = (PFNGLCREATESHADERPROGRAMVPROC)get_proc("glCreateShaderProgramv"); gl3wBindProgramPipeline = (PFNGLBINDPROGRAMPIPELINEPROC)get_proc("glBindProgramPipeline"); gl3wDeleteProgramPipelines = (PFNGLDELETEPROGRAMPIPELINESPROC)get_proc("glDeleteProgramPipelines"); gl3wGenProgramPipelines = (PFNGLGENPROGRAMPIPELINESPROC)get_proc("glGenProgramPipelines"); gl3wIsProgramPipeline = (PFNGLISPROGRAMPIPELINEPROC)get_proc("glIsProgramPipeline"); gl3wGetProgramPipelineiv = (PFNGLGETPROGRAMPIPELINEIVPROC)get_proc("glGetProgramPipelineiv"); gl3wProgramUniform1i = (PFNGLPROGRAMUNIFORM1IPROC)get_proc("glProgramUniform1i"); gl3wProgramUniform1iv = (PFNGLPROGRAMUNIFORM1IVPROC)get_proc("glProgramUniform1iv"); gl3wProgramUniform1f = (PFNGLPROGRAMUNIFORM1FPROC)get_proc("glProgramUniform1f"); gl3wProgramUniform1fv = (PFNGLPROGRAMUNIFORM1FVPROC)get_proc("glProgramUniform1fv"); gl3wProgramUniform1d = (PFNGLPROGRAMUNIFORM1DPROC)get_proc("glProgramUniform1d"); gl3wProgramUniform1dv = (PFNGLPROGRAMUNIFORM1DVPROC)get_proc("glProgramUniform1dv"); gl3wProgramUniform1ui = (PFNGLPROGRAMUNIFORM1UIPROC)get_proc("glProgramUniform1ui"); gl3wProgramUniform1uiv = (PFNGLPROGRAMUNIFORM1UIVPROC)get_proc("glProgramUniform1uiv"); gl3wProgramUniform2i = (PFNGLPROGRAMUNIFORM2IPROC)get_proc("glProgramUniform2i"); gl3wProgramUniform2iv = (PFNGLPROGRAMUNIFORM2IVPROC)get_proc("glProgramUniform2iv"); gl3wProgramUniform2f = (PFNGLPROGRAMUNIFORM2FPROC)get_proc("glProgramUniform2f"); gl3wProgramUniform2fv = (PFNGLPROGRAMUNIFORM2FVPROC)get_proc("glProgramUniform2fv"); gl3wProgramUniform2d = (PFNGLPROGRAMUNIFORM2DPROC)get_proc("glProgramUniform2d"); gl3wProgramUniform2dv = (PFNGLPROGRAMUNIFORM2DVPROC)get_proc("glProgramUniform2dv"); gl3wProgramUniform2ui = (PFNGLPROGRAMUNIFORM2UIPROC)get_proc("glProgramUniform2ui"); gl3wProgramUniform2uiv = (PFNGLPROGRAMUNIFORM2UIVPROC)get_proc("glProgramUniform2uiv"); gl3wProgramUniform3i = (PFNGLPROGRAMUNIFORM3IPROC)get_proc("glProgramUniform3i"); gl3wProgramUniform3iv = (PFNGLPROGRAMUNIFORM3IVPROC)get_proc("glProgramUniform3iv"); gl3wProgramUniform3f = (PFNGLPROGRAMUNIFORM3FPROC)get_proc("glProgramUniform3f"); gl3wProgramUniform3fv = (PFNGLPROGRAMUNIFORM3FVPROC)get_proc("glProgramUniform3fv"); gl3wProgramUniform3d = (PFNGLPROGRAMUNIFORM3DPROC)get_proc("glProgramUniform3d"); gl3wProgramUniform3dv = (PFNGLPROGRAMUNIFORM3DVPROC)get_proc("glProgramUniform3dv"); gl3wProgramUniform3ui = (PFNGLPROGRAMUNIFORM3UIPROC)get_proc("glProgramUniform3ui"); gl3wProgramUniform3uiv = (PFNGLPROGRAMUNIFORM3UIVPROC)get_proc("glProgramUniform3uiv"); gl3wProgramUniform4i = (PFNGLPROGRAMUNIFORM4IPROC)get_proc("glProgramUniform4i"); gl3wProgramUniform4iv = (PFNGLPROGRAMUNIFORM4IVPROC)get_proc("glProgramUniform4iv"); gl3wProgramUniform4f = (PFNGLPROGRAMUNIFORM4FPROC)get_proc("glProgramUniform4f"); gl3wProgramUniform4fv = (PFNGLPROGRAMUNIFORM4FVPROC)get_proc("glProgramUniform4fv"); gl3wProgramUniform4d = (PFNGLPROGRAMUNIFORM4DPROC)get_proc("glProgramUniform4d"); gl3wProgramUniform4dv = (PFNGLPROGRAMUNIFORM4DVPROC)get_proc("glProgramUniform4dv"); gl3wProgramUniform4ui = (PFNGLPROGRAMUNIFORM4UIPROC)get_proc("glProgramUniform4ui"); gl3wProgramUniform4uiv = (PFNGLPROGRAMUNIFORM4UIVPROC)get_proc("glProgramUniform4uiv"); gl3wProgramUniformMatrix2fv = (PFNGLPROGRAMUNIFORMMATRIX2FVPROC)get_proc("glProgramUniformMatrix2fv"); gl3wProgramUniformMatrix3fv = (PFNGLPROGRAMUNIFORMMATRIX3FVPROC)get_proc("glProgramUniformMatrix3fv"); gl3wProgramUniformMatrix4fv = (PFNGLPROGRAMUNIFORMMATRIX4FVPROC)get_proc("glProgramUniformMatrix4fv"); gl3wProgramUniformMatrix2dv = (PFNGLPROGRAMUNIFORMMATRIX2DVPROC)get_proc("glProgramUniformMatrix2dv"); gl3wProgramUniformMatrix3dv = (PFNGLPROGRAMUNIFORMMATRIX3DVPROC)get_proc("glProgramUniformMatrix3dv"); gl3wProgramUniformMatrix4dv = (PFNGLPROGRAMUNIFORMMATRIX4DVPROC)get_proc("glProgramUniformMatrix4dv"); gl3wProgramUniformMatrix2x3fv = (PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC)get_proc( "glProgramUniformMatrix2x3fv"); gl3wProgramUniformMatrix3x2fv = (PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC)get_proc( "glProgramUniformMatrix3x2fv"); gl3wProgramUniformMatrix2x4fv = (PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC)get_proc( "glProgramUniformMatrix2x4fv"); gl3wProgramUniformMatrix4x2fv = (PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC)get_proc( "glProgramUniformMatrix4x2fv"); gl3wProgramUniformMatrix3x4fv = (PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC)get_proc( "glProgramUniformMatrix3x4fv"); gl3wProgramUniformMatrix4x3fv = (PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC)get_proc( "glProgramUniformMatrix4x3fv"); gl3wProgramUniformMatrix2x3dv = (PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC)get_proc( "glProgramUniformMatrix2x3dv"); gl3wProgramUniformMatrix3x2dv = (PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC)get_proc( "glProgramUniformMatrix3x2dv"); gl3wProgramUniformMatrix2x4dv = (PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC)get_proc( "glProgramUniformMatrix2x4dv"); gl3wProgramUniformMatrix4x2dv = (PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC)get_proc( "glProgramUniformMatrix4x2dv"); gl3wProgramUniformMatrix3x4dv = (PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC)get_proc( "glProgramUniformMatrix3x4dv"); gl3wProgramUniformMatrix4x3dv = (PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC)get_proc( "glProgramUniformMatrix4x3dv"); gl3wValidateProgramPipeline = (PFNGLVALIDATEPROGRAMPIPELINEPROC)get_proc("glValidateProgramPipeline"); gl3wGetProgramPipelineInfoLog = (PFNGLGETPROGRAMPIPELINEINFOLOGPROC)get_proc( "glGetProgramPipelineInfoLog"); gl3wVertexAttribL1d = (PFNGLVERTEXATTRIBL1DPROC)get_proc("glVertexAttribL1d"); gl3wVertexAttribL2d = (PFNGLVERTEXATTRIBL2DPROC)get_proc("glVertexAttribL2d"); gl3wVertexAttribL3d = (PFNGLVERTEXATTRIBL3DPROC)get_proc("glVertexAttribL3d"); gl3wVertexAttribL4d = (PFNGLVERTEXATTRIBL4DPROC)get_proc("glVertexAttribL4d"); gl3wVertexAttribL1dv = (PFNGLVERTEXATTRIBL1DVPROC)get_proc("glVertexAttribL1dv"); gl3wVertexAttribL2dv = (PFNGLVERTEXATTRIBL2DVPROC)get_proc("glVertexAttribL2dv"); gl3wVertexAttribL3dv = (PFNGLVERTEXATTRIBL3DVPROC)get_proc("glVertexAttribL3dv"); gl3wVertexAttribL4dv = (PFNGLVERTEXATTRIBL4DVPROC)get_proc("glVertexAttribL4dv"); gl3wVertexAttribLPointer = (PFNGLVERTEXATTRIBLPOINTERPROC)get_proc("glVertexAttribLPointer"); gl3wGetVertexAttribLdv = (PFNGLGETVERTEXATTRIBLDVPROC)get_proc("glGetVertexAttribLdv"); gl3wViewportArrayv = (PFNGLVIEWPORTARRAYVPROC)get_proc("glViewportArrayv"); gl3wViewportIndexedf = (PFNGLVIEWPORTINDEXEDFPROC)get_proc("glViewportIndexedf"); gl3wViewportIndexedfv = (PFNGLVIEWPORTINDEXEDFVPROC)get_proc("glViewportIndexedfv"); gl3wScissorArrayv = (PFNGLSCISSORARRAYVPROC)get_proc("glScissorArrayv"); gl3wScissorIndexed = (PFNGLSCISSORINDEXEDPROC)get_proc("glScissorIndexed"); gl3wScissorIndexedv = (PFNGLSCISSORINDEXEDVPROC)get_proc("glScissorIndexedv"); gl3wDepthRangeArrayv = (PFNGLDEPTHRANGEARRAYVPROC)get_proc("glDepthRangeArrayv"); gl3wDepthRangeIndexed = (PFNGLDEPTHRANGEINDEXEDPROC)get_proc("glDepthRangeIndexed"); gl3wGetFloati_v = (PFNGLGETFLOATI_VPROC)get_proc("glGetFloati_v"); gl3wGetDoublei_v = (PFNGLGETDOUBLEI_VPROC)get_proc("glGetDoublei_v"); gl3wCreateSyncFromCLeventARB = (PFNGLCREATESYNCFROMCLEVENTARBPROC)get_proc( "glCreateSyncFromCLeventARB"); gl3wDebugMessageControlARB = (PFNGLDEBUGMESSAGECONTROLARBPROC)get_proc("glDebugMessageControlARB"); gl3wDebugMessageInsertARB = (PFNGLDEBUGMESSAGEINSERTARBPROC)get_proc("glDebugMessageInsertARB"); gl3wDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC)get_proc("glDebugMessageCallbackARB"); gl3wGetDebugMessageLogARB = (PFNGLGETDEBUGMESSAGELOGARBPROC)get_proc("glGetDebugMessageLogARB"); gl3wGetGraphicsResetStatusARB = (PFNGLGETGRAPHICSRESETSTATUSARBPROC)get_proc( "glGetGraphicsResetStatusARB"); gl3wGetnTexImageARB = (PFNGLGETNTEXIMAGEARBPROC)get_proc("glGetnTexImageARB"); gl3wReadnPixelsARB = (PFNGLREADNPIXELSARBPROC)get_proc("glReadnPixelsARB"); gl3wGetnCompressedTexImageARB = (PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC)get_proc( "glGetnCompressedTexImageARB"); gl3wGetnUniformfvARB = (PFNGLGETNUNIFORMFVARBPROC)get_proc("glGetnUniformfvARB"); gl3wGetnUniformivARB = (PFNGLGETNUNIFORMIVARBPROC)get_proc("glGetnUniformivARB"); gl3wGetnUniformuivARB = (PFNGLGETNUNIFORMUIVARBPROC)get_proc("glGetnUniformuivARB"); gl3wGetnUniformdvARB = (PFNGLGETNUNIFORMDVARBPROC)get_proc("glGetnUniformdvARB"); gl3wDrawArraysInstancedBaseInstance = (PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)get_proc( "glDrawArraysInstancedBaseInstance"); gl3wDrawElementsInstancedBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)get_proc( "glDrawElementsInstancedBaseInstance"); gl3wDrawElementsInstancedBaseVertexBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)get_proc( "glDrawElementsInstancedBaseVertexBaseInstance"); gl3wDrawTransformFeedbackInstanced = (PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC)get_proc( "glDrawTransformFeedbackInstanced"); gl3wDrawTransformFeedbackStreamInstanced = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC)get_proc( "glDrawTransformFeedbackStreamInstanced"); gl3wGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC)get_proc("glGetInternalformativ"); gl3wGetActiveAtomicCounterBufferiv = (PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC)get_proc( "glGetActiveAtomicCounterBufferiv"); gl3wBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)get_proc("glBindImageTexture"); gl3wMemoryBarrier = (PFNGLMEMORYBARRIERPROC)get_proc("glMemoryBarrier"); gl3wTexStorage1D = (PFNGLTEXSTORAGE1DPROC)get_proc("glTexStorage1D"); gl3wTexStorage2D = (PFNGLTEXSTORAGE2DPROC)get_proc("glTexStorage2D"); gl3wTexStorage3D = (PFNGLTEXSTORAGE3DPROC)get_proc("glTexStorage3D"); gl3wTextureStorage1DEXT = (PFNGLTEXTURESTORAGE1DEXTPROC)get_proc("glTextureStorage1DEXT"); gl3wTextureStorage2DEXT = (PFNGLTEXTURESTORAGE2DEXTPROC)get_proc("glTextureStorage2DEXT"); gl3wTextureStorage3DEXT = (PFNGLTEXTURESTORAGE3DEXTPROC)get_proc("glTextureStorage3DEXT"); gl3wDebugMessageControl = (PFNGLDEBUGMESSAGECONTROLPROC)get_proc("glDebugMessageControl"); gl3wDebugMessageInsert = (PFNGLDEBUGMESSAGEINSERTPROC)get_proc("glDebugMessageInsert"); gl3wDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)get_proc("glDebugMessageCallback"); gl3wGetDebugMessageLog = (PFNGLGETDEBUGMESSAGELOGPROC)get_proc("glGetDebugMessageLog"); gl3wPushDebugGroup = (PFNGLPUSHDEBUGGROUPPROC)get_proc("glPushDebugGroup"); gl3wPopDebugGroup = (PFNGLPOPDEBUGGROUPPROC)get_proc("glPopDebugGroup"); gl3wObjectLabel = (PFNGLOBJECTLABELPROC)get_proc("glObjectLabel"); gl3wGetObjectLabel = (PFNGLGETOBJECTLABELPROC)get_proc("glGetObjectLabel"); gl3wObjectPtrLabel = (PFNGLOBJECTPTRLABELPROC)get_proc("glObjectPtrLabel"); gl3wGetObjectPtrLabel = (PFNGLGETOBJECTPTRLABELPROC)get_proc("glGetObjectPtrLabel"); gl3wClearBufferData = (PFNGLCLEARBUFFERDATAPROC)get_proc("glClearBufferData"); gl3wClearBufferSubData = (PFNGLCLEARBUFFERSUBDATAPROC)get_proc("glClearBufferSubData"); gl3wClearNamedBufferDataEXT = (PFNGLCLEARNAMEDBUFFERDATAEXTPROC)get_proc("glClearNamedBufferDataEXT"); gl3wClearNamedBufferSubDataEXT = (PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC)get_proc( "glClearNamedBufferSubDataEXT"); gl3wDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)get_proc("glDispatchCompute"); gl3wDispatchComputeIndirect = (PFNGLDISPATCHCOMPUTEINDIRECTPROC)get_proc("glDispatchComputeIndirect"); gl3wCopyImageSubData = (PFNGLCOPYIMAGESUBDATAPROC)get_proc("glCopyImageSubData"); gl3wTextureView = (PFNGLTEXTUREVIEWPROC)get_proc("glTextureView"); gl3wBindVertexBuffer = (PFNGLBINDVERTEXBUFFERPROC)get_proc("glBindVertexBuffer"); gl3wVertexAttribFormat = (PFNGLVERTEXATTRIBFORMATPROC)get_proc("glVertexAttribFormat"); gl3wVertexAttribIFormat = (PFNGLVERTEXATTRIBIFORMATPROC)get_proc("glVertexAttribIFormat"); gl3wVertexAttribLFormat = (PFNGLVERTEXATTRIBLFORMATPROC)get_proc("glVertexAttribLFormat"); gl3wVertexAttribBinding = (PFNGLVERTEXATTRIBBINDINGPROC)get_proc("glVertexAttribBinding"); gl3wVertexBindingDivisor = (PFNGLVERTEXBINDINGDIVISORPROC)get_proc("glVertexBindingDivisor"); gl3wVertexArrayBindVertexBufferEXT = (PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC)get_proc( "glVertexArrayBindVertexBufferEXT"); gl3wVertexArrayVertexAttribFormatEXT = (PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC)get_proc( "glVertexArrayVertexAttribFormatEXT"); gl3wVertexArrayVertexAttribIFormatEXT = (PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC)get_proc( "glVertexArrayVertexAttribIFormatEXT"); gl3wVertexArrayVertexAttribLFormatEXT = (PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC)get_proc( "glVertexArrayVertexAttribLFormatEXT"); gl3wVertexArrayVertexAttribBindingEXT = (PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC)get_proc( "glVertexArrayVertexAttribBindingEXT"); gl3wVertexArrayVertexBindingDivisorEXT = (PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC)get_proc( "glVertexArrayVertexBindingDivisorEXT"); gl3wFramebufferParameteri = (PFNGLFRAMEBUFFERPARAMETERIPROC)get_proc("glFramebufferParameteri"); gl3wGetFramebufferParameteriv = (PFNGLGETFRAMEBUFFERPARAMETERIVPROC)get_proc( "glGetFramebufferParameteriv"); gl3wNamedFramebufferParameteriEXT = (PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC)get_proc( "glNamedFramebufferParameteriEXT"); gl3wGetNamedFramebufferParameterivEXT = (PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC)get_proc( "glGetNamedFramebufferParameterivEXT"); gl3wGetInternalformati64v = (PFNGLGETINTERNALFORMATI64VPROC)get_proc("glGetInternalformati64v"); gl3wInvalidateTexSubImage = (PFNGLINVALIDATETEXSUBIMAGEPROC)get_proc("glInvalidateTexSubImage"); gl3wInvalidateTexImage = (PFNGLINVALIDATETEXIMAGEPROC)get_proc("glInvalidateTexImage"); gl3wInvalidateBufferSubData = (PFNGLINVALIDATEBUFFERSUBDATAPROC)get_proc("glInvalidateBufferSubData"); gl3wInvalidateBufferData = (PFNGLINVALIDATEBUFFERDATAPROC)get_proc("glInvalidateBufferData"); gl3wInvalidateFramebuffer = (PFNGLINVALIDATEFRAMEBUFFERPROC)get_proc("glInvalidateFramebuffer"); gl3wInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)get_proc( "glInvalidateSubFramebuffer"); gl3wMultiDrawArraysIndirect = (PFNGLMULTIDRAWARRAYSINDIRECTPROC)get_proc("glMultiDrawArraysIndirect"); gl3wMultiDrawElementsIndirect = (PFNGLMULTIDRAWELEMENTSINDIRECTPROC)get_proc( "glMultiDrawElementsIndirect"); gl3wGetProgramInterfaceiv = (PFNGLGETPROGRAMINTERFACEIVPROC)get_proc("glGetProgramInterfaceiv"); gl3wGetProgramResourceIndex = (PFNGLGETPROGRAMRESOURCEINDEXPROC)get_proc("glGetProgramResourceIndex"); gl3wGetProgramResourceName = (PFNGLGETPROGRAMRESOURCENAMEPROC)get_proc("glGetProgramResourceName"); gl3wGetProgramResourceiv = (PFNGLGETPROGRAMRESOURCEIVPROC)get_proc("glGetProgramResourceiv"); gl3wGetProgramResourceLocation = (PFNGLGETPROGRAMRESOURCELOCATIONPROC)get_proc( "glGetProgramResourceLocation"); gl3wGetProgramResourceLocationIndex = (PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC)get_proc( "glGetProgramResourceLocationIndex"); gl3wShaderStorageBlockBinding = (PFNGLSHADERSTORAGEBLOCKBINDINGPROC)get_proc( "glShaderStorageBlockBinding"); gl3wTexBufferRange = (PFNGLTEXBUFFERRANGEPROC)get_proc("glTexBufferRange"); gl3wTextureBufferRangeEXT = (PFNGLTEXTUREBUFFERRANGEEXTPROC)get_proc("glTextureBufferRangeEXT"); gl3wTexStorage2DMultisample = (PFNGLTEXSTORAGE2DMULTISAMPLEPROC)get_proc("glTexStorage2DMultisample"); gl3wTexStorage3DMultisample = (PFNGLTEXSTORAGE3DMULTISAMPLEPROC)get_proc("glTexStorage3DMultisample"); gl3wTextureStorage2DMultisampleEXT = (PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC)get_proc( "glTextureStorage2DMultisampleEXT"); gl3wTextureStorage3DMultisampleEXT = (PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC)get_proc( "glTextureStorage3DMultisampleEXT"); } <file_sep>/src/TimeSpan.h #ifndef COLORCYCLING__TIMESPAN_H #define COLORCYCLING__TIMESPAN_H #include <cmath> #include <limits> #include <stdexcept> struct TimeSpan { private: static const long TicksPerMillisecond = 10000; static constexpr float MillisecondsPerTick = 1.0 / TicksPerMillisecond; static const long TicksPerSecond = TicksPerMillisecond * 1000; static constexpr float SecondsPerTick = 1.0 / TicksPerSecond; static const long TicksPerMinute = TicksPerSecond * 60; static constexpr float MinutesPerTick = 1.0 / TicksPerMinute; static const long MaxSeconds = std::numeric_limits<long>::max() / TicksPerSecond; static const long MinSeconds = std::numeric_limits<long>::min() / TicksPerSecond; static const long MaxMilliSeconds = std::numeric_limits<long>::max() / TicksPerMillisecond; static const long MinMilliSeconds = std::numeric_limits<long>::min() / TicksPerMillisecond; static const int MillisPerSecond = 1000; static const int MillisPerMinute = MillisPerSecond * 60; public: TimeSpan() noexcept = default; explicit TimeSpan(long ticks) noexcept: m_ticks(ticks) { } TimeSpan(int hour, int minute, int second) : m_ticks(toTicks(hour, minute, second)) { } static TimeSpan seconds(float value) { return interval(value, MillisPerSecond); } static TimeSpan milliseconds(float value) { return interval(value, 1); } static TimeSpan minutes(float value) { return interval(value, MillisPerMinute); } [[nodiscard]] long getTicks() const { return m_ticks; } [[nodiscard]] int getMilliseconds() const { return (int) ((m_ticks / TicksPerMillisecond) % 1000); } [[nodiscard]] int getMinutes() const { return (int) ((m_ticks / TicksPerMinute) % 60); } [[nodiscard]] int getSeconds() const { return (int) ((m_ticks / TicksPerSecond) % 60); } [[nodiscard]] float getTotalMilliseconds() const { float temp = (float) m_ticks * MillisecondsPerTick; if (temp > MaxMilliSeconds) return (float) MaxMilliSeconds; if (temp < MinMilliSeconds) return (float) MinMilliSeconds; return temp; } [[nodiscard]] float getTotalMinutes() const { return (float) m_ticks * MinutesPerTick; } [[nodiscard]] float getTotalSeconds() const { return (float) m_ticks * SecondsPerTick; } private: static long toTicks(int hour, int minute, int second) { long totalSeconds = (long) hour * 3600 + (long) minute * 60 + (long) second; if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds) throw std::invalid_argument("totalSeconds is out of the bounds"); return totalSeconds * TicksPerSecond; } private: static TimeSpan interval(float value, int scale) { if (std::isnan(value)) throw std::invalid_argument("value cannot be nan (not a number)"); float tmp = value * scale; float millis = tmp + (value >= 0 ? 0.5 : -0.5); if ((millis > std::numeric_limits<long>::max() / TicksPerMillisecond) || (millis < std::numeric_limits<long>::min() / TicksPerMillisecond)) throw std::overflow_error("Specifed time is tool long"); return TimeSpan{(long) millis * TicksPerMillisecond}; } public: static const TimeSpan Zero; private: long m_ticks{0}; }; bool operator==(const TimeSpan &left, const TimeSpan &right); bool operator!=(const TimeSpan &left, const TimeSpan &right); bool operator<(const TimeSpan &left, const TimeSpan &right); bool operator>(const TimeSpan &left, const TimeSpan &right); bool operator<=(const TimeSpan &left, const TimeSpan &right); bool operator>=(const TimeSpan &left, const TimeSpan &right); TimeSpan operator+(const TimeSpan &left, const TimeSpan &right); TimeSpan &operator+=(TimeSpan &left, const TimeSpan &right); TimeSpan operator-(const TimeSpan &left, const TimeSpan &right); TimeSpan &operator-=(TimeSpan &left, const TimeSpan &right); #endif//COLORCYCLING__TIMESPAN_H <file_sep>/src/VertexArray.h #pragma once #include <GL/glew.h> class VertexArray { public: VertexArray() { glGenVertexArrays(1, &m_vao); } void bind() const { glBindVertexArray(m_vao); } ~VertexArray() { glDeleteBuffers(1, &m_vao); } static void unbind() { glBindVertexArray(0); } private: unsigned int m_vao{0}; }; <file_sep>/extlibs/imgui/examples/imgui_impl_allegro5.h // dear imgui: Renderer + Platform Binding for Allegro 5 // (Info: Allegro 5 is a cross-platform general purpose library for handling // windows, inputs, graphics, etc.) // Implemented features: // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. // Read the FAQ about ImTextureID! [X] Platform: Clipboard support (from // Allegro 5.1.12) [X] Platform: Mouse cursor shape and visibility. Disable // with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Issues: // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers // and convert vertices manually. [ ] Platform: Missing gamepad support. // You can copy and use unmodified imgui_impl_* files in your project. See // main.cpp for an example of using this. If you are new to dear imgui, read // examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui, Original Allegro 5 code by @birthggd #pragma once #include "imgui.h" // IMGUI_IMPL_API struct ALLEGRO_DISPLAY; union ALLEGRO_EVENT; IMGUI_IMPL_API bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display); IMGUI_IMPL_API void ImGui_ImplAllegro5_Shutdown(); IMGUI_IMPL_API void ImGui_ImplAllegro5_NewFrame(); IMGUI_IMPL_API void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event); // Use if you want to reset your rendering device without losing Dear ImGui // state. IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects(); <file_sep>/src/Util.h #ifndef COLORCYCLING__UTIL_H #define COLORCYCLING__UTIL_H #include <cstdint> namespace Util { void endianSwap(int32_t *value); void endianSwap(int16_t *value); void endianSwap(uint16_t *value); unsigned int nextPow2(unsigned int x); }// namespace Util #endif//COLORCYCLING__UTIL_H <file_sep>/src/Shader.h #pragma once #include <cassert> #include <map> #include <vector> #include <GL/glew.h> #include <glm/vec2.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> #include "Debug.h" #include "Texture.h" class Shader { public: enum Type { Vertex, Fragment, }; Shader(const char *vertexShader, const char *fragmentShader) { if (vertexShader == nullptr && fragmentShader == nullptr) { return; } m_program = compile(vertexShader, fragmentShader); } ~Shader() { if (m_program != 0) { GL_CHECK(glDeleteProgram(m_program)); } } [[nodiscard]] unsigned int getHandle() const { return m_program; } private: struct Guard { explicit Guard(const Shader& shader) : m_previousProgram(0) , m_currentProgram(shader.m_program) { GLint prev = 0; GL_CHECK(glGetIntegerv(GL_CURRENT_PROGRAM, &prev)); m_previousProgram = prev; if (m_previousProgram != m_currentProgram) { GL_CHECK(glUseProgram(m_currentProgram)); } } ~Guard() { if (m_previousProgram != m_currentProgram) { GL_CHECK(glUseProgram(m_previousProgram)); } } GLuint m_previousProgram; GLuint m_currentProgram; }; public: void setUniform(std::string_view name, int value) const { Guard guard(*this); auto loc = getUniformLocation(name); GL_CHECK(glUniform1i(loc, value)); } void setAttribute(std::string_view name, const glm::vec2 &value) const { Guard guard(*this); auto loc = getAttributeLocation(name); GL_CHECK(glVertexAttrib2f(loc, value.x, value.y)); } void setUniform(std::string_view name, const glm::mat4 &value) const { Guard guard(*this); auto loc = getUniformLocation(name); GL_CHECK(glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(value))); } void setUniform(std::string_view name, const Texture& tex) { Guard guard(*this); int loc = getUniformLocation(name); if (loc == -1) return; m_textures[loc] = &tex; } static void bind(const Shader *shader) { if (shader != nullptr && shader->m_program != 0) { GL_CHECK(glUseProgram(static_cast<GLuint>(shader->m_program))); // bind textures GLint index = 0; for (auto &item : shader->m_textures) { GL_CHECK(glActiveTexture(GL_TEXTURE0 + index)); GL_CHECK(glUniform1i(item.first, index)); item.second->bind(); index++; } } else { GL_CHECK(glUseProgram(0)); } } [[nodiscard]] int getAttributeLocation(std::string_view name) const { GLint loc; GL_CHECK(loc = glGetAttribLocation(static_cast<GLuint>(m_program), name.data())); return loc; } private: [[nodiscard]] int getUniformLocation(std::string_view name) const { GLint loc; GL_CHECK(loc = glGetUniformLocation(static_cast<GLuint>(m_program), name.data())); return loc; } static GLuint compileShader(Type type, const char *source) { auto id = glCreateShader(type == Type::Vertex ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER); // compile glShaderSource(id, 1, &source, nullptr); glCompileShader(id); GLint compileStatus = GL_FALSE; GL_CHECK(glGetShaderiv(id, GL_COMPILE_STATUS, &compileStatus)); // if compilation failed if (compileStatus == GL_FALSE) { GLint infoLogLength = 0; GL_CHECK(glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infoLogLength)); assert(infoLogLength > 0); std::vector<char> infoLog(infoLogLength); GL_CHECK(glGetShaderInfoLog(id, infoLogLength, nullptr, infoLog.data())); const auto typeText = type == Type::Vertex ? "Vertex" : "Fragment"; std::cerr << "Error while compiling " << typeText << "shader:\n" << infoLog.data() << "\n"; } return id; } static GLuint compile(const char *vertexShaderCode, const char *fragmentShaderCode) { assert(vertexShaderCode != nullptr || fragmentShaderCode != nullptr); GLuint program; GL_CHECK(program = glCreateProgram()); if (vertexShaderCode != nullptr) { auto id = compileShader(Type::Vertex, vertexShaderCode); GL_CHECK(glAttachShader(program, id)); GL_CHECK(glDeleteShader(id)); // the shader is still here because it is attached to the program } if (fragmentShaderCode != nullptr) { auto id = compileShader(Type::Fragment, fragmentShaderCode); GL_CHECK(glAttachShader(program, id)); GL_CHECK(glDeleteShader(id)); // the shader is still here because it is attached to the program } GL_CHECK(glLinkProgram(program)); GLint linkStatus = GL_FALSE; GL_CHECK(glGetProgramiv(program, GL_LINK_STATUS, &linkStatus)); if (linkStatus == GL_FALSE) { GLint infoLogLength; GL_CHECK(glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength)); assert(infoLogLength > 0); std::vector<char> infoLog(infoLogLength); GL_CHECK(glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.data())); std::cerr << "Error while linking program:\n" << infoLog.data() << "\n"; throw std::runtime_error("Error while linking program"); } return program; } private: unsigned m_program{0}; std::map<int, const Texture *> m_textures; };<file_sep>/extlibs/imgui/examples/imgui_impl_sdl.h // dear imgui: Platform Binding for SDL2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, // Vulkan..) (Info: SDL2 is a cross-platform general purpose library for // handling windows, inputs, graphics context creation, etc.) // Implemented features: // [X] Platform: Mouse cursor shape and visibility. Disable with // 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. [X] Platform: // Clipboard support. [X] Platform: Keyboard arrays indexed using // SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE). [X] // Platform: Gamepad support. Enabled with 'io.ConfigFlags |= // ImGuiConfigFlags_NavEnableGamepad'. // Missing features: // [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it // explicitly disable the regular Windows IME. You can restore Windows IME by // compiling SDL with SDL_DISABLE_WINDOWS_IME. // You can copy and use unmodified imgui_impl_* files in your project. See // main.cpp for an example of using this. If you are new to dear imgui, read // examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui #pragma once #include "imgui.h" // IMGUI_IMPL_API struct SDL_Window; typedef union SDL_Event SDL_Event; IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL( SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window); IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); <file_sep>/src/Window.cpp #include "Window.h" #include <GL/glew.h> #include <SDL.h> #include <imgui.h> #include <imgui/examples/imgui_impl_opengl3.h> #include <imgui/examples/imgui_impl_sdl.h> #include <iostream> #include <sstream> Window::Window() = default; void Window::init() { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { std::ostringstream ss; ss << "Error when initializing SDL (error=" << SDL_GetError() << ")"; throw std::runtime_error(ss.str()); } //Check for joysticks if (SDL_NumJoysticks() < 1) { std::cout << "Warning: No joysticks connected!\n"; } else { //Load joystick m_gameController = SDL_GameControllerOpen(0); if (!m_gameController) { std::cout << "Warning: Unable to open game controller! SDL Error: " << SDL_GetError() << "\n"; } } // Decide GL+GLSL versions #if __APPLE__ // GL 3.2 Core + GLSL 150 const char *glsl_version = "#version 150"; SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);// Always required on Mac SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); #else // GL 3.0 + GLSL 130 const char *glsl_version = "#version 130"; SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif // Create window with graphics context SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); auto window_flags = (SDL_WindowFlags) ( SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); m_window = SDL_CreateWindow("SDL/OpenGL Doom Fire", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); // setup OpenGL m_glContext = SDL_GL_CreateContext(m_window); if (!m_glContext) { std::ostringstream ss; ss << "Error when creating GL context (error=" << SDL_GetError() << ")"; throw std::runtime_error(ss.str()); } SDL_GL_MakeCurrent(m_window, m_glContext); SDL_GL_SetSwapInterval(1); auto err = glGetError(); if (err != GL_NO_ERROR) { std::ostringstream ss; ss << "Error when initializing OpenGL " << SDL_GetError(); throw std::runtime_error(ss.str()); }; err = glewInit(); if (err != GLEW_OK) { std::ostringstream ss; ss << "Error when initializing glew " << glewGetErrorString(err); throw std::runtime_error(ss.str()); } // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); // Setup Dear ImGui style ImGui::StyleColorsDark(); // Setup Platform/Renderer bindings // window is the SDL_Window* // contex is the SDL_GLContext ImGui_ImplSDL2_InitForOpenGL(m_window, m_glContext); ImGui_ImplOpenGL3_Init(glsl_version); } void Window::display() { SDL_GL_SwapWindow(m_window); } bool Window::pollEvent(SDL_Event &event) { return SDL_PollEvent(&event); } Window::~Window() { //Close game controller SDL_GameControllerClose(m_gameController); m_gameController = nullptr; ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(m_glContext); SDL_DestroyWindow(m_window); SDL_Quit(); } <file_sep>/extlibs/imgui/examples/imgui_impl_dx10.cpp // dear imgui: Renderer for DirectX10 // This needs to be used along with a Platform Binding (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as // ImTextureID. Read the FAQ about ImTextureID! [X] Renderer: Support for large // meshes (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See // main.cpp for an example of using this. If you are new to dear imgui, read // examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is // bound when calling ImGui_ImplDX10_RenderDrawData(). 2019-05-29: DirectX10: // Added support for large mesh (64K+ vertices), enable // ImGuiBackendFlags_RendererHasVtxOffset flag. 2019-04-30: DirectX10: Added // support for special ImDrawCallback_ResetRenderState callback to reset render // state. 2018-12-03: Misc: Added #pragma comment statement to automatically // link with d3dcompiler.lib when using D3DCompile(). 2018-11-30: Misc: Setting // up io.BackendRendererName so it can be displayed in the About Window. // 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown // functions. 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the // old combined DX10+Win32 example. 2018-06-08: DirectX10: Use // draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix // and clipping rectangle. 2018-04-09: Misc: Fixed erroneous call to // io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example // but removed in 1.47 (Nov 2015) on other back-ends. 2018-02-16: Misc: // Obsoleted the io.RenderDrawListsFn callback and exposed // ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available // from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2016-05-07: DirectX10: Disabling depth-write. #include "imgui.h" #include "imgui_impl_dx10.h" // DirectX #include <stdio.h> #include <d3d10_1.h> #include <d3d10.h> #include <d3dcompiler.h> #ifdef _MSC_VER #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib // as we are using D3DCompile() below. #endif // DirectX data static ID3D10Device* g_pd3dDevice = NULL; static IDXGIFactory* g_pFactory = NULL; static ID3D10Buffer* g_pVB = NULL; static ID3D10Buffer* g_pIB = NULL; static ID3D10VertexShader* g_pVertexShader = NULL; static ID3D10InputLayout* g_pInputLayout = NULL; static ID3D10Buffer* g_pVertexConstantBuffer = NULL; static ID3D10PixelShader* g_pPixelShader = NULL; static ID3D10SamplerState* g_pFontSampler = NULL; static ID3D10ShaderResourceView* g_pFontTextureView = NULL; static ID3D10RasterizerState* g_pRasterizerState = NULL; static ID3D10BlendState* g_pBlendState = NULL; static ID3D10DepthStencilState* g_pDepthStencilState = NULL; static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000; struct VERTEX_CONSTANT_BUFFER { float mvp[4][4]; }; static void ImGui_ImplDX10_SetupRenderState( ImDrawData* draw_data, ID3D10Device* ctx) { // Setup viewport D3D10_VIEWPORT vp; memset(&vp, 0, sizeof(D3D10_VIEWPORT)); vp.Width = (UINT)draw_data->DisplaySize.x; vp.Height = (UINT)draw_data->DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0; ctx->RSSetViewports(1, &vp); // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; ctx->IASetInputLayout(g_pInputLayout); ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset); ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->VSSetShader(g_pVertexShader); ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); ctx->PSSetShader(g_pPixelShader); ctx->PSSetSamplers(0, 1, &g_pFontSampler); ctx->GSSetShader(NULL); // Setup render state const float blend_factor[4] = {0.f, 0.f, 0.f, 0.f}; ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff); ctx->OMSetDepthStencilState(g_pDepthStencilState, 0); ctx->RSSetState(g_pRasterizerState); } // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), // but you can now call this directly from your main loop) void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized if(draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; ID3D10Device* ctx = g_pd3dDevice; // Create and grow vertex/index buffers if needed if(!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount) { if(g_pVB) { g_pVB->Release(); g_pVB = NULL; } g_VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D10_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); desc.Usage = D3D10_USAGE_DYNAMIC; desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert); desc.BindFlags = D3D10_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; desc.MiscFlags = 0; if(ctx->CreateBuffer(&desc, NULL, &g_pVB) < 0) return; } if(!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount) { if(g_pIB) { g_pIB->Release(); g_pIB = NULL; } g_IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D10_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); desc.Usage = D3D10_USAGE_DYNAMIC; desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D10_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; if(ctx->CreateBuffer(&desc, NULL, &g_pIB) < 0) return; } // Copy and convert all vertices into a single contiguous buffer ImDrawVert* vtx_dst = NULL; ImDrawIdx* idx_dst = NULL; g_pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst); g_pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst); for(int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } g_pVB->Unmap(); g_pIB->Unmap(); // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos // is (0,0) for single viewport apps. { void* mapped_resource; if(g_pVertexConstantBuffer->Map( D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) return; VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource; float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; float mvp[4][4] = { {2.0f / (R - L), 0.0f, 0.0f, 0.0f}, {0.0f, 2.0f / (T - B), 0.0f, 0.0f}, {0.0f, 0.0f, 0.5f, 0.0f}, {(R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f}, }; memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); g_pVertexConstantBuffer->Unmap(); } // Backup DX state that will be modified to restore it afterwards // (unfortunately this is very ugly looking and verbose. Close your eyes!) struct BACKUP_DX10_STATE { UINT ScissorRectsCount, ViewportsCount; D3D10_RECT ScissorRects [D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; ID3D10RasterizerState* RS; ID3D10BlendState* BlendState; FLOAT BlendFactor[4]; UINT SampleMask; UINT StencilRef; ID3D10DepthStencilState* DepthStencilState; ID3D10ShaderResourceView* PSShaderResource; ID3D10SamplerState* PSSampler; ID3D10PixelShader* PS; ID3D10VertexShader* VS; ID3D10GeometryShader* GS; D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology; ID3D10Buffer *IndexBuffer, *VertexBuffer, *VSConstantBuffer; UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; DXGI_FORMAT IndexBufferFormat; ID3D10InputLayout* InputLayout; }; BACKUP_DX10_STATE old; old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects); ctx->RSGetViewports(&old.ViewportsCount, old.Viewports); ctx->RSGetState(&old.RS); ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask); ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); ctx->PSGetShaderResources(0, 1, &old.PSShaderResource); ctx->PSGetSamplers(0, 1, &old.PSSampler); ctx->PSGetShader(&old.PS); ctx->VSGetShader(&old.VS); ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); ctx->GSGetShader(&old.GS); ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology); ctx->IAGetIndexBuffer( &old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); ctx->IAGetInputLayout(&old.InputLayout); // Setup desired DX state ImGui_ImplDX10_SetupRenderState(draw_data, ctx); // Render command lists // (Because we merged all buffers into a single one, we maintain our own // offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for(int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for(int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if(pcmd->UserCallback) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value // used by the user to request the renderer to reset render // state.) if(pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplDX10_SetupRenderState(draw_data, ctx); else pcmd->UserCallback(cmd_list, pcmd); } else { // Apply scissor/clipping rectangle const D3D10_RECT r = {(LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y)}; ctx->RSSetScissorRects(1, &r); // Bind texture, Draw ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->TextureId; ctx->PSSetShaderResources(0, 1, &texture_srv); ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset); } } global_idx_offset += cmd_list->IdxBuffer.Size; global_vtx_offset += cmd_list->VtxBuffer.Size; } // Restore modified DX state ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); ctx->RSSetViewports(old.ViewportsCount, old.Viewports); ctx->RSSetState(old.RS); if(old.RS) old.RS->Release(); ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if(old.BlendState) old.BlendState->Release(); ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if(old.DepthStencilState) old.DepthStencilState->Release(); ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if(old.PSShaderResource) old.PSShaderResource->Release(); ctx->PSSetSamplers(0, 1, &old.PSSampler); if(old.PSSampler) old.PSSampler->Release(); ctx->PSSetShader(old.PS); if(old.PS) old.PS->Release(); ctx->VSSetShader(old.VS); if(old.VS) old.VS->Release(); ctx->GSSetShader(old.GS); if(old.GS) old.GS->Release(); ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if(old.VSConstantBuffer) old.VSConstantBuffer->Release(); ctx->IASetPrimitiveTopology(old.PrimitiveTopology); ctx->IASetIndexBuffer( old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if(old.IndexBuffer) old.IndexBuffer->Release(); ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if(old.VertexBuffer) old.VertexBuffer->Release(); ctx->IASetInputLayout(old.InputLayout); if(old.InputLayout) old.InputLayout->Release(); } static void ImGui_ImplDX10_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system { D3D10_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D10_USAGE_DEFAULT; desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; ID3D10Texture2D* pTexture = NULL; D3D10_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); // Create texture view D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc; ZeroMemory(&srv_desc, sizeof(srv_desc)); srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srv_desc.Texture2D.MipLevels = desc.MipLevels; srv_desc.Texture2D.MostDetailedMip = 0; g_pd3dDevice->CreateShaderResourceView( pTexture, &srv_desc, &g_pFontTextureView); pTexture->Release(); } // Store our identifier io.Fonts->TexID = (ImTextureID)g_pFontTextureView; // Create texture sampler { D3D10_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler); } } bool ImGui_ImplDX10_CreateDeviceObjects() { if(!g_pd3dDevice) return false; if(g_pFontSampler) ImGui_ImplDX10_InvalidateDeviceObjects(); // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we // introduce a dependency to a given version of d3dcompiler_XX.dll (see // D3DCOMPILER_DLL_A) If you would like to use this DX10 sample code but // remove this dependency you can: // 1) compile once, save the compiled shader blobs into a file or source // code and pass them to CreateVertexShader()/CreatePixelShader() // [preferred solution] 2) use code to detect any version of the DLL and // grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. // Create the vertex shader { static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ float2 pos : POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ PS_INPUT output;\ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ output.col = input.col;\ output.uv = input.uv;\ return output;\ }"; ID3DBlob* vertexShaderBlob; if(FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to // get error showing in (const // char*)pErrorBlob->GetBufferPointer(). Make sure to // Release() the blob! if(g_pd3dDevice->CreateVertexShader( vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK) { vertexShaderBlob->Release(); return false; } // Create the input layout D3D10_INPUT_ELEMENT_DESC local_layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0}, }; if(g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) { vertexShaderBlob->Release(); return false; } vertexShaderBlob->Release(); // Create the constant buffer { D3D10_BUFFER_DESC desc; desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER); desc.Usage = D3D10_USAGE_DYNAMIC; desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; desc.MiscFlags = 0; g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer); } } // Create the pixel shader { static const char* pixelShader = "struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ sampler sampler0;\ Texture2D texture0;\ \ float4 main(PS_INPUT input) : SV_Target\ {\ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ return out_col; \ }"; ID3DBlob* pixelShaderBlob; if(FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to // get error showing in (const // char*)pErrorBlob->GetBufferPointer(). Make sure to // Release() the blob! if(g_pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK) { pixelShaderBlob->Release(); return false; } pixelShaderBlob->Release(); } // Create the blending setup { D3D10_BLEND_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.AlphaToCoverageEnable = false; desc.BlendEnable[0] = true; desc.SrcBlend = D3D10_BLEND_SRC_ALPHA; desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA; desc.BlendOp = D3D10_BLEND_OP_ADD; desc.SrcBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA; desc.DestBlendAlpha = D3D10_BLEND_ZERO; desc.BlendOpAlpha = D3D10_BLEND_OP_ADD; desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL; g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState); } // Create the rasterizer state { D3D10_RASTERIZER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.FillMode = D3D10_FILL_SOLID; desc.CullMode = D3D10_CULL_NONE; desc.ScissorEnable = true; desc.DepthClipEnable = true; g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState); } // Create depth-stencil State { D3D10_DEPTH_STENCIL_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.DepthEnable = false; desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL; desc.DepthFunc = D3D10_COMPARISON_ALWAYS; desc.StencilEnable = false; desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP; desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS; desc.BackFace = desc.FrontFace; g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState); } ImGui_ImplDX10_CreateFontsTexture(); return true; } void ImGui_ImplDX10_InvalidateDeviceObjects() { if(!g_pd3dDevice) return; if(g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; } if(g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as // well. if(g_pIB) { g_pIB->Release(); g_pIB = NULL; } if(g_pVB) { g_pVB->Release(); g_pVB = NULL; } if(g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; } if(g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; } if(g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; } if(g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; } if(g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; } if(g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; } if(g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; } } bool ImGui_ImplDX10_Init(ID3D10Device* device) { // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx10"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the // ImDrawCmd::VtxOffset field, // allowing for large meshes. // Get factory from device IDXGIDevice* pDXGIDevice = NULL; IDXGIAdapter* pDXGIAdapter = NULL; IDXGIFactory* pFactory = NULL; if(device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK) if(pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK) if(pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK) { g_pd3dDevice = device; g_pFactory = pFactory; } if(pDXGIDevice) pDXGIDevice->Release(); if(pDXGIAdapter) pDXGIAdapter->Release(); g_pd3dDevice->AddRef(); return true; } void ImGui_ImplDX10_Shutdown() { ImGui_ImplDX10_InvalidateDeviceObjects(); if(g_pFactory) { g_pFactory->Release(); g_pFactory = NULL; } if(g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } } void ImGui_ImplDX10_NewFrame() { if(!g_pFontSampler) ImGui_ImplDX10_CreateDeviceObjects(); } <file_sep>/README.MD # Doom Fire Fire effect from Doom PSX/Nintendo64 with SDL2/OpenGL. Take a look to [How Doom fire was done](https://fabiensanglard.net/doom_fire_psx/index.html) by <NAME>. ![Doom Fire](https://raw.githubusercontent.com/scemino/DoomFire/master/doc/doom_fire.gif) ## Prerequisites * [SDL2](https://www.libsdl.org/download-2.0.php) Simple DirectMedia Layer * [Dear ImGui](https://github.com/ocornut/imgui) Bloat-free Immediate Mode Graphical User interface for C++ with minimal dependencies * [GLEW](https://github.com/nigels-com/glew) The OpenGL Extension Wrangler Library * [GLM](https://glm.g-truc.net/0.9.9/index.html) OpenGL Mathematics ## Building ```bash mkdir build cd build cmake .. cmake --build . cd .. ``` <file_sep>/extlibs/imgui/examples/imgui_impl_glut.h // dear imgui: Platform Binding for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless // you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2020, you are being // abused. Please show some resistance. !!! // !!! Nowadays, prefer using GLFW or SDL instead! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or // TAB from CTRL+I [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. // You can copy and use unmodified imgui_impl_* files in your project. See // main.cpp for an example of using this. If you are new to dear imgui, read // examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui #pragma once #include "imgui.h" // IMGUI_IMPL_API IMGUI_IMPL_API bool ImGui_ImplGLUT_Init(); IMGUI_IMPL_API void ImGui_ImplGLUT_InstallFuncs(); IMGUI_IMPL_API void ImGui_ImplGLUT_Shutdown(); IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame(); // You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions // installed automatically, or call them yourself from your own GLUT handlers. // We are using the same weird names as GLUT for consistency.. //---------------------------------------- GLUT name //--------------------------------------------- Decent Name --------- IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc( int button, int state, int x, int y); // ~ MouseButtonFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MouseWheelFunc( int button, int dir, int x, int y); // ~ MouseWheelFunc IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc( unsigned char c, int x, int y); // ~ CharPressedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc( unsigned char c, int x, int y); // ~ CharReleasedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc( int key, int x, int y); // ~ KeyPressedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc( int key, int x, int y); // ~ KeyReleasedFunc <file_sep>/extlibs/imgui/examples/libs/gl3w/GL/gl3w.h #ifndef __gl3w_h_ #define __gl3w_h_ #include <GL/glcorearb.h> #ifndef __gl_h_ #define __gl_h_ #endif #ifdef __cplusplus extern "C" { #endif /* gl3w api */ int gl3wInit(void); int gl3wIsSupported(int major, int minor); void* gl3wGetProcAddress(const char* proc); /* OpenGL functions */ extern PFNGLCULLFACEPROC gl3wCullFace; extern PFNGLFRONTFACEPROC gl3wFrontFace; extern PFNGLHINTPROC gl3wHint; extern PFNGLLINEWIDTHPROC gl3wLineWidth; extern PFNGLPOINTSIZEPROC gl3wPointSize; extern PFNGLPOLYGONMODEPROC gl3wPolygonMode; extern PFNGLSCISSORPROC gl3wScissor; extern PFNGLTEXPARAMETERFPROC gl3wTexParameterf; extern PFNGLTEXPARAMETERFVPROC gl3wTexParameterfv; extern PFNGLTEXPARAMETERIPROC gl3wTexParameteri; extern PFNGLTEXPARAMETERIVPROC gl3wTexParameteriv; extern PFNGLTEXIMAGE1DPROC gl3wTexImage1D; extern PFNGLTEXIMAGE2DPROC gl3wTexImage2D; extern PFNGLDRAWBUFFERPROC gl3wDrawBuffer; extern PFNGLCLEARPROC gl3wClear; extern PFNGLCLEARCOLORPROC gl3wClearColor; extern PFNGLCLEARSTENCILPROC gl3wClearStencil; extern PFNGLCLEARDEPTHPROC gl3wClearDepth; extern PFNGLSTENCILMASKPROC gl3wStencilMask; extern PFNGLCOLORMASKPROC gl3wColorMask; extern PFNGLDEPTHMASKPROC gl3wDepthMask; extern PFNGLDISABLEPROC gl3wDisable; extern PFNGLENABLEPROC gl3wEnable; extern PFNGLFINISHPROC gl3wFinish; extern PFNGLFLUSHPROC gl3wFlush; extern PFNGLBLENDFUNCPROC gl3wBlendFunc; extern PFNGLLOGICOPPROC gl3wLogicOp; extern PFNGLSTENCILFUNCPROC gl3wStencilFunc; extern PFNGLSTENCILOPPROC gl3wStencilOp; extern PFNGLDEPTHFUNCPROC gl3wDepthFunc; extern PFNGLPIXELSTOREFPROC gl3wPixelStoref; extern PFNGLPIXELSTOREIPROC gl3wPixelStorei; extern PFNGLREADBUFFERPROC gl3wReadBuffer; extern PFNGLREADPIXELSPROC gl3wReadPixels; extern PFNGLGETBOOLEANVPROC gl3wGetBooleanv; extern PFNGLGETDOUBLEVPROC gl3wGetDoublev; extern PFNGLGETERRORPROC gl3wGetError; extern PFNGLGETFLOATVPROC gl3wGetFloatv; extern PFNGLGETINTEGERVPROC gl3wGetIntegerv; extern PFNGLGETSTRINGPROC gl3wGetString; extern PFNGLGETTEXIMAGEPROC gl3wGetTexImage; extern PFNGLGETTEXPARAMETERFVPROC gl3wGetTexParameterfv; extern PFNGLGETTEXPARAMETERIVPROC gl3wGetTexParameteriv; extern PFNGLGETTEXLEVELPARAMETERFVPROC gl3wGetTexLevelParameterfv; extern PFNGLGETTEXLEVELPARAMETERIVPROC gl3wGetTexLevelParameteriv; extern PFNGLISENABLEDPROC gl3wIsEnabled; extern PFNGLDEPTHRANGEPROC gl3wDepthRange; extern PFNGLVIEWPORTPROC gl3wViewport; extern PFNGLDRAWARRAYSPROC gl3wDrawArrays; extern PFNGLDRAWELEMENTSPROC gl3wDrawElements; extern PFNGLGETPOINTERVPROC gl3wGetPointerv; extern PFNGLPOLYGONOFFSETPROC gl3wPolygonOffset; extern PFNGLCOPYTEXIMAGE1DPROC gl3wCopyTexImage1D; extern PFNGLCOPYTEXIMAGE2DPROC gl3wCopyTexImage2D; extern PFNGLCOPYTEXSUBIMAGE1DPROC gl3wCopyTexSubImage1D; extern PFNGLCOPYTEXSUBIMAGE2DPROC gl3wCopyTexSubImage2D; extern PFNGLTEXSUBIMAGE1DPROC gl3wTexSubImage1D; extern PFNGLTEXSUBIMAGE2DPROC gl3wTexSubImage2D; extern PFNGLBINDTEXTUREPROC gl3wBindTexture; extern PFNGLDELETETEXTURESPROC gl3wDeleteTextures; extern PFNGLGENTEXTURESPROC gl3wGenTextures; extern PFNGLISTEXTUREPROC gl3wIsTexture; extern PFNGLBLENDCOLORPROC gl3wBlendColor; extern PFNGLBLENDEQUATIONPROC gl3wBlendEquation; extern PFNGLDRAWRANGEELEMENTSPROC gl3wDrawRangeElements; extern PFNGLTEXIMAGE3DPROC gl3wTexImage3D; extern PFNGLTEXSUBIMAGE3DPROC gl3wTexSubImage3D; extern PFNGLCOPYTEXSUBIMAGE3DPROC gl3wCopyTexSubImage3D; extern PFNGLACTIVETEXTUREPROC gl3wActiveTexture; extern PFNGLSAMPLECOVERAGEPROC gl3wSampleCoverage; extern PFNGLCOMPRESSEDTEXIMAGE3DPROC gl3wCompressedTexImage3D; extern PFNGLCOMPRESSEDTEXIMAGE2DPROC gl3wCompressedTexImage2D; extern PFNGLCOMPRESSEDTEXIMAGE1DPROC gl3wCompressedTexImage1D; extern PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC gl3wCompressedTexSubImage3D; extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC gl3wCompressedTexSubImage2D; extern PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC gl3wCompressedTexSubImage1D; extern PFNGLGETCOMPRESSEDTEXIMAGEPROC gl3wGetCompressedTexImage; extern PFNGLBLENDFUNCSEPARATEPROC gl3wBlendFuncSeparate; extern PFNGLMULTIDRAWARRAYSPROC gl3wMultiDrawArrays; extern PFNGLMULTIDRAWELEMENTSPROC gl3wMultiDrawElements; extern PFNGLPOINTPARAMETERFPROC gl3wPointParameterf; extern PFNGLPOINTPARAMETERFVPROC gl3wPointParameterfv; extern PFNGLPOINTPARAMETERIPROC gl3wPointParameteri; extern PFNGLPOINTPARAMETERIVPROC gl3wPointParameteriv; extern PFNGLGENQUERIESPROC gl3wGenQueries; extern PFNGLDELETEQUERIESPROC gl3wDeleteQueries; extern PFNGLISQUERYPROC gl3wIsQuery; extern PFNGLBEGINQUERYPROC gl3wBeginQuery; extern PFNGLENDQUERYPROC gl3wEndQuery; extern PFNGLGETQUERYIVPROC gl3wGetQueryiv; extern PFNGLGETQUERYOBJECTIVPROC gl3wGetQueryObjectiv; extern PFNGLGETQUERYOBJECTUIVPROC gl3wGetQueryObjectuiv; extern PFNGLBINDBUFFERPROC gl3wBindBuffer; extern PFNGLDELETEBUFFERSPROC gl3wDeleteBuffers; extern PFNGLGENBUFFERSPROC gl3wGenBuffers; extern PFNGLISBUFFERPROC gl3wIsBuffer; extern PFNGLBUFFERDATAPROC gl3wBufferData; extern PFNGLBUFFERSUBDATAPROC gl3wBufferSubData; extern PFNGLGETBUFFERSUBDATAPROC gl3wGetBufferSubData; extern PFNGLMAPBUFFERPROC gl3wMapBuffer; extern PFNGLUNMAPBUFFERPROC gl3wUnmapBuffer; extern PFNGLGETBUFFERPARAMETERIVPROC gl3wGetBufferParameteriv; extern PFNGLGETBUFFERPOINTERVPROC gl3wGetBufferPointerv; extern PFNGLBLENDEQUATIONSEPARATEPROC gl3wBlendEquationSeparate; extern PFNGLDRAWBUFFERSPROC gl3wDrawBuffers; extern PFNGLSTENCILOPSEPARATEPROC gl3wStencilOpSeparate; extern PFNGLSTENCILFUNCSEPARATEPROC gl3wStencilFuncSeparate; extern PFNGLSTENCILMASKSEPARATEPROC gl3wStencilMaskSeparate; extern PFNGLATTACHSHADERPROC gl3wAttachShader; extern PFNGLBINDATTRIBLOCATIONPROC gl3wBindAttribLocation; extern PFNGLCOMPILESHADERPROC gl3wCompileShader; extern PFNGLCREATEPROGRAMPROC gl3wCreateProgram; extern PFNGLCREATESHADERPROC gl3wCreateShader; extern PFNGLDELETEPROGRAMPROC gl3wDeleteProgram; extern PFNGLDELETESHADERPROC gl3wDeleteShader; extern PFNGLDETACHSHADERPROC gl3wDetachShader; extern PFNGLDISABLEVERTEXATTRIBARRAYPROC gl3wDisableVertexAttribArray; extern PFNGLENABLEVERTEXATTRIBARRAYPROC gl3wEnableVertexAttribArray; extern PFNGLGETACTIVEATTRIBPROC gl3wGetActiveAttrib; extern PFNGLGETACTIVEUNIFORMPROC gl3wGetActiveUniform; extern PFNGLGETATTACHEDSHADERSPROC gl3wGetAttachedShaders; extern PFNGLGETATTRIBLOCATIONPROC gl3wGetAttribLocation; extern PFNGLGETPROGRAMIVPROC gl3wGetProgramiv; extern PFNGLGETPROGRAMINFOLOGPROC gl3wGetProgramInfoLog; extern PFNGLGETSHADERIVPROC gl3wGetShaderiv; extern PFNGLGETSHADERINFOLOGPROC gl3wGetShaderInfoLog; extern PFNGLGETSHADERSOURCEPROC gl3wGetShaderSource; extern PFNGLGETUNIFORMLOCATIONPROC gl3wGetUniformLocation; extern PFNGLGETUNIFORMFVPROC gl3wGetUniformfv; extern PFNGLGETUNIFORMIVPROC gl3wGetUniformiv; extern PFNGLGETVERTEXATTRIBDVPROC gl3wGetVertexAttribdv; extern PFNGLGETVERTEXATTRIBFVPROC gl3wGetVertexAttribfv; extern PFNGLGETVERTEXATTRIBIVPROC gl3wGetVertexAttribiv; extern PFNGLGETVERTEXATTRIBPOINTERVPROC gl3wGetVertexAttribPointerv; extern PFNGLISPROGRAMPROC gl3wIsProgram; extern PFNGLISSHADERPROC gl3wIsShader; extern PFNGLLINKPROGRAMPROC gl3wLinkProgram; extern PFNGLSHADERSOURCEPROC gl3wShaderSource; extern PFNGLUSEPROGRAMPROC gl3wUseProgram; extern PFNGLUNIFORM1FPROC gl3wUniform1f; extern PFNGLUNIFORM2FPROC gl3wUniform2f; extern PFNGLUNIFORM3FPROC gl3wUniform3f; extern PFNGLUNIFORM4FPROC gl3wUniform4f; extern PFNGLUNIFORM1IPROC gl3wUniform1i; extern PFNGLUNIFORM2IPROC gl3wUniform2i; extern PFNGLUNIFORM3IPROC gl3wUniform3i; extern PFNGLUNIFORM4IPROC gl3wUniform4i; extern PFNGLUNIFORM1FVPROC gl3wUniform1fv; extern PFNGLUNIFORM2FVPROC gl3wUniform2fv; extern PFNGLUNIFORM3FVPROC gl3wUniform3fv; extern PFNGLUNIFORM4FVPROC gl3wUniform4fv; extern PFNGLUNIFORM1IVPROC gl3wUniform1iv; extern PFNGLUNIFORM2IVPROC gl3wUniform2iv; extern PFNGLUNIFORM3IVPROC gl3wUniform3iv; extern PFNGLUNIFORM4IVPROC gl3wUniform4iv; extern PFNGLUNIFORMMATRIX2FVPROC gl3wUniformMatrix2fv; extern PFNGLUNIFORMMATRIX3FVPROC gl3wUniformMatrix3fv; extern PFNGLUNIFORMMATRIX4FVPROC gl3wUniformMatrix4fv; extern PFNGLVALIDATEPROGRAMPROC gl3wValidateProgram; extern PFNGLVERTEXATTRIB1DPROC gl3wVertexAttrib1d; extern PFNGLVERTEXATTRIB1DVPROC gl3wVertexAttrib1dv; extern PFNGLVERTEXATTRIB1FPROC gl3wVertexAttrib1f; extern PFNGLVERTEXATTRIB1FVPROC gl3wVertexAttrib1fv; extern PFNGLVERTEXATTRIB1SPROC gl3wVertexAttrib1s; extern PFNGLVERTEXATTRIB1SVPROC gl3wVertexAttrib1sv; extern PFNGLVERTEXATTRIB2DPROC gl3wVertexAttrib2d; extern PFNGLVERTEXATTRIB2DVPROC gl3wVertexAttrib2dv; extern PFNGLVERTEXATTRIB2FPROC gl3wVertexAttrib2f; extern PFNGLVERTEXATTRIB2FVPROC gl3wVertexAttrib2fv; extern PFNGLVERTEXATTRIB2SPROC gl3wVertexAttrib2s; extern PFNGLVERTEXATTRIB2SVPROC gl3wVertexAttrib2sv; extern PFNGLVERTEXATTRIB3DPROC gl3wVertexAttrib3d; extern PFNGLVERTEXATTRIB3DVPROC gl3wVertexAttrib3dv; extern PFNGLVERTEXATTRIB3FPROC gl3wVertexAttrib3f; extern PFNGLVERTEXATTRIB3FVPROC gl3wVertexAttrib3fv; extern PFNGLVERTEXATTRIB3SPROC gl3wVertexAttrib3s; extern PFNGLVERTEXATTRIB3SVPROC gl3wVertexAttrib3sv; extern PFNGLVERTEXATTRIB4NBVPROC gl3wVertexAttrib4Nbv; extern PFNGLVERTEXATTRIB4NIVPROC gl3wVertexAttrib4Niv; extern PFNGLVERTEXATTRIB4NSVPROC gl3wVertexAttrib4Nsv; extern PFNGLVERTEXATTRIB4NUBPROC gl3wVertexAttrib4Nub; extern PFNGLVERTEXATTRIB4NUBVPROC gl3wVertexAttrib4Nubv; extern PFNGLVERTEXATTRIB4NUIVPROC gl3wVertexAttrib4Nuiv; extern PFNGLVERTEXATTRIB4NUSVPROC gl3wVertexAttrib4Nusv; extern PFNGLVERTEXATTRIB4BVPROC gl3wVertexAttrib4bv; extern PFNGLVERTEXATTRIB4DPROC gl3wVertexAttrib4d; extern PFNGLVERTEXATTRIB4DVPROC gl3wVertexAttrib4dv; extern PFNGLVERTEXATTRIB4FPROC gl3wVertexAttrib4f; extern PFNGLVERTEXATTRIB4FVPROC gl3wVertexAttrib4fv; extern PFNGLVERTEXATTRIB4IVPROC gl3wVertexAttrib4iv; extern PFNGLVERTEXATTRIB4SPROC gl3wVertexAttrib4s; extern PFNGLVERTEXATTRIB4SVPROC gl3wVertexAttrib4sv; extern PFNGLVERTEXATTRIB4UBVPROC gl3wVertexAttrib4ubv; extern PFNGLVERTEXATTRIB4UIVPROC gl3wVertexAttrib4uiv; extern PFNGLVERTEXATTRIB4USVPROC gl3wVertexAttrib4usv; extern PFNGLVERTEXATTRIBPOINTERPROC gl3wVertexAttribPointer; extern PFNGLUNIFORMMATRIX2X3FVPROC gl3wUniformMatrix2x3fv; extern PFNGLUNIFORMMATRIX3X2FVPROC gl3wUniformMatrix3x2fv; extern PFNGLUNIFORMMATRIX2X4FVPROC gl3wUniformMatrix2x4fv; extern PFNGLUNIFORMMATRIX4X2FVPROC gl3wUniformMatrix4x2fv; extern PFNGLUNIFORMMATRIX3X4FVPROC gl3wUniformMatrix3x4fv; extern PFNGLUNIFORMMATRIX4X3FVPROC gl3wUniformMatrix4x3fv; extern PFNGLCOLORMASKIPROC gl3wColorMaski; extern PFNGLGETBOOLEANI_VPROC gl3wGetBooleani_v; extern PFNGLGETINTEGERI_VPROC gl3wGetIntegeri_v; extern PFNGLENABLEIPROC gl3wEnablei; extern PFNGLDISABLEIPROC gl3wDisablei; extern PFNGLISENABLEDIPROC gl3wIsEnabledi; extern PFNGLBEGINTRANSFORMFEEDBACKPROC gl3wBeginTransformFeedback; extern PFNGLENDTRANSFORMFEEDBACKPROC gl3wEndTransformFeedback; extern PFNGLBINDBUFFERRANGEPROC gl3wBindBufferRange; extern PFNGLBINDBUFFERBASEPROC gl3wBindBufferBase; extern PFNGLTRANSFORMFEEDBACKVARYINGSPROC gl3wTransformFeedbackVaryings; extern PFNGLGETTRANSFORMFEEDBACKVARYINGPROC gl3wGetTransformFeedbackVarying; extern PFNGLCLAMPCOLORPROC gl3wClampColor; extern PFNGLBEGINCONDITIONALRENDERPROC gl3wBeginConditionalRender; extern PFNGLENDCONDITIONALRENDERPROC gl3wEndConditionalRender; extern PFNGLVERTEXATTRIBIPOINTERPROC gl3wVertexAttribIPointer; extern PFNGLGETVERTEXATTRIBIIVPROC gl3wGetVertexAttribIiv; extern PFNGLGETVERTEXATTRIBIUIVPROC gl3wGetVertexAttribIuiv; extern PFNGLVERTEXATTRIBI1IPROC gl3wVertexAttribI1i; extern PFNGLVERTEXATTRIBI2IPROC gl3wVertexAttribI2i; extern PFNGLVERTEXATTRIBI3IPROC gl3wVertexAttribI3i; extern PFNGLVERTEXATTRIBI4IPROC gl3wVertexAttribI4i; extern PFNGLVERTEXATTRIBI1UIPROC gl3wVertexAttribI1ui; extern PFNGLVERTEXATTRIBI2UIPROC gl3wVertexAttribI2ui; extern PFNGLVERTEXATTRIBI3UIPROC gl3wVertexAttribI3ui; extern PFNGLVERTEXATTRIBI4UIPROC gl3wVertexAttribI4ui; extern PFNGLVERTEXATTRIBI1IVPROC gl3wVertexAttribI1iv; extern PFNGLVERTEXATTRIBI2IVPROC gl3wVertexAttribI2iv; extern PFNGLVERTEXATTRIBI3IVPROC gl3wVertexAttribI3iv; extern PFNGLVERTEXATTRIBI4IVPROC gl3wVertexAttribI4iv; extern PFNGLVERTEXATTRIBI1UIVPROC gl3wVertexAttribI1uiv; extern PFNGLVERTEXATTRIBI2UIVPROC gl3wVertexAttribI2uiv; extern PFNGLVERTEXATTRIBI3UIVPROC gl3wVertexAttribI3uiv; extern PFNGLVERTEXATTRIBI4UIVPROC gl3wVertexAttribI4uiv; extern PFNGLVERTEXATTRIBI4BVPROC gl3wVertexAttribI4bv; extern PFNGLVERTEXATTRIBI4SVPROC gl3wVertexAttribI4sv; extern PFNGLVERTEXATTRIBI4UBVPROC gl3wVertexAttribI4ubv; extern PFNGLVERTEXATTRIBI4USVPROC gl3wVertexAttribI4usv; extern PFNGLGETUNIFORMUIVPROC gl3wGetUniformuiv; extern PFNGLBINDFRAGDATALOCATIONPROC gl3wBindFragDataLocation; extern PFNGLGETFRAGDATALOCATIONPROC gl3wGetFragDataLocation; extern PFNGLUNIFORM1UIPROC gl3wUniform1ui; extern PFNGLUNIFORM2UIPROC gl3wUniform2ui; extern PFNGLUNIFORM3UIPROC gl3wUniform3ui; extern PFNGLUNIFORM4UIPROC gl3wUniform4ui; extern PFNGLUNIFORM1UIVPROC gl3wUniform1uiv; extern PFNGLUNIFORM2UIVPROC gl3wUniform2uiv; extern PFNGLUNIFORM3UIVPROC gl3wUniform3uiv; extern PFNGLUNIFORM4UIVPROC gl3wUniform4uiv; extern PFNGLTEXPARAMETERIIVPROC gl3wTexParameterIiv; extern PFNGLTEXPARAMETERIUIVPROC gl3wTexParameterIuiv; extern PFNGLGETTEXPARAMETERIIVPROC gl3wGetTexParameterIiv; extern PFNGLGETTEXPARAMETERIUIVPROC gl3wGetTexParameterIuiv; extern PFNGLCLEARBUFFERIVPROC gl3wClearBufferiv; extern PFNGLCLEARBUFFERUIVPROC gl3wClearBufferuiv; extern PFNGLCLEARBUFFERFVPROC gl3wClearBufferfv; extern PFNGLCLEARBUFFERFIPROC gl3wClearBufferfi; extern PFNGLGETSTRINGIPROC gl3wGetStringi; extern PFNGLDRAWARRAYSINSTANCEDPROC gl3wDrawArraysInstanced; extern PFNGLDRAWELEMENTSINSTANCEDPROC gl3wDrawElementsInstanced; extern PFNGLTEXBUFFERPROC gl3wTexBuffer; extern PFNGLPRIMITIVERESTARTINDEXPROC gl3wPrimitiveRestartIndex; extern PFNGLGETINTEGER64I_VPROC gl3wGetInteger64i_v; extern PFNGLGETBUFFERPARAMETERI64VPROC gl3wGetBufferParameteri64v; extern PFNGLFRAMEBUFFERTEXTUREPROC gl3wFramebufferTexture; extern PFNGLVERTEXATTRIBDIVISORPROC gl3wVertexAttribDivisor; extern PFNGLMINSAMPLESHADINGPROC gl3wMinSampleShading; extern PFNGLBLENDEQUATIONIPROC gl3wBlendEquationi; extern PFNGLBLENDEQUATIONSEPARATEIPROC gl3wBlendEquationSeparatei; extern PFNGLBLENDFUNCIPROC gl3wBlendFunci; extern PFNGLBLENDFUNCSEPARATEIPROC gl3wBlendFuncSeparatei; extern PFNGLISRENDERBUFFERPROC gl3wIsRenderbuffer; extern PFNGLBINDRENDERBUFFERPROC gl3wBindRenderbuffer; extern PFNGLDELETERENDERBUFFERSPROC gl3wDeleteRenderbuffers; extern PFNGLGENRENDERBUFFERSPROC gl3wGenRenderbuffers; extern PFNGLRENDERBUFFERSTORAGEPROC gl3wRenderbufferStorage; extern PFNGLGETRENDERBUFFERPARAMETERIVPROC gl3wGetRenderbufferParameteriv; extern PFNGLISFRAMEBUFFERPROC gl3wIsFramebuffer; extern PFNGLBINDFRAMEBUFFERPROC gl3wBindFramebuffer; extern PFNGLDELETEFRAMEBUFFERSPROC gl3wDeleteFramebuffers; extern PFNGLGENFRAMEBUFFERSPROC gl3wGenFramebuffers; extern PFNGLCHECKFRAMEBUFFERSTATUSPROC gl3wCheckFramebufferStatus; extern PFNGLFRAMEBUFFERTEXTURE1DPROC gl3wFramebufferTexture1D; extern PFNGLFRAMEBUFFERTEXTURE2DPROC gl3wFramebufferTexture2D; extern PFNGLFRAMEBUFFERTEXTURE3DPROC gl3wFramebufferTexture3D; extern PFNGLFRAMEBUFFERRENDERBUFFERPROC gl3wFramebufferRenderbuffer; extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC gl3wGetFramebufferAttachmentParameteriv; extern PFNGLGENERATEMIPMAPPROC gl3wGenerateMipmap; extern PFNGLBLITFRAMEBUFFERPROC gl3wBlitFramebuffer; extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC gl3wRenderbufferStorageMultisample; extern PFNGLFRAMEBUFFERTEXTURELAYERPROC gl3wFramebufferTextureLayer; extern PFNGLMAPBUFFERRANGEPROC gl3wMapBufferRange; extern PFNGLFLUSHMAPPEDBUFFERRANGEPROC gl3wFlushMappedBufferRange; extern PFNGLBINDVERTEXARRAYPROC gl3wBindVertexArray; extern PFNGLDELETEVERTEXARRAYSPROC gl3wDeleteVertexArrays; extern PFNGLGENVERTEXARRAYSPROC gl3wGenVertexArrays; extern PFNGLISVERTEXARRAYPROC gl3wIsVertexArray; extern PFNGLGETUNIFORMINDICESPROC gl3wGetUniformIndices; extern PFNGLGETACTIVEUNIFORMSIVPROC gl3wGetActiveUniformsiv; extern PFNGLGETACTIVEUNIFORMNAMEPROC gl3wGetActiveUniformName; extern PFNGLGETUNIFORMBLOCKINDEXPROC gl3wGetUniformBlockIndex; extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC gl3wGetActiveUniformBlockiv; extern PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC gl3wGetActiveUniformBlockName; extern PFNGLUNIFORMBLOCKBINDINGPROC gl3wUniformBlockBinding; extern PFNGLCOPYBUFFERSUBDATAPROC gl3wCopyBufferSubData; extern PFNGLDRAWELEMENTSBASEVERTEXPROC gl3wDrawElementsBaseVertex; extern PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC gl3wDrawRangeElementsBaseVertex; extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC gl3wDrawElementsInstancedBaseVertex; extern PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC gl3wMultiDrawElementsBaseVertex; extern PFNGLPROVOKINGVERTEXPROC gl3wProvokingVertex; extern PFNGLFENCESYNCPROC gl3wFenceSync; extern PFNGLISSYNCPROC gl3wIsSync; extern PFNGLDELETESYNCPROC gl3wDeleteSync; extern PFNGLCLIENTWAITSYNCPROC gl3wClientWaitSync; extern PFNGLWAITSYNCPROC gl3wWaitSync; extern PFNGLGETINTEGER64VPROC gl3wGetInteger64v; extern PFNGLGETSYNCIVPROC gl3wGetSynciv; extern PFNGLTEXIMAGE2DMULTISAMPLEPROC gl3wTexImage2DMultisample; extern PFNGLTEXIMAGE3DMULTISAMPLEPROC gl3wTexImage3DMultisample; extern PFNGLGETMULTISAMPLEFVPROC gl3wGetMultisamplefv; extern PFNGLSAMPLEMASKIPROC gl3wSampleMaski; extern PFNGLBLENDEQUATIONIARBPROC gl3wBlendEquationiARB; extern PFNGLBLENDEQUATIONSEPARATEIARBPROC gl3wBlendEquationSeparateiARB; extern PFNGLBLENDFUNCIARBPROC gl3wBlendFunciARB; extern PFNGLBLENDFUNCSEPARATEIARBPROC gl3wBlendFuncSeparateiARB; extern PFNGLMINSAMPLESHADINGARBPROC gl3wMinSampleShadingARB; extern PFNGLNAMEDSTRINGARBPROC gl3wNamedStringARB; extern PFNGLDELETENAMEDSTRINGARBPROC gl3wDeleteNamedStringARB; extern PFNGLCOMPILESHADERINCLUDEARBPROC gl3wCompileShaderIncludeARB; extern PFNGLISNAMEDSTRINGARBPROC gl3wIsNamedStringARB; extern PFNGLGETNAMEDSTRINGARBPROC gl3wGetNamedStringARB; extern PFNGLGETNAMEDSTRINGIVARBPROC gl3wGetNamedStringivARB; extern PFNGLBINDFRAGDATALOCATIONINDEXEDPROC gl3wBindFragDataLocationIndexed; extern PFNGLGETFRAGDATAINDEXPROC gl3wGetFragDataIndex; extern PFNGLGENSAMPLERSPROC gl3wGenSamplers; extern PFNGLDELETESAMPLERSPROC gl3wDeleteSamplers; extern PFNGLISSAMPLERPROC gl3wIsSampler; extern PFNGLBINDSAMPLERPROC gl3wBindSampler; extern PFNGLSAMPLERPARAMETERIPROC gl3wSamplerParameteri; extern PFNGLSAMPLERPARAMETERIVPROC gl3wSamplerParameteriv; extern PFNGLSAMPLERPARAMETERFPROC gl3wSamplerParameterf; extern PFNGLSAMPLERPARAMETERFVPROC gl3wSamplerParameterfv; extern PFNGLSAMPLERPARAMETERIIVPROC gl3wSamplerParameterIiv; extern PFNGLSAMPLERPARAMETERIUIVPROC gl3wSamplerParameterIuiv; extern PFNGLGETSAMPLERPARAMETERIVPROC gl3wGetSamplerParameteriv; extern PFNGLGETSAMPLERPARAMETERIIVPROC gl3wGetSamplerParameterIiv; extern PFNGLGETSAMPLERPARAMETERFVPROC gl3wGetSamplerParameterfv; extern PFNGLGETSAMPLERPARAMETERIUIVPROC gl3wGetSamplerParameterIuiv; extern PFNGLQUERYCOUNTERPROC gl3wQueryCounter; extern PFNGLGETQUERYOBJECTI64VPROC gl3wGetQueryObjecti64v; extern PFNGLGETQUERYOBJECTUI64VPROC gl3wGetQueryObjectui64v; extern PFNGLVERTEXP2UIPROC gl3wVertexP2ui; extern PFNGLVERTEXP2UIVPROC gl3wVertexP2uiv; extern PFNGLVERTEXP3UIPROC gl3wVertexP3ui; extern PFNGLVERTEXP3UIVPROC gl3wVertexP3uiv; extern PFNGLVERTEXP4UIPROC gl3wVertexP4ui; extern PFNGLVERTEXP4UIVPROC gl3wVertexP4uiv; extern PFNGLTEXCOORDP1UIPROC gl3wTexCoordP1ui; extern PFNGLTEXCOORDP1UIVPROC gl3wTexCoordP1uiv; extern PFNGLTEXCOORDP2UIPROC gl3wTexCoordP2ui; extern PFNGLTEXCOORDP2UIVPROC gl3wTexCoordP2uiv; extern PFNGLTEXCOORDP3UIPROC gl3wTexCoordP3ui; extern PFNGLTEXCOORDP3UIVPROC gl3wTexCoordP3uiv; extern PFNGLTEXCOORDP4UIPROC gl3wTexCoordP4ui; extern PFNGLTEXCOORDP4UIVPROC gl3wTexCoordP4uiv; extern PFNGLMULTITEXCOORDP1UIPROC gl3wMultiTexCoordP1ui; extern PFNGLMULTITEXCOORDP1UIVPROC gl3wMultiTexCoordP1uiv; extern PFNGLMULTITEXCOORDP2UIPROC gl3wMultiTexCoordP2ui; extern PFNGLMULTITEXCOORDP2UIVPROC gl3wMultiTexCoordP2uiv; extern PFNGLMULTITEXCOORDP3UIPROC gl3wMultiTexCoordP3ui; extern PFNGLMULTITEXCOORDP3UIVPROC gl3wMultiTexCoordP3uiv; extern PFNGLMULTITEXCOORDP4UIPROC gl3wMultiTexCoordP4ui; extern PFNGLMULTITEXCOORDP4UIVPROC gl3wMultiTexCoordP4uiv; extern PFNGLNORMALP3UIPROC gl3wNormalP3ui; extern PFNGLNORMALP3UIVPROC gl3wNormalP3uiv; extern PFNGLCOLORP3UIPROC gl3wColorP3ui; extern PFNGLCOLORP3UIVPROC gl3wColorP3uiv; extern PFNGLCOLORP4UIPROC gl3wColorP4ui; extern PFNGLCOLORP4UIVPROC gl3wColorP4uiv; extern PFNGLSECONDARYCOLORP3UIPROC gl3wSecondaryColorP3ui; extern PFNGLSECONDARYCOLORP3UIVPROC gl3wSecondaryColorP3uiv; extern PFNGLVERTEXATTRIBP1UIPROC gl3wVertexAttribP1ui; extern PFNGLVERTEXATTRIBP1UIVPROC gl3wVertexAttribP1uiv; extern PFNGLVERTEXATTRIBP2UIPROC gl3wVertexAttribP2ui; extern PFNGLVERTEXATTRIBP2UIVPROC gl3wVertexAttribP2uiv; extern PFNGLVERTEXATTRIBP3UIPROC gl3wVertexAttribP3ui; extern PFNGLVERTEXATTRIBP3UIVPROC gl3wVertexAttribP3uiv; extern PFNGLVERTEXATTRIBP4UIPROC gl3wVertexAttribP4ui; extern PFNGLVERTEXATTRIBP4UIVPROC gl3wVertexAttribP4uiv; extern PFNGLDRAWARRAYSINDIRECTPROC gl3wDrawArraysIndirect; extern PFNGLDRAWELEMENTSINDIRECTPROC gl3wDrawElementsIndirect; extern PFNGLUNIFORM1DPROC gl3wUniform1d; extern PFNGLUNIFORM2DPROC gl3wUniform2d; extern PFNGLUNIFORM3DPROC gl3wUniform3d; extern PFNGLUNIFORM4DPROC gl3wUniform4d; extern PFNGLUNIFORM1DVPROC gl3wUniform1dv; extern PFNGLUNIFORM2DVPROC gl3wUniform2dv; extern PFNGLUNIFORM3DVPROC gl3wUniform3dv; extern PFNGLUNIFORM4DVPROC gl3wUniform4dv; extern PFNGLUNIFORMMATRIX2DVPROC gl3wUniformMatrix2dv; extern PFNGLUNIFORMMATRIX3DVPROC gl3wUniformMatrix3dv; extern PFNGLUNIFORMMATRIX4DVPROC gl3wUniformMatrix4dv; extern PFNGLUNIFORMMATRIX2X3DVPROC gl3wUniformMatrix2x3dv; extern PFNGLUNIFORMMATRIX2X4DVPROC gl3wUniformMatrix2x4dv; extern PFNGLUNIFORMMATRIX3X2DVPROC gl3wUniformMatrix3x2dv; extern PFNGLUNIFORMMATRIX3X4DVPROC gl3wUniformMatrix3x4dv; extern PFNGLUNIFORMMATRIX4X2DVPROC gl3wUniformMatrix4x2dv; extern PFNGLUNIFORMMATRIX4X3DVPROC gl3wUniformMatrix4x3dv; extern PFNGLGETUNIFORMDVPROC gl3wGetUniformdv; extern PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC gl3wGetSubroutineUniformLocation; extern PFNGLGETSUBROUTINEINDEXPROC gl3wGetSubroutineIndex; extern PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC gl3wGetActiveSubroutineUniformiv; extern PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC gl3wGetActiveSubroutineUniformName; extern PFNGLGETACTIVESUBROUTINENAMEPROC gl3wGetActiveSubroutineName; extern PFNGLUNIFORMSUBROUTINESUIVPROC gl3wUniformSubroutinesuiv; extern PFNGLGETUNIFORMSUBROUTINEUIVPROC gl3wGetUniformSubroutineuiv; extern PFNGLGETPROGRAMSTAGEIVPROC gl3wGetProgramStageiv; extern PFNGLPATCHPARAMETERIPROC gl3wPatchParameteri; extern PFNGLPATCHPARAMETERFVPROC gl3wPatchParameterfv; extern PFNGLBINDTRANSFORMFEEDBACKPROC gl3wBindTransformFeedback; extern PFNGLDELETETRANSFORMFEEDBACKSPROC gl3wDeleteTransformFeedbacks; extern PFNGLGENTRANSFORMFEEDBACKSPROC gl3wGenTransformFeedbacks; extern PFNGLISTRANSFORMFEEDBACKPROC gl3wIsTransformFeedback; extern PFNGLPAUSETRANSFORMFEEDBACKPROC gl3wPauseTransformFeedback; extern PFNGLRESUMETRANSFORMFEEDBACKPROC gl3wResumeTransformFeedback; extern PFNGLDRAWTRANSFORMFEEDBACKPROC gl3wDrawTransformFeedback; extern PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC gl3wDrawTransformFeedbackStream; extern PFNGLBEGINQUERYINDEXEDPROC gl3wBeginQueryIndexed; extern PFNGLENDQUERYINDEXEDPROC gl3wEndQueryIndexed; extern PFNGLGETQUERYINDEXEDIVPROC gl3wGetQueryIndexediv; extern PFNGLRELEASESHADERCOMPILERPROC gl3wReleaseShaderCompiler; extern PFNGLSHADERBINARYPROC gl3wShaderBinary; extern PFNGLGETSHADERPRECISIONFORMATPROC gl3wGetShaderPrecisionFormat; extern PFNGLDEPTHRANGEFPROC gl3wDepthRangef; extern PFNGLCLEARDEPTHFPROC gl3wClearDepthf; extern PFNGLGETPROGRAMBINARYPROC gl3wGetProgramBinary; extern PFNGLPROGRAMBINARYPROC gl3wProgramBinary; extern PFNGLPROGRAMPARAMETERIPROC gl3wProgramParameteri; extern PFNGLUSEPROGRAMSTAGESPROC gl3wUseProgramStages; extern PFNGLACTIVESHADERPROGRAMPROC gl3wActiveShaderProgram; extern PFNGLCREATESHADERPROGRAMVPROC gl3wCreateShaderProgramv; extern PFNGLBINDPROGRAMPIPELINEPROC gl3wBindProgramPipeline; extern PFNGLDELETEPROGRAMPIPELINESPROC gl3wDeleteProgramPipelines; extern PFNGLGENPROGRAMPIPELINESPROC gl3wGenProgramPipelines; extern PFNGLISPROGRAMPIPELINEPROC gl3wIsProgramPipeline; extern PFNGLGETPROGRAMPIPELINEIVPROC gl3wGetProgramPipelineiv; extern PFNGLPROGRAMUNIFORM1IPROC gl3wProgramUniform1i; extern PFNGLPROGRAMUNIFORM1IVPROC gl3wProgramUniform1iv; extern PFNGLPROGRAMUNIFORM1FPROC gl3wProgramUniform1f; extern PFNGLPROGRAMUNIFORM1FVPROC gl3wProgramUniform1fv; extern PFNGLPROGRAMUNIFORM1DPROC gl3wProgramUniform1d; extern PFNGLPROGRAMUNIFORM1DVPROC gl3wProgramUniform1dv; extern PFNGLPROGRAMUNIFORM1UIPROC gl3wProgramUniform1ui; extern PFNGLPROGRAMUNIFORM1UIVPROC gl3wProgramUniform1uiv; extern PFNGLPROGRAMUNIFORM2IPROC gl3wProgramUniform2i; extern PFNGLPROGRAMUNIFORM2IVPROC gl3wProgramUniform2iv; extern PFNGLPROGRAMUNIFORM2FPROC gl3wProgramUniform2f; extern PFNGLPROGRAMUNIFORM2FVPROC gl3wProgramUniform2fv; extern PFNGLPROGRAMUNIFORM2DPROC gl3wProgramUniform2d; extern PFNGLPROGRAMUNIFORM2DVPROC gl3wProgramUniform2dv; extern PFNGLPROGRAMUNIFORM2UIPROC gl3wProgramUniform2ui; extern PFNGLPROGRAMUNIFORM2UIVPROC gl3wProgramUniform2uiv; extern PFNGLPROGRAMUNIFORM3IPROC gl3wProgramUniform3i; extern PFNGLPROGRAMUNIFORM3IVPROC gl3wProgramUniform3iv; extern PFNGLPROGRAMUNIFORM3FPROC gl3wProgramUniform3f; extern PFNGLPROGRAMUNIFORM3FVPROC gl3wProgramUniform3fv; extern PFNGLPROGRAMUNIFORM3DPROC gl3wProgramUniform3d; extern PFNGLPROGRAMUNIFORM3DVPROC gl3wProgramUniform3dv; extern PFNGLPROGRAMUNIFORM3UIPROC gl3wProgramUniform3ui; extern PFNGLPROGRAMUNIFORM3UIVPROC gl3wProgramUniform3uiv; extern PFNGLPROGRAMUNIFORM4IPROC gl3wProgramUniform4i; extern PFNGLPROGRAMUNIFORM4IVPROC gl3wProgramUniform4iv; extern PFNGLPROGRAMUNIFORM4FPROC gl3wProgramUniform4f; extern PFNGLPROGRAMUNIFORM4FVPROC gl3wProgramUniform4fv; extern PFNGLPROGRAMUNIFORM4DPROC gl3wProgramUniform4d; extern PFNGLPROGRAMUNIFORM4DVPROC gl3wProgramUniform4dv; extern PFNGLPROGRAMUNIFORM4UIPROC gl3wProgramUniform4ui; extern PFNGLPROGRAMUNIFORM4UIVPROC gl3wProgramUniform4uiv; extern PFNGLPROGRAMUNIFORMMATRIX2FVPROC gl3wProgramUniformMatrix2fv; extern PFNGLPROGRAMUNIFORMMATRIX3FVPROC gl3wProgramUniformMatrix3fv; extern PFNGLPROGRAMUNIFORMMATRIX4FVPROC gl3wProgramUniformMatrix4fv; extern PFNGLPROGRAMUNIFORMMATRIX2DVPROC gl3wProgramUniformMatrix2dv; extern PFNGLPROGRAMUNIFORMMATRIX3DVPROC gl3wProgramUniformMatrix3dv; extern PFNGLPROGRAMUNIFORMMATRIX4DVPROC gl3wProgramUniformMatrix4dv; extern PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC gl3wProgramUniformMatrix2x3fv; extern PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC gl3wProgramUniformMatrix3x2fv; extern PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC gl3wProgramUniformMatrix2x4fv; extern PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC gl3wProgramUniformMatrix4x2fv; extern PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC gl3wProgramUniformMatrix3x4fv; extern PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC gl3wProgramUniformMatrix4x3fv; extern PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC gl3wProgramUniformMatrix2x3dv; extern PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC gl3wProgramUniformMatrix3x2dv; extern PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC gl3wProgramUniformMatrix2x4dv; extern PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC gl3wProgramUniformMatrix4x2dv; extern PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC gl3wProgramUniformMatrix3x4dv; extern PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC gl3wProgramUniformMatrix4x3dv; extern PFNGLVALIDATEPROGRAMPIPELINEPROC gl3wValidateProgramPipeline; extern PFNGLGETPROGRAMPIPELINEINFOLOGPROC gl3wGetProgramPipelineInfoLog; extern PFNGLVERTEXATTRIBL1DPROC gl3wVertexAttribL1d; extern PFNGLVERTEXATTRIBL2DPROC gl3wVertexAttribL2d; extern PFNGLVERTEXATTRIBL3DPROC gl3wVertexAttribL3d; extern PFNGLVERTEXATTRIBL4DPROC gl3wVertexAttribL4d; extern PFNGLVERTEXATTRIBL1DVPROC gl3wVertexAttribL1dv; extern PFNGLVERTEXATTRIBL2DVPROC gl3wVertexAttribL2dv; extern PFNGLVERTEXATTRIBL3DVPROC gl3wVertexAttribL3dv; extern PFNGLVERTEXATTRIBL4DVPROC gl3wVertexAttribL4dv; extern PFNGLVERTEXATTRIBLPOINTERPROC gl3wVertexAttribLPointer; extern PFNGLGETVERTEXATTRIBLDVPROC gl3wGetVertexAttribLdv; extern PFNGLVIEWPORTARRAYVPROC gl3wViewportArrayv; extern PFNGLVIEWPORTINDEXEDFPROC gl3wViewportIndexedf; extern PFNGLVIEWPORTINDEXEDFVPROC gl3wViewportIndexedfv; extern PFNGLSCISSORARRAYVPROC gl3wScissorArrayv; extern PFNGLSCISSORINDEXEDPROC gl3wScissorIndexed; extern PFNGLSCISSORINDEXEDVPROC gl3wScissorIndexedv; extern PFNGLDEPTHRANGEARRAYVPROC gl3wDepthRangeArrayv; extern PFNGLDEPTHRANGEINDEXEDPROC gl3wDepthRangeIndexed; extern PFNGLGETFLOATI_VPROC gl3wGetFloati_v; extern PFNGLGETDOUBLEI_VPROC gl3wGetDoublei_v; extern PFNGLCREATESYNCFROMCLEVENTARBPROC gl3wCreateSyncFromCLeventARB; extern PFNGLDEBUGMESSAGECONTROLARBPROC gl3wDebugMessageControlARB; extern PFNGLDEBUGMESSAGEINSERTARBPROC gl3wDebugMessageInsertARB; extern PFNGLDEBUGMESSAGECALLBACKARBPROC gl3wDebugMessageCallbackARB; extern PFNGLGETDEBUGMESSAGELOGARBPROC gl3wGetDebugMessageLogARB; extern PFNGLGETGRAPHICSRESETSTATUSARBPROC gl3wGetGraphicsResetStatusARB; extern PFNGLGETNTEXIMAGEARBPROC gl3wGetnTexImageARB; extern PFNGLREADNPIXELSARBPROC gl3wReadnPixelsARB; extern PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC gl3wGetnCompressedTexImageARB; extern PFNGLGETNUNIFORMFVARBPROC gl3wGetnUniformfvARB; extern PFNGLGETNUNIFORMIVARBPROC gl3wGetnUniformivARB; extern PFNGLGETNUNIFORMUIVARBPROC gl3wGetnUniformuivARB; extern PFNGLGETNUNIFORMDVARBPROC gl3wGetnUniformdvARB; extern PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC gl3wDrawArraysInstancedBaseInstance; extern PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC gl3wDrawElementsInstancedBaseInstance; extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC gl3wDrawElementsInstancedBaseVertexBaseInstance; extern PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC gl3wDrawTransformFeedbackInstanced; extern PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC gl3wDrawTransformFeedbackStreamInstanced; extern PFNGLGETINTERNALFORMATIVPROC gl3wGetInternalformativ; extern PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC gl3wGetActiveAtomicCounterBufferiv; extern PFNGLBINDIMAGETEXTUREPROC gl3wBindImageTexture; extern PFNGLMEMORYBARRIERPROC gl3wMemoryBarrier; extern PFNGLTEXSTORAGE1DPROC gl3wTexStorage1D; extern PFNGLTEXSTORAGE2DPROC gl3wTexStorage2D; extern PFNGLTEXSTORAGE3DPROC gl3wTexStorage3D; extern PFNGLTEXTURESTORAGE1DEXTPROC gl3wTextureStorage1DEXT; extern PFNGLTEXTURESTORAGE2DEXTPROC gl3wTextureStorage2DEXT; extern PFNGLTEXTURESTORAGE3DEXTPROC gl3wTextureStorage3DEXT; extern PFNGLDEBUGMESSAGECONTROLPROC gl3wDebugMessageControl; extern PFNGLDEBUGMESSAGEINSERTPROC gl3wDebugMessageInsert; extern PFNGLDEBUGMESSAGECALLBACKPROC gl3wDebugMessageCallback; extern PFNGLGETDEBUGMESSAGELOGPROC gl3wGetDebugMessageLog; extern PFNGLPUSHDEBUGGROUPPROC gl3wPushDebugGroup; extern PFNGLPOPDEBUGGROUPPROC gl3wPopDebugGroup; extern PFNGLOBJECTLABELPROC gl3wObjectLabel; extern PFNGLGETOBJECTLABELPROC gl3wGetObjectLabel; extern PFNGLOBJECTPTRLABELPROC gl3wObjectPtrLabel; extern PFNGLGETOBJECTPTRLABELPROC gl3wGetObjectPtrLabel; extern PFNGLCLEARBUFFERDATAPROC gl3wClearBufferData; extern PFNGLCLEARBUFFERSUBDATAPROC gl3wClearBufferSubData; extern PFNGLCLEARNAMEDBUFFERDATAEXTPROC gl3wClearNamedBufferDataEXT; extern PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC gl3wClearNamedBufferSubDataEXT; extern PFNGLDISPATCHCOMPUTEPROC gl3wDispatchCompute; extern PFNGLDISPATCHCOMPUTEINDIRECTPROC gl3wDispatchComputeIndirect; extern PFNGLCOPYIMAGESUBDATAPROC gl3wCopyImageSubData; extern PFNGLTEXTUREVIEWPROC gl3wTextureView; extern PFNGLBINDVERTEXBUFFERPROC gl3wBindVertexBuffer; extern PFNGLVERTEXATTRIBFORMATPROC gl3wVertexAttribFormat; extern PFNGLVERTEXATTRIBIFORMATPROC gl3wVertexAttribIFormat; extern PFNGLVERTEXATTRIBLFORMATPROC gl3wVertexAttribLFormat; extern PFNGLVERTEXATTRIBBINDINGPROC gl3wVertexAttribBinding; extern PFNGLVERTEXBINDINGDIVISORPROC gl3wVertexBindingDivisor; extern PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC gl3wVertexArrayBindVertexBufferEXT; extern PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC gl3wVertexArrayVertexAttribFormatEXT; extern PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC gl3wVertexArrayVertexAttribIFormatEXT; extern PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC gl3wVertexArrayVertexAttribLFormatEXT; extern PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC gl3wVertexArrayVertexAttribBindingEXT; extern PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC gl3wVertexArrayVertexBindingDivisorEXT; extern PFNGLFRAMEBUFFERPARAMETERIPROC gl3wFramebufferParameteri; extern PFNGLGETFRAMEBUFFERPARAMETERIVPROC gl3wGetFramebufferParameteriv; extern PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC gl3wNamedFramebufferParameteriEXT; extern PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC gl3wGetNamedFramebufferParameterivEXT; extern PFNGLGETINTERNALFORMATI64VPROC gl3wGetInternalformati64v; extern PFNGLINVALIDATETEXSUBIMAGEPROC gl3wInvalidateTexSubImage; extern PFNGLINVALIDATETEXIMAGEPROC gl3wInvalidateTexImage; extern PFNGLINVALIDATEBUFFERSUBDATAPROC gl3wInvalidateBufferSubData; extern PFNGLINVALIDATEBUFFERDATAPROC gl3wInvalidateBufferData; extern PFNGLINVALIDATEFRAMEBUFFERPROC gl3wInvalidateFramebuffer; extern PFNGLINVALIDATESUBFRAMEBUFFERPROC gl3wInvalidateSubFramebuffer; extern PFNGLMULTIDRAWARRAYSINDIRECTPROC gl3wMultiDrawArraysIndirect; extern PFNGLMULTIDRAWELEMENTSINDIRECTPROC gl3wMultiDrawElementsIndirect; extern PFNGLGETPROGRAMINTERFACEIVPROC gl3wGetProgramInterfaceiv; extern PFNGLGETPROGRAMRESOURCEINDEXPROC gl3wGetProgramResourceIndex; extern PFNGLGETPROGRAMRESOURCENAMEPROC gl3wGetProgramResourceName; extern PFNGLGETPROGRAMRESOURCEIVPROC gl3wGetProgramResourceiv; extern PFNGLGETPROGRAMRESOURCELOCATIONPROC gl3wGetProgramResourceLocation; extern PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC gl3wGetProgramResourceLocationIndex; extern PFNGLSHADERSTORAGEBLOCKBINDINGPROC gl3wShaderStorageBlockBinding; extern PFNGLTEXBUFFERRANGEPROC gl3wTexBufferRange; extern PFNGLTEXTUREBUFFERRANGEEXTPROC gl3wTextureBufferRangeEXT; extern PFNGLTEXSTORAGE2DMULTISAMPLEPROC gl3wTexStorage2DMultisample; extern PFNGLTEXSTORAGE3DMULTISAMPLEPROC gl3wTexStorage3DMultisample; extern PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC gl3wTextureStorage2DMultisampleEXT; extern PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC gl3wTextureStorage3DMultisampleEXT; #define glCullFace gl3wCullFace #define glFrontFace gl3wFrontFace #define glHint gl3wHint #define glLineWidth gl3wLineWidth #define glPointSize gl3wPointSize #define glPolygonMode gl3wPolygonMode #define glScissor gl3wScissor #define glTexParameterf gl3wTexParameterf #define glTexParameterfv gl3wTexParameterfv #define glTexParameteri gl3wTexParameteri #define glTexParameteriv gl3wTexParameteriv #define glTexImage1D gl3wTexImage1D #define glTexImage2D gl3wTexImage2D #define glDrawBuffer gl3wDrawBuffer #define glClear gl3wClear #define glClearColor gl3wClearColor #define glClearStencil gl3wClearStencil #define glClearDepth gl3wClearDepth #define glStencilMask gl3wStencilMask #define glColorMask gl3wColorMask #define glDepthMask gl3wDepthMask #define glDisable gl3wDisable #define glEnable gl3wEnable #define glFinish gl3wFinish #define glFlush gl3wFlush #define glBlendFunc gl3wBlendFunc #define glLogicOp gl3wLogicOp #define glStencilFunc gl3wStencilFunc #define glStencilOp gl3wStencilOp #define glDepthFunc gl3wDepthFunc #define glPixelStoref gl3wPixelStoref #define glPixelStorei gl3wPixelStorei #define glReadBuffer gl3wReadBuffer #define glReadPixels gl3wReadPixels #define glGetBooleanv gl3wGetBooleanv #define glGetDoublev gl3wGetDoublev #define glGetError gl3wGetError #define glGetFloatv gl3wGetFloatv #define glGetIntegerv gl3wGetIntegerv #define glGetString gl3wGetString #define glGetTexImage gl3wGetTexImage #define glGetTexParameterfv gl3wGetTexParameterfv #define glGetTexParameteriv gl3wGetTexParameteriv #define glGetTexLevelParameterfv gl3wGetTexLevelParameterfv #define glGetTexLevelParameteriv gl3wGetTexLevelParameteriv #define glIsEnabled gl3wIsEnabled #define glDepthRange gl3wDepthRange #define glViewport gl3wViewport #define glDrawArrays gl3wDrawArrays #define glDrawElements gl3wDrawElements #define glGetPointerv gl3wGetPointerv #define glPolygonOffset gl3wPolygonOffset #define glCopyTexImage1D gl3wCopyTexImage1D #define glCopyTexImage2D gl3wCopyTexImage2D #define glCopyTexSubImage1D gl3wCopyTexSubImage1D #define glCopyTexSubImage2D gl3wCopyTexSubImage2D #define glTexSubImage1D gl3wTexSubImage1D #define glTexSubImage2D gl3wTexSubImage2D #define glBindTexture gl3wBindTexture #define glDeleteTextures gl3wDeleteTextures #define glGenTextures gl3wGenTextures #define glIsTexture gl3wIsTexture #define glBlendColor gl3wBlendColor #define glBlendEquation gl3wBlendEquation #define glDrawRangeElements gl3wDrawRangeElements #define glTexImage3D gl3wTexImage3D #define glTexSubImage3D gl3wTexSubImage3D #define glCopyTexSubImage3D gl3wCopyTexSubImage3D #define glActiveTexture gl3wActiveTexture #define glSampleCoverage gl3wSampleCoverage #define glCompressedTexImage3D gl3wCompressedTexImage3D #define glCompressedTexImage2D gl3wCompressedTexImage2D #define glCompressedTexImage1D gl3wCompressedTexImage1D #define glCompressedTexSubImage3D gl3wCompressedTexSubImage3D #define glCompressedTexSubImage2D gl3wCompressedTexSubImage2D #define glCompressedTexSubImage1D gl3wCompressedTexSubImage1D #define glGetCompressedTexImage gl3wGetCompressedTexImage #define glBlendFuncSeparate gl3wBlendFuncSeparate #define glMultiDrawArrays gl3wMultiDrawArrays #define glMultiDrawElements gl3wMultiDrawElements #define glPointParameterf gl3wPointParameterf #define glPointParameterfv gl3wPointParameterfv #define glPointParameteri gl3wPointParameteri #define glPointParameteriv gl3wPointParameteriv #define glGenQueries gl3wGenQueries #define glDeleteQueries gl3wDeleteQueries #define glIsQuery gl3wIsQuery #define glBeginQuery gl3wBeginQuery #define glEndQuery gl3wEndQuery #define glGetQueryiv gl3wGetQueryiv #define glGetQueryObjectiv gl3wGetQueryObjectiv #define glGetQueryObjectuiv gl3wGetQueryObjectuiv #define glBindBuffer gl3wBindBuffer #define glDeleteBuffers gl3wDeleteBuffers #define glGenBuffers gl3wGenBuffers #define glIsBuffer gl3wIsBuffer #define glBufferData gl3wBufferData #define glBufferSubData gl3wBufferSubData #define glGetBufferSubData gl3wGetBufferSubData #define glMapBuffer gl3wMapBuffer #define glUnmapBuffer gl3wUnmapBuffer #define glGetBufferParameteriv gl3wGetBufferParameteriv #define glGetBufferPointerv gl3wGetBufferPointerv #define glBlendEquationSeparate gl3wBlendEquationSeparate #define glDrawBuffers gl3wDrawBuffers #define glStencilOpSeparate gl3wStencilOpSeparate #define glStencilFuncSeparate gl3wStencilFuncSeparate #define glStencilMaskSeparate gl3wStencilMaskSeparate #define glAttachShader gl3wAttachShader #define glBindAttribLocation gl3wBindAttribLocation #define glCompileShader gl3wCompileShader #define glCreateProgram gl3wCreateProgram #define glCreateShader gl3wCreateShader #define glDeleteProgram gl3wDeleteProgram #define glDeleteShader gl3wDeleteShader #define glDetachShader gl3wDetachShader #define glDisableVertexAttribArray gl3wDisableVertexAttribArray #define glEnableVertexAttribArray gl3wEnableVertexAttribArray #define glGetActiveAttrib gl3wGetActiveAttrib #define glGetActiveUniform gl3wGetActiveUniform #define glGetAttachedShaders gl3wGetAttachedShaders #define glGetAttribLocation gl3wGetAttribLocation #define glGetProgramiv gl3wGetProgramiv #define glGetProgramInfoLog gl3wGetProgramInfoLog #define glGetShaderiv gl3wGetShaderiv #define glGetShaderInfoLog gl3wGetShaderInfoLog #define glGetShaderSource gl3wGetShaderSource #define glGetUniformLocation gl3wGetUniformLocation #define glGetUniformfv gl3wGetUniformfv #define glGetUniformiv gl3wGetUniformiv #define glGetVertexAttribdv gl3wGetVertexAttribdv #define glGetVertexAttribfv gl3wGetVertexAttribfv #define glGetVertexAttribiv gl3wGetVertexAttribiv #define glGetVertexAttribPointerv gl3wGetVertexAttribPointerv #define glIsProgram gl3wIsProgram #define glIsShader gl3wIsShader #define glLinkProgram gl3wLinkProgram #define glShaderSource gl3wShaderSource #define glUseProgram gl3wUseProgram #define glUniform1f gl3wUniform1f #define glUniform2f gl3wUniform2f #define glUniform3f gl3wUniform3f #define glUniform4f gl3wUniform4f #define glUniform1i gl3wUniform1i #define glUniform2i gl3wUniform2i #define glUniform3i gl3wUniform3i #define glUniform4i gl3wUniform4i #define glUniform1fv gl3wUniform1fv #define glUniform2fv gl3wUniform2fv #define glUniform3fv gl3wUniform3fv #define glUniform4fv gl3wUniform4fv #define glUniform1iv gl3wUniform1iv #define glUniform2iv gl3wUniform2iv #define glUniform3iv gl3wUniform3iv #define glUniform4iv gl3wUniform4iv #define glUniformMatrix2fv gl3wUniformMatrix2fv #define glUniformMatrix3fv gl3wUniformMatrix3fv #define glUniformMatrix4fv gl3wUniformMatrix4fv #define glValidateProgram gl3wValidateProgram #define glVertexAttrib1d gl3wVertexAttrib1d #define glVertexAttrib1dv gl3wVertexAttrib1dv #define glVertexAttrib1f gl3wVertexAttrib1f #define glVertexAttrib1fv gl3wVertexAttrib1fv #define glVertexAttrib1s gl3wVertexAttrib1s #define glVertexAttrib1sv gl3wVertexAttrib1sv #define glVertexAttrib2d gl3wVertexAttrib2d #define glVertexAttrib2dv gl3wVertexAttrib2dv #define glVertexAttrib2f gl3wVertexAttrib2f #define glVertexAttrib2fv gl3wVertexAttrib2fv #define glVertexAttrib2s gl3wVertexAttrib2s #define glVertexAttrib2sv gl3wVertexAttrib2sv #define glVertexAttrib3d gl3wVertexAttrib3d #define glVertexAttrib3dv gl3wVertexAttrib3dv #define glVertexAttrib3f gl3wVertexAttrib3f #define glVertexAttrib3fv gl3wVertexAttrib3fv #define glVertexAttrib3s gl3wVertexAttrib3s #define glVertexAttrib3sv gl3wVertexAttrib3sv #define glVertexAttrib4Nbv gl3wVertexAttrib4Nbv #define glVertexAttrib4Niv gl3wVertexAttrib4Niv #define glVertexAttrib4Nsv gl3wVertexAttrib4Nsv #define glVertexAttrib4Nub gl3wVertexAttrib4Nub #define glVertexAttrib4Nubv gl3wVertexAttrib4Nubv #define glVertexAttrib4Nuiv gl3wVertexAttrib4Nuiv #define glVertexAttrib4Nusv gl3wVertexAttrib4Nusv #define glVertexAttrib4bv gl3wVertexAttrib4bv #define glVertexAttrib4d gl3wVertexAttrib4d #define glVertexAttrib4dv gl3wVertexAttrib4dv #define glVertexAttrib4f gl3wVertexAttrib4f #define glVertexAttrib4fv gl3wVertexAttrib4fv #define glVertexAttrib4iv gl3wVertexAttrib4iv #define glVertexAttrib4s gl3wVertexAttrib4s #define glVertexAttrib4sv gl3wVertexAttrib4sv #define glVertexAttrib4ubv gl3wVertexAttrib4ubv #define glVertexAttrib4uiv gl3wVertexAttrib4uiv #define glVertexAttrib4usv gl3wVertexAttrib4usv #define glVertexAttribPointer gl3wVertexAttribPointer #define glUniformMatrix2x3fv gl3wUniformMatrix2x3fv #define glUniformMatrix3x2fv gl3wUniformMatrix3x2fv #define glUniformMatrix2x4fv gl3wUniformMatrix2x4fv #define glUniformMatrix4x2fv gl3wUniformMatrix4x2fv #define glUniformMatrix3x4fv gl3wUniformMatrix3x4fv #define glUniformMatrix4x3fv gl3wUniformMatrix4x3fv #define glColorMaski gl3wColorMaski #define glGetBooleani_v gl3wGetBooleani_v #define glGetIntegeri_v gl3wGetIntegeri_v #define glEnablei gl3wEnablei #define glDisablei gl3wDisablei #define glIsEnabledi gl3wIsEnabledi #define glBeginTransformFeedback gl3wBeginTransformFeedback #define glEndTransformFeedback gl3wEndTransformFeedback #define glBindBufferRange gl3wBindBufferRange #define glBindBufferBase gl3wBindBufferBase #define glTransformFeedbackVaryings gl3wTransformFeedbackVaryings #define glGetTransformFeedbackVarying gl3wGetTransformFeedbackVarying #define glClampColor gl3wClampColor #define glBeginConditionalRender gl3wBeginConditionalRender #define glEndConditionalRender gl3wEndConditionalRender #define glVertexAttribIPointer gl3wVertexAttribIPointer #define glGetVertexAttribIiv gl3wGetVertexAttribIiv #define glGetVertexAttribIuiv gl3wGetVertexAttribIuiv #define glVertexAttribI1i gl3wVertexAttribI1i #define glVertexAttribI2i gl3wVertexAttribI2i #define glVertexAttribI3i gl3wVertexAttribI3i #define glVertexAttribI4i gl3wVertexAttribI4i #define glVertexAttribI1ui gl3wVertexAttribI1ui #define glVertexAttribI2ui gl3wVertexAttribI2ui #define glVertexAttribI3ui gl3wVertexAttribI3ui #define glVertexAttribI4ui gl3wVertexAttribI4ui #define glVertexAttribI1iv gl3wVertexAttribI1iv #define glVertexAttribI2iv gl3wVertexAttribI2iv #define glVertexAttribI3iv gl3wVertexAttribI3iv #define glVertexAttribI4iv gl3wVertexAttribI4iv #define glVertexAttribI1uiv gl3wVertexAttribI1uiv #define glVertexAttribI2uiv gl3wVertexAttribI2uiv #define glVertexAttribI3uiv gl3wVertexAttribI3uiv #define glVertexAttribI4uiv gl3wVertexAttribI4uiv #define glVertexAttribI4bv gl3wVertexAttribI4bv #define glVertexAttribI4sv gl3wVertexAttribI4sv #define glVertexAttribI4ubv gl3wVertexAttribI4ubv #define glVertexAttribI4usv gl3wVertexAttribI4usv #define glGetUniformuiv gl3wGetUniformuiv #define glBindFragDataLocation gl3wBindFragDataLocation #define glGetFragDataLocation gl3wGetFragDataLocation #define glUniform1ui gl3wUniform1ui #define glUniform2ui gl3wUniform2ui #define glUniform3ui gl3wUniform3ui #define glUniform4ui gl3wUniform4ui #define glUniform1uiv gl3wUniform1uiv #define glUniform2uiv gl3wUniform2uiv #define glUniform3uiv gl3wUniform3uiv #define glUniform4uiv gl3wUniform4uiv #define glTexParameterIiv gl3wTexParameterIiv #define glTexParameterIuiv gl3wTexParameterIuiv #define glGetTexParameterIiv gl3wGetTexParameterIiv #define glGetTexParameterIuiv gl3wGetTexParameterIuiv #define glClearBufferiv gl3wClearBufferiv #define glClearBufferuiv gl3wClearBufferuiv #define glClearBufferfv gl3wClearBufferfv #define glClearBufferfi gl3wClearBufferfi #define glGetStringi gl3wGetStringi #define glDrawArraysInstanced gl3wDrawArraysInstanced #define glDrawElementsInstanced gl3wDrawElementsInstanced #define glTexBuffer gl3wTexBuffer #define glPrimitiveRestartIndex gl3wPrimitiveRestartIndex #define glGetInteger64i_v gl3wGetInteger64i_v #define glGetBufferParameteri64v gl3wGetBufferParameteri64v #define glFramebufferTexture gl3wFramebufferTexture #define glVertexAttribDivisor gl3wVertexAttribDivisor #define glMinSampleShading gl3wMinSampleShading #define glBlendEquationi gl3wBlendEquationi #define glBlendEquationSeparatei gl3wBlendEquationSeparatei #define glBlendFunci gl3wBlendFunci #define glBlendFuncSeparatei gl3wBlendFuncSeparatei #define glIsRenderbuffer gl3wIsRenderbuffer #define glBindRenderbuffer gl3wBindRenderbuffer #define glDeleteRenderbuffers gl3wDeleteRenderbuffers #define glGenRenderbuffers gl3wGenRenderbuffers #define glRenderbufferStorage gl3wRenderbufferStorage #define glGetRenderbufferParameteriv gl3wGetRenderbufferParameteriv #define glIsFramebuffer gl3wIsFramebuffer #define glBindFramebuffer gl3wBindFramebuffer #define glDeleteFramebuffers gl3wDeleteFramebuffers #define glGenFramebuffers gl3wGenFramebuffers #define glCheckFramebufferStatus gl3wCheckFramebufferStatus #define glFramebufferTexture1D gl3wFramebufferTexture1D #define glFramebufferTexture2D gl3wFramebufferTexture2D #define glFramebufferTexture3D gl3wFramebufferTexture3D #define glFramebufferRenderbuffer gl3wFramebufferRenderbuffer #define glGetFramebufferAttachmentParameteriv \ gl3wGetFramebufferAttachmentParameteriv #define glGenerateMipmap gl3wGenerateMipmap #define glBlitFramebuffer gl3wBlitFramebuffer #define glRenderbufferStorageMultisample gl3wRenderbufferStorageMultisample #define glFramebufferTextureLayer gl3wFramebufferTextureLayer #define glMapBufferRange gl3wMapBufferRange #define glFlushMappedBufferRange gl3wFlushMappedBufferRange #define glBindVertexArray gl3wBindVertexArray #define glDeleteVertexArrays gl3wDeleteVertexArrays #define glGenVertexArrays gl3wGenVertexArrays #define glIsVertexArray gl3wIsVertexArray #define glGetUniformIndices gl3wGetUniformIndices #define glGetActiveUniformsiv gl3wGetActiveUniformsiv #define glGetActiveUniformName gl3wGetActiveUniformName #define glGetUniformBlockIndex gl3wGetUniformBlockIndex #define glGetActiveUniformBlockiv gl3wGetActiveUniformBlockiv #define glGetActiveUniformBlockName gl3wGetActiveUniformBlockName #define glUniformBlockBinding gl3wUniformBlockBinding #define glCopyBufferSubData gl3wCopyBufferSubData #define glDrawElementsBaseVertex gl3wDrawElementsBaseVertex #define glDrawRangeElementsBaseVertex gl3wDrawRangeElementsBaseVertex #define glDrawElementsInstancedBaseVertex gl3wDrawElementsInstancedBaseVertex #define glMultiDrawElementsBaseVertex gl3wMultiDrawElementsBaseVertex #define glProvokingVertex gl3wProvokingVertex #define glFenceSync gl3wFenceSync #define glIsSync gl3wIsSync #define glDeleteSync gl3wDeleteSync #define glClientWaitSync gl3wClientWaitSync #define glWaitSync gl3wWaitSync #define glGetInteger64v gl3wGetInteger64v #define glGetSynciv gl3wGetSynciv #define glTexImage2DMultisample gl3wTexImage2DMultisample #define glTexImage3DMultisample gl3wTexImage3DMultisample #define glGetMultisamplefv gl3wGetMultisamplefv #define glSampleMaski gl3wSampleMaski #define glBlendEquationiARB gl3wBlendEquationiARB #define glBlendEquationSeparateiARB gl3wBlendEquationSeparateiARB #define glBlendFunciARB gl3wBlendFunciARB #define glBlendFuncSeparateiARB gl3wBlendFuncSeparateiARB #define glMinSampleShadingARB gl3wMinSampleShadingARB #define glNamedStringARB gl3wNamedStringARB #define glDeleteNamedStringARB gl3wDeleteNamedStringARB #define glCompileShaderIncludeARB gl3wCompileShaderIncludeARB #define glIsNamedStringARB gl3wIsNamedStringARB #define glGetNamedStringARB gl3wGetNamedStringARB #define glGetNamedStringivARB gl3wGetNamedStringivARB #define glBindFragDataLocationIndexed gl3wBindFragDataLocationIndexed #define glGetFragDataIndex gl3wGetFragDataIndex #define glGenSamplers gl3wGenSamplers #define glDeleteSamplers gl3wDeleteSamplers #define glIsSampler gl3wIsSampler #define glBindSampler gl3wBindSampler #define glSamplerParameteri gl3wSamplerParameteri #define glSamplerParameteriv gl3wSamplerParameteriv #define glSamplerParameterf gl3wSamplerParameterf #define glSamplerParameterfv gl3wSamplerParameterfv #define glSamplerParameterIiv gl3wSamplerParameterIiv #define glSamplerParameterIuiv gl3wSamplerParameterIuiv #define glGetSamplerParameteriv gl3wGetSamplerParameteriv #define glGetSamplerParameterIiv gl3wGetSamplerParameterIiv #define glGetSamplerParameterfv gl3wGetSamplerParameterfv #define glGetSamplerParameterIuiv gl3wGetSamplerParameterIuiv #define glQueryCounter gl3wQueryCounter #define glGetQueryObjecti64v gl3wGetQueryObjecti64v #define glGetQueryObjectui64v gl3wGetQueryObjectui64v #define glVertexP2ui gl3wVertexP2ui #define glVertexP2uiv gl3wVertexP2uiv #define glVertexP3ui gl3wVertexP3ui #define glVertexP3uiv gl3wVertexP3uiv #define glVertexP4ui gl3wVertexP4ui #define glVertexP4uiv gl3wVertexP4uiv #define glTexCoordP1ui gl3wTexCoordP1ui #define glTexCoordP1uiv gl3wTexCoordP1uiv #define glTexCoordP2ui gl3wTexCoordP2ui #define glTexCoordP2uiv gl3wTexCoordP2uiv #define glTexCoordP3ui gl3wTexCoordP3ui #define glTexCoordP3uiv gl3wTexCoordP3uiv #define glTexCoordP4ui gl3wTexCoordP4ui #define glTexCoordP4uiv gl3wTexCoordP4uiv #define glMultiTexCoordP1ui gl3wMultiTexCoordP1ui #define glMultiTexCoordP1uiv gl3wMultiTexCoordP1uiv #define glMultiTexCoordP2ui gl3wMultiTexCoordP2ui #define glMultiTexCoordP2uiv gl3wMultiTexCoordP2uiv #define glMultiTexCoordP3ui gl3wMultiTexCoordP3ui #define glMultiTexCoordP3uiv gl3wMultiTexCoordP3uiv #define glMultiTexCoordP4ui gl3wMultiTexCoordP4ui #define glMultiTexCoordP4uiv gl3wMultiTexCoordP4uiv #define glNormalP3ui gl3wNormalP3ui #define glNormalP3uiv gl3wNormalP3uiv #define glColorP3ui gl3wColorP3ui #define glColorP3uiv gl3wColorP3uiv #define glColorP4ui gl3wColorP4ui #define glColorP4uiv gl3wColorP4uiv #define glSecondaryColorP3ui gl3wSecondaryColorP3ui #define glSecondaryColorP3uiv gl3wSecondaryColorP3uiv #define glVertexAttribP1ui gl3wVertexAttribP1ui #define glVertexAttribP1uiv gl3wVertexAttribP1uiv #define glVertexAttribP2ui gl3wVertexAttribP2ui #define glVertexAttribP2uiv gl3wVertexAttribP2uiv #define glVertexAttribP3ui gl3wVertexAttribP3ui #define glVertexAttribP3uiv gl3wVertexAttribP3uiv #define glVertexAttribP4ui gl3wVertexAttribP4ui #define glVertexAttribP4uiv gl3wVertexAttribP4uiv #define glDrawArraysIndirect gl3wDrawArraysIndirect #define glDrawElementsIndirect gl3wDrawElementsIndirect #define glUniform1d gl3wUniform1d #define glUniform2d gl3wUniform2d #define glUniform3d gl3wUniform3d #define glUniform4d gl3wUniform4d #define glUniform1dv gl3wUniform1dv #define glUniform2dv gl3wUniform2dv #define glUniform3dv gl3wUniform3dv #define glUniform4dv gl3wUniform4dv #define glUniformMatrix2dv gl3wUniformMatrix2dv #define glUniformMatrix3dv gl3wUniformMatrix3dv #define glUniformMatrix4dv gl3wUniformMatrix4dv #define glUniformMatrix2x3dv gl3wUniformMatrix2x3dv #define glUniformMatrix2x4dv gl3wUniformMatrix2x4dv #define glUniformMatrix3x2dv gl3wUniformMatrix3x2dv #define glUniformMatrix3x4dv gl3wUniformMatrix3x4dv #define glUniformMatrix4x2dv gl3wUniformMatrix4x2dv #define glUniformMatrix4x3dv gl3wUniformMatrix4x3dv #define glGetUniformdv gl3wGetUniformdv #define glGetSubroutineUniformLocation gl3wGetSubroutineUniformLocation #define glGetSubroutineIndex gl3wGetSubroutineIndex #define glGetActiveSubroutineUniformiv gl3wGetActiveSubroutineUniformiv #define glGetActiveSubroutineUniformName gl3wGetActiveSubroutineUniformName #define glGetActiveSubroutineName gl3wGetActiveSubroutineName #define glUniformSubroutinesuiv gl3wUniformSubroutinesuiv #define glGetUniformSubroutineuiv gl3wGetUniformSubroutineuiv #define glGetProgramStageiv gl3wGetProgramStageiv #define glPatchParameteri gl3wPatchParameteri #define glPatchParameterfv gl3wPatchParameterfv #define glBindTransformFeedback gl3wBindTransformFeedback #define glDeleteTransformFeedbacks gl3wDeleteTransformFeedbacks #define glGenTransformFeedbacks gl3wGenTransformFeedbacks #define glIsTransformFeedback gl3wIsTransformFeedback #define glPauseTransformFeedback gl3wPauseTransformFeedback #define glResumeTransformFeedback gl3wResumeTransformFeedback #define glDrawTransformFeedback gl3wDrawTransformFeedback #define glDrawTransformFeedbackStream gl3wDrawTransformFeedbackStream #define glBeginQueryIndexed gl3wBeginQueryIndexed #define glEndQueryIndexed gl3wEndQueryIndexed #define glGetQueryIndexediv gl3wGetQueryIndexediv #define glReleaseShaderCompiler gl3wReleaseShaderCompiler #define glShaderBinary gl3wShaderBinary #define glGetShaderPrecisionFormat gl3wGetShaderPrecisionFormat #define glDepthRangef gl3wDepthRangef #define glClearDepthf gl3wClearDepthf #define glGetProgramBinary gl3wGetProgramBinary #define glProgramBinary gl3wProgramBinary #define glProgramParameteri gl3wProgramParameteri #define glUseProgramStages gl3wUseProgramStages #define glActiveShaderProgram gl3wActiveShaderProgram #define glCreateShaderProgramv gl3wCreateShaderProgramv #define glBindProgramPipeline gl3wBindProgramPipeline #define glDeleteProgramPipelines gl3wDeleteProgramPipelines #define glGenProgramPipelines gl3wGenProgramPipelines #define glIsProgramPipeline gl3wIsProgramPipeline #define glGetProgramPipelineiv gl3wGetProgramPipelineiv #define glProgramUniform1i gl3wProgramUniform1i #define glProgramUniform1iv gl3wProgramUniform1iv #define glProgramUniform1f gl3wProgramUniform1f #define glProgramUniform1fv gl3wProgramUniform1fv #define glProgramUniform1d gl3wProgramUniform1d #define glProgramUniform1dv gl3wProgramUniform1dv #define glProgramUniform1ui gl3wProgramUniform1ui #define glProgramUniform1uiv gl3wProgramUniform1uiv #define glProgramUniform2i gl3wProgramUniform2i #define glProgramUniform2iv gl3wProgramUniform2iv #define glProgramUniform2f gl3wProgramUniform2f #define glProgramUniform2fv gl3wProgramUniform2fv #define glProgramUniform2d gl3wProgramUniform2d #define glProgramUniform2dv gl3wProgramUniform2dv #define glProgramUniform2ui gl3wProgramUniform2ui #define glProgramUniform2uiv gl3wProgramUniform2uiv #define glProgramUniform3i gl3wProgramUniform3i #define glProgramUniform3iv gl3wProgramUniform3iv #define glProgramUniform3f gl3wProgramUniform3f #define glProgramUniform3fv gl3wProgramUniform3fv #define glProgramUniform3d gl3wProgramUniform3d #define glProgramUniform3dv gl3wProgramUniform3dv #define glProgramUniform3ui gl3wProgramUniform3ui #define glProgramUniform3uiv gl3wProgramUniform3uiv #define glProgramUniform4i gl3wProgramUniform4i #define glProgramUniform4iv gl3wProgramUniform4iv #define glProgramUniform4f gl3wProgramUniform4f #define glProgramUniform4fv gl3wProgramUniform4fv #define glProgramUniform4d gl3wProgramUniform4d #define glProgramUniform4dv gl3wProgramUniform4dv #define glProgramUniform4ui gl3wProgramUniform4ui #define glProgramUniform4uiv gl3wProgramUniform4uiv #define glProgramUniformMatrix2fv gl3wProgramUniformMatrix2fv #define glProgramUniformMatrix3fv gl3wProgramUniformMatrix3fv #define glProgramUniformMatrix4fv gl3wProgramUniformMatrix4fv #define glProgramUniformMatrix2dv gl3wProgramUniformMatrix2dv #define glProgramUniformMatrix3dv gl3wProgramUniformMatrix3dv #define glProgramUniformMatrix4dv gl3wProgramUniformMatrix4dv #define glProgramUniformMatrix2x3fv gl3wProgramUniformMatrix2x3fv #define glProgramUniformMatrix3x2fv gl3wProgramUniformMatrix3x2fv #define glProgramUniformMatrix2x4fv gl3wProgramUniformMatrix2x4fv #define glProgramUniformMatrix4x2fv gl3wProgramUniformMatrix4x2fv #define glProgramUniformMatrix3x4fv gl3wProgramUniformMatrix3x4fv #define glProgramUniformMatrix4x3fv gl3wProgramUniformMatrix4x3fv #define glProgramUniformMatrix2x3dv gl3wProgramUniformMatrix2x3dv #define glProgramUniformMatrix3x2dv gl3wProgramUniformMatrix3x2dv #define glProgramUniformMatrix2x4dv gl3wProgramUniformMatrix2x4dv #define glProgramUniformMatrix4x2dv gl3wProgramUniformMatrix4x2dv #define glProgramUniformMatrix3x4dv gl3wProgramUniformMatrix3x4dv #define glProgramUniformMatrix4x3dv gl3wProgramUniformMatrix4x3dv #define glValidateProgramPipeline gl3wValidateProgramPipeline #define glGetProgramPipelineInfoLog gl3wGetProgramPipelineInfoLog #define glVertexAttribL1d gl3wVertexAttribL1d #define glVertexAttribL2d gl3wVertexAttribL2d #define glVertexAttribL3d gl3wVertexAttribL3d #define glVertexAttribL4d gl3wVertexAttribL4d #define glVertexAttribL1dv gl3wVertexAttribL1dv #define glVertexAttribL2dv gl3wVertexAttribL2dv #define glVertexAttribL3dv gl3wVertexAttribL3dv #define glVertexAttribL4dv gl3wVertexAttribL4dv #define glVertexAttribLPointer gl3wVertexAttribLPointer #define glGetVertexAttribLdv gl3wGetVertexAttribLdv #define glViewportArrayv gl3wViewportArrayv #define glViewportIndexedf gl3wViewportIndexedf #define glViewportIndexedfv gl3wViewportIndexedfv #define glScissorArrayv gl3wScissorArrayv #define glScissorIndexed gl3wScissorIndexed #define glScissorIndexedv gl3wScissorIndexedv #define glDepthRangeArrayv gl3wDepthRangeArrayv #define glDepthRangeIndexed gl3wDepthRangeIndexed #define glGetFloati_v gl3wGetFloati_v #define glGetDoublei_v gl3wGetDoublei_v #define glCreateSyncFromCLeventARB gl3wCreateSyncFromCLeventARB #define glDebugMessageControlARB gl3wDebugMessageControlARB #define glDebugMessageInsertARB gl3wDebugMessageInsertARB #define glDebugMessageCallbackARB gl3wDebugMessageCallbackARB #define glGetDebugMessageLogARB gl3wGetDebugMessageLogARB #define glGetGraphicsResetStatusARB gl3wGetGraphicsResetStatusARB #define glGetnTexImageARB gl3wGetnTexImageARB #define glReadnPixelsARB gl3wReadnPixelsARB #define glGetnCompressedTexImageARB gl3wGetnCompressedTexImageARB #define glGetnUniformfvARB gl3wGetnUniformfvARB #define glGetnUniformivARB gl3wGetnUniformivARB #define glGetnUniformuivARB gl3wGetnUniformuivARB #define glGetnUniformdvARB gl3wGetnUniformdvARB #define glDrawArraysInstancedBaseInstance gl3wDrawArraysInstancedBaseInstance #define glDrawElementsInstancedBaseInstance \ gl3wDrawElementsInstancedBaseInstance #define glDrawElementsInstancedBaseVertexBaseInstance \ gl3wDrawElementsInstancedBaseVertexBaseInstance #define glDrawTransformFeedbackInstanced gl3wDrawTransformFeedbackInstanced #define glDrawTransformFeedbackStreamInstanced \ gl3wDrawTransformFeedbackStreamInstanced #define glGetInternalformativ gl3wGetInternalformativ #define glGetActiveAtomicCounterBufferiv gl3wGetActiveAtomicCounterBufferiv #define glBindImageTexture gl3wBindImageTexture #define glMemoryBarrier gl3wMemoryBarrier #define glTexStorage1D gl3wTexStorage1D #define glTexStorage2D gl3wTexStorage2D #define glTexStorage3D gl3wTexStorage3D #define glTextureStorage1DEXT gl3wTextureStorage1DEXT #define glTextureStorage2DEXT gl3wTextureStorage2DEXT #define glTextureStorage3DEXT gl3wTextureStorage3DEXT #define glDebugMessageControl gl3wDebugMessageControl #define glDebugMessageInsert gl3wDebugMessageInsert #define glDebugMessageCallback gl3wDebugMessageCallback #define glGetDebugMessageLog gl3wGetDebugMessageLog #define glPushDebugGroup gl3wPushDebugGroup #define glPopDebugGroup gl3wPopDebugGroup #define glObjectLabel gl3wObjectLabel #define glGetObjectLabel gl3wGetObjectLabel #define glObjectPtrLabel gl3wObjectPtrLabel #define glGetObjectPtrLabel gl3wGetObjectPtrLabel #define glClearBufferData gl3wClearBufferData #define glClearBufferSubData gl3wClearBufferSubData #define glClearNamedBufferDataEXT gl3wClearNamedBufferDataEXT #define glClearNamedBufferSubDataEXT gl3wClearNamedBufferSubDataEXT #define glDispatchCompute gl3wDispatchCompute #define glDispatchComputeIndirect gl3wDispatchComputeIndirect #define glCopyImageSubData gl3wCopyImageSubData #define glTextureView gl3wTextureView #define glBindVertexBuffer gl3wBindVertexBuffer #define glVertexAttribFormat gl3wVertexAttribFormat #define glVertexAttribIFormat gl3wVertexAttribIFormat #define glVertexAttribLFormat gl3wVertexAttribLFormat #define glVertexAttribBinding gl3wVertexAttribBinding #define glVertexBindingDivisor gl3wVertexBindingDivisor #define glVertexArrayBindVertexBufferEXT gl3wVertexArrayBindVertexBufferEXT #define glVertexArrayVertexAttribFormatEXT gl3wVertexArrayVertexAttribFormatEXT #define glVertexArrayVertexAttribIFormatEXT \ gl3wVertexArrayVertexAttribIFormatEXT #define glVertexArrayVertexAttribLFormatEXT \ gl3wVertexArrayVertexAttribLFormatEXT #define glVertexArrayVertexAttribBindingEXT \ gl3wVertexArrayVertexAttribBindingEXT #define glVertexArrayVertexBindingDivisorEXT \ gl3wVertexArrayVertexBindingDivisorEXT #define glFramebufferParameteri gl3wFramebufferParameteri #define glGetFramebufferParameteriv gl3wGetFramebufferParameteriv #define glNamedFramebufferParameteriEXT gl3wNamedFramebufferParameteriEXT #define glGetNamedFramebufferParameterivEXT \ gl3wGetNamedFramebufferParameterivEXT #define glGetInternalformati64v gl3wGetInternalformati64v #define glInvalidateTexSubImage gl3wInvalidateTexSubImage #define glInvalidateTexImage gl3wInvalidateTexImage #define glInvalidateBufferSubData gl3wInvalidateBufferSubData #define glInvalidateBufferData gl3wInvalidateBufferData #define glInvalidateFramebuffer gl3wInvalidateFramebuffer #define glInvalidateSubFramebuffer gl3wInvalidateSubFramebuffer #define glMultiDrawArraysIndirect gl3wMultiDrawArraysIndirect #define glMultiDrawElementsIndirect gl3wMultiDrawElementsIndirect #define glGetProgramInterfaceiv gl3wGetProgramInterfaceiv #define glGetProgramResourceIndex gl3wGetProgramResourceIndex #define glGetProgramResourceName gl3wGetProgramResourceName #define glGetProgramResourceiv gl3wGetProgramResourceiv #define glGetProgramResourceLocation gl3wGetProgramResourceLocation #define glGetProgramResourceLocationIndex gl3wGetProgramResourceLocationIndex #define glShaderStorageBlockBinding gl3wShaderStorageBlockBinding #define glTexBufferRange gl3wTexBufferRange #define glTextureBufferRangeEXT gl3wTextureBufferRangeEXT #define glTexStorage2DMultisample gl3wTexStorage2DMultisample #define glTexStorage3DMultisample gl3wTexStorage3DMultisample #define glTextureStorage2DMultisampleEXT gl3wTextureStorage2DMultisampleEXT #define glTextureStorage3DMultisampleEXT gl3wTextureStorage3DMultisampleEXT #ifdef __cplusplus } #endif #endif <file_sep>/extlibs/imgui/examples/imgui_impl_glfw.h // dear imgui: Platform Binding for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..) // (Info: GLFW is a cross-platform general purpose library for handling windows, // inputs, OpenGL/Vulkan graphics context creation, etc.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= // ImGuiConfigFlags_NavEnableGamepad'. [x] Platform: Mouse cursor shape and // visibility. Disable with 'io.ConfigFlags |= // ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing // from GLFW. [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, // e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). // You can copy and use unmodified imgui_impl_* files in your project. See // main.cpp for an example of using this. If you are new to dear imgui, read // examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui // About GLSL version: // The 'glsl_version' initialization parameter defaults to "#version 150" if // NULL. Only override if your GL version doesn't handle this GLSL version. Keep // NULL if unsure! #pragma once #include "imgui.h" // IMGUI_IMPL_API struct GLFWwindow; IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL( GLFWwindow* window, bool install_callbacks); IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan( GLFWwindow* window, bool install_callbacks); IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); // GLFW callbacks // - When calling Init with 'install_callbacks=true': GLFW callbacks will be // installed for you. They will call user's previously installed callbacks, if // any. // - When calling Init with 'install_callbacks=false': GLFW callbacks won't be // installed. You will need to call those function yourself from your own GLFW // callbacks. IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback( GLFWwindow* window, int button, int action, int mods); IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback( GLFWwindow* window, double xoffset, double yoffset); IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback( GLFWwindow* window, int key, int scancode, int action, int mods); IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback( GLFWwindow* window, unsigned int c); <file_sep>/src/DoomFireApplication.cpp #include "DoomFireApplication.h" #include "Util.h" #include <GL/glew.h> #include <SDL.h> #include <cstring> #include <imgui.h> #include <iostream> #include <glm/vec2.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> static const char *vertexShaderSource = R"(#version 330 core uniform mat4 xform; layout (location = 0) in vec4 attr_vertex; out vec2 uv; void main() { gl_Position = xform * attr_vertex; uv = (attr_vertex.xy * vec2(0.5, -0.5) + 0.5); })"; static const char *fragmentShaderSource = R"(#version 330 core out vec4 FragColor; in vec2 uv; uniform sampler2D img_tex; uniform sampler1D pal_tex; void main() { float cidx = texture(img_tex, uv).x; vec3 color = texture(pal_tex, cidx).xyz; FragColor.xyz = color; FragColor.a = 1.0; })"; struct Vertex { glm::vec2 pos; }; enum class VertexAttributeType { Byte = GL_BYTE, UnsignedByte = GL_UNSIGNED_BYTE, Short = GL_SHORT, UnsignedShort = GL_UNSIGNED_SHORT, Float = GL_FLOAT, }; struct VertexAttribute { const char *name; int size; VertexAttributeType type; bool normalized; std::size_t offset; }; static constexpr Vertex vertices[] = { {{1.0f, 1.0f}}, // top right {{1.0f, -1.0f}}, // bottom right {{-1.0f, -1.0f}}, // bottom left {{-1.0f, 1.0f}}, // top left }; static constexpr unsigned int indices[] = { // note that we start from 0! 0, 1, 3,// first triangle 1, 2, 3 // second triangle }; const std::uint8_t palette[] = { 0x07, 0x07, 0x07, 0x1F, 0x07, 0x07, 0x2F, 0x0F, 0x07, 0x47, 0x0F, 0x07, 0x57, 0x17, 0x07, 0x67, 0x1F, 0x07, 0x77, 0x1F, 0x07, 0x8F, 0x27, 0x07, 0x9F, 0x2F, 0x07, 0xAF, 0x3F, 0x07, 0xBF, 0x47, 0x07, 0xC7, 0x47, 0x07, 0xDF, 0x4F, 0x07, 0xDF, 0x57, 0x07, 0xDF, 0x57, 0x07, 0xD7, 0x5F, 0x07, 0xD7, 0x5F, 0x07, 0xD7, 0x67, 0x0F, 0xCF, 0x6F, 0x0F, 0xCF, 0x77, 0x0F, 0xCF, 0x7F, 0x0F, 0xCF, 0x87, 0x17, 0xC7, 0x87, 0x17, 0xC7, 0x8F, 0x17, 0xC7, 0x97, 0x1F, 0xBF, 0x9F, 0x1F, 0xBF, 0x9F, 0x1F, 0xBF, 0xA7, 0x27, 0xBF, 0xA7, 0x27, 0xBF, 0xAF, 0x2F, 0xB7, 0xAF, 0x2F, 0xB7, 0xB7, 0x2F, 0xB7, 0xB7, 0x37, 0xCF, 0xCF, 0x6F, 0xDF, 0xDF, 0x9F, 0xEF, 0xEF, 0xC7, 0xFF, 0xFF, 0xFF}; static int drawPalette(const std::uint8_t *pal, int numColors = 256, int numColorsByRow = 13, const ImVec2 &size = ImVec2(12, 12), const ImVec2 &spacing = ImVec2(2, 2)) { auto pos = ImGui::GetCursorScreenPos(); const auto begPos = pos; auto drawList = ImGui::GetWindowDrawList(); auto numRows = numColors / numColorsByRow; if (numColors % numColorsByRow != 0) numRows++; auto num = 0; int index = -1; for (auto j = 0; j < numRows; ++j) { for (auto i = 0; i < numColorsByRow; ++i) { if (num == numColors) break; num++; auto color = ImColor(static_cast<int>(pal[0]), static_cast<int>(pal[1]), static_cast<int>(pal[2]), 255); pal += 3; auto max = ImVec2(pos.x + size.x, pos.y + size.y); drawList->AddRectFilled(pos, max, color); drawList->AddRect(pos, max, ImColor(0.8f, 0.8f, 0.8f, 1.0f), 0.0f, ImDrawCornerFlags_All, 0.2f); if (ImGui::IsMouseHoveringRect(pos, max)) { index = num; } pos.x += (size.x + spacing.x); } pos.x = begPos.x; pos.y += (size.y + spacing.y); } ImGui::SetCursorScreenPos({begPos.x, pos.y}); return index; } void DoomFireApplication::reset() { // Set whole screen to 0 (color: 0x07,0x07,0x07) memset(m_image.data(), 0, m_image.size()); // Set bottom line to 37 (color white: 0xFF,0xFF,0xFF) memset(m_image.data() + (FIRE_HEIGHT - 1) * FIRE_WIDTH, 36, FIRE_WIDTH); } void DoomFireApplication::onInit() { Application::onInit(); reset(); m_vbo = std::make_unique<VertexBuffer>(VertexBuffer::Type::Array); m_ebo = std::make_unique<VertexBuffer>(VertexBuffer::Type::Element); m_shader = std::make_unique<Shader>(vertexShaderSource, fragmentShaderSource); m_vao = std::make_unique<VertexArray>(); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). m_vao->bind(); m_vbo->buffer(sizeof(vertices), vertices); m_ebo->buffer(sizeof(indices), indices); VertexAttribute attributes[]{ "attr_vertex", 2, VertexAttributeType::Float, false, sizeof(Vertex) }; for (auto info : attributes) { auto loc = m_shader->getAttributeLocation(info.name); if (loc == -1) continue; GL_CHECK(glEnableVertexAttribArray(loc)); GL_CHECK(glVertexAttribPointer(loc, info.size, static_cast<GLenum>(info.type), info.normalized ? GL_TRUE : GL_FALSE, info.offset, nullptr)); } VertexArray::unbind(); VertexBuffer::unbind(VertexBuffer::Type::Array); VertexBuffer::unbind(VertexBuffer::Type::Element); m_img_tex = std::make_unique<Texture>(Texture::Format::Alpha, FIRE_WIDTH, FIRE_HEIGHT, nullptr); m_pal_tex = std::make_unique<Texture>(Texture::Format::Rgb, 256, palette); m_shader->setUniform("img_tex", *m_img_tex); m_shader->setUniform("pal_tex", *m_pal_tex); } int width = 1280; int height = 720; int amountX = 0; int amountY = 0; void DoomFireApplication::onEvent(SDL_Event &event) { switch (event.type) case SDL_WINDOWEVENT: { int w, h; SDL_GL_GetDrawableSize(m_window.getNativeHandle(), &w, &h); reshape(w, h); break; case SDL_KEYDOWN: if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) { m_done = true; } break; case SDL_CONTROLLERAXISMOTION: if (event.jaxis.axis == 0) { amountX = static_cast<int>((10.f * event.jaxis.value) / std::numeric_limits<std::int16_t>::max()); } else if (event.jaxis.axis == 1) { amountY = static_cast<int>((10.f * event.jaxis.value) / std::numeric_limits<std::int16_t>::max()); } break; case SDL_JOYBUTTONDOWN: { auto button = event.jbutton.button; if (button == 0) { reset(); } } break; } } void DoomFireApplication::onRender() { glClearColor(0.3f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); m_vao->bind(); m_target.draw(PrimitiveType::Triangles, ElementType::UnsignedInt, 6, m_shader.get()); m_vao->unbind(); Application::onRender(); } void DoomFireApplication::onUpdate(const TimeSpan &elapsed) { if (amountX != 0) { width += amountX; std::clamp(width, 10, 1280 * 2); reshape(width, height); } if (amountY != 0) { height += amountY; std::clamp(height, 10, 720 * 2); reshape(width, height); } // Update palette buffer doFire(); m_img_tex->setData(FIRE_WIDTH, FIRE_HEIGHT, m_image.data()); } void DoomFireApplication::reshape(int x, int y) const { auto aspect = (float) x / (float) y; auto fbaspect = (float) FIRE_WIDTH / (float) FIRE_HEIGHT; glViewport(0, 0, x, y); glm::vec3 vaspect(1, 1, 1); if (aspect > fbaspect) { vaspect[0] = fbaspect / aspect; } else if (fbaspect > aspect) { vaspect[1] = aspect / fbaspect; } auto xform = glm::scale(glm::mat4(1), vaspect); m_shader->setUniform("xform", xform); } void DoomFireApplication::onImGuiRender() { ImGui::Begin("Info"); ImGui::Text("%.2f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); if (ImGui::Button("Reset")) { reset(); } drawPalette(palette, 37); ImGui::End(); } void DoomFireApplication::spreadFire(int src) { auto pixel = m_image[src]; if (pixel == 0) { m_image[src - FIRE_WIDTH] = 0; } else { auto randIdx = static_cast<int>(3.0f * static_cast<float>(rand()) / RAND_MAX); auto dst = src - randIdx + 1; m_image[dst - FIRE_WIDTH] = pixel - (randIdx & 1); } } void DoomFireApplication::doFire() { for (auto x = 0; x < FIRE_WIDTH; x++) { for (auto y = 1; y < FIRE_HEIGHT; y++) { spreadFire(y * FIRE_WIDTH + x); } } } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.16) project(DoomFire) set(CMAKE_CXX_STANDARD 17) find_package(GLEW REQUIRED) find_package(SDL2 REQUIRED) if (NOT WIN32) find_package(OpenGL REQUIRED) endif () include_directories(${PROJECT_SOURCE_DIR}/extlibs/imgui ${PROJECT_SOURCE_DIR}/extlibs) add_library(imgui # Main Imgui files extlibs/imgui/imgui.cpp extlibs/imgui/imgui_draw.cpp extlibs/imgui/imgui_widgets.cpp extlibs/imgui/misc/cpp/imgui_stdlib.cpp # SDL2+OpenGL-specific files extlibs/imgui/examples/imgui_impl_sdl.cpp) include_directories(${NGLIB_HEADERS_DIR} ${SDL2_INCLUDE_DIRS}) add_executable(${PROJECT_NAME} src/main.cpp src/Application.cpp src/DoomFireApplication.cpp src/TimeSpan.cpp src/Util.cpp src/Window.cpp extlibs/imgui/examples/imgui_impl_opengl3.cpp) target_compile_definitions(${PROJECT_NAME} PUBLIC "$<$<CONFIG:DEBUG>:DEBUG>") target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARIES} GLEW::GLEW imgui) <file_sep>/src/Application.h #ifndef COLORCYCLING__APPLICATION_H #define COLORCYCLING__APPLICATION_H #include "TimeSpan.h" #include "Window.h" class Application { public: Application(); virtual ~Application(); void run(); protected: virtual void onInit(); virtual void onExit(); virtual void onUpdate(const TimeSpan& elapsed); virtual void onRender(); virtual void onImGuiRender(); virtual void onEvent(SDL_Event& event); private: void processEvents(); protected: Window m_window; bool m_done{false}; float m_fps{0}; int m_frames{0}; }; #endif//COLORCYCLING__APPLICATION_H <file_sep>/src/main.cpp #include "DoomFireApplication.h" int main() { DoomFireApplication app; app.run(); return EXIT_SUCCESS; }<file_sep>/extlibs/imgui/examples/example_marmalade/main.cpp // dear imgui: standalone example application for Marmalade // If you are new to dear imgui, see examples/README.txt and documentation at // the top of imgui.cpp. // Copyright (C) 2015 by <NAME> // This file is part of Dear ImGui #include "imgui.h" #include "imgui_impl_marmalade.h" #include <stdio.h> #include <s3eKeyboard.h> #include <s3ePointer.h> #include <IwGx.h> int main(int, char**) { IwGxInit(); // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; // io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard // Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); // ImGui::StyleColorsClassic(); // Setup Platform/Renderer bindings ImGui_Marmalade_Init(true); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can // also load multiple fonts and use ImGui::PushFont()/PopFont() to select // them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you // need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please // handle those errors in your application (e.g. use an assertion, or // display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and // stored into a texture when calling // ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame // below will call. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string // literal you need to write a double backslash \\ ! // io.Fonts->AddFontDefault(); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); // ImFont* font = // io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, // NULL, io.Fonts->GetGlyphRangesJapanese()); IM_ASSERT(font != NULL); // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Main loop while(true) { if(s3eDeviceCheckQuitRequest()) break; // Poll and handle inputs // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to // tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data // to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input // data to your main application. Generally you may always pass all // inputs to dear imgui, and hide them from your application based on // those two flags. s3eKeyboardUpdate(); s3ePointerUpdate(); // Start the Dear ImGui frame ImGui_Marmalade_NewFrame(); ImGui::NewFrame(); // 1. Show the big demo window (Most of the sample code is in // ImGui::ShowDemoWindow()! You can browse its code to learn more about // Dear ImGui!). if(show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End // pair to created a named window. { static float f = 0.0f; static int counter = 0; ImGui::Begin("Hello, world!"); // Create a window called "Hello, // world!" and append into it. ImGui::Text( "This is some useful text."); // Display some text (you can use // a format strings too) ImGui::Checkbox( "Demo Window", &show_demo_window); // Edit bools storing our // window open/close state ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color if(ImGui::Button( "Button")) // Buttons return true when clicked (most widgets // return true when edited/activated) counter++; ImGui::SameLine(); ImGui::Text("counter = %d", counter); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); } // 3. Show another simple window. if(show_another_window) { ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable // (the window will have a closing button // that will clear the bool when clicked) ImGui::Text("Hello from another window!"); if(ImGui::Button("Close Me")) show_another_window = false; ImGui::End(); } // Rendering ImGui::Render(); IwGxSetColClear(clear_color.x * 255, clear_color.y * 255, clear_color.z * 255, clear_color.w * 255); IwGxClear(); ImGui_Marmalade_RenderDrawData(ImGui::GetDrawData()); IwGxSwapBuffers(); s3eDeviceYield(0); } // Cleanup ImGui_Marmalade_Shutdown(); ImGui::DestroyContext(); IwGxTerminate(); return 0; } <file_sep>/src/VertexBuffer.h #pragma once #include <GL/glew.h> class VertexBuffer { public: enum class Type { Array, Element }; /// Creates a new data store for a buffer object. /// \param type: Specifies the target to which the buffer object is bound. explicit VertexBuffer(Type type) : m_type(type) { glGenBuffers(1, &m_vbo); } ~VertexBuffer() { glDeleteBuffers(1, &m_vbo); } /// Sets new data to a buffer object. /// \param size: Specifies the size in bytes of the buffer object's new data store. /// \param data: Specifies a pointer to data that will be copied into the data store for initialization, or nullptr if no data is to be copied. void buffer(size_t size, const void *data) const { auto target = getTarget(m_type); glBindBuffer(target, m_vbo); glBufferData(target, size, data, GL_STATIC_DRAW); } void bind() const { auto target = getTarget(m_type); glBindBuffer(target, m_vbo); } static void unbind(Type type) { auto target = getTarget(type); glBindBuffer(target, 0); } private: static GLenum getTarget(Type type) { return type == Type::Array ? GL_ARRAY_BUFFER : GL_ELEMENT_ARRAY_BUFFER; } private: Type m_type; unsigned int m_vbo{0}; };<file_sep>/extlibs/imgui/imconfig.h //----------------------------------------------------------------------------- // COMPILE-TIME OPTIONS FOR DEAR IMGUI // Runtime options (clipboard callbacks, enabling various features, etc.) can // generally be set via the ImGuiIO structure. You can use // ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to // rewire memory allocation functions. //----------------------------------------------------------------------------- // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or // maintain a patch/branch with your modifications to imconfig.h) B) or add // configuration directives in your own file and compile with #define // IMGUI_USER_CONFIG "myfilename.h" If you do so you need to make sure that // configuration settings are defined consistently _everywhere_ Dear ImGui is // used, which include the imgui*.cpp files but also _any_ of your code that // uses Dear ImGui. This is because some compile-time options have an affect on // data structures. Defining those options in imconfig.h will ensure every // compilation unit gets to see the same data structure layouts. Call // IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures // your files are using are matching the ones imgui.cpp is using. //----------------------------------------------------------------------------- #pragma once //---- Define assertion handler. Defaults to calling assert(). // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } // while (0)' block so it can be used as a single statement. //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts //---- Define attributes of all API symbols declarations, e.g. for DLL under //Windows // Using dear imgui via a shared library is not recommended, because of function // call overhead and because we don't guarantee backward nor forward ABI // compatibility. //#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllimport ) //---- Don't define obsolete functions/enums/behaviors. Consider enabling from //time to time after updating to avoid using soon-to-be obsolete function/names. //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Disable all of Dear ImGui or don't implement standard windows. // It is very strongly recommended to NOT disable the demo windows during // development. Please read comments in imgui_demo.cpp. //#define IMGUI_DISABLE // Disable //everything: all headers and source files will be empty. #define //IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: //ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. #define //IMGUI_DISABLE_METRICS_WINDOW // Disable debug/metrics //window: ShowMetricsWindow() will be empty. //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't //implement default clipboard handler. Won't use and link with //OpenClipboard/GetClipboardData/CloseClipboard etc. #define //IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement //default IME handler. Won't use and link with //ImmGetContext/ImmSetCompositionWindow. #define IMGUI_DISABLE_WIN32_FUNCTIONS //// [Win32] Won't use and link with any Win32 function (clipboard, ime). //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement //default OSX clipboard handler (need to link with '-framework //ApplicationServices', this is why this is not the default). #define //IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement //ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you //don't want to link with vsnprintf) #define //IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement //ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement //them yourself. #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // //Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite so you can //implement them yourself if you don't want to link with //fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement //default allocators calling malloc()/free() to avoid linking with them. You //will need to call ImGui::SetAllocatorFunctions(). //---- Include imgui_user.h at the end of imgui.h as a convenience //#define IMGUI_INCLUDE_IMGUI_USER_H //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to //another) #define IMGUI_USE_BGRA_PACKED_COLOR //---- Use 32-bit for ImWchar (default is 16-bit) to support full unicode code //points. #define IMGUI_USE_WCHAR32 //---- Avoid multiple STB libraries implementations, or redefine path/filenames //to prioritize another version // By default the embedded implementations are declared static and not available // outside of imgui cpp files. //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //---- Unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined, use the much //faster STB sprintf library implementation of vsnprintf instead of the one from //the default C library. // Note that stb_sprintf.h is meant to be provided by the user and available in // the include path at compile time. Also, the compatibility checks of the // arguments and formats done by clang and GCC will be disabled in order to // support the extra formats provided by STB sprintf. #define // IMGUI_USE_STB_SPRINTF //---- Define constructor and implicit cast operators to convert back<>forth //between your math types and ImVec2/ImVec4. // This will be inlined as part of ImVec2 and ImVec4 class declarations. /* #define IM_VEC2_CLASS_EXTRA \ ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ operator MyVec2() const { return MyVec2(x,y); } #define IM_VEC4_CLASS_EXTRA \ ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ operator MyVec4() const { return MyVec4(x,y,z,w); } */ //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large //meshes with more than 64K vertices. // Your renderer back-end will need to support it (most example renderer // back-ends support both 16/32-bit indices). Another way to allow large meshes // while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your // renderer. Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int //---- Override ImDrawCallback signature (will need to modify renderer back-ends //accordingly) struct ImDrawList; struct ImDrawCmd; typedef void // (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* // my_renderer_user_data); #define ImDrawCallback MyImDrawCallback //---- Debug Tools: Macro to break in Debugger // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break // into them for easy debugging.) //#define IM_DEBUG_BREAK IM_ASSERT(0) //#define IM_DEBUG_BREAK __debugbreak() //---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead //of ItemHoverable(), // (which comes earlier in the code, will catch a few extra items, allow picking // items other than Hovered one.) This adds a small runtime cost which is why it // is not enabled by default. //#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX //---- Debug Tools: Enable slower asserts //#define IMGUI_DEBUG_PARANOID //---- Tip: You can add extra functions within the ImGui:: namespace, here or in //your own headers files. /* namespace ImGui { void MyFunction(const char* name, const MyMatrix44& v); } */ <file_sep>/src/Application.cpp #include "Application.h" #include "StopWatch.h" #include <imgui.h> #include <imgui/examples/imgui_impl_opengl3.h> #include <imgui/examples/imgui_impl_sdl.h> #include <utility> namespace { const TimeSpan TimePerFrame = TimeSpan::seconds(1.f / 60.f); } Application::Application() = default; Application::~Application() = default; void Application::run() { onInit(); processEvents(); int frames = 0; StopWatch fpsStopWatch; StopWatch stopWatch; auto timeSinceLastUpdate = TimeSpan::Zero; // Main loop while (!m_done) { auto elapsed = stopWatch.restart(); timeSinceLastUpdate += elapsed; while (timeSinceLastUpdate > TimePerFrame) { timeSinceLastUpdate -= TimePerFrame; processEvents(); onUpdate(TimePerFrame); } if (fpsStopWatch.getElapsedTime() >= TimeSpan::seconds(1)) { m_fps = static_cast<float>(frames) / fpsStopWatch.getElapsedTime().getTotalSeconds(); fpsStopWatch.restart(); frames = 0; } onRender(); frames++; m_window.display(); } onExit(); } void Application::processEvents() { SDL_Event event; while (m_window.pollEvent(event)) { ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) { m_done = true; } else { if (!ImGui::GetIO().WantTextInput && !ImGui::GetIO().WantCaptureMouse) { onEvent(event); } } } } void Application::onInit() { m_window.init(); } void Application::onExit() { } void Application::onUpdate(const TimeSpan &) { } void Application::onRender() { // Render dear imgui ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(m_window.getNativeHandle()); ImGui::NewFrame(); onImGuiRender(); // imgui render ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); m_frames++; } void Application::onImGuiRender() { } void Application::onEvent(SDL_Event &) { } <file_sep>/src/RenderTarget.h #pragma once #include "Debug.h" #include "VertexBuffer.h" #include "Shader.h" enum class PrimitiveType { Points, LineStrip, LineLoop, Lines, TriangleStrip, TriangleFan, Triangles, }; enum class ElementType { Byte = GL_BYTE, UnsignedByte = GL_UNSIGNED_BYTE, Short = GL_SHORT, UnsignedShort = GL_UNSIGNED_SHORT, Int = GL_INT, UnsignedInt = GL_UNSIGNED_INT, }; class RenderTarget { public: void draw(const PrimitiveType primitiveType, const ElementType elementType, size_t size, const Shader *pShader) { if (pShader) Shader::bind(pShader); GL_CHECK(glDrawElements(getEnum(primitiveType), size, static_cast<GLenum>(elementType), nullptr)); } private: static GLenum getEnum(PrimitiveType type) { switch (type) { case PrimitiveType::Points:return GL_POINTS; case PrimitiveType::LineStrip:return GL_LINE_STRIP; case PrimitiveType::LineLoop:return GL_LINE_LOOP; case PrimitiveType::Lines:return GL_LINES; case PrimitiveType::TriangleStrip:return GL_TRIANGLE_STRIP; case PrimitiveType::TriangleFan:return GL_TRIANGLE_FAN; case PrimitiveType::Triangles:return GL_TRIANGLES; } assert(false); } };<file_sep>/extlibs/imgui/examples/example_glfw_opengl2/main.cpp // dear imgui: standalone example application for GLFW + OpenGL2, using legacy // fixed pipeline If you are new to dear imgui, see examples/README.txt and // documentation at the top of imgui.cpp. (GLFW is a cross-platform general // purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics // context creation, etc.) // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, // VBO, VAO, etc.)** // **Prefer using the code in the example_glfw_opengl2/ folder** // See imgui_impl_glfw.cpp for details. #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl2.h" #include <stdio.h> #ifdef __APPLE__ #define GL_SILENCE_DEPRECATION #endif #include <GLFW/glfw3.h> // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to // maximize ease of testing and compatibility with old VS compilers. To link // with VS2010-era libraries, VS2015+ requires linking with // legacy_stdio_definitions.lib, which we do using this pragma. Your own project // should not be affected, as you are likely to link with a newer binary of GLFW // that is adequate for your version of Visual Studio. #if defined(_MSC_VER) && (_MSC_VER >= 1900) && \ !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) #pragma comment(lib, "legacy_stdio_definitions") #endif static void glfw_error_callback(int error, const char* description) { fprintf(stderr, "Glfw Error %d: %s\n", error, description); } int main(int, char**) { // Setup window glfwSetErrorCallback(glfw_error_callback); if(!glfwInit()) return 1; GLFWwindow* window = glfwCreateWindow( 1280, 720, "Dear ImGui GLFW+OpenGL2 example", NULL, NULL); if(window == NULL) return 1; glfwMakeContextCurrent(window); glfwSwapInterval(1); // Enable vsync // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; // io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable // Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); // ImGui::StyleColorsClassic(); // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL2_Init(); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can // also load multiple fonts and use ImGui::PushFont()/PopFont() to select // them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you // need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please // handle those errors in your application (e.g. use an assertion, or // display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and // stored into a texture when calling // ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame // below will call. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string // literal you need to write a double backslash \\ ! // io.Fonts->AddFontDefault(); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); // io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); // ImFont* font = // io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, // NULL, io.Fonts->GetGlyphRangesJapanese()); IM_ASSERT(font != NULL); // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Main loop while(!glfwWindowShouldClose(window)) { // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to // tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data // to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input // data to your main application. Generally you may always pass all // inputs to dear imgui, and hide them from your application based on // those two flags. glfwPollEvents(); // Start the Dear ImGui frame ImGui_ImplOpenGL2_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); // 1. Show the big demo window (Most of the sample code is in // ImGui::ShowDemoWindow()! You can browse its code to learn more about // Dear ImGui!). if(show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End // pair to created a named window. { static float f = 0.0f; static int counter = 0; ImGui::Begin("Hello, world!"); // Create a window called "Hello, // world!" and append into it. ImGui::Text( "This is some useful text."); // Display some text (you can use // a format strings too) ImGui::Checkbox( "Demo Window", &show_demo_window); // Edit bools storing our // window open/close state ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color if(ImGui::Button( "Button")) // Buttons return true when clicked (most widgets // return true when edited/activated) counter++; ImGui::SameLine(); ImGui::Text("counter = %d", counter); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); } // 3. Show another simple window. if(show_another_window) { ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable // (the window will have a closing button // that will clear the bool when clicked) ImGui::Text("Hello from another window!"); if(ImGui::Button("Close Me")) show_another_window = false; ImGui::End(); } // Rendering ImGui::Render(); int display_w, display_h; glfwGetFramebufferSize(window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor( clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); // If you are using this code with non-legacy OpenGL header/contexts // (which you should not, prefer using imgui_impl_opengl3.cpp!!), you // may need to backup/reset/restore current shader using the commented // lines below. // GLint last_program; // glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); // glUseProgram(0); ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData()); // glUseProgram(last_program); glfwMakeContextCurrent(window); glfwSwapBuffers(window); } // Cleanup ImGui_ImplOpenGL2_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwDestroyWindow(window); glfwTerminate(); return 0; } <file_sep>/extlibs/imgui/examples/imgui_impl_marmalade.h // dear imgui: Renderer + Platform Binding for Marmalade + IwGx // Marmalade code: Copyright (C) 2015 by <NAME> (this file is part of // Dear ImGui) // Implemented features: // [X] Renderer: User texture binding. Use 'CIwTexture*' as ImTextureID. Read // the FAQ about ImTextureID! // You can copy and use unmodified imgui_impl_* files in your project. See // main.cpp for an example of using this. If you are new to dear imgui, read // examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui #pragma once #include "imgui.h" // IMGUI_IMPL_API IMGUI_IMPL_API bool ImGui_Marmalade_Init(bool install_callbacks); IMGUI_IMPL_API void ImGui_Marmalade_Shutdown(); IMGUI_IMPL_API void ImGui_Marmalade_NewFrame(); IMGUI_IMPL_API void ImGui_Marmalade_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui // state. IMGUI_IMPL_API void ImGui_Marmalade_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_Marmalade_CreateDeviceObjects(); // Callbacks (installed by default if you enable 'install_callbacks' during // initialization) You can also handle inputs yourself and use those as a // reference. IMGUI_IMPL_API int32 ImGui_Marmalade_PointerButtonEventCallback( void* system_data, void* user_data); IMGUI_IMPL_API int32 ImGui_Marmalade_KeyCallback( void* system_data, void* user_data); IMGUI_IMPL_API int32 ImGui_Marmalade_CharCallback( void* system_data, void* user_data); <file_sep>/src/Texture.h #pragma once #include <cassert> #include <GL/glew.h> #include "Debug.h" class Texture { public: enum class Format { Rgba, Rgb, Alpha, }; enum class Type { Texture1D, Texture2D, }; explicit Texture(Type type = Type::Texture2D, Format format = Format::Rgba) : m_type(type), m_format{format} { GL_CHECK(glGenTextures(1, &m_img_tex)); } Texture(Format format, const int width, const int height, const void *data) : m_type(Type::Texture2D), m_format{format} { GL_CHECK(glGenTextures(1, &m_img_tex)); bind(); auto glFormat = getGlFormat(format); glTexImage2D(GL_TEXTURE_2D, 0, glFormat, width, height, 0, glFormat, GL_UNSIGNED_BYTE, data); updateFilters(); } Texture(Format format, const int width, const void *data) : m_type(Type::Texture1D), m_format{format} { GL_CHECK(glGenTextures(1, &m_img_tex)); bind(); auto glFormat = getGlFormat(format); glTexImage1D(GL_TEXTURE_1D, 0, glFormat, width, 0, glFormat, GL_UNSIGNED_BYTE, data); updateFilters(); } ~Texture() { GL_CHECK(glDeleteTextures(1, &m_img_tex)); } void setSmooth(bool smooth = true) { if (m_smooth == smooth) { return; } m_smooth = smooth; if (!m_img_tex) return; GL_CHECK(glBindTexture(getGlType(m_type), m_img_tex)); updateFilters(); } [[nodiscard]] bool isSmooth() const noexcept { return m_smooth; } void setData(const int width, const int height, const void *data) const { auto type = getGlType(m_type); GL_CHECK(glBindTexture(type, m_img_tex)); if(m_type == Type::Texture2D) { GL_CHECK(glTexSubImage2D(type, 0, 0, 0, width, height, getGlFormat(m_format), GL_UNSIGNED_BYTE, data)); }else { GL_CHECK(glTexSubImage1D(type, 0, 0, width, getGlFormat(m_format), GL_UNSIGNED_BYTE, data)); } GL_CHECK(glTexParameteri(type, GL_TEXTURE_MAG_FILTER, m_smooth ? GL_LINEAR : GL_NEAREST)); GL_CHECK(glTexParameteri(type, GL_TEXTURE_MIN_FILTER, getGlFilter(m_smooth))); } void bind() const { auto type = getGlType(m_type); GL_CHECK(glBindTexture(type, m_img_tex)); } private: void updateFilters(){ auto type = getGlType(m_type); GL_CHECK(glTexParameteri(type, GL_TEXTURE_MAG_FILTER, getGlFilter(m_smooth))); GL_CHECK(glTexParameteri(type, GL_TEXTURE_MIN_FILTER, getGlFilter(m_smooth))); } static GLenum getGlType(Type type) { return type == Type::Texture2D ? GL_TEXTURE_2D : GL_TEXTURE_1D; } static GLenum getGlFilter(bool smooth) { return smooth ? GL_LINEAR : GL_NEAREST; } static GLenum getGlFormat(Format format) { switch(format){ case Format::Alpha: return GL_RED; case Format::Rgba: return GL_RGBA; case Format::Rgb: return GL_RGB; } assert(false); } private: Type m_type; Format m_format; bool m_smooth{false}; unsigned int m_img_tex{0}; };
9c148fef23161c96889b967218915eb238984480
[ "CMake", "Markdown", "Makefile", "C", "C++" ]
34
C
scemino/DoomFire
d99a9e65a2b8caa58ca119547a387ca261bdf8a1
c9702732791f3d6cb6ef3d94c06c968430ab4657
refs/heads/master
<repo_name>cadmuxe/pinyinjs<file_sep>/bm.js function loadpyjs(jsname, onload){ var d = document, js=d.createElement('scr'+'ipt'); js.type = 'text/javascript'; js.async = false; if(arguments.length > 1){ js.onload=onload; } js.setAttribute('src', 'https://cdn.jsdelivr.net/gh/cadmuxe/pinyinjs@2d2791dc3158b624a4dafdf887e4ca4633708df5/' + jsname); d.head.appendChild(js); } function loadpyjss(cssurl){ var d= document, css=d.createElement('link'); css.rel = 'stylesheet'; css.type = 'text/css'; css.href = cssurl; css.media='all'; d.head.appendChild(css); } loadpyjss('https://cdn.jsdelivr.net/gh/cadmuxe/pinyinjs/simple-input-method/simple-input-method.css') loadpyjs('dict/pinyin_dict_notone.js'); loadpyjs('pinyinUtil.js'); loadpyjs('simple-input-method/simple-input-method.js',function(){ console.log("Script loaded"); SimpleInputMethod.init('.edit_area'); });
3283fbcf2bce1ff209a341b5a5f79af6bfeb387f
[ "JavaScript" ]
1
JavaScript
cadmuxe/pinyinjs
6816e03aa8698be2a54745cfbe71f12afa703b2e
cff20d69fa26aa2734e34ff2d1587e8cb5dcbedb
refs/heads/main
<repo_name>lazywintercat/spring_portfolio<file_sep>/acoountbook/src/main/java/com/spring/dao/ScheduleDAOImpl.java package com.spring.dao; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.spring.dao.ScheduleDAO; import com.spring.vo.ScheduleVO; @Repository public class ScheduleDAOImpl implements ScheduleDAO { @Inject private SqlSession session; private static String namespace = "com.spring.mappers.scheduleMapper"; @Override public List<ScheduleVO> selectSchedule(Map params) throws Exception { return session.selectList(namespace + ".selectSchedule", params); } @Override public int insertSchedule(ScheduleVO vo) throws Exception { return session.insert(namespace + ".insertSchedule", vo); } @Override public ScheduleVO readSchedule(Map params) throws Exception { return session.selectOne(namespace + ".readSchedule", params); } @Override public int updateSchedule(Map params) throws Exception { return session.update(namespace + ".updateSchedule", params); } @Override public int deleteSchedule(Map params) throws Exception { return session.delete(namespace + ".deleteSchedule", params); } } <file_sep>/acoountbook/src/main/java/com/spring/controller/MemberController.java package com.spring.controller; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.spring.service.MemberService; import com.spring.vo.MemberVO; @Controller @RequestMapping("/member/*") public class MemberController { @Inject MemberService service; private static final Logger logger = LoggerFactory.getLogger(MemberController.class); //회원가입 get 메서드(회원가입 폼으로 이동) @RequestMapping(value="/register", method = RequestMethod.GET) public String getRegister() throws Exception{ logger.info("get register"); return "/board/register"; } //회원가입 post(회원가입 누를때 넘어옴) @RequestMapping(value="/register", method = RequestMethod.POST) public String postRegister(MemberVO vo) throws Exception{ logger.info("post register"); service.register(vo); return "/board/list"; } //로그인 팝업 @RequestMapping(value="/login", method = RequestMethod.GET) public String login() throws Exception{ logger.info("get login"); return "/board/login"; } //로그인 @RequestMapping(value="/login", method = RequestMethod.POST) public String login(MemberVO vo, HttpServletRequest req, RedirectAttributes rttr) throws Exception{ logger.info("post login"); HttpSession session = req.getSession(); MemberVO login = service.login(vo); if(login == null) { session.setAttribute("member", null); //rttr.addFlashAttribute("msg", false); session.setAttribute("msg", false); System.out.println("로그인 null"); }else { session.setAttribute("member", login); session.setAttribute("msg", null); System.out.println("성공"); } return "redirect:/board/list"; } //로그아웃 @RequestMapping(value="/logout") public String logout(HttpSession session) throws Exception{ logger.info("logout"); session.invalidate(); return "redirect:/board/list"; } //회원정보 수정뷰 @RequestMapping(value="memberModifyView", method = RequestMethod.GET) public String registerUpdateView() throws Exception{ logger.info("memberModifyView"); return "board/memberModifyView"; } //회원정보 수정 @RequestMapping(value="memberModify", method = RequestMethod.POST) public String registerUpdate(MemberVO vo, HttpSession session) throws Exception{ logger.info("memberModify"); service.memberUpdate(vo); /* session.invalidate(); */ return "redirect:/board/list"; } //회원탈퇴 뷰 @RequestMapping(value="memberDeleteView" , method = RequestMethod.GET) public String memberDeleteView() throws Exception{ logger.info("memberDeleteView"); return "board/memberDeleteView"; } //회원탈퇴 @RequestMapping(value="memberDelete", method = RequestMethod.POST) public String memberDelete(MemberVO vo, HttpSession session, RedirectAttributes rttr) throws Exception{ logger.info("memberdelete"); // //세션의 member를 가져와 member 변수에 넣어줌 // MemberVO member = (MemberVO) session.getAttribute("member"); // //세션에 들어있는 비밀번호 // String sessionPass = member.getUserPass(); // //vo에 들어있는 비밀번호 // String voPass = vo.getUserPass(); // // if(!(sessionPass.equals(voPass))) { // rttr.addFlashAttribute("msg",false); // return "redirect:/member/memberModifyView"; // } service.memberDelete(vo); session.invalidate(); return "redirect:/board/list"; } //패스워드 체크 @ResponseBody @RequestMapping(value="/passChk", method = RequestMethod.POST) public int passChk(MemberVO vo) throws Exception{ int result = service.passChk(vo); return result; } //중복 아이디 체크 @ResponseBody @RequestMapping(value="/idChk", method =RequestMethod.POST ) public int idChk(MemberVO vo) throws Exception{ int result = service.idChk(vo); return result; } } <file_sep>/acoountbook/src/main/java/com/spring/controller/news/NewsVO.java package com.spring.portfolio.news; public class NewsVO { private String href; private String title; private String writer; private String writeDate; private String sid1; public String getSid1() { return sid1; } public void setSid1(String sid1) { this.sid1 = sid1; } public NewsVO() { // TODO Auto-generated constructor stub } public NewsVO(String href, String title, String writer, String writeDate) { super(); this.href = href; this.title = title; this.writer = writer; this.writeDate = writeDate; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getWriteDate() { return writeDate; } public void setWriteDate(String writeDate) { this.writeDate = writeDate; } @Override public String toString() { return "NewsVO [href=" + href + ", title=" + title + ", writer=" + writer + ", writeDate=" + writeDate + ", sid1=" + sid1 + "]"; } } <file_sep>/acoountbook/src/main/java/com/spring/controller/ScheduleController.java package com.spring.controller; import java.net.InetAddress; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.spring.service.ScheduleService; import com.spring.vo.MemberVO; import com.spring.vo.ScheduleVO; @Controller @RequestMapping("/schedule/*") public class ScheduleController { private static final Logger logger = LoggerFactory.getLogger(ScheduleController.class); @Inject private ScheduleService service; @RequestMapping(value = "/scheduleList", method = { RequestMethod.GET, RequestMethod.POST}) public String Schedule(/*@RequestParam String userId*/MemberVO vo , Model model) throws Exception { logger.info("scheduleList"); try { model.addAttribute("userId", vo.getUserId()); } catch(Exception e) { e.printStackTrace(); } return "board/scheduleList"; } @ResponseBody @RequestMapping(value = "/selectSchedule", method = { RequestMethod.GET, RequestMethod.POST}) public List<ScheduleVO> selectSchedule(@RequestBody Map<String, Object> params, Model model) throws Exception { logger.info("selectSchedule"); List<ScheduleVO> result = null; System.out.println(params); try { result = service.selectSchedule(params); // 날짜 뒤에 .0 없애기 System.out.println(result); for (int i=0; i<result.size(); i++) { String tempStr = result.get(i).getStartDate(); String tempEnd = result.get(i).getEndDate(); // tempStr = tempStr.substring(0, tempStr.length()-2); // tempEnd = tempEnd.substring(0, tempEnd.length()-2); result.get(i).setStartDate(tempStr); result.get(i).setEndDate(tempEnd); System.out.println("startdate :" +tempStr ); System.out.println("enddate :" +tempEnd ); System.out.println(result); } } catch(Exception e) { e.printStackTrace(); } return result; } @RequestMapping(value = "/insertSchedule", method = { RequestMethod.GET, RequestMethod.POST}) public String insertSchedule(ScheduleVO vo) throws Exception { logger.info("insertSchedule"); vo.setMemo(vo.getMemo().replaceAll("\n", "<br>")); vo.setStartDate(vo.getStartDate()); vo.setEndDate(vo.getEndDate()); System.out.println(vo); try { service.insertSchedule(vo); } catch(Exception e) { e.printStackTrace(); } return "redirect:/schedule/scheduleList"; } @ResponseBody @RequestMapping(value = "/readSchedule", method = { RequestMethod.GET, RequestMethod.POST}) public ScheduleVO readSchedule(@RequestBody Map<String, Object> params) throws Exception { logger.info("readSchedule"); ScheduleVO result = null; try { result = service.readSchedule(params); result.setMemo(result.getMemo().replaceAll("<br>", "\n")); // 날짜 뒤에 .0 없애기 String tempStr = result.getStartDate(); String tempEnd = result.getEndDate(); tempStr = tempStr.substring(0, tempStr.length()-2); tempEnd = tempEnd.substring(0, tempEnd.length()-2); result.setStartDate(tempStr); result.setEndDate(tempEnd); } catch(Exception e) { e.printStackTrace(); } return result; } @ResponseBody @RequestMapping(value = "/updateSchedule", method = { RequestMethod.GET, RequestMethod.POST}) public int updateSchedule(@RequestBody Map<String, String> params) throws Exception { logger.info("updateSchedule"); int result = 0; params.put("memo", params.get("memo").replaceAll("\n", "<br>")); try { result = service.updateSchedule(params); } catch(Exception e) { e.printStackTrace(); } return result; } @ResponseBody @RequestMapping(value = "/deleteSchedule", method = { RequestMethod.GET, RequestMethod.POST}) public int deleteSchedule(@RequestBody Map<String, Object> params) throws Exception { logger.info("deleteSchedule"); int result = 0; try { result = service.deleteSchedule(params); System.out.println("==============================================================================result : " + result); } catch(Exception e) { e.printStackTrace(); } return result; } } <file_sep>/acoountbook/src/main/java/com/spring/service/BoardServiceImpl.java package com.spring.service; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.spring.dao.BoardDAO; import com.spring.vo.BoardVO; import com.spring.vo.Criteria; import com.spring.vo.SearchCriteria; @Service public class BoardServiceImpl implements BoardService{ @Inject private BoardDAO dao; //게시글 작성 @Override public int write(BoardVO boardVO) throws Exception { return dao.write(boardVO); } //게시글 리스트 @Override public List<BoardVO> list(SearchCriteria scri) throws Exception { return dao.list(scri); } //게시글 총 갯수 @Override public int listCount(SearchCriteria scri) throws Exception { return dao.listCount(scri); } //게시글 읽기 @Transactional(isolation = Isolation.READ_COMMITTED) @Override public BoardVO read(int bno) throws Exception { dao.boardHit(bno); return dao.read(bno); } //게시글 수정 @Override public void update(BoardVO boardVO) throws Exception { dao.update(boardVO); } //게시글 삭제 @Override public void delete(int bno) throws Exception { dao.delete(bno); } } <file_sep>/acoountbook/src/main/java/com/spring/controller/BoardController.java package com.spring.controller; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.apache.commons.io.FileUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.support.RequestContextUtils; import com.google.gson.JsonObject; import com.spring.service.BoardService; import com.spring.service.ReplyService; import com.spring.vo.BoardVO; import com.spring.vo.Criteria; import com.spring.vo.PageMaker; import com.spring.vo.ReplyVO; import com.spring.vo.SearchCriteria; @Controller @RequestMapping("/board/*") public class BoardController { private static final Logger logger = LoggerFactory.getLogger(BoardController.class); @Inject BoardService service; @Inject ReplyService replyService; // 게시글 작성 뷰 @RequestMapping(value = "/board/writeView", method = RequestMethod.GET) public String writeView() throws Exception { logger.info("writeView"); return "board/writeView"; } // 게시글 작성 @RequestMapping(value = "/board/write", method = RequestMethod.POST) public String writer(BoardVO boardVO, RedirectAttributes rttr) throws Exception { logger.info("write"); service.write(boardVO); rttr.addFlashAttribute("result", "writeOK"); return "redirect:/board/list"; } // 게시글 리스트 @RequestMapping(value = "/list", method = RequestMethod.GET) public String list(Model model, @ModelAttribute("scri") SearchCriteria scri, HttpServletRequest request) throws Exception { logger.info("list"); model.addAttribute("list", service.list(scri)); PageMaker pageMaker = new PageMaker(); pageMaker.setCri(scri); pageMaker.setTotalCount(service.listCount(scri)); model.addAttribute("pageMaker", pageMaker); return "board/list"; } // 게시글 읽기 @RequestMapping(value = "/readView", method = RequestMethod.GET) public String read(BoardVO boardVO, @ModelAttribute("scri") SearchCriteria scri, Model model) throws Exception { logger.info("read"); model.addAttribute("read", service.read(boardVO.getBno())); model.addAttribute("scri", scri); List<ReplyVO> replyList = replyService.readReply(boardVO.getBno()); model.addAttribute("replyList", replyList); return "board/readView"; } // 게시글 수정 뷰 @RequestMapping(value = "/updateView", method = RequestMethod.GET) public String updateView(BoardVO boardVO, @ModelAttribute("scri") SearchCriteria scri, Model model) throws Exception { logger.info("updateView"); model.addAttribute("update", service.read(boardVO.getBno())); model.addAttribute("scri", scri); return "board/updateView"; } // 게시글 수정 @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(BoardVO boardVO, @ModelAttribute("scri") SearchCriteria scri, RedirectAttributes rttr) throws Exception { logger.info("update"); service.update(boardVO); rttr.addAttribute("page", scri.getPage()); rttr.addAttribute("perPageNum", scri.getPerPageNum()); rttr.addAttribute("searchType", scri.getSearchType()); rttr.addAttribute("keyword", scri.getKeyword()); rttr.addFlashAttribute("result", "updateOK"); return "redirect:/board/list"; } // 게시글 삭제 @RequestMapping(value = "/delete", method = RequestMethod.POST) public String delete(BoardVO boardVO, @ModelAttribute("scri") SearchCriteria scri, RedirectAttributes rttr) throws Exception { logger.info("delete"); service.delete(boardVO.getBno()); rttr.addAttribute("page", scri.getPage()); rttr.addAttribute("perPageNum", scri.getPerPageNum()); rttr.addAttribute("searchType", scri.getSearchType()); rttr.addAttribute("keyword", scri.getKeyword()); rttr.addFlashAttribute("result", "deleteOK"); return "redirect:/board/list"; } // 댓글 작성 @RequestMapping(value = "/replyWrite", method = RequestMethod.POST) public String replyWrite(ReplyVO vo, SearchCriteria scri, RedirectAttributes rttr) throws Exception { logger.info("replyWrite"); replyService.writeReply(vo); rttr.addAttribute("bno", vo.getBno()); rttr.addAttribute("page", scri.getPage()); rttr.addAttribute("perPageNum", scri.getPerPageNum()); rttr.addAttribute("searchType", scri.getSearchType()); rttr.addAttribute("keyword", scri.getKeyword()); return "redirect:/board/readView"; } //댓글 수정 //댓글 수정 GET @RequestMapping(value="/replyUpdateView", method = RequestMethod.GET) public String replyUpdateView(ReplyVO vo, SearchCriteria scri, Model model) throws Exception { logger.info("reply Write"); model.addAttribute("replyUpdate", replyService.selectReply(vo.getRno())); model.addAttribute("scri", scri); return "board/replyUpdateView"; } //댓글 수정 POST @RequestMapping(value="/replyUpdate", method = RequestMethod.POST) public String replyUpdate(ReplyVO vo, SearchCriteria scri, RedirectAttributes rttr) throws Exception { logger.info("reply update"); replyService.updateReply(vo); rttr.addAttribute("bno", vo.getBno()); rttr.addAttribute("page", scri.getPage()); rttr.addAttribute("perPageNum", scri.getPerPageNum()); rttr.addAttribute("searchType", scri.getSearchType()); rttr.addAttribute("keyword", scri.getKeyword()); return "redirect:/board/readView"; } //댓글 삭제 GET @RequestMapping(value="/replyDeleteView", method = RequestMethod.GET) public String replyDeleteView(ReplyVO vo, SearchCriteria scri, Model model,RedirectAttributes rttr) throws Exception { logger.info("reply Write"); model.addAttribute("replyDelete", replyService.selectReply(vo.getRno())); model.addAttribute("scri", scri); return "board/replyDeleteView"; } //댓글 삭제 @RequestMapping(value="/replyDelete", method = RequestMethod.POST) public String replyDelete(ReplyVO vo, RedirectAttributes rttr,SearchCriteria scri) throws Exception { logger.info("reply delete"); replyService.deleteReply(vo); rttr.addAttribute("bno", vo.getBno()); rttr.addAttribute("page", scri.getPage()); rttr.addAttribute("perPageNum", scri.getPerPageNum()); rttr.addAttribute("searchType", scri.getSearchType()); rttr.addAttribute("keyword", scri.getKeyword()); return "redirect:/board/readView"; } //써머노트 이미지 업로드 @RequestMapping(value="/uploadSummernoteImageFile", produces = "application/json; charset=utf8") @ResponseBody public String uploadSummernoteImageFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request ) { JsonObject jsonObject = new JsonObject(); //String fileRoot = "D:\\upimg\\"; // 외부경로로 저장을 희망할때. // 내부경로로 저장 String contextRoot = new HttpServletRequestWrapper(request).getRealPath("/"); String fileRoot = contextRoot+"resources/fileupload/"; String originalFileName = multipartFile.getOriginalFilename(); //오리지날 파일명 String extension = originalFileName.substring(originalFileName.lastIndexOf(".")); //파일 확장자 String savedFileName = UUID.randomUUID() + extension; //저장될 파일 명 File targetFile = new File(fileRoot + savedFileName); try { InputStream fileStream = multipartFile.getInputStream(); FileUtils.copyInputStreamToFile(fileStream, targetFile); //파일 저장 jsonObject.addProperty("url","/resources/fileupload/"+savedFileName); //contextroot + resources + 저장할 내부 폴더명 jsonObject.addProperty("responseCode", "success"); } catch (IOException e) { FileUtils.deleteQuietly(targetFile); //저장된 파일 삭제 jsonObject.addProperty("responseCode", "error"); e.printStackTrace(); } String a = jsonObject.toString(); return a; } }
60553dec41a7f60be6be21a0164b8e627be73a65
[ "Java" ]
6
Java
lazywintercat/spring_portfolio
b17c40fbafae318b358c6797816f328e3b7a3aaf
88d385f8958c7da2b5d5ecbc5c88e370a5ca9722
refs/heads/master
<repo_name>AWernerCS/user-signup<file_sep>/main.py import webapp2 import re import cgi user_regular = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") password_regular = re.compile(r"^.{3,20}$") email_regular = re.compile(r"^[\S]+@[\S]+.[\S]+$") def build_page(error_username='', error_password='', error_verifyPassword='', error_email='', usernamePreserve='', emailPreserve = ''): header = """ <html> <head> <style> .errorUsername, .errorPassword, .errorVerifyPassword, .errorEmail { color: red; } </style> </head> <body> <h1>Signup</h1>""" username_label = "<label>Username:</label>" username_input = "<input type='text' name='username' value='"+ usernamePreserve +"'' required />" password_label = "<label>Password:</label>" password_input = "<input type='<PASSWORD>' name='<PASSWORD>' required />" verifyPassword_label = "<label>Verify Password:</label>" verifyPassword_input = "<input type='<PASSWORD>' name='<PASSWORD>' required />" email_label = "<label>Email (optional):</label>" email_input = "<input type='text' name='email' value='" + emailPreserve + "' />" errorUsername = "<span class='errorUsername'> " + error_username + "</span>" errorPassword = "<span class='errorPassword'> " + error_password + "</span>" errorVerifyPassword = "<span class='errorVerifyPassword'> " + error_verifyPassword + "</span>" errorEmail = "<span class='errorEmail'> " + error_email + "</span>" submit = "<input type='submit'/>" form = ("<form method='post'>" + "<table><tr><td>" + username_label + "</td><td>" + username_input + errorUsername + "</td></tr>" + "<tr><td>" + password_label + "</td><td>" + password_input + errorPassword + "</td></tr>" + "<tr><td>" + verifyPassword_label + "</td><td>" + verifyPassword_input + errorVerifyPassword + "</td></tr>" + "<tr><td>" + email_label + "</td><td>" + email_input + errorEmail + "</td></tr></table><br />" + submit + "</form></body></html>") return header + form def valid_username(username): return user_regular.match(username) def valid_password(password): return password_regular.match(password) def valid_email(email): return email_regular.match(email) class MainHandler(webapp2.RequestHandler): def get(self): self.response.write(build_page()) def post(self): username = self.request.get("username") password = self.request.get("password") verifyPassword = self.request.get("verifyPassword") email = self.request.get("email") checked_username = valid_username(username) checked_password = <PASSWORD>(<PASSWORD>) checked_email = valid_email(email) username = cgi.escape(username) email = cgi.escape(email) if not checked_username: self.response.write(build_page("Invalid username.", '', '', '', username, email)) elif not checked_email: self.response.write(build_page('', '', '', "Invalid email address.", username, email)) elif not checked_password: self.response.write(build_page('', "Invalid password.", '', '', username, email)) elif not (password == verifyPassword): self.response.write(build_page('', '', "Passwords do not match.", '', username, email)) else: self.redirect("/success?username=" + username) class SuccessHandler(webapp2.RequestHandler): def get(self): self.response.out.write("<center><h1>Welcome, " + self.request.get('username') + "!</h1><img src='http://cdn.inquisitr.com/wp-content/uploads/2010/02/catgif8.gif' /></center>") app = webapp2.WSGIApplication([ ('/', MainHandler), ('/success', SuccessHandler) ], debug=True)
032930a5314285895e24c8bdc9c06bdb46fe7c07
[ "Python" ]
1
Python
AWernerCS/user-signup
9ebc2d164c07150de93f036d4719dde4497ee582
e7b03fab89b56de266354d044a83b6548f3a6433
refs/heads/master
<repo_name>olvb/piton<file_sep>/tests/features/06_str.py # bool conversion if "": print_int(3) # type declaration and literal s: str = "ABC 123" print_str(s) # escape special chars print_str("\"\t\n") # TODO backslash escaping #print_str("\\\\") # TODO single quote, multiline # eq/neq print_bool("ABC" == "ABC") print_bool("ABC" == "123") print_bool("ABC" == "") print_bool("" == "ABC") print_bool("" == "") print_bool("ABC" != "ABC") print_bool("ABC" != "123") print_bool("ABC" != "") print_bool("" != "ABC") print_bool("" != "") # not print_bool(not "") print_bool(not "ABC") # length print_int(str_len("ABC 123")) print_int(str_len("")) # concatenation print_str("ABC" + "123") print_str("" + "ABC") print_str("" + "") print_str("ABC" + " " + "123") # subscript access print_str(s[0]) print_str(s[2]) print_str("ABC"[0]) print_str("ABC"[2]) # automatic type conversion print_str(s[True]) print_str(s[False]) # nested subscript access print_str("ABC"[0][0]) # TODO subscript assign # input #name: str = input("enter your name: ") #print_str("hi " + name + "!\n") <file_sep>/tests/errors/assign_self.py a: int = a <file_sep>/tests/errors/invalid_type_param.py def a(b: list): print_int(1) <file_sep>/tests/features/05_bool.py # type declaration and literals b: bool = True print_bool(b) print_bool(True) print_bool(False) # arithmetics print_int(False + True) print_int(False - True) print_int(False * True) # TODO: auto convert integer division to float #print_int(False / True) # and/or/not print_bool(False and False) print_bool(False and True) print_bool(False or False) print_bool(False or True) print_bool(not False) #print_bool(not True) # eq/neq print_bool(False == False) print_bool(False == True) print_bool(False != False) print_bool(False != True) # lt/gt print_bool(False > False) print_bool(False > True) print_bool(True > False) print_bool(False < False) print_bool(False < True) print_bool(True < False) # lte/gte print_bool(False >= False) print_bool(False >= True) print_bool(True >= False) print_bool(False <= False) print_bool(False <= True) print_bool(True <= False) <file_sep>/tests/errors/duplicate_decl_def.py def a() -> int: return 1 a: int = 2<file_sep>/tests/features/01_decl_assign.py # declare and assign literal a: int = 1 print_int(a) # reassign a = 2 print_int(a) # declare/assign variable b: int = a print_int(b) # declare/assign expression c: int = 3 + 4 print_int(c) # declare/assign nested expressions d: int = ((5 + 6) * 7) print_int(d) # declare inside if if True: e: int = 8 print_int(e) # declare in else if False: print_int(9) else: f: int = 10 print_int(f) # declare same variable inside if and else if True: g: int = 11 print_int(g) else: g: int = 12 print_int(g) if False: h: int = 13 print_int(h) else: h: int = 14 print_int(h) # declare inside while i: int = 0 while i < 5: j: int = i print_int(j) i = i + 1 <file_sep>/tests/errors/subscript_index_type.py a: str = "ABC" b: str = "123" a[b] <file_sep>/tests/errors/param_type.py def a(b: int): return a("ABC")<file_sep>/test_features.py #!/usr/bin/env python3 ## run all tests in tests/features/ directory ## or with files given as arg (ex ./run_features_tests tests/features/01_decl_assign.py) import sys import os import subprocess from shutil import copyfile PITON_PATH = 'src/piton.rkt' TESTS_PATH = 'tests/features/' LIB_PATH = 'tests.lib' def fail(piton_output, python_output): print("------------------") print("Failed with output:\n" + piton_output + '\n') print("Expected:\n" + python_output + '\n') print("------------------") sys.exit(1) def fail_error(): print("------------------") print("Failed with error") print("------------------") sys.exit(1) def scan_tests(): test_paths = [] for file in os.scandir(TESTS_PATH): if file.is_dir(): continue if not file.name.endswith('.py'): continue test_paths.append(TESTS_PATH + file.name) test_paths.sort() return test_paths def run_test(test_path): print("Testing " + test_path + "...") with open(test_path) as f: content = f.read() # prepare python file including lib content = 'from ' + LIB_PATH + ' import *\n' + content with open('.test_tmp.py', 'w') as f: f.write(content) # run python python_cmd = 'python3 .test_tmp.py' python_output = subprocess.check_output([python_cmd], shell=True) python_output = python_output.decode('utf-8').strip() # compile with piton and run spim copyfile(test_path, '.test_tmp.py') compile_cmd = PITON_PATH + ' .test_tmp.py' try: subprocess.check_output([compile_cmd], shell=True) run_cmd = 'spim -file .test_tmp.s' piton_output = subprocess.check_output([run_cmd], shell=True) except subprocess.CalledProcessError as e: fail_error() # compare outputs piton_output = piton_output.decode('utf-8').strip() piton_output = '\n'.join(piton_output.split('\n')[5:]) if piton_output != python_output: fail(piton_output, python_output) def clean_up(): os.remove('.test_tmp.py') os.remove('.test_tmp.s') def main(): if len(sys.argv) > 1: test_paths = sys.argv[1:] else: test_paths = scan_tests() for test_path in test_paths: run_test(test_path) print("All tests passed") clean_up() main() <file_sep>/tests/errors/return_type.py def a() -> int: return "ABC"<file_sep>/tests/features/11_var_scopes.py i1: int = 1 s1: str = "1" # read var in enclosing scope def a(): print_int(i1) print_str(s1) a() # assign var in enclosing scope # not compatible with python #def b(): # i1 = 2 # s1 = "2" #b() #print_int(i1) #print_str(s1) def c(): i1: int = 3 s1: str = "3" # read var in enclosing scope, deeper def a(): print_int(i1) print_str(s1) a() # assign var in enclosing scope, deeper # not compatible with python #def b(): # i1: int = 4 # s1: str = "4" #b() #print_int(i1) #print_str(s1) c() i2: int = 5 s2: str = "5" # read var in nested enclosing scope def d(): def e(): print_int(i2) print_str(s2) e() d() # assign var in nested enclosing scope # not compatible with python #def f(): # def g(): # i2: int = 6 # s2: str = "6" # g() #f() #print_int(i2) #print_str(s2) # call outer scope functions with outer scope vars, from # read var in enclosing scope def g(): print_int(i1) print_str(s1) # assign var in enclosing scope # not compatible with python #def h(): # i1: int = 2 # s1: str = "2" def i(): def j(): g() j() i() print_int(i1) print_str(s1) <file_sep>/tests/features/12_func_scopes.py def i1() -> int: print_int(1) return 1 def s1() -> str: print_str("1") return "1" # call func in enclosing scope def a(): i1() s1() a() # call func returning val in enclosing scope def b(): i: int = i1() s: str = s1() print_int(i) print_str(s) b() def c(): def i2() -> int: print_int(2) return 1 def s2() -> str: print_str("2") return "2" # call func in enclosing scope, deeper def a(): i2() s2() a() # call func var in enclosing scope, deeper def b(): i: int = i2() s: str = s2() print_int(i) print_str(s) b() c() def i3() -> int: print_int(3) return 3 def s3() -> str: print_str("3") return "3" # call func in nested enclosing scope def d(): def e(): i3() s3() e() d() # call func returning var in nested enclosing scope def f(): def g(): i: int = i3() s: str = s3() print_int(i) print_str(s) g() f() # call outer scope functions with outer scope vars, from # read var in enclosing scope def g(): i: int = i1() s: str = s1() print_int(i) print_str(s) def i(): def j(): g() j() i() <file_sep>/tests/features/03_operators.py # operator precedence print_int(3 + 2 * 5) print_int(3 - 2 * 5) print_int(3 * 2 + 5) print_int(3 * 2 - 5) print_bool(not True or False) print_bool(not True and False or True) # TODO: auto convert int division to float #print_int(3 + 2 / 5) #print_int(3 - 2 / 5) #print_int(3 / 2 + 5) #print_int(3 / 2 - 5) print_bool(-6 + 2 * 3 == 4 - 4) print_bool(-6 + 2 * 3 != 4 - 4) print_bool(-6 + 2 * 3 > 4 - 4) print_bool(-6 + 2 * 3 < 4 - 4) print_bool(-6 + 2 * 3 >= 4 - 4) print_bool(-6 + 2 * 3 <= 4 - 4) # parenthised operations print_int((3 + 2) * 5) <file_sep>/tests/errors/funcdef_in_else.py if True: print_int(1) else: def b(): print_int(2) <file_sep>/tests/errors/no_type_decl.py a: int a = 1<file_sep>/tests/errors/duplicate_defs.py def a() -> int: return 1 def a() -> int: return 2<file_sep>/tests/errors/not_subscriptable.py a: int = 1 a[1] <file_sep>/tests/errors/invalid_type_decl.py a: list = "ABC" <file_sep>/tests/errors/func_assign.py def a(): print_int(1) def b(): print_int(2) a = b <file_sep>/README.md ## A Python counterfeit Piton is both a language mimicking the syntax and semantics of Python and a compiler for this language, implemented in Racket. While type annotations are optional in Python (see [PEP 484][1] and [526][2]), they are mandatory in Piton, which is statically and strongly typed. Piton does not implement concepts such as inheritance or classes. For now, the compiler only supports MIPS assembly, but x86 may be added some day. [1]: https://www.python.org/dev/peps/pep-0484/ [2]: https://www.python.org/dev/peps/pep-0526/ ## Sample program and tests The *tests/* folder contains a fairly exhaustive demonstration of all features and errors supported. You will need [Spim][3] (a MIPS simulator) and Python 3.6 to run *test_features.py*, as this script will execute all the code in *tests/features/* and compare Piton and Python output. The *samples/* folder contains a short program showcasing Piton features. You may compile it with: src/piton.rkt samples/poetry_generator.py and then run the resulting assembly in Spim with: spim -f samples/poetry_generator.s [3]: http://spimsimulator.sourceforge.net/ ## Features ### The basics Piton comes with scalar types *int* and *bool*, and not-so-scalar *string*. ints and bools are assigned by copy and strings by reference, all of them are immutable. The *NoneType* also exists internally, as well as a *function* type, but no *function* nor *NoneType* variable may be declared with the language. Ints and bools come with basic arithmetic, comparison and logical operators as well as the unary *not* operator. Strings can be tested for equality and concatenated with the *+* operator, and offer subscript access to individual characters. Supported controls structures are limited to *if*-(*else*) and *while*. Indentation is handled in the same fashion as in Python, it can vary in length and mix tabs and spaces. Comments are also supported. ### Functions Function calls are implemented, and Piton's standard library includes typed *print* and *len* routines. Defining new functions is also possible, including nested functions (declared in the body of an outer function). Functions names share the same namespace as variables. As said before, an internal *function* type does exists but cannot be used to declare variables nor function parameters, and function variables cannot be reassigned. Recursion is fully supported, without tail-call optimization just as in Python. ### Scoping Python's lexical scoping follows the LEGB rule: Local, Enclosed, Global, Built-in. In a Python file, symbols at the upper-most level are assigned to the global scope (not considering the case of modules). In contrast, Piton does not really have a proper global scope, but all upper-most symbols are located in a implicit *main* function, which scope acts a a kind of global scope enclosing everything else except built-ins. Apart from this, Piton follow the same LEGB order for symbol resolution and supports variable and function shadowing. Function bodies open a new scope, conditional branches do not, just as in Python. ### Safety While Python is highly permissive and dynamic, Piton aims to be a safe static language. Its type system allows arity checking and type checking (including function parameters and return values) at compile-time. A couple of run-time dynamic checks are also performed, such as bounds checking for subscript access and zero division. ## Implementation ### Inlining To simplify compilation, all binary and unary operations are converted into internal function calls, as well as subscript accesses. In order to avoid the runtime overhead of numerous functions call, these internal functions (as well as the typed *print* functions) are inlined by the compiler. What makes it possible is that during the semantic analysis, all nested function calls are flattened so as to avoid trouble with return values needing to be passed to the enclosing call. For instance, code such as this one: ```python print_int(a + 2 * b) ``` will be transformed inside Piton's AST into: ```python auto_8493 = mul_ints(2, b) auto_8494 = add_ints(a, auto_8493) print(auto_8494) ``` Inlining then becomes much easier as all returned values are already explicitly pushed on the stack. Note that to avoid issues with nested calls inside conditional statements, a internal AST *Block* structure is used to enclose the flattened statements. Indeed, the additional "flat" statements cannot just be plainly inserted before the conditional statement, as they need to be reevaluated at every iteration in the case of a while loop. ### Indentation parsing Python-style indentation parsing rests on the emission of *Indent*/*Dedents* tokens (see [Python 3 full grammar][3]). This requires the ability to emit several tokens from one parsing rule, in order to handle multiple dedents performed in one line such as in the following example: ```python def greet(name: str): if name == "William": print_str("Hi Bill!") else: print_str("Hello " + name) # this line unidents 2 levels at once greet("Sarah") ``` Racket's yacc parser does not handle this situation out of the box. However, it is possible to wrap multiple tokens into one, and intercept all calls from the lexer to the parser so as to unwrap theses tokens and enqueue them, before dequeuing one and returning it to the lexer. [3]: https://docs.python.org/3/reference/grammar.html ### MIPS conventions MIPS register *$t9* is dedicated to storing the results of conditional expressions, as well as operations needed a temporary register immediately released, such as memory-to-memory moves. Registers *$t8* and *$t9* are used for the retrieval of enclosing scope variables (see following paragraph). Register *$t4*, *$t5* and *$t6* are available when we need to load memory values in registers to pass them to an instruction expecting register operands, or reciprocally when the result of a instruction has to be put in a register before being stored in memory. Functions arguments are passed by pushing them on the stack before calling the function. Registers *$a0* to *$a3* are only used to pass arguments to inlined functions. On the other hand, the *$v0* register is always used to pass back return values. The *$sp* register is actually used a a frame pointer and is never modified within a function, the compiler being in charge of tracking the size of the stack. ### Activation links Free variables are resolved at runtime using activation links, as described on [this page][4]. The tricky part to understand is that while it is possible to know at compile-time to which scope belongs a variable referred by a non-local symbol, we do not know yet where it will lay in memory relatively to the current frame, as this depends on the execution flow: ```python name: str = input() def greet(greeting: str): print_str(greeting + " " + name) def greet_warmly(): greet("Hello dear" + name) if be_warm: greet_warmly() else: greet("Hello") ``` In this example, the symbol *name* inside *greet* always refer to the same variable belonging to the immediate outer scope of *greet*. But depending on where *greet* is called from, the frame of this scope might be the previous one on the stack, or the one before. Activation links build a chain allowing us to walk back up to the address of frame where the non-local variable is stored. At each function call, in addition to the return address and the arguments, the current frame pointer is pushed onto the stack. When accessing a non-local variable, the compiler knows how many times it has to walk up the activation link chain, because it knows the level of the relevant scope relatively to the current scope. Once the address the scope's frame is known, all that is left to do is to use the address of the variable relative to that frame. [4]: http://pages.cs.wisc.edu/~fischer/cs536.s06/course.hold/html/NOTES/8.RUNTIME-VAR-ACCESS.html#accessLink ## What's missing Piton is an academic project (part of [Pablo Rauzy's compilers course][5]) obviously missing many real-life features. For instance, memory management is inexistent and objects allocated on the heap are never released. This is anyway a bit out of the scope of this project. What could be interesting would be the implementation of generics, using *any* as a type placeholder. This would make Piton code closer to real Python by removing the need of typed versions of standard function such as *print*, and could also allow for the introduction of type-safe lists. Full type annotation of function variables would allow them to become first-class objects that one could pass around while preserving type safety. Finally, beyond *float* support, it could also be interesting to add a notion of inheritance for built-in types such as numbers, as in the Python language specification. [5]: https://pablo.rauzy.name/teaching.html#liec <file_sep>/tests/features/10_func_def.py # no args, no return def a(): print_int(1) a() # single arg, no return def b(a: int): print_int(a) b(2) # multiple args, no return def c(a: int, b: int): print_int(a) print_int(b) c(3, 4) # no args, return def d() -> int: return 4 print_int(d()) # single arg, return def e(a: int) -> int: print_int(5) print_int(a) return 1 print_int(e(6)) # multiple args, return def f(a: int, b: int) -> int: print_int(7) print_int(a) print_int(b) return 1 print_int(f(8, 9)) # more than 4 args def fbis(a: int, b: int, c: int, d: int, e: int) -> int: return a + b + c + d + e print_int(fbis(1, 2, 3, 4, 5)) # nested calls def g(a: int): print_int(a) def h(a: int): g(a) h(10) # recursivity def i(a: int): print_int(a) if a > 0: i(a - 1) i(11) # nested definitions def j(a: int) -> int: def k(a: int) -> int: return a print_int(k(a)) j(12) # recursivity for nested functions def k(): def i(a: int): print_int(a) if a > 0: i(a - 1) i(11) k() # returns # return without value def l(): print_int(13) return # no typecheck after return print_bool("ABC") l() # return inside if def m(): if (True): print_int(14) return else: print_int(15) print_int(16) m() # return inside while def n(): while (True): return print_int(17) n() # no semantics check after return def o(): print_int(18) return a: int = "ABC" + True o() <file_sep>/tests/errors/no_body_while.py while True: print_int(1)<file_sep>/tests/features/13_indent.py # basics if True: print_int(1) else: print_int(2) print_int(3) # trailing line post-dedent # 2-level if True: print_int(4) if False: print_int(5) else: print_int(6) print_int(7) else: print_int(8) if True: print_int(9) else: print_int(10) print_int(11) print_int(12) # 2-level dedent if True: print_int(13) if True: print_int(14) # empty lines if True: print_int(4) if False: print_int(5) else: print_int(6) print_int(7) else: print_int(8) if True: print_int(9) else: print_int(10) print_int(11) print_int(12) # empty lines with wrong indent TODO no supported #if True: # # print_int(4) # if False: # print_int(5) # # else: # print_int(6) # # # print_int(7) # #print_int(12) # coherent mix of tabs and spaces with varied width if True: print_int(4) if False: print_int(5) else: print_int(6) print_int(7) else: print_int(8) if True: print_int(9) else: print_int(10) print_int(11) print_int(12) # no trailing eof after dedent if True: print_int(4)<file_sep>/tests/errors/arity_too_many.py def a(b: int, c: int, d: int) -> int: return b + c + d a(1, 2, 3, 4)<file_sep>/tests/errors/duplicate_params.py def a(b: int, b: int) -> int: return a + b<file_sep>/tests/features/04_int.py # type declaration and literals i: int = 1 print_int(i) print_int(1) print_int(-1) # arithmetics print_int(1 + 2) print_int(3 - 4) print_int(5 * 6) # TODO: auto convert integer division to float #print_int(7 / 8) # eq/neq print_bool(9 == 9) print_bool(9 == 10) print_bool(10 != 11) print_bool(10 != 11) # not print_bool(not 0) print_bool(not 10) # lt/gt print_bool(9 > 9) print_bool(9 > 10) print_bool(10 > 9) print_bool(9 < 9) print_bool(9 < 10) print_bool(10 < 9) # lte/gte print_bool(9 >= 9) print_bool(9 >= 10) print_bool(10 >= 9) print_bool(9 <= 9) print_bool(9 <= 10) print_bool(10 <= 9) <file_sep>/tests/features/02_lines_spaces_comments.py # comment print_int(1) print_int(2) # same line comment # multiple... # ...comments print_int(3) # freely indented comment print_int(4) # empty line print_int(4) # multiple empty lines print_int(5) # chaotic spacing a :int =4+2 *1 print_int ( a ) # no trailing line before eof print_int(7)<file_sep>/tests/errors/else_without_if.py else: print_int(1)<file_sep>/tests/errors/no_body_else.py if True: print_int(1) else: print_int(2) <file_sep>/test_errors.py #!/usr/bin/env python3 ## run all tests in tests/errors/ directory import sys import os import subprocess from shutil import copyfile PITON_PATH = 'src/piton.rkt' TESTS_PATH = 'tests/errors/' def scan_tests(): test_paths = [] for file in os.scandir(TESTS_PATH): if file.is_dir(): continue if not file.name.endswith('.py'): continue test_paths.append(TESTS_PATH + file.name) test_paths.sort() return test_paths def run_test(test_path): print("Testing " + test_path + "...") copyfile(test_path, '.test_tmp.py') compile_cmd = PITON_PATH + ' .test_tmp.py' try: subprocess.check_output([compile_cmd], shell=True) # if compile succeeds, check for runtime error run_cmd = 'spim -file .test_tmp.s' piton_output = subprocess.check_output([run_cmd], shell=True) piton_output = piton_output.decode('utf-8').strip() piton_output = '\n'.join(piton_output.split("\n")[5:]) print(piton_output + '\n') except subprocess.CalledProcessError as e: print() def cleanup(): os.remove('.test_tmp.s') def main(): test_paths = scan_tests() for test_path in test_paths: run_test(test_path) main() <file_sep>/tests/features/09_while.py # while i: int = 0 while i < 5: print_int(i) i = i + 1 # while False while False: print_int(5) # inline while i = 6 while i < 9: i = i + 1 print_int(i) # auto bool conversion i = 1 while i: print_int(15) i = i - 1 <file_sep>/tests/errors/out_of_range_subscript.py a: str = "ABC" a[4]<file_sep>/tests/features/08_if.py # if if True: print_int(1) # multiline if if True: print_int(2) print_int(3) # if False if False: print_int(4) # inline if if True: print_int(5) # if else if True: print_int(4) else: print_int(5) # multiline if else if True: print_int(6) print_int(7) else: print_int(8) print_int(9) # if False else if False: print_int(10) else: print_int(11) # inline if else if True: print_int(12) else : print_int(13) #TODO elif? <file_sep>/tests/errors/unterminated_str.py a:str = "aaaaa <file_sep>/tests/errors/duplicate_decls.py a: int = 1 a: int = 2<file_sep>/tests/errors/assign_type.py a: int = 1 a = "ABC"<file_sep>/tests/features/07_call.py # call with variable arg a: int = 1 print_int(a) # call with literal arg print_int(1) # call with expression arg print_int(2 + 0) # call with nested expressions arg print_int(((2 + 0) * 2)) # call with call in arg print_int(str_len("ABC")) # TODO call with multiple args <file_sep>/tests/errors/arg_type.py def a(b: int): print_int(b) a("ABC")<file_sep>/tests/errors/no_body_if.py if True: print_int(1) <file_sep>/tests/lib.py print_int = print print_str = print print_bool = print str_len = len <file_sep>/tests/errors/decl_type.py a: int = "ABC"<file_sep>/tests/errors/op_type.py 1 + "ABC" <file_sep>/tests/errors/if_else_conflict.py if True: a: int = 1 else: a: str = "ABC" <file_sep>/tests/errors/no_type_param.py def a(b): print_int(1)<file_sep>/samples/poetry_generator.py #str_len = len #print_str = print def has_space(text: str) -> bool: length: int = str_len(text) i: int = 0 while i < length: if text[i] == " ": return True i = i + 1 return False def is_vowel(letter: str) -> bool: if letter == "a": return True if letter == "e": return True if letter == "i": return True if letter == "i": return True if letter == "u": return True if letter == "y": return True return False def is_single_digit(text: str) -> bool: if text == "0": return True if text == "1": return True if text == "2": return True if text == "3": return True if text == "4": return True if text == "5": return True if text == "6": return True if text == "7": return True if text == "8": return True if text == "9": return True return False def letter_to_digit(letter: str) -> int: if letter == "0": return 0 if letter == "1": return 1 if letter == "2": return 2 if letter == "3": return 3 if letter == "4": return 4 if letter == "5": return 5 if letter == "6": return 6 if letter == "7": return 7 if letter == "8": return 8 if letter == "9": return 9 def get_prefix(word: str, n: int) -> str: length: int = str_len(word) # safety checks if n < 0: n = 0 if n > length: n = length count: int = 0 prefix: str = "" while count < n: prefix = prefix + word[count] count = count + 1 return prefix def get_suffix(word: str, n: int) -> str: length: int = str_len(word) # safety checks if n < 0: n = 0 if n > length: n = length suffix: str = "" count: int = 0 while count < n: suffix = suffix + word[length - n + count] count = count + 1 return suffix def replace_suffix(word: str, old_suffix_length: int, new_suffix: str) -> str: return get_prefix(word, str_len(word) - old_suffix_length) + new_suffix def generate_poetry(): def seems_singular(word: str) -> bool: suffix: str = get_suffix(word, 3) if suffix == "ius": return True suffix = get_suffix(word, 1) return suffix != "s" def singularize(plural: str) -> str: ## some incomplete special rules: # children -> child if plural == "children": return "child" # {atoes} -> {ato} (potato) suffix: str = get_suffix(plural, 5) if suffix == "atoes": return replace_suffix(plural, 5, "ato") # {ives} -> {ife} (life, wife) suffix = get_suffix(plural, 4) if suffix == "ives": return replace_suffix(plural, 4, "ife") # {men} -> {man} (man, woman) suffix = get_suffix(plural, 3) if suffix == "men": return replace_suffix(plural, 3, "man") ## general rules # penn{ies} -> penn{y} (consonant + ies -> y) suffix = get_suffix(plural, 4) if not is_vowel(suffix[0]) and get_suffix(suffix, 3) == "ies": return replace_suffix(plural, 3, "y") # rad{i} -> rad{ius} suffix = get_suffix(plural, 1) if suffix == "i": return replace_suffix(plural, 1, "ius") # pit{ches} -> pit{ch} # wi{shes} -> wi{sh} suffix = get_suffix(plural, 4) if suffix == "ches": return replace_suffix(plural, 4, "ch") if suffix == "shes": return replace_suffix(plural, 4, "sh") # bo{xes} -> bo{x} suffix = get_suffix(plural, 3) if suffix == "xes": return replace_suffix(plural, 3, "x") ## very general rule, wrong with singulars ending with s if not seems_singular(plural): return replace_suffix(plural, 1, "") else: return plural topic: str = input("what do you want your poetry to be about? > ") while str_len(topic) == 0 or has_space(topic): if str_len(topic) == 0: topic = input("please enter a subject > ") else: topic = input("please enter a simpler subject > ") how_much: str = input("one a scale of 1 to 9, how poetic do you want to be? > ") while not is_single_digit(how_much) or how_much == "0": how_much = input("please enter a digit between 1 and 9 > ") topic = singularize(topic) if is_vowel(get_prefix(topic, 1)): determiner: str = "an" # NB: variable declaration in if/else else: determiner: str = "a" def poetize(topic: str, degree: int) -> str: def add_more_poetry(poetry: str, topic: str, degree: int) -> str: if not degree: # poetry degree zero return determiner + " " + topic + " is " + determiner + " " + topic # NB: determiner is a free variable else: return add_more_poetry(poetry, topic, degree - 1) + " is " + determiner + " " + topic # NB: unindenting several levels in one eol return add_more_poetry("", topic, degree) poetry: str = poetize(topic, letter_to_digit(how_much)) print_str(poetry) generate_poetry()
f5982879f9d5cdac7e867d5e3f3f78ee2b210907
[ "Markdown", "Python" ]
45
Python
olvb/piton
66d0c0af8c3f61a138606e06b3433afe2dd7d014
0f197a94c8dba06a9504a6e7b585c20c22252376
refs/heads/master
<file_sep># log-param-spring-boot-starter log param spring boot starter ## Usage ### pom.xml ```xml <dependency> <groupId>com.github.ztmark</groupId> <artifactId>log-param-spring-boot-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> ``` ### Annotation ```java class DemoService { @LogParam public String greeting(Person person) { return "Hello " + person.getName(); } } ``` OR ```java @LogParam class DemoService { public String greeting(Person person) { return "Hello " + person.getName(); } } ``` ### properties disable log param ```properties log-param.disable=true ```<file_sep>package com.github.ztmark.autoconfigure; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Author: Mark * Date : 2017/5/28 */ @ConfigurationProperties(prefix = "log-param") public class LogParamProperties { private boolean disable = false; public boolean isDisable() { return disable; } public void setDisable(boolean disable) { this.disable = disable; } }
3793014fda20934aad24c307e98cc3bedacf6592
[ "Markdown", "Java" ]
2
Markdown
ztmark/log-param-spring-boot-starter
ffccdf8c1d6ba5d0f6034c7de1bc5781e2778404
9be12a1dc86bfb1dfe126c2e7b8ea43b4de5b39b
refs/heads/master
<file_sep>import React, {Component} from 'react'; import Navbar from './components/Navbar'; import QuoteCards from './components/QuoteCards'; import Logo from './logo.svg'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { working: false }; } handleClick = () => { this.setState({working: !this.state.working }); }; render(){ const working = this.state.working ? 'App-logo App-logo-working' : 'App-logo'; return ( <div className="App"> <Navbar /> <button onClick={this.handleClick}>Rotate logo (with setState)</button> <img src={Logo} alt="logo" className={working} /> <QuoteCards character="<NAME>" image="https://cdn.glitch.com/3c3ffadc-3406-4440-bb95-d40ec8fcde72%2FHomerSimpson.png?1497567511939" quote="In theory, Communism works! In theory."/> <QuoteCards character="Otto" image="https://cdn.glitch.com/3c3ffadc-3406-4440-bb95-d40ec8fcde72%2FOttoMann.png?1497567511803cd" quote="Oh, wow, windows. I don't think I could afford this place."/> </div> ) }; } export default App;
faec25d4e918b11e1fa3e856f17d58cfe5c901a9
[ "JavaScript" ]
1
JavaScript
Paul-Arnaud/simpson-quotes
babae73bf85c3250dad95425f1ed5fcae93a831a
9dda5f1214a0a9520c1e433798bbc1d8d3a33419
refs/heads/master
<repo_name>philLITERALLY/Roll-QC-V1<file_sep>/camera_setup.py '''This module sets up the camera''' # import the necessary packages from threading import Thread import cv2 # My Modules import handle_config import info_logger import program_state class WebcamVideoStream: def __init__(self, src=0): # initialize the video camera stream and read the first frame # from the stream self.stream = cv2.VideoCapture(src) (self.grabbed, self.frame) = self.stream.read() def start(self): # start the thread to read frames from the video stream Thread(target=self.update, args=()).start() return self def update(self): # keep looping infinitely until the program is stopped while not program_state.STOP_PROGRAM: # otherwise, read the next frame from the stream (self.grabbed, self.frame) = self.stream.read() def read(self): # return the frame most recently read return self.frame <file_sep>/config.ini [CALIBRATION] actual_width = 300.0 actual_height = 30.0 pixel_widths = [363.1280517578125, 364.0, 374.0, 374.0] pixel_heights = [36.312801361083984, 37.0, 37.0, 37.0] [CAMERA] cam_width = 3246 cam_height = 2448 cam_fps = 30 cam_exposure = -8 frame_width = 1440 frame_height = 1080 [LANE] lane_count = 4 lane_width = 571 lane_height = 140 lane_width_start = [154, 725, 1296, 1867] lane_width_end = [725, 1296, 1867, 2438] lane_height_start = 792 #902 lane_height_end = 932 #1042 edge_gap = 10 lane_history = 20 [DRAW] font = 0 green = (0, 255, 0) red = (0, 0, 255) orange = (0, 165, 255) yellow = (0, 255, 255) white = (255, 255, 255) pass_fail_y = [0, 100, 200] [THRESHOLD] white_thresh = 230.0 min_area = 2000 fail_width_low = 260.0 fail_width_high = 313.0 fail_height_low = 22.0 fail_height_high = 45.0 lane_fail_widths_low = [311.1333333333333, 319.8, 334.5674255371094, 334.5674255371094] lane_fail_widths_high = [375.86207509358724, 387.07666666666665, 399.59666666666664, 399.59666666666664] lane_fail_heights_low = [27.866666666666667, 27.866666666666667, 27.982861328124997, 27.982861328124997] lane_fail_heights_high = [103.68803787231445, 109.5, 106.4999771118164, 106.4999771118164] [AIO] aio_wait = 0.2 [RESULTS] export_times = ['6:30:00', '06:30:00', '18:30:00'] folder_location = C:\Users\User\Desktop\Results\
682a5d0ba80b77c7b5966aa7e7d26fe1d182d42e
[ "Python", "INI" ]
2
Python
philLITERALLY/Roll-QC-V1
d578227b42428c365b994f1c539c08323231567f
4650f88e1c3818dd54389cfbe6ec20f67a9cba39
refs/heads/master
<repo_name>OB11TO/alexa<file_sep>/Thomas.py import pyttsx3 import os import random import webbrowser import time import speech_recognition as sr import pandas as pd from tkinter import * from fuzzywuzzy import fuzz from colorama import * import sys import keyboard from Funchin import * from cmd import * # Глобальные переменные text = '' r = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty('voices') adress = '' j = 0 task_number = 0 # Имя голосового помошника ndel = ['Alexa', 'Алекса', 'Алекс'] # Описания функций комманд def add_file(x): # история запросов file = open('commands.txt', 'a',encoding = 'UTF-8') if x != '': file.write(x+'\n') file.close() def clear_task(): #удаляет ключевые слова global text,ndel for z in ndel: text = text.replace(z,'').strip() text = text.replace(' ',' ').strip() def comparison(x): # осуществляет поиск самой подходящей под запрос функции global commands,j,add_file ans = '' for i in range(len(commands)): k = fuzz.ratio(x,commands[i]) if (k > 50)&(k > j): ans = commands[i] j = k if (ans != 'Спасибо!')& (ans != 'Приветик'): add_file(ans) return(str(ans)) # распознавание def talk(): global text, clear_task text = '' with sr.Microphone() as sourse: print('Здравстуй OB11TO: ') r.adjust_for_ambient_noise(sourse) audio = r.listen(sourse, phrase_time_limit=3) try: text = (r.recognize_google(audio, language="ru-RU")).lower() except(sr.UnknownValueError): pass except(TypeError): pass os.system('cls') lb['text'] = text clear_task() # выполнение команд def cmd_exe(): global cmds, engine, comparison, check_searching, task_number, text, lb text = comparison(text) print(text) check_searching() if (text in cmds): if (text != 'Приветик') & (text!= 'как тебя зовут') & (text != 'кто ты') & (text != 'Спасибо') & (text != 'покажи список команд'): os.system("echo Одну секунду | RHVoice-test -p Anna") cmds[text]() elif text == '': pass else: print('Команда не найдена!') task_number += 1 if (task_number % 10 == 0): os.system("echo У тебя будет еще вопрос? | RHVoice-test -p Anna") engine.runAndWait() engine.stop() # основной бесконечный цикл def main(): global text, talk, cmd_exe, j try: talk() if text != '': cmd_exe() j = 0 except(UnboundLocalError): pass except(TypeError): pass # раздел создания интерфейса os.system("echo Alexa к вашим услугам! | RHVoice-test -p Anna") root = Tk() root.geometry('250x350') root.configure(bg = 'black') root.title('Alexa') root.resizable(False, False) lb = Label(root, text = text) lb.configure(bg = 'gray') lb.place(x = 25, y = 25, height = 25, width = 200) but1 = Button(root, text = 'Вопрос?', command = main) but1.configure(bd = 1, font = ('Castellar', 25), bg = 'gray') but1.place(x = 50, y = 160, height = 50, width = 150) but2 = Button(root, text = 'Выход', command = quit) but2.configure(bd = 1, font = ('Castellar',25), bg = 'gray') but2.place(x = 50, y = 220, height = 50, width = 150) root.mainloop() <file_sep>/cmd.py from Funchin import * commands = ['Приветик', 'открой гитхаб', 'открой файл', 'down comp', 'выруби компьютер', 'Спасибо', 'покажи файл', 'покажи список команд', 'open vk', 'открой браузер', 'открой интернет', 'открой youtube', 'включи музон', 'вруби музыку', 'сколько время', 'очисти файл', 'открой стату', 'покажи cтатистику', 'покажи красивую девушку', 'открой музыку', 'переведи', 'планы', 'на будущее', 'что планируется', 'play lil pump', 'загугли', 'апдейт', 'апгрейт', 'как тебя зовут', 'кто ты', 'Прогноз погоды', 'накинь малины', 'сделай смарт', 'сделай французкскую атмосферу', 'сделай по красоте', 'кто твой создатель'] cmds = { 'Приветик' : hello, 'выруби компьютер' : shut, 'down comp' : shut, 'Спасибо' : quit, 'покажи cтатистику' : pri_com, 'загугли':web_search, 'открой браузер' : brows, 'включи vk' : ovk, 'открой интернет' : brows, 'открой youtube' : youtube, 'вруби музыку' : musik, 'open vk' : ovk, 'открой стату' : pri_com, 'включи музон' : musik, 'очисти файл' : clear_analis, 'покажи файл' : pri_com, 'открой файл' : pri_com, 'открой музыку' : musik, 'планы' : plans, 'на будущее' : plans, 'что планируется' : plans, 'открой гитхаб' : github, 'pump' : playLILPump, 'сколько время' : time, 'переведи' : check_translate, 'play lil pump': playLILPump , 'апдейт':update, 'как тебя зовут' :alexa, 'кто ты': alexa, 'апгрейт': upgrade, 'Прогноз погоды' :weather, 'накинь малины': playYoloTAgMAlina, 'сделай смарт': playPharaohSmart, 'сделай французкскую атмосферу': playZazJuVew, 'сделай по красоте': playKatyaNovemvber, 'кто твой создатель': obiitoOne } <file_sep>/README.md # Alexa Простой голосовой помощник Алекса, написанный для себя. <file_sep>/Funchin.py import pyttsx3 import os import webbrowser import time import speech_recognition as sr import pandas as pd from tkinter import * from fuzzywuzzy import fuzz from colorama import * import sys import requests # Глобальные переменные text = '' r = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty('voices') adress = '' j = 0 task_number = 0 def hello(): #функция приветствия os.system("echo Приветик. OBIITO. Есть вопросы ? | RHVoice-test -p Anna") def plans(): os.system("echo Моя задача будет состоять в том, чтобы помочь управлять системой Умный дом.\ В настоящее время мы работаем над виртуальной частью программного обеспечения.\ Мы также работаем над оптимизацией всех существующих функций в коде.\ В дальнейшем мы планируем работать над технической частью проекта.\ Она будет состоять из создания элементов умного дома с использованием микроконтроллеров Arduino.\ В конечном итоге виртуальная и техническая части проекта будут объединены.\ Моя конечная цель будет достигнута.| RHVoice-test -p Anna") def alexa(): os.system("echo Меня зовут Alexa. Я простой голосовой помошник, \ предназначенный для упрощения пользования системой Линукс.\ Создал меня разработчик OBITO. Будут ли вопросы ко мне? | RHVoice-test -p Anna") def obiitoOne(): os.system("echo Он один из основателей Черных Быков. И первый человек пробудивший менгекё шаринган.\ Непобедимый и бесмертный.\ Мой сообщник и создатель. Единственный, кому удалось узнать тайну вечного цукуёми.\ Вот кто такой OBITO | RHVoice-test -p Anna") def time(): # узнает время import datetime now = datetime.datetime.now() os.system("echo Сейчас %d %d | RHVoice-test -p Anna" % (now.hour, now.minute)) def clear_analis(): # очистка файла с историей запросов file = open('commands.txt', 'w', encoding = 'UTF-8') file.close() os.system("Файл аналитики был очищен! | RHVoice-test -p Anna") def github(): # открывает гитхаб os.system("echo Открываю твою страницу Гитхаба | RHVoice-test -p Anna") webbrowser.open('https://github.com/OB11TO') def brows(): # открывает браузер os.system("echo Открываю | RHVoice-test -p Anna") webbrowser.open('https://google.ru') def ovk(): # открывает вк os.system("echo Вк открыт | RHVoice-test -p Anna") webbrowser.open('https://vk.com/feed') def youtube(): # открывает ютюб os.system("echo Открываю youtube | RHVoice-test -p Anna") webbrowser.open('https://www.youtube.com') def update(): # проверка обновления os.system('sudo apt-get update') def upgrade(): # установка обновлений os.system('sudo apt-get upgrade') def shut(): # выключает компьютер global quit os.system('sudo shutdown -h now') quit() def playLILPump(): #включает пампа os.system("echo Включаю Лил пампа | RHVoice-test -p Anna") webbrowser.open('https://www.youtube.com/watch?v=DPxL7dO5XPc') def playKatyaNovemvber(): os.system("echo Уже приготовила для тебя кое-что. Закрывай глаза и наслаждайся | RHVoice-test -p Anna") webbrowser.open('https://disk.yandex.ru/client/disk?idApp=client&dialog=slider&idDialog=%2Fdisk%2Flv_0_20210922170703.mp4') def playYoloTAgMAlina(): os.system("echo Брат, ща покайфуешь, отвечаю, держи малину! | RHVoice-test -p Anna") webbrowser.open('https://www.youtube.com/watch?v=XAOLChiYRT8') def playPharaohSmart(): os.system("echo Всегда смарт, я как вода, специально для тебя Аксинья!!!! | RHVoice-test -p Anna") webbrowser.open('https://www.youtube.com/watch?v=2NI1fDkToCA') def playZazJuVew(): os.system("echo Погрузимся немного во Францию. Специально для бабушки Николь играет следующий трек| RHVoice-test -p Anna") webbrowser.open('https://www.youtube.com/watch?v=0TFNGRYMz1U') def musik(): # включает музыку webbrowser.open('https://vk.com/') def web_search(): # осуществляет поиск в интернете по запросу (adress) global adress webbrowser.open('https://yandex.ru/yandsearch?clid=2028026&text={}&lr=11373'.format(adress)) def check_translate(): global text word = text word = word.replace('переведи','').strip() webbrowser.open('https://translate.google.ru/#view=home&op=translate&sl=auto&tl=ru&text={}'.format(word)) text = '' def check_searching(): # проверяет нужно-ли искать в интернете global text,wifi_name,add_file global adress global web_search if 'загугли' in text: add_file('загугли') adress = text.replace('загугли','').strip() text = text.replace(adress,'').strip() web_search() text = '' elif 'загугли' in text: add_file('загугли') adress = text.replace('загугли','').strip() text = text.replace(adress,'').strip() web_search() text = '' adress = '' def pri_com(): # выводит на экран историю запросов z = {} mas = [] mas2 = [] mas3 = [] mas4 = [] file = open('commands.txt', 'r', encoding = 'UTF-8') k = file.readlines() for i in range(len(k)): line = str(k[i].replace('\n','').strip()) mas.append(line) file.close() for i in range(len(mas)): x = mas[i] if x in z: z[x] += 1 if not(x in z): b = {x : 1} z.update(b) if not(x in mas2): mas2.append(x) for i in mas2: mas3.append(z[i]) for i in range(1, len(mas3)+1): mas4.append(str(i)+') ') list = pd.DataFrame({ 'command' : mas2, 'count' : mas3 }, index = mas4) list.index.name = '№' print(list) def weather(): url = 'https://wttr.in' weather_parameters = { '1': '', 'T': '', 'M': '', 'lang':'ru' } response = requests.get(url, params=weather_parameters) print(response.text) os.system("echo Ваш прогноз погоды | RHVoice-test -p Anna") def quit(): # функция выхода из программы global engine os.system("echo Обращайтесь OBIITO | RHVoice-test -p Anna") engine.stop() os.system('cls') exit(0)
c84a3f50f2e651e9aa1431ed5f907197fe4e2b8b
[ "Markdown", "Python" ]
4
Python
OB11TO/alexa
581155befa578450368871091100999c190d4709
838ee663b3b2dd14a10deba71ff05474ea1a84bf
refs/heads/master
<repo_name>p0ria/ng-dalahoo-table<file_sep>/src/lib/table-search/dalahoo-table-search.component.ts import {Component, ElementRef, EventEmitter, OnInit, Output, ViewChild} from '@angular/core'; import {fromEvent} from "rxjs"; import {debounceTime} from "rxjs/operators"; @Component({ selector: 'dalahoo-table-search', templateUrl: './dalahoo-table-search.component.html', styleUrls: ['./dalahoo-table-search.component.scss'] }) export class DalahooTableSearchComponent implements OnInit { @Output() searchChanged = new EventEmitter<string>(); @ViewChild('searchInput', {static: true}) searchInputElRef: ElementRef; private searchInputEl: HTMLInputElement; constructor() { } ngOnInit(): void { this.searchInputEl = this.searchInputElRef.nativeElement as HTMLInputElement; fromEvent(this.searchInputEl, 'input').pipe( debounceTime(500) ).subscribe(_ => { let searchTerm = this.searchInputEl.value; this.searchChanged.emit(searchTerm); }) } } <file_sep>/README.md #Dalahoo Table A simple and powerful Datatable for Angular based on [Dalahoo Website](https://dalahoo.com/) Table with some additional features. ![Preview video][] ## Key features - Custom header cell template - Custom row cell template - Builtin sorting and searching - Custom column filtering ## Prerequisites - Angular version 5 or higher - FontAwesome ## Installation 1. Install ng-dalahoo-table with `npm`: `npm install ng-dalahoo-table --save` 2. Add `DalahooTableModule` to `imports` in `src/app/app.module.ts`: ```typescript @NgModule({ imports: [ BrowserModule, DalahooTableModule ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { } ``` 3. Add FontAwesome: * Install fontawesome via npm: `npm install fontawesome --save` * Add `fontawesome scss` file to `styles` section in `package.json` file: ``` "styles": [ "../node_modules/font-awesome/scss/font-awesome.scss" ] ``` * Add these two lines to `styles.scss` file: ``` $fa-font-path: "../../../node_modules/font-awesome/fonts"; @import '~font-awesome/scss/font-awesome.scss'; ``` ## Example ```html <dalahoo-table [items]="items" #table> <dalahoo-table-header> <dalahoo-table-header-cell field="group" flex="1"> گروه </dalahoo-table-header-cell> <dalahoo-table-header-cell field="title" flex="1"> عنوان </dalahoo-table-header-cell> <dalahoo-table-header-cell field="capacity" flex="0 0 100px" [isCenter]="true"> ظرفیت </dalahoo-table-header-cell> <dalahoo-table-header-cell field="duration" flex="0 0 100px" [isCenter]="true"> مدت </dalahoo-table-header-cell> <dalahoo-table-header-cell field="date" flex="0 0 120px" [isCenter]="true"> تاریخ </dalahoo-table-header-cell> </dalahoo-table-header> <dalahoo-table-body> <dalahoo-table-row *ngFor="let item of table.displayItems"> <dalahoo-table-row-cell > <span [highlightMatch]="item.group"></span> </dalahoo-table-row-cell> <dalahoo-table-row-cell > <span [highlightMatch]="item.title"></span> </dalahoo-table-row-cell> <dalahoo-table-row-cell > <span>{{item.capacity}}</span> </dalahoo-table-row-cell> <dalahoo-table-row-cell> <span [highlightMatch]="item.duration"></span> </dalahoo-table-row-cell> <dalahoo-table-row-cell> <span [highlightMatch]="item.date"></span> </dalahoo-table-row-cell> </dalahoo-table-row> </dalahoo-table-body> </dalahoo-table> ``` ## Filter functionality * Create a component that implements Filterable<T> interface * Add this component inside `<dalahoo-table-header-cell>` tag wrapped inside `<dalahoo-table-header-cell-filter>` tag ```typescript @Component({ selector: 'app-capacity-filter', templateUrl: './capacity-filter.component.html', styleUrls: ['./capacity-filter.component.scss'] }) export class CapacityFilterComponent implements Filterable<Item>, OnInit { @Output() filterChanged = new BehaviorSubject<boolean>(false); isAvailableChecked = true; isUnAvailableChecked = false; ngOnInit(): void { this.trigger(); } trigger() { let isFiltered = !this.isAvailableChecked || !this.isUnAvailableChecked; this.filterChanged.next(isFiltered); } filter = (item: Item): boolean => { if(this.isAvailableChecked && this.isUnAvailableChecked) return true; if(this.isAvailableChecked) if(item.capacity == 'موجود') return true; if(this.isUnAvailableChecked) if(item.capacity == 'ناموجود') return true; return false; }; availableCheckChanged(checked: boolean) { this.isAvailableChecked = checked; this.trigger(); } unAvailableCheckChanged(checked: boolean) { this.isUnAvailableChecked = checked; this.trigger(); } } ``` ```html <dalahoo-table-header-cell field="capacity" flex="0 0 100px" [isCenter]="true"> ظرفیت <dalahoo-table-header-cell-filter width="150px" height="70px" [filter]="capacityFilter"> <app-capacity-filter #capacityFilter></app-capacity-filter> </dalahoo-table-header-cell-filter> </dalahoo-table-header-cell> ``` [Preview video]: https://public-media.driftvideo.com/videos-gifs/HYFY-RECORDING-1139828-1181483-1585222869-.gif <file_sep>/src/lib/interfaces/filterable.interface.ts import {Observable} from "rxjs"; export interface Filterable<T> { filter: (item: T) => boolean; filterChanged: Observable<boolean>; } <file_sep>/src/public_api.ts /* * Public API Surface of ng-dalahoo-table */ export * from './lib/dalahoo-table.module'; export * from './lib/dalahoo-table.component'; export * from './lib/table-body/dalahoo-table-body.component'; export * from './lib/table-header/dalahoo-table-header.component'; export * from './lib/table-header/table-header-cell/dalahoo-table-header-cell.component'; export * from './lib/table-header/table-header-cell/table-header-cell-filter/dalahoo-table-header-cell-filter.component'; export * from './lib/table-row/dalahoo-table-row.component'; export * from './lib/table-row/table-row-cell/dalahoo-table-row-cell.component'; export * from './lib/table-search/dalahoo-table-search.component'; export * from './lib/directives/click-outside.directive'; export * from './lib/directives/highlight-match.directive'; export * from './lib/interfaces/filterable.interface'; <file_sep>/src/lib/table-header/table-header-cell/dalahoo-table-header-cell.component.ts import { AfterContentInit, Component, ContentChild, HostBinding, Input, OnDestroy, OnInit } from '@angular/core'; import {Subscription} from "rxjs"; import {DalahooTableHeaderCellFilterComponent} from "./table-header-cell-filter/dalahoo-table-header-cell-filter.component"; @Component({ selector: 'dalahoo-table-header-cell', templateUrl: './dalahoo-table-header-cell.component.html', styleUrls: ['./dalahoo-table-header-cell.component.scss'] }) export class DalahooTableHeaderCellComponent implements OnInit, OnDestroy, AfterContentInit { @Input() field: string; @Input() @HostBinding('style.flex') flex: string = '1'; @Input() @HostBinding('class.center') isCenter: boolean = false; @ContentChild(DalahooTableHeaderCellFilterComponent, {static: true}) filterComponent: DalahooTableHeaderCellFilterComponent; @HostBinding('class.filter-active') isFiltered: boolean = false; filterChangedSub: Subscription; @HostBinding('class.filter') isFilterable: boolean = false; @HostBinding('class.filter-open') isFilterOpen: boolean = false; constructor(){} ngOnInit(): void { } ngAfterContentInit(): void { if(this.filterComponent) { this.isFilterable = true; this.filterChangedSub = this.filterComponent.filter.filterChanged.subscribe( event => this.isFiltered = event); } } ngOnDestroy(): void { if(this.filterChangedSub) this.filterChangedSub.unsubscribe(); } toggleFilterOpen(event: MouseEvent) { event.stopPropagation(); this.isFilterOpen = !this.isFilterOpen; } } <file_sep>/src/lib/directives/highlight-match.directive.ts import {Directive, ElementRef, Input, OnChanges, SimpleChanges} from '@angular/core'; @Directive({ selector: '[highlightMatch]' }) export class HighlightMatchDirective implements OnChanges{ @Input() highlightMatch; constructor(private elementRef: ElementRef) { } ngOnChanges(changes: SimpleChanges): void { let el = this.elementRef.nativeElement as HTMLElement; el.innerHTML = this.highlightMatch; } } <file_sep>/src/lib/dalahoo-table.module.ts import { NgModule } from '@angular/core'; import {CommonModule} from "@angular/common"; import {DalahooTableComponent} from "./dalahoo-table.component"; import {HighlightMatchDirective} from "./directives/highlight-match.directive"; import {ClickOutsideDirective} from "./directives/click-outside.directive"; import {DalahooTableBodyComponent} from "./table-body/dalahoo-table-body.component"; import {DalahooTableHeaderComponent} from "./table-header/dalahoo-table-header.component"; import {DalahooTableHeaderCellComponent} from "./table-header/table-header-cell/dalahoo-table-header-cell.component"; import {DalahooTableHeaderCellFilterComponent} from "./table-header/table-header-cell/table-header-cell-filter/dalahoo-table-header-cell-filter.component"; import {DalahooTableRowComponent} from "./table-row/dalahoo-table-row.component"; import {DalahooTableRowCellComponent} from "./table-row/table-row-cell/dalahoo-table-row-cell.component"; import {DalahooTableSearchComponent} from "./table-search/dalahoo-table-search.component"; const COMPONENTS = [ DalahooTableComponent, DalahooTableBodyComponent, DalahooTableHeaderComponent, DalahooTableHeaderCellComponent, DalahooTableHeaderCellFilterComponent, DalahooTableRowComponent, DalahooTableRowCellComponent, DalahooTableSearchComponent ]; const DIRECTIVES = [ HighlightMatchDirective, ClickOutsideDirective ]; @NgModule({ declarations: [...COMPONENTS, ...DIRECTIVES], imports: [ CommonModule ], exports: [...COMPONENTS, ...DIRECTIVES] }) export class DalahooTableModule { } <file_sep>/src/lib/dalahoo-table.component.ts import { AfterViewInit, ChangeDetectionStrategy, Component, ContentChildren, ElementRef, Input, OnInit, QueryList, Renderer2, } from '@angular/core'; import {BehaviorSubject, combineLatest} from "rxjs"; import {Filterable} from "./interfaces/filterable.interface"; import {DalahooTableHeaderCellComponent} from "./table-header/table-header-cell/dalahoo-table-header-cell.component"; import {DalahooTableRowCellComponent} from "./table-row/table-row-cell/dalahoo-table-row-cell.component"; import {DalahooTableHeaderCellFilterComponent} from "./table-header/table-header-cell/table-header-cell-filter/dalahoo-table-header-cell-filter.component"; @Component({ selector: 'dalahoo-table', templateUrl: './dalahoo-table.component.html', styleUrls: ['./dalahoo-table.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class DalahooTableComponent implements OnInit, AfterViewInit{ @Input() set sort(value: string){ this.sort$.next( {field: value, asc: null}); } @Input() set items(value: any[]) { this.items$.next(value); } @ContentChildren(DalahooTableHeaderCellComponent, {descendants: true}) headerCellComponents: QueryList<DalahooTableHeaderCellComponent>; @ContentChildren(DalahooTableRowCellComponent, {descendants: true, read: ElementRef}) rowCellElements: QueryList<ElementRef>; @ContentChildren(DalahooTableHeaderCellComponent, {descendants: true, read: ElementRef}) headerCellElements: QueryList<ElementRef>; @ContentChildren(DalahooTableHeaderCellFilterComponent, {descendants: true}) filterCellComponents: QueryList<DalahooTableHeaderCellFilterComponent>; displayItems = []; items$ = new BehaviorSubject<any[]>([]); sort$ = new BehaviorSubject<{field: string, asc: boolean}>(null); search$ = new BehaviorSubject<string>(null); filter$ = new BehaviorSubject<Filterable<any>[]>([]); private sortField: string; constructor(private renderer: Renderer2) { } ngOnInit(): void { combineLatest(this.items$, this.search$, this.sort$, this.filter$) .subscribe(([items, search, sort, filters]) => { let filteredItems = this.filterItems(items, filters); let searchedItems = this.searchItems(filteredItems, search); let sortFiled = sort ? sort.field : null; let sortAsc = sort ? sort.asc : null; let sortedItems = this.sortItems(searchedItems, sortFiled, sortAsc); this.displayItems = sortedItems; }) } ngAfterViewInit(): void { this.bindRows(); this.rowCellElements.changes.subscribe(() => { this.bindRows(); }); this.bindSorting(); this.bindFiltering(); } bindRows() { let headerCells = this.headerCellComponents.toArray(); let rowCells = this.rowCellElements.toArray(); for(let i = 0; i < rowCells.length; i++) { let rowCell = rowCells[i].nativeElement as HTMLElement; let headerCell = headerCells[i % headerCells.length]; this.renderer.setStyle(rowCell, 'flex', headerCell.flex); headerCell.isCenter ? this.renderer.addClass(rowCell, 'center') : this.renderer.removeClass(rowCell, 'center'); } } bindSorting() { let headerCells = this.headerCellElements.toArray(); headerCells.forEach(headerCellElement => { let header = headerCellElement.nativeElement as HTMLElement; let field = header.getAttribute('field'); if(field) header.onclick = () => { let toggle = this.sortField === field; let asc = this.sort$ && this.sort$.value && this.sort$.value.asc; this.sort$.next({field: field, asc: toggle ? !asc : true}); }; }) } bindFiltering() { let filterCells = this.filterCellComponents.toArray(); filterCells.forEach(filterCell => { filterCell.filter.filterChanged.subscribe(filter => { let filters = [...this.filter$.value]; if(filter) { if(!filters.includes(filterCell.filter)) filters.push(filterCell.filter); } else { filters = filters.filter(f => f !== filterCell.filter); } this.filter$.next(filters); }); }); } sortItems(items: any[], field = null, asc: boolean = true): any[] { if(!items || items.length == 0) return []; let sortedItems = [...items]; this.sortField = field || this.sortField; if(this.sortField) { this.addSortClassToHeaderCell(asc); sortedItems.sort((a, b) => { if(asc) return a[this.sortField] <= b[this.sortField] ? -1 : 1; else return a[this.sortField] < b[this.sortField] ? 1 : -1; }); } return sortedItems; } filterItems(items: any[], filters: Filterable<any>[]): any[] { if(!items || !items.length) return []; if(!filters || !filters.length) return items; let filteredItems = items.filter(item => filters.every(filter => filter.filter(item))); return filteredItems; } searchItems(items: any[], search): any[] { if(!items || items.length == 0) return []; if(!search) return items; let searchedItems = []; items.forEach(item => searchedItems.push({...item})); return searchedItems.filter(item => Object.entries(item).some(entry => { const key = entry[0]; const value = entry[1]; const valueText = value.toString(); const index = valueText.indexOf(search); if(index == -1) return false; if(typeof value == 'string') { let highlightedValue = valueText.substring(0,index) + "<span class='highlight'>" + valueText.substring(index, index + search.length) + "</span>" + valueText.substring(index + search.length); item[key] = highlightedValue; } return true; }) ); } addSortClassToHeaderCell(asc: boolean) { if(!this.headerCellElements) return; this.headerCellElements.toArray(); this.headerCellElements.forEach(cellElement => { let cell = cellElement.nativeElement as HTMLElement; const isTarget = cell.getAttribute('field') == this.sortField; this.renderer.removeClass(cell, 'des'); this.renderer.removeClass(cell, 'asc'); if(isTarget) this.renderer.addClass(cell, asc ? 'asc' : 'des'); }) } searchChanged($event: string) { this.search$.next($event); } } <file_sep>/src/lib/table-header/table-header-cell/table-header-cell-filter/dalahoo-table-header-cell-filter.component.ts import { AfterViewInit, Component, ElementRef, forwardRef, HostBinding, HostListener, Inject, Input, OnInit, } from '@angular/core'; import {Filterable} from "../../../interfaces/filterable.interface"; import {DalahooTableHeaderCellComponent} from "../dalahoo-table-header-cell.component"; @Component({ selector: 'dalahoo-table-header-cell-filter', templateUrl: './dalahoo-table-header-cell-filter.component.html', styleUrls: ['./dalahoo-table-header-cell-filter.component.scss'] }) export class DalahooTableHeaderCellFilterComponent implements OnInit, AfterViewInit { @Input() @HostBinding('style.width') width = '100%'; @Input() @HostBinding('style.height') height = '100%'; @Input() filter: Filterable<any>; constructor( private elementRef: ElementRef<HTMLElement>, @Inject(forwardRef(() => DalahooTableHeaderCellComponent)) private parent: DalahooTableHeaderCellComponent) {} ngOnInit(): void { } ngAfterViewInit(): void { let el = this.elementRef.nativeElement; let table = document.querySelector<HTMLElement>('dalahoo-table'); let parent = el.parentElement; if(this.parent.isCenter) { let elWidth = el.clientWidth; let parentWidth = parent.clientWidth; let offset = Math.floor((parentWidth - elWidth) / 2); el.style.right = offset + 'px'; } else { el.style.right = "0"; } let elLeft = el.getBoundingClientRect().left; let tableLeft = table.getBoundingClientRect().left; let tableOffset = elLeft - tableLeft; if(tableOffset < 0) { let right = parseInt(el.style.right.split('px')[0]); el.style.right = right + tableOffset + 'px'; } } @HostListener('click', ['$event']) click(event: MouseEvent) { event.stopPropagation(); } }
fc92523bae2cbc2683b4d62278dacfe21ed6d0ba
[ "Markdown", "TypeScript" ]
9
TypeScript
p0ria/ng-dalahoo-table
aed3cbb9bbb9cd2c3a1d6576749f56c4f9fbbf81
9c0f06e85b2a613025f748a35d1799bc29ad7294
refs/heads/master
<file_sep>TO COMPILE: javac -d classes -cp ./junit-4.12.jar src/main/java/cs1302/lists/*.java src/test/java/cs1302/lists/*.java */ To EXCECUTE DRIVER CLASS: go into DIRECTORY classes/ type $java Driver /* Created by <NAME> (811190857) * #include "Driver.java" * #include "List.java" * #include "Node.java" * #include "ArrayList.java" * #include "LinkedList.java" * #include "DoubleLinkedList.java" * */ Data is in TIME(MicroSeconds): The person searching for was not in the list to make sure it was worst case scenario. FIGURE 1.1 - Data ___________________________________________________________________ | ArrayList Records |Prepend | Append | Get | Remove | Search | | 10 | 8.7 | 6.3 | 5.0 | 6.3 | 17.7 | | 1,000 | 34.1 | 29.6 | .73 | 36.6 | 411.9 | | 10,000 | 360.2 | 362.0 | 1.5 | 391.0 | 772.2 | | 100,000 | 1212.6 | 3325.2 |1.7 | 3230.8 | 3618.4 | | | | | | | | |_______________________|________|________|_______|________|________| FIGURE 1.2 ___________________________________________________________________ | LinkedList Records |Prepend | Append | Get | Remove | Search | | 10 | 6.8 | 5.3 | 6.3 | 3.5 | 10.3 | | 1,000 | 1.0 | 1.0 | 9.0 | 11.8 | 58.3 | | 10,000 | 4.0 | 2.2 | 101.0 | 116.7 | 526.8 | | 100,000 | 9.4 | 3.4 | 1038.1| 1145.2 | 4650.5 | | | | | | | | |_______________________|________|________|_______|________|________| FIGURE 1.3 ___________________________________________________________________ | DLinkedList Records |Prepend | Append | Get | Remove | Search | | 10 | 3.5 | 3.0 | 6.7 | 3.6 | 10.6 | | 1,000 | 1.5 | .60 | 13.0 | 9.8 | 51.1 | | 10,000 | 2.7 | 0.60 | 133.5 | 141.0 | 845.0 | | 100,000 | 7.6 | .762 |2081.3 | 962.0 | 3841.3 | | | | | | | | |_______________________|________|________|_______|________|________| THESE WERE THE INPUTS: populated an array of 10000 People: Prepending <NAME> Appending <NAME> Getting person at index 5000 Removing person at index 5000 Search for person not in list __________________________________________________________________________________________________________________________________________ /* *Introduction/Speed */ To start off with, I decided on using People Object for the type within the Arrays. For each person, they had a Name, Proffession, and a Height. This was to ensure that the time to run a method would be larger than an integer/string/primative datatype because more memory is being passed around. To my surprise, the time it took to iterate and end a method was astonishingly fast at 100,000, I had to change the orignal milliseconds to nanoseconds to get a better judge of time. While doing this, I could more accurately see where I had lost time, however becuase the numbers are so small, on each run proccess, it could change dramatically. While it was fast, I could not finish the run process when there were 1,000,000 people. Nike would always timeout and I couldn't get the data I wanted. ___________________________________________________________________________________________________________________________________________ /* *A closer Look at my methods * Typedef WorstCaseScenario = wcs */ __________ ArrayList | __________| Prepend::O(N) Method contains one for loop and the the parameters within the loop don't change the #of loops. Append:: O(N) Method contains one for loop and the the parameters within the loop don't change the #of loops. Add:: O(N) Method contains one for loop and the the parameters within the loop don't change the #of loops. Get:: O(1) Gets the location. No loop needed, always runs once. Remove:: O(N) Goes through loop, recopying array into a temp array, and avoiding the one it is supposed to remove. Search:: O(N) If it finds what it is looking for, it leaves loop, otherwise wcs it looks at entire array. Total = 5(N) When compared to Actual table's average and wcs: Add/Prepend/Append:: O(N) wcs O(N) Get:: O(1) wcs O(1) Remove:: O(N) wcs O(N) Search:: O(N) wcs O(N) My Results: Implementation: Spot on! ___________ LinkedList | ___________| Prepend:: O(1) calls add method, which runs once because index is 0 and no loop within add method. Append:: O(1) No Loops within method and executes once no matter what. Add:: O(1) No Loops within method and executes once no matter what. Get:: O(N) starts from the beggining and loops until at the index, if index at the end, then wcs. Remove:: O(N) Runs through each Node until it gets to the right index. Search:: O(N) If it finds what it is looking for, it leaves loop, otherwise wcs it looks at every node. When compared to Actual table's average and wcs: Add/Prepend/Append:: O(1) wcs O(1) Get:: O(N) wcs O(N) Remove:: O(1) wcs O(1) Search:: O(N) wcs O(N) Total = 3(N) My Results: Implementation: Remove method was off by *N. ____________ DLinkedList | ____________| Prepend:: O(1) Runs once. Contains 3 if statements and no loops Append:: O(1) Runs once. No loops included Add:: O(N) Runs once if index is at 0 or at end, otherwise runs N number of times. Get:: O(N) Mixed it up and added a do while loop to get to the right node based off the index. Remove:: O(N) if index is 0 or index is the last size, method runs once, otherwise goes into while loop N times. Search:: O(N) If it finds what it is looking for, it leaves loop, otherwise wcs it looks at every node. Total = 4(N) When compared to Actual table's average and wcs: Add/Prepend/Append:: O(1) wcs O(1) Get:: O(N) wcs O(N) Remove:: O(1) wcs O(1) Search:: O(N) wcs O(N) My Results: Remove and add were off by *N ___________________________________________________________________________________________________________________________________________ /* *Analysis */ Based on our bigO notations listed above, we can expect that LinkedList will be the fastest as the array is larger, followed by DLinkedList and lastely ArrayList. However this was not the case. Figures 2.1 to 2.5(shown below) shows a side by side comparisons of each method that was called to each of the list classes implemented. For the most part, DLinkedList shown to execute the fastest or closest to the fastest, in multiple populations and methods (except get). Overall becuase the time is in microseconds, these results can vary by a large amount on each run. However, LinkedList and DlinkedList do show to be similiar in speed for each method. The ArrayList is considerablly slower than the two other lists except within the get method, which it excels in speed. Overall, if you were coding for a database that doesn't move memory around a whole bunch and just gets information, then the arrayList would be the best option. However, if the job calls for consistent memory change, then LinkedList or DLinkedList would be the better option. A DlinkedList in general takes up more memory because each node has knowledge of it's previous and next node, while the LinkedList only has information based on its next Node. This means that you can get to any node and can move reverse, while a LinkedList is linear and will only let you move forward. ___________________________________________________________________________________________________________________________________________ FIGURE 2.1 - Comparisons Preppending: __________________________________________________________ | | Preppending | |_______________________|____10_____1000____10000___100000_| | ArrayList Records | 8.7 | 34.1 | 360.2 | 1212.6 | | LinkedList Records | 6.8 | 1.0 | 4.0 | 9.4 | | DLinkedList Records | 3.5 | 1.5 | 2.7 | 7.6 | | | | | | | | | | | | | |_______________________|________|________|_______|________| Figure 2.2 Appending: __________________________________________________________ | | Appending | |_______________________|____10_____1000____10000___100000_| | ArrayList Records | 6.3 | 29.6 | 362.0 | 3325.2 | | LinkedList Records | 5.3 | 1.0 | 2.2 | 3.4 | | DLinkedList Records | 3.0 | .60 | .60| .762 | | | | | | | | | | | | | |_______________________|________|________|_______|________| Figure 2.3 Get: __________________________________________________________ | | Get | |_______________________|____10_____1000____10000___100000_| | ArrayList Records | 5.0 | .73 | 1.5 | 1.7 | | LinkedList Records | 6.3 | 9.0 | 101.0 | 1038.1 | | DLinkedList Records | 2.7 | 0.60 | 133.5 | 141.0 | | | | | | | | | | | | | |_______________________|________|________|_______|________| Figure 2.4: Remove: __________________________________________________________ | | Remove | |_______________________|____10_____1000____10000___100000_| | ArrayList Records | 6.3 | 36.6 | 391.0 | 3280.8 | | LinkedList Records | 3.5 | 11.8 | 116.7 | 1145.2 | | DLinkedList Records | 3.6 | 9.8 | 141.0 | 962.0 | | | | | | | | | | | | | |_______________________|________|________|_______|________| Figure 2.5 Search: __________________________________________________________ | | Search | |_______________________|____10_____1000____10000___100000_| | ArrayList Records | 17.7 | 411.9 | 772.2 | 3618.4 | | LinkedList Records | 10.3 | 58.3 | 526.8 | 3650.5 | | DLinkedList Records | 10.6 | 51.1 | 845.0 | 3841.3 | | | 7.6 | .762 |2081.3 | 962.0 | | | | | | | |_______________________|________|________|_______|________| <file_sep> import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; /* * Welcome to Kevin's list implementation * We implemented the DoublyLinkList, ArrayList, and LinkLists * This is to be able to gain more knowledge of the * speed of each of the methods based on the expnential growth * of populations. * * Made by: <NAME> * * */ public class Driver { public static void main(String []args) { //tests methods, each creation of array list will do , 10, 1000, 10000, 100,000 and 1,000,000 tets createArrayListAttempt(); createLinkedListAttempt(); createDoubleLinkedListAttempt(); } static void createDoubleLinkedListAttempt() { long start, end; File DoubleLinkedList = new File("DoubleLinkedList.txt"); try { DoubleLinkedList.createNewFile(); //creates files to input intel about arraylist FileWriter aListWriter = new FileWriter(DoubleLinkedList, false); //used to write into created file. DoubleLinkedList<Person> list1000 = new DoubleLinkedList<Person>();//array of 1000 ints aListWriter.write("Array of 100 people:"); aListWriter.close(); aListWriter = new FileWriter(DoubleLinkedList, true); BufferedWriter bListWriter = new BufferedWriter(aListWriter); bListWriter.newLine(); populate10(list1000); //make it random persons /////////////// start = System.nanoTime(); list1000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>an: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list1000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); Person p = list1000.get(5); end = System.nanoTime(); bListWriter.write("Getting person at location 5: " + (end - start)); bListWriter.newLine(); ////////////////// start = System.nanoTime(); list1000.remove(5); end = System.nanoTime(); bListWriter.write("Removing at index 5:" + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list1000.search(new Person("Misc", "Wrestler", 6.6), 0, list1000.size()-1) ; end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////// DoubleLinkedList<Person> list10000 = new DoubleLinkedList<Person>(); bListWriter.write("Array of 1000 People:"); populate1000(list10000); //make it random persons /////////////// start = System.nanoTime(); list10000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list10000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list10000.get(500); end = System.nanoTime(); bListWriter.write("Getting person at index 500: " + (end - start)); bListWriter.newLine(); /////////////// start = System.nanoTime(); list10000.remove(500); end = System.nanoTime(); bListWriter.write("Removing person: " + p.getName() +" at index 500" + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list10000.search(new Person("Hello", "Dancer", 5.5), 0, list10000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////// DoubleLinkedList<Person> list100000 = new DoubleLinkedList<Person>(); bListWriter.write("Array of 10000 People:"); populate10000(list100000); //make it random persons /////////////// start = System.nanoTime(); list100000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list100000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list100000.get(5000); end = System.nanoTime(); bListWriter.write("Getting person at index 5000: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); //////////////////// start = System.nanoTime(); list100000.remove(5000); end = System.nanoTime(); bListWriter.write("Removing person" + p.getName() + "at index 5000: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list100000.search(new Person("Hello", "Dancer", 5.5), 0, list100000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ////////////////////////////////////////// DoubleLinkedList<Person> list1000000 = new DoubleLinkedList<Person>(); bListWriter.write("Array of 100000 people:"); populate100000(list1000000); //make it random persons /////////////// start = System.nanoTime(); list1000000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start) + "\n"); ///////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)+ "\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list1000000.get(50000); end = System.nanoTime(); bListWriter.write("Getting person at index 50000: " + (end - start)+ "\n"); bListWriter.newLine(); //////////////////////////// start = System.nanoTime(); list1000000.remove(50000); end = System.nanoTime(); bListWriter.write("Removing " + p.getName() +" person at index 50000: " + (end - start)+ "\n"); /////////////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.search(new Person("Hello", "Dancer", 5.5), 0, list1000000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)+ "\n\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////////////////////////////////// /* DoubleLinkedList<Person> list10000000 = new DoubleLinkedList<Person>(); bListWriter.write("Array of 1000000 people:"); populate1000000(list10000000); //make it random persons /////////////// start = System.nanoTime(); list10000000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>an: " + (end - start) + "\n"); ///////////// bListWriter.newLine(); start = System.nanoTime(); list10000000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)+ "\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list10000000.get(500000); end = System.nanoTime(); bListWriter.write("Getting person at index 500000: " + (end - start)+ "\n"); bListWriter.newLine(); //////////////////////////// start = System.nanoTime(); list10000000.remove(500000); end = System.nanoTime(); bListWriter.write("Removing " + p.getName() +" person at index 500000: " + (end - start)+ "\n"); /////////////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.search(new Person("Hello", "Dancer", 5.5), 0, list10000000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)+ "\n\n"); bListWriter.newLine(); bListWriter.newLine(); */ bListWriter.close(); aListWriter.close(); System.out.println("End"); //////////////////////////////// //end of arrayList testing. //////////////////////////////////////////// }catch(IOException e) { System.out.println("Problem with file." + e.getMessage()); } } static void createArrayListAttempt() { long start, end; File arrayList = new File("ArrayList.txt"); try { arrayList.createNewFile(); //creates files to input intel about arraylist FileWriter aListWriter = new FileWriter(arrayList, false); //used to write into created file. ArrayList<Person> list1000 = new ArrayList<Person>(10);//array of 1000 ints aListWriter.write("Array of 10 people:"); aListWriter.close(); aListWriter = new FileWriter(arrayList, true); BufferedWriter bListWriter = new BufferedWriter(aListWriter); bListWriter.newLine(); populateArray(list1000); //make it random persons /////////////// start = System.nanoTime(); list1000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list1000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); Person p = list1000.get(5); end = System.nanoTime(); bListWriter.write("Getting person at location 5: " + (end - start)); bListWriter.newLine(); ////////////////// start = System.nanoTime(); list1000.remove(5); end = System.nanoTime(); bListWriter.write("Removing: " + p.getName() + "at index 5:" + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list1000.search(new Person("Misc", "Wrestler", 6.6), 0, list1000.size()-1) ; end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////// ArrayList<Person> list10000 = new ArrayList<Person>(1000); bListWriter.write("Array of 1000 People:"); populateArray(list10000); //make it random persons /////////////// start = System.nanoTime(); list10000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list10000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list10000.get(500); end = System.nanoTime(); bListWriter.write("Getting person at index 500: " + (end - start)); bListWriter.newLine(); /////////////// start = System.nanoTime(); list10000.remove(500); end = System.nanoTime(); bListWriter.write("Removing person: " + p.getName() +" at index 500" + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list10000.search(new Person("Hello", "Dancer", 5.5), 0, list10000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////// ArrayList<Person> list100000 = new ArrayList<Person>(10000); bListWriter.write("Array of 10000 People:"); populateArray(list100000); //make it random persons /////////////// start = System.nanoTime(); list100000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list100000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list100000.get(5000); end = System.nanoTime(); bListWriter.write("Getting person at index 5000: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); //////////////////// start = System.nanoTime(); list100000.remove(5000); end = System.nanoTime(); bListWriter.write("Removing person" + p.getName() + "at index 5000: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list100000.search(new Person("Hello", "Dancer", 5.5), 0, list100000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ////////////////////////////////////////// ArrayList<Person> list1000000 = new ArrayList<Person>(100000); bListWriter.write("Array of 100000 people:"); populateArray(list1000000); //make it random persons /////////////// start = System.nanoTime(); list1000000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start) + "\n"); ///////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)+ "\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list1000000.get(50000); end = System.nanoTime(); bListWriter.write("Getting person at index 50000: " + (end - start)+ "\n"); bListWriter.newLine(); //////////////////////////// start = System.nanoTime(); list1000000.remove(50000); end = System.nanoTime(); bListWriter.write("Removing " + p.getName() +" person at index 50000: " + (end - start)+ "\n"); /////////////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.search(new Person("Hello", "Dancer", 5.5), 0, list1000000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)+ "\n\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////////////////////////////////// bListWriter.close(); aListWriter.close(); System.out.println("End"); //////////////////////////////// //end of arrayList testing. //////////////////////////////////////////// }catch(IOException e) { System.out.println("Problem with file." + e.getMessage()); } } static void createLinkedListAttempt(){ long start, end; File linkedList = new File("LinkedList.txt"); try { linkedList.createNewFile(); //creates files to input intel about arraylist FileWriter aListWriter = new FileWriter(linkedList, false); //used to write into created file. LinkedList<Person> list1000 = new LinkedList<Person>();//array of 1000 ints aListWriter.write("Array of 100 people:"); aListWriter.close(); aListWriter = new FileWriter(linkedList, true); BufferedWriter bListWriter = new BufferedWriter(aListWriter); bListWriter.newLine(); populate10(list1000); //make it random persons /////////////// start = System.nanoTime(); list1000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending Jackie Chan: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list1000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); Person p = list1000.get(5); end = System.nanoTime(); bListWriter.write("Getting person at location 5: " + (end - start)); bListWriter.newLine(); ////////////////// start = System.nanoTime(); list1000.remove(5); end = System.nanoTime(); bListWriter.write("Removing: " + p.getName() + "at index 5:" + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list1000.search(new Person("Misc", "Wrestler", 6.6), 0, list1000.size()-1) ; end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////// LinkedList<Person> list10000 = new LinkedList<Person>(); bListWriter.write("Array of 1000 People:"); populate1000(list10000); //make it random persons /////////////// start = System.nanoTime(); list10000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending Jack<NAME>an: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list10000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list10000.get(500); end = System.nanoTime(); bListWriter.write("Getting person at index 500: " + (end - start)); bListWriter.newLine(); /////////////// start = System.nanoTime(); list10000.remove(500); end = System.nanoTime(); bListWriter.write("Removing person: " + p.getName() +" at index 500" + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list10000.search(new Person("Hello", "Dancer", 5.5), 0, list10000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////// LinkedList<Person> list100000 = new LinkedList<Person>(); bListWriter.write("Array of 10000 People:"); populate10000(list100000); //make it random persons /////////////// start = System.nanoTime(); list100000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////// start = System.nanoTime(); list100000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending John Cena " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list100000.get(5000); end = System.nanoTime(); bListWriter.write("Getting person at index 5000: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); //////////////////// start = System.nanoTime(); list100000.remove(5000); end = System.nanoTime(); bListWriter.write("Removing person" + p.getName() + "at index 5000: " + (end - start)); bListWriter.write("\n"); bListWriter.newLine(); /////////////////// start = System.nanoTime(); list100000.search(new Person("Hello", "Dancer", 5.5), 0, list100000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)); bListWriter.write("\n"); bListWriter.write("\n"); bListWriter.newLine(); bListWriter.newLine(); ////////////////////////////////////////// LinkedList<Person> list1000000 = new LinkedList<Person>(); bListWriter.write("Array of 100000 people:"); populate100000(list1000000); //make it random persons /////////////// start = System.nanoTime(); list1000000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start) + "\n"); ///////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)+ "\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list1000000.get(50000); end = System.nanoTime(); bListWriter.write("Getting person at index 50000: " + (end - start)+ "\n"); bListWriter.newLine(); //////////////////////////// start = System.nanoTime(); list1000000.remove(50000); end = System.nanoTime(); bListWriter.write("Removing " + p.getName() +" person at index 50000: " + (end - start)+ "\n"); /////////////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.search(new Person("Hello", "Dancer", 5.5), 0, list1000000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)+ "\n\n"); bListWriter.newLine(); bListWriter.newLine(); ///////////////////////////////////////////////// /* ////////////////////////////////////////// LinkedList<Person> list10000000 = new LinkedList<Person>(); bListWriter.write("Array of 1000000 people:"); populate1000000(list10000000); //make it random persons /////////////// start = System.nanoTime(); list10000000.prepend(new Person("<NAME>", "Fighter", 5.5)); end = System.nanoTime(); bListWriter.write("Prepending <NAME>: " + (end - start) + "\n"); ///////////// bListWriter.newLine(); start = System.nanoTime(); list10000000.append(new Person("<NAME>", "Wrestler", 6.6)); end = System.nanoTime(); bListWriter.write("Appending <NAME> " + (end - start)+ "\n"); bListWriter.newLine(); ///////////////// start = System.nanoTime(); p = list10000000.get(500000); end = System.nanoTime(); bListWriter.write("Getting person at index 500000: " + (end - start)+ "\n"); bListWriter.newLine(); //////////////////////////// start = System.nanoTime(); list10000000.remove(500000); end = System.nanoTime(); bListWriter.write("Removing " + p.getName() +" person at index 500000: " + (end - start)+ "\n"); /////////////////// bListWriter.newLine(); start = System.nanoTime(); list1000000.search(new Person("Hello", "Dancer", 5.5), 0, list10000000.size()-1); end = System.nanoTime(); bListWriter.write("Search for person not in list: " + (end - start)+ "\n\n"); bListWriter.newLine(); bListWriter.newLine(); */ ///////////////////////////////////////////////// bListWriter.close(); aListWriter.close(); System.out.println("End"); //////////////////////////////// //end of arrayList testing. //////////////////////////////////////////// }catch(IOException e) { System.out.println("Problem with file." + e.getMessage()); } } static void populateArray(List<Person> array) { char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y','z'}; int length = array.size(); for(int i = 0; i < length; i++) { double random = (double)(Math.random()*10); int letter = (int)(Math.random() * ((25) + 1)); String nameGenerator = ""; nameGenerator += letters[letter] ; if(i ==0) { array.prepend(new Person(nameGenerator,nameGenerator, random)); } else if(i == length) { array.append(new Person(nameGenerator,nameGenerator, random)); } else { array.add(i,new Person(nameGenerator,nameGenerator, random)); } } } static void populate10(List<Person> array) { char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y','z'}; int length = array.size(); for(int i = 0; i < 10; i++) { double random = (double)(Math.random()*10); int letter = (int)(Math.random() * ((25) + 1)); String nameGenerator = ""; nameGenerator += letters[letter] ; array.add(i,new Person(nameGenerator,nameGenerator, random)); } } static void populate100(List<Person> array) { char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y','z'}; int length = array.size(); for(int i = 0; i < 100; i++) { double random = (double)(Math.random()*10); int letter = (int)(Math.random() * ((25) + 1)); String nameGenerator = ""; nameGenerator += letters[letter] ; array.add(i,new Person(nameGenerator,nameGenerator, random)); } } static void populate1000(List<Person> array) { char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y','z'}; int length = array.size(); for(int i = 0; i < 1000; i++) { double random = (double)(Math.random()*10); int letter = (int)(Math.random() * ((25) + 1)); String nameGenerator = ""; nameGenerator += letters[letter] ; array.add(i,new Person(nameGenerator,nameGenerator, random)); } } static void populate10000(List<Person> array) { char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y','z'}; int length = array.size(); for(int i = 0; i < 10000; i++) { double random = (double)(Math.random()*10); int letter = (int)(Math.random() * ((25) + 1)); String nameGenerator = ""; nameGenerator += letters[letter] ; array.add(i,new Person(nameGenerator,nameGenerator, random)); } } static void populate100000(List<Person> array) { char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y','z'}; int length = array.size(); for(int i = 0; i < 100000; i++) { double random = (double)(Math.random()*10); int letter = (int)(Math.random() * ((25) + 1)); String nameGenerator = ""; nameGenerator += letters[letter] ; array.add(i,new Person(nameGenerator,nameGenerator, random)); } } static void populate1000000(List<Person> array) { char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y','z'}; int length = array.size(); for(int i = 0; i < 1000000; i++) { double random = (double)(Math.random()*10); int letter = (int)(Math.random() * ((25) + 1)); String nameGenerator = ""; nameGenerator += letters[letter] ; array.add(i,new Person(nameGenerator,nameGenerator, random)); } } } <file_sep> public class Node<T> { public T data; //the object public Node<T> next;//used for linkedlist and doubly linked list public Node<T> prev;//can only be used for doublylinked list public Node() { } public Node(T data) {//constructor for linkedlist, however this proved to be the wrong choice and was later discarded this.data = data; this.next = null; } public Node(T data, Node<T> next) {//never used. this.next = next; this.data = data; } } <file_sep> import static org.junit.Assert.*; import org.junit.Test; public class LinkedListTest { @Test public void testAppend() { LinkedList<Person> list = new LinkedList<Person>();//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); list.append(p); assertEquals(p, list.get(list.size()-1)); } @Test public void testPrepend() { LinkedList<Person> list = new LinkedList<Person>();//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); list.prepend(p); assertEquals(p, list.get(0)); } @Test public void testAdd() { LinkedList<Person> list = new LinkedList<Person>();//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); Person q = new Person("Charlie", "Coder", 5.9); list.add(0, q); list.add(1, p); assertEquals(p, list.get(1)); } @Test public void testRemove() { LinkedList<Person> list = new LinkedList<Person>();//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); Person q = new Person("Charlie", "Coder", 5.9); Person z = new Person("s", "Coder", 5.9); list.add(0, q); list.prepend(p); list.append(z); list.remove(1); assertTrue(list.get(1) != q); } @Test public void testSearch() { LinkedList<Person> list = new LinkedList<Person>();//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); if(list.search(p, 0, list.size()-1) != -1) ; } } <file_sep> public class ArrayList<T extends Comparable<T>> implements List<T> { @SuppressWarnings("unchecked") private T[] array; private int size = 0; ArrayList(int size) { this.size = size; array = (T[]) new Comparable[size]; } ArrayList() { size = 0; } @Override public void append(T elem) { size++; // create a temporary array @SuppressWarnings("unchecked") T[] tmp = (T[]) new Comparable[size]; // copy elements from the original array into the temp array for (int i = 0; i < array.length; i++) { tmp[i] = array[i]; } // for // add the element to the last position in the temp array tmp[tmp.length - 1] = elem; // replace the array with the temp array array = tmp; } // append @Override public void add(int index, T elem) throws IndexOutOfBoundsException { //dont add to size if(index > size) { throw new IndexOutOfBoundsException(); } T[] temp = (T[]) new Comparable[size + 1]; for(int i = 0; i < size+1; i++) { if(i == index) temp[i] = elem; else if(i < index) temp[i] = array[i]; else temp[i] = array[i-1]; } array = temp; } // add public boolean isEmpty() { return size == 0; } @Override public T get(int idx) throws IndexOutOfBoundsException { if(isEmpty() || idx >= size) { throw new IndexOutOfBoundsException(); } return array[idx]; } // get @Override public void prepend(T elem) { size++; // create a temporary array @SuppressWarnings("unchecked") T[] tmp = (T[]) new Comparable[size]; // add the element to the fist position in the temp array tmp[0] = elem; // copy elements from the original array into the temp array for (int i = 1; i < size; i++) { tmp[i] = array[i -1]; } // for // replace the array with the temp array array = tmp; } // prepend @Override public void remove(int index) throws IndexOutOfBoundsException { if(isEmpty() || index >= size()) throw new IndexOutOfBoundsException(); else { size--; T[] temp = (T[]) new Comparable[size]; for(int i = 0; i < size; i++) { if(i < index) temp[i] = array[i]; else temp[i] = array[i+1]; } array = temp; } } // remove @Override public int search(T s, int lo, int hi) throws IndexOutOfBoundsException { if(isEmpty() ) throw new IndexOutOfBoundsException(); for(int i = lo; i <hi-1; i++) { if(s.compareTo(array[i]) > 0) { return i; } } return -1 ; } // search @Override public int size() { return size; } // size @Override public String toString() { String temp = ""; for(int i = 0; i < size(); i++){ temp+= get(i) ; temp+= "; "; if(i % 10 == 0 && i != 0) { temp+= "\n"; } } return temp; } } // ArrayList <file_sep> import static org.junit.Assert.*; import org.junit.Test; public class ArrayListTest { @Test public void testAppend() { ArrayList<Person> list = new ArrayList<Person>(1);//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); list.append(p); assertEquals(p, list.get(list.size()-1)); // fail("Not yet implemented"); } @Test public void testAdd() { ArrayList<Person> list = new ArrayList<Person>(3);//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); list.add(1, p); assertEquals(p, list.get(1)); } @Test public void testPrepend() { ArrayList<Person> list = new ArrayList<Person>(1);//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); list.prepend(p); assertEquals(p, list.get(0)); } @Test public void testRemove() { ArrayList<Person> list = new ArrayList<Person>(1);//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); list.prepend(p); list.remove(0); assertTrue(list.get(0) != p); } @Test public void testSearch() { ArrayList<Person> list = new ArrayList<Person>(1);//create list of 5 ppl Person p = new Person("Kevin", "Coder", 5.9); if(list.search(p, 0, list.size()-1) != -1) ; } }
1f32652e5ff5ec7cfc54560c22d1bd57052f1695
[ "Java", "Text" ]
6
Text
Scare983/1302SortingTimeTests
1297f3472f660449cf2a5f53e0c8f00605f761c9
09982d9645d96bf32227dbc4eb1c08f1e0c96da9
refs/heads/master
<repo_name>panqc/mp4v2<file_sep>/sps.h #include <stdint.h> #include <stdio.h> #include <assert.h> #include "bs.h" /** Sequence Parameter Set @see 7.3.2.1 Sequence parameter set RBSP syntax @see read_seq_parameter_set_rbsp @see write_seq_parameter_set_rbsp @see debug_sps */ typedef struct { int profile_idc; int constraint_set0_flag; int constraint_set1_flag; int constraint_set2_flag; int constraint_set3_flag; int constraint_set4_flag; int constraint_set5_flag; int reserved_zero_2bits; int level_idc; int seq_parameter_set_id; int chroma_format_idc; int separate_colour_plane_flag; int ChromaArrayType; int bit_depth_luma_minus8; int bit_depth_chroma_minus8; int qpprime_y_zero_transform_bypass_flag; int seq_scaling_matrix_present_flag; int seq_scaling_list_present_flag[8]; int ScalingList4x4[6]; int UseDefaultScalingMatrix4x4Flag[6]; int ScalingList8x8[2]; int UseDefaultScalingMatrix8x8Flag[2]; int log2_max_frame_num_minus4; int pic_order_cnt_type; int log2_max_pic_order_cnt_lsb_minus4; int delta_pic_order_always_zero_flag; int offset_for_non_ref_pic; int offset_for_top_to_bottom_field; int num_ref_frames_in_pic_order_cnt_cycle; int offset_for_ref_frame[256]; int max_num_ref_frames; int gaps_in_frame_num_value_allowed_flag; int pic_width_in_mbs_minus1; int pic_height_in_map_units_minus1; int frame_mbs_only_flag; int mb_adaptive_frame_field_flag; int direct_8x8_inference_flag; int frame_cropping_flag; int frame_crop_left_offset; int frame_crop_right_offset; int frame_crop_top_offset; int frame_crop_bottom_offset; int vui_parameters_present_flag; struct { int aspect_ratio_info_present_flag; int aspect_ratio_idc; int sar_width; int sar_height; int overscan_info_present_flag; int overscan_appropriate_flag; int video_signal_type_present_flag; int video_format; int video_full_range_flag; int colour_description_present_flag; int colour_primaries; int transfer_characteristics; int matrix_coefficients; int chroma_loc_info_present_flag; int chroma_sample_loc_type_top_field; int chroma_sample_loc_type_bottom_field; int timing_info_present_flag; int num_units_in_tick; int time_scale; int fixed_frame_rate_flag; int nal_hrd_parameters_present_flag; int vcl_hrd_parameters_present_flag; int low_delay_hrd_flag; int pic_struct_present_flag; int bitstream_restriction_flag; int motion_vectors_over_pic_boundaries_flag; int max_bytes_per_pic_denom; int max_bits_per_mb_denom; int log2_max_mv_length_horizontal; int log2_max_mv_length_vertical; int num_reorder_frames; int max_dec_frame_buffering; } vui; struct { int cpb_cnt_minus1; int bit_rate_scale; int cpb_size_scale; int bit_rate_value_minus1[32]; // up to cpb_cnt_minus1, which is <= 31 int cpb_size_value_minus1[32]; int cbr_flag[32]; int initial_cpb_removal_delay_length_minus1; int cpb_removal_delay_length_minus1; int dpb_output_delay_length_minus1; int time_offset_length; } hrd; } sps_t; /** Access unit delimiter @see 7.3.1 NAL unit syntax @see read_nal_unit @see write_nal_unit @see debug_nal */ typedef struct { int primary_pic_type; } aud_t; /** Network Abstraction Layer (NAL) unit @see 7.3.1 NAL unit syntax @see read_nal_unit @see write_nal_unit @see debug_nal */ typedef struct { int forbidden_zero_bit; int nal_ref_idc; int nal_unit_type; void* parsed; // FIXME int sizeof_parsed; //uint8_t* rbsp_buf; //int rbsp_size; } nal_t; typedef struct { int clock_timestamp_flag; int ct_type; int nuit_field_based_flag; int counting_type; int full_timestamp_flag; int discontinuity_flag; int cnt_dropped_flag; int n_frames; int seconds_value; int minutes_value; int hours_value; int seconds_flag; int minutes_flag; int hours_flag; int time_offset; } picture_timestamp_t; typedef struct { int _is_initialized; int cpb_removal_delay; int dpb_output_delay; int pic_struct; picture_timestamp_t clock_timestamps[3]; // 3 is the maximum possible value } sei_picture_timing_t; typedef struct { int rbsp_size; uint8_t* rbsp_buf; } slice_data_rbsp_t; typedef struct { int type; // 0:h264 1:h265 int init; int profile_idc; int level_idc; int tier_idc; int width; int height; int crop_left; int crop_right; int crop_top; int crop_bottom; float max_framerate; // ��SPS����õ���֡�ʣ�Ϊ0��ʾSPS��û����Ӧ���ֶμ��� int chroma_format_idc; // YUV��ɫ�ռ� 0: monochrome 1:420 2:422 3:444 int encoding_type; // Ϊ1��ʾCABAC 0��ʾCAVLC int bit_depth_luma; int bit_depth_chroma; } videoinfo_t; int h264_get_width(sps_t *sps); int h264_get_height(sps_t* sps); int nal_to_rbsp(const int nal_header_size, const uint8_t* nal_buf, int* nal_size, uint8_t* rbsp_buf, int* rbsp_size); void read_hrd_parameters(sps_t* sps , bs_t* b); void read_vui_parameters(sps_t* sps, bs_t* b); void read_rbsp_trailing_bits( bs_t* b); void read_scaling_list(bs_t* b, int* scalingList, int sizeOfScalingList, int useDefaultScalingMatrixFlag ); void read_seq_parameter_set_rbsp(bs_t* b, sps_t* sps ); //NAL ref idc codes #define NAL_REF_IDC_PRIORITY_HIGHEST 3 #define NAL_REF_IDC_PRIORITY_HIGH 2 #define NAL_REF_IDC_PRIORITY_LOW 1 #define NAL_REF_IDC_PRIORITY_DISPOSABLE 0 //Table 7-1 NAL unit type codes #define NAL_UNIT_TYPE_UNSPECIFIED 0 // Unspecified #define NAL_UNIT_TYPE_CODED_SLICE_NON_IDR 1 // Coded slice of a non-IDR picture #define NAL_UNIT_TYPE_CODED_SLICE_DATA_PARTITION_A 2 // Coded slice data partition A #define NAL_UNIT_TYPE_CODED_SLICE_DATA_PARTITION_B 3 // Coded slice data partition B #define NAL_UNIT_TYPE_CODED_SLICE_DATA_PARTITION_C 4 // Coded slice data partition C #define NAL_UNIT_TYPE_CODED_SLICE_IDR 5 // Coded slice of an IDR picture #define NAL_UNIT_TYPE_SEI 6 // Supplemental enhancement information (SEI) #define NAL_UNIT_TYPE_SPS 7 // Sequence parameter set #define NAL_UNIT_TYPE_PPS 8 // Picture parameter set #define NAL_UNIT_TYPE_AUD 9 // Access unit delimiter #define NAL_UNIT_TYPE_END_OF_SEQUENCE 10 // End of sequence #define NAL_UNIT_TYPE_END_OF_STREAM 11 // End of stream #define NAL_UNIT_TYPE_FILLER 12 // Filler data #define NAL_UNIT_TYPE_SPS_EXT 13 // Sequence parameter set extension // 14..18 // Reserved #define NAL_UNIT_TYPE_CODED_SLICE_AUX 19 // Coded slice of an auxiliary coded picture without partitioning // 20..23 // Reserved // 24..31 // Unspecified //7.4.3 Table 7-6. Name association to slice_type #define SH_SLICE_TYPE_P 0 // P (P slice) #define SH_SLICE_TYPE_B 1 // B (B slice) #define SH_SLICE_TYPE_I 2 // I (I slice) #define SH_SLICE_TYPE_SP 3 // SP (SP slice) #define SH_SLICE_TYPE_SI 4 // SI (SI slice) //as per footnote to Table 7-6, the *_ONLY slice types indicate that all other slices in that picture are of the same type #define SH_SLICE_TYPE_P_ONLY 5 // P (P slice) #define SH_SLICE_TYPE_B_ONLY 6 // B (B slice) #define SH_SLICE_TYPE_I_ONLY 7 // I (I slice) #define SH_SLICE_TYPE_SP_ONLY 8 // SP (SP slice) #define SH_SLICE_TYPE_SI_ONLY 9 // SI (SI slice) //Appendix E. Table E-1 Meaning of sample aspect ratio indicator #define SAR_Unspecified 0 // Unspecified #define SAR_1_1 1 // 1:1 #define SAR_12_11 2 // 12:11 #define SAR_10_11 3 // 10:11 #define SAR_16_11 4 // 16:11 #define SAR_40_33 5 // 40:33 #define SAR_24_11 6 // 24:11 #define SAR_20_11 7 // 20:11 #define SAR_32_11 8 // 32:11 #define SAR_80_33 9 // 80:33 #define SAR_18_11 10 // 18:11 #define SAR_15_11 11 // 15:11 #define SAR_64_33 12 // 64:33 #define SAR_160_99 13 // 160:99 // 14..254 Reserved #define SAR_Extended 255 // Extended_SAR //7.4.3.1 Table 7-7 modification_of_pic_nums_idc operations for modification of reference picture lists #define RPLR_IDC_ABS_DIFF_ADD 0 #define RPLR_IDC_ABS_DIFF_SUBTRACT 1 #define RPLR_IDC_LONG_TERM 2 #define RPLR_IDC_END 3 //7.4.3.3 Table 7-9 Memory management control operation (memory_management_control_operation) values #define MMCO_END 0 #define MMCO_SHORT_TERM_UNUSED 1 #define MMCO_LONG_TERM_UNUSED 2 #define MMCO_SHORT_TERM_TO_LONG_TERM 3 #define MMCO_LONG_TERM_MAX_INDEX 4 #define MMCO_ALL_UNUSED 5 #define MMCO_CURRENT_TO_LONG_TERM 6 //7.4.2.4 Table 7-5 Meaning of primary_pic_type #define AUD_PRIMARY_PIC_TYPE_I 0 // I #define AUD_PRIMARY_PIC_TYPE_IP 1 // I, P #define AUD_PRIMARY_PIC_TYPE_IPB 2 // I, P, B #define AUD_PRIMARY_PIC_TYPE_SI 3 // SI #define AUD_PRIMARY_PIC_TYPE_SISP 4 // SI, SP #define AUD_PRIMARY_PIC_TYPE_ISI 5 // I, SI #define AUD_PRIMARY_PIC_TYPE_ISIPSP 6 // I, SI, P, SP #define AUD_PRIMARY_PIC_TYPE_ISIPSPB 7 // I, SI, P, SP, B #define H264_PROFILE_BASELINE 66 #define H264_PROFILE_MAIN 77 #define H264_PROFILE_EXTENDED 88 #define H264_PROFILE_HIGH 100 // file handle for debug output extern FILE* h264_dbgfile; <file_sep>/h264_aac_2_mp4.c #include <stdio.h> #include <string.h> #include <strings.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> #include <sys/time.h> #include <mp4v2/mp4v2.h> #if 0 #include "sps_pps_parser.h" #else #include "sps.h" #endif #define MAX_FRMAES 1024 *256 #define PER_RD_SZ 1024*1024 #define uint16_t unsigned short #define uint8_t unsigned char #define uint32_t unsigned int enum { PK_BY_FILE = 0, PK_BY_REAL_STREAM }PK_type_t; enum { SPS_FRAME, PPS_FRAME, I_FRAME, P_FRAME, B_FRAME, }; typedef struct { FILE * v_fd; FILE * a_fd; MP4FileHandle mp4_hd; }File_handle_t; typedef struct { const uint8_t* pSequence; uint16_t sequenceLen; }SPS_cfg_t; typedef struct { const uint8_t* pPict; uint16_t pictLen; }PPS_cfg_t; typedef struct { MP4TrackId trackId; int32_t frameRate; //为了方便动态修改,而不只是从nalu中获取. uint32_t timeScale; MP4Duration sampleDuration; uint16_t width; uint16_t height; uint8_t AVCProfileIndication; uint8_t profile_compat; uint8_t AVCLevelIndication; uint8_t sampleLenFieldSizeMinusOne; int32_t fsz; //PK_BY_FILE模式下为vidoe文件的大小,PK_BY_FILE模式则为-1. SPS_cfg_t *sps; PPS_cfg_t *pps; }Video_tk_cfg_t; typedef struct { uint32_t timeScale; MP4Duration sampleDuration; uint8_t audioType; MP4TrackId trackId; const uint8_t* pConfig; uint32_t configSize; }Audio_tk_cfg_t; typedef struct { File_handle_t hd; Video_tk_cfg_t *v; Audio_tk_cfg_t *a; }tk_para_cfg_t; tk_para_cfg_t *tk_m = NULL; typedef struct { int frame_pos; //能够记录1024 *256帧的位置. int frame_sz; //记录帧的大小. int frame_type; }frame_inf_t; enum { MV_MPEG_4, MV_MPEG_2, }Mpeg_version; enum { AP_AAC_MAIN = 0, AP_AAC_LC, AP_AAC_SSR }Aac_profile; enum { SP_96000 = 0, SP_88200, SP_64000, SP_48000, SP_44100, SP_32000, SP_24000, SP_22050, SP_16000, SP_12000, SP_11025, SP_8000, SP_7350, //12: SP_MAX, }Aac_sampling; enum { CH_AOT_0 = 0, //Defined in AOT Specifc Config CH_FC_1, //1 channel: front-center CH_FLR_2, //2 channels: front-left, front-right CH_FCLR_3, //3 channels: front-center, front-left, front-right CH_FCLR_BC_4, //4 channels: front-center, front-left, front-right, back-center CH_FCLR_BLR_5, //5 channels: front-center, front-left, front-right, back-left, back-right CH_FCLR_BLR_LFE_6, //6 channels: front-center, front-left, front-right, back-left, back-right, LFE-channel CH_FCLR_SLR_BLR_LFE_7, //8 channels: front-center, front-left, front-right, side-left, side-right, back-left, back-right, LFE-channel CH_MAX, }Aac_chn; typedef struct { char mpeg_ver; char profile; char sampling; char chns; }Aac_t; void print_tnt(char *buf, int len, const char *comment) { int i = 0; printf("\r\n%s start buf:%p len:%d \r\n", comment, buf, len); for(i = 0; i < len; i++) { printf("%02x ", buf[i] & 0xff); //&0xff 是为了防止64位平台中打印0xffffffa0 这样的,实际打印0xa0即可 } printf("\r\n"); } int print_frmae_info(frame_inf_t * inf, int nums) { int i = 0; while( i < nums) { printf("seq:[%d], fm_sz:[%d], fm_pos:[%d], fm_type:[%d]\n", i+1, inf[i].frame_sz, inf[i].frame_pos, inf[i].frame_type ); i++; } printf("all frame : [%d]\n", nums); } int add_video_tk(MP4FileHandle hdl, Video_tk_cfg_t *v) { printf("[%d %d %d]:[%d:%ld]\n", v->frameRate, v->width, v->height, v->timeScale, v->sampleDuration ); MP4TrackId video_tk = 0; video_tk = MP4AddH264VideoTrack( hdl, v->timeScale, v->timeScale / v->frameRate,//每一帧的字节数,[TWT]:出现这里算错,导致无法解码. v->width, v->height, v->AVCProfileIndication, v->profile_compat, v->AVCLevelIndication, 3); MP4SetVideoProfileLevel(hdl, 0x7f); // Simple Profile @ Level 3 v->trackId = video_tk; return 0; } int add_audio_tk(MP4FileHandle hdl, Audio_tk_cfg_t *a) { MP4TrackId audio_tk = 0; audio_tk = MP4AddAudioTrack(hdl, a->timeScale, a->sampleDuration, a->audioType); MP4SetAudioProfileLevel(hdl, 0x2); a->trackId = audio_tk; //[TVT]:pConfig 要么设定死,要么解析aac数据. uint8_t buf3[2] = { 0x11, 0x88 }; MP4SetTrackESConfiguration(hdl, a->trackId, buf3, 2); return 0; } int spare_sps(char *date, int sz, Video_tk_cfg_t *v) { #if 0 SPS _sps; float fps = 0.0; get_bit_context buffer; memset(&buffer, 0, sizeof(get_bit_context)); buffer.buf = date; buffer.buf_size = sz - 1; //从sps pps中获取信息 h264dec_seq_parameter_set(&buffer, &_sps); v->width = h264_get_width(&_sps); v->height = h264_get_height(&_sps); int ret = h264_get_framerate(&fps, &_sps); if (ret == 0) v->frameRate = (double)fps; #else sps_t _sps; char tmpbuf[40] ={'\0'}; int len = sz; int rc = nal_to_rbsp(0, date, &sz, tmpbuf, &len ); bs_t* b = bs_new(tmpbuf, len); //从sps pps中获取信息 read_seq_parameter_set_rbsp(b, &_sps); v->width = h264_get_width(&_sps); v->height = h264_get_height(&_sps); bs_free(b); #endif v->AVCProfileIndication = date[1]; v->profile_compat = date[2]; v->AVCLevelIndication = date[3]; return 0; } int spare_aac(FILE *fd, Aac_t * aac) { if(!aac) { printf("Input aac point is NULL, exit\n"); return -1; } if(fd <= 0) { perror("Open file failed :"); return -1; } char head[9] = {'\0'}; int sz = fread(head, sizeof(head), 1, fd); if(sz > 0) { if((head[0]&0xff == 0xff) && (head[1]&0xf0 == 0xf0)) { aac->mpeg_ver = (head[1] & 0x08) >> 3; aac->profile = (head[2] & 0xc0) >> 6; aac->sampling = (head[2] & 0x3c) >> 2; aac->chns = (head[2] & 0x01) << 2 | ((head[3] & 0xc0) >> 6); } } fseek(fd, 0L, SEEK_SET); } int get_sampling(char samp_seq) { int samp[] = {96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000}; if( (samp_seq > sizeof(samp)) || (samp_seq < 0)) { printf("Input sampling que is error, do not rang.\n"); return -1; } return samp[samp_seq]; } int pri_aac_inf(Aac_t *aac) { if(!aac) return -1; switch(aac->mpeg_ver) { case 0: printf("mpeg version :""MPEG_4\n");break; case 1: printf("mpeg version :""MPEG_2\n");break; default:printf("mpeg version :""unknown\n");break; } switch(aac->profile) { case 0: printf("profile :""Main\n");break; case 1: printf("profile :""LC\n");break; case 2: printf("profile :""SSR\n");break; default:printf("profile :""unknown\n");break; } int samp = 0; switch(aac->sampling) { case 0: samp = 96000;break; case 1: samp = 88200;break; case 2: samp = 64000;break; case 3: samp = 48000;break; case 4: samp = 44100;break; case 5: samp = 32000;break; case 6: samp = 24000;break; case 7: samp = 22050;break; case 8: samp = 16000;break; case 9: samp = 12000;break; case 10: samp = 11025;break; case 11: samp = 8000; break; default:printf("sampling :""unknown\n");break; } printf("sampling :""%dHz\n", samp); switch(aac->chns) { case 0: printf("chns :""0\n");break; case 1: printf("chns :""1\n");break; case 2: printf("chns :""2\n");break; default:printf("chns :""unknown\n");break; } return 0; } int write_video_2_mp4(char *wbuf, int len, tk_para_cfg_t *tk, int *type) { unsigned char naluType; MP4FileHandle pHandle = tk->hd.mp4_hd; Video_tk_cfg_t *v_m = tk->v; int addStream = 1; char *pNalu = NULL; if (wbuf[0] != 0 || wbuf[1] != 0 || wbuf[2] != 0 || wbuf[3] != 1) return -1; len -= 4; pNalu = wbuf+4; naluType = pNalu[0]&0x1F; switch (naluType) { case 0x07: case 0x08: if(naluType == 0x07) {// SPS *type = SPS_FRAME; spare_sps(pNalu +1, len -1, v_m); add_video_tk(pHandle, v_m); MP4AddH264SequenceParameterSet(pHandle, v_m->trackId, pNalu, len); } else { //PPS *type = PPS_FRAME; MP4AddH264PictureParameterSet(pHandle, v_m->trackId, pNalu, len); } break; default: wbuf[0] = (len>>24)&0xFF; wbuf[1] = (len>>16)&0xFF; wbuf[2] = (len>>8)&0xFF; wbuf[3] = (len>>0)&0xFF; *type = I_FRAME; MP4WriteSample(pHandle, v_m->trackId, wbuf, len+4, MP4_INVALID_DURATION, 0, 1); break; } return 0; } int read_aac_frame(char *rbuf, int len, FILE * a_fd) { char aac_head[7] = {0}; int ret = fread(aac_head, 1, sizeof(aac_head), a_fd); if(ret <= 0 ) { printf("read aac head failed, exit !\n"); return -1; } //printf("[%02x %02x %02x]\n", aac_head[0]&0xff, aac_head[1]&0xff, aac_head[2]&0xff); int body_size = (aac_head[3] & 0x03) << 11; body_size += aac_head[4] << 3; body_size += (aac_head[5] & 0xe0) >> 5; ret = fread(rbuf, 1, body_size - 7, a_fd); if(ret <= 0 ) { printf("read aac frame body failed, exit !\n"); return -1; } return ret; } int write_audio_2Mp4(char *wbuf, int len, tk_para_cfg_t *tk) { //print_tnt(wbuf, 12, "audio"); if(MP4WriteSample(tk->hd.mp4_hd, tk->a->trackId, wbuf, len, MP4_INVALID_DURATION, 0, 1) == false) { } return 0; } int parse_pps_sps(Video_tk_cfg_t *v ) { if(!v) return -1; SPS_cfg_t *sps; PPS_cfg_t *pps; return 0; } uint32_t get_time_ms() { struct timeval _stime; gettimeofday(&_stime, NULL); return (_stime.tv_sec * 1000 + _stime.tv_usec / 1000); } int write_h264_aac(tk_para_cfg_t *tk) { //video --- int sqe = 0; int sz = 0; int pos = 0; int len = 0; int frames = 0; int remain = 0; int file_sz = 0; char end_flag = 1; char *start = NULL; char wbuf[1024 * 720] = {0}; char *v_buffer = malloc(PER_RD_SZ); frame_inf_t v_frame[MAX_FRMAES]; memset(&v_frame, 0, sizeof(v_frame)); memset(wbuf, 0, sizeof(wbuf)); //audio --- int i = 0; int re_sz = 0; int offse = 0; int a_remain = 0; int frame_len = 0; int last_frame_len = 0; int FM_SE = 1024*16; int RD_SE = 1024*1024; char aacframe[1024 * 16] = {'\0'}; char *a_buffer=( char *)malloc(RD_SE); //-------------------------------------- uint32_t tick_exp_tmp = 0; uint32_t tick_exp = 0; static int szs = 0; char audio_end = 0; char video_end = 0; //计算音频 和 视频 每帧的时间. uint32_t audio_tick_gap = tk->a->sampleDuration * 1000 / tk->a->timeScale; uint32_t video_tick_gap = (1000.0 + 1.0) / tk->v->frameRate ; printf("[%ld]:[%d]\n", tk->a->sampleDuration, tk->a->timeScale); printf("++++[%d]:[%d]++++\n", audio_tick_gap, video_tick_gap); uint32_t audio_tick_now, video_tick_now, last_update; //add trick if have. //if(tk->a->pConfig) { //parse ... add_audio_tk(tk->hd.mp4_hd, tk->a); } if(tk->v->sps && tk->v->pps) { parse_pps_sps(tk->v); Video_tk_cfg_t *v = tk->v; add_video_tk(tk->hd.mp4_hd, tk->v); MP4AddH264SequenceParameterSet(tk->hd.mp4_hd, v->trackId, v->sps->pSequence, v->sps->sequenceLen); MP4AddH264PictureParameterSet(tk->hd.mp4_hd, v->trackId, v->pps->pPict, v->pps->pictLen); } video_tick_now = audio_tick_now = get_time_ms(); while(1) { last_update = get_time_ms(); //write video if( (tk->hd.v_fd > 0) && (!video_end)) { if(last_update - video_tick_now > video_tick_gap - tick_exp) { if(end_flag) { pos = 0; if((len = fread(v_buffer, 1, PER_RD_SZ, tk->hd.v_fd)) <= 0) { video_end = 1; continue; } } while(1) { if((v_buffer[pos+0] == 0 && v_buffer[pos+1] == 0 && v_buffer[pos+2] == 0 && v_buffer[pos+3] == 1) || (v_buffer[pos+0] == 0 && v_buffer[pos+1] == 0 && v_buffer[pos+2] == 1)) { (v_buffer[pos+2] == 1)?(sqe = 3):(sqe = 4); if(!start) { //首次检测到帧. int pos1 = file_sz + pos; v_frame[frames].frame_pos = pos1; //记录帧的在文件的位置, 便于以后查找. start = &v_buffer[pos]; pos += sqe; frames++; end_flag = 0; continue; } else { int type = 0; int pos2 = file_sz + pos; //加上上次read的长度,得到当前在文件中的位置. if(remain > 0) { memcpy(wbuf + remain, &v_buffer[0], pos); //加上 上次不完整部分数据. sz = pos + remain; remain = 0; //上次read 剩下的不完整帧. } else { sz = pos2 - v_frame[frames - 1].frame_pos; memcpy(wbuf, start, sz); } write_video_2_mp4(wbuf, sz, tk, &type); v_frame[frames].frame_pos = pos2; v_frame[frames-1].frame_type = type; v_frame[frames-1].frame_sz = sz; memset(wbuf, 0, sizeof(sz)); start = &v_buffer[pos]; frames++; pos += sqe; end_flag = 0; continue; } } else if( len == pos) {//存下这次read帧中, 剩下的不完整帧数据. remain = file_sz + pos - v_frame[frames-1].frame_pos; if(remain > 0) { int add = v_frame[frames-1].frame_pos - file_sz; memset(wbuf, 0, sizeof(sz)); memcpy(wbuf, &v_buffer[add] ,remain); if(file_sz + pos == tk->v->fsz) { //写最后一帧数据. int type = 0; write_video_2_mp4(wbuf, remain, tk, &type); v_frame[frames-1].frame_type = type; v_frame[frames-1].frame_sz = remain; } } end_flag = 1; file_sz += len; break; } pos++; } video_tick_now = get_time_ms(); } } //write audio. if((tk->hd.a_fd > 0) && (!audio_end)) { if(last_update - audio_tick_now > audio_tick_gap - tick_exp) { #if 0 int lenth = read_aac_frame(audio_buff, aac_sz, tk->hd.a_fd); if(lenth <= 0) { audio_end = 1; continue; } szs += lenth; write_audio_2Mp4(audio_buff, lenth, tk); memset(audio_buff, 0, aac_sz); audio_tick_now = get_time_ms(); #else memset(a_buffer, '\0', RD_SE); re_sz = fread(a_buffer, 1, RD_SE, tk->hd.a_fd); if( re_sz<= 0) { printf("read over !\n"); audio_end = 1; continue; } while(1) { //Sync words: 0xfff; if((a_buffer[i]&0xff == 0xff) && (a_buffer[i+1]&0xf0 == 0xf0) ) { //frame_length: 13 bit frame_len = 0; frame_len |= (a_buffer[i+3] & 0x03) <<11; //low 2 bit frame_len |= (a_buffer[i+4] & 0xff) <<3; //middle 8 bit frame_len |= (a_buffer[i+5] & 0xe0) >>5; //hight 3bit memset(aacframe, '\0', FM_SE); if(re_sz >= frame_len) { memcpy(aacframe, &a_buffer[i],frame_len); write_audio_2Mp4(&aacframe[7], frame_len -1, tk); i += frame_len; //加一帧的长度. re_sz -= frame_len;//剩下的帧数据... frame_len = 0; if(re_sz == 0) break; } else { a_remain = frame_len - re_sz; memcpy(aacframe, &a_buffer[i], re_sz); //保存剩下的帧数. last_frame_len = frame_len; offse = re_sz; re_sz = 0; frame_len = 0; i = 0; break; } continue; } else { if(a_remain > 0) { memcpy(aacframe + offse, &a_buffer[i], a_remain); //保存剩下的帧数. write_audio_2Mp4(&aacframe[7], last_frame_len -1, tk); i += a_remain; //加上次剩下的帧数据的长度. re_sz -= a_remain;//接着上次剩下的帧数据... a_remain = 0; continue; } } i++; } audio_tick_now = get_time_ms(); #endif } } tick_exp_tmp = get_time_ms(); tick_exp = tick_exp_tmp - last_update;//计算循环一次的时间间隔. if(audio_end && video_end) break; usleep(800); } printf("pack end-\n"); //print_frmae_info(frame, frames); free(v_buffer); free(a_buffer); return 0; } int set_tk_para(tk_para_cfg_t *tk) { if(!tk) { printf("Input tk_para_cfg_t obj is null, exit\n"); exit(-1); } tk_m = tk; return 0; } int file_init(const char (*files)[36], tk_para_cfg_t *tk) { const char *video_file = files[0]; const char *audio_file = files[1]; const char *mp4_file = files[2]; Aac_t aac; memset(&aac, 0, sizeof(Aac_t)); printf("****[%s]:[%s]:[%s]\n", files[0], files[1], files[2]); //video file if(!(tk->hd.v_fd = fopen(video_file, "rb")) ) { perror("Open vidoe file faile:"); return -1; } struct stat st; lstat(video_file, &st); tk->v->fsz = st.st_size; tk->v->frameRate = 21; tk->v->timeScale = 100000;//????? tk->v->sps = NULL; tk->v->pps = NULL; //audio file if(!(tk->hd.a_fd = fopen(audio_file, "rb")) ) { perror("Open audio file faile:"); return -1; } spare_aac(tk->hd.a_fd, &aac); tk->a->sampleDuration = 1024; //(aac.chns==2) ? (1024*2) : (1024); //AAC的一帧是 1024个采样点数 tk->a->timeScale = get_sampling(aac.sampling); //采样率, eg:48000; tk->a->audioType = MP4_MPEG4_AUDIO_TYPE; //在采样率为44100Hz时(即每秒44100个sample), //当前AAC一帧的播放时间[frame_duration]是 = 1024* (1000000/44100) = 22.32ms (单位为ms) //mp4 file tk->hd.mp4_hd = MP4Create(mp4_file, 0); if(tk->hd.mp4_hd == MP4_INVALID_FILE_HANDLE) { printf("Create mp4 handle fialed."); return -1; } MP4SetTimeScale(tk->hd.mp4_hd, tk->v->timeScale); pri_aac_inf(&aac); return 0; } int file_destroy(File_handle_t *hand) { fclose(hand->v_fd); fclose(hand->a_fd); MP4Close(hand->mp4_hd, 0); return 0; } int write_av_date(tk_para_cfg_t *tk) { write_h264_aac(tk); return 0; } int pack_av_by_file_stream(const char (*file)[36], tk_para_cfg_t *tk) { file_init(file, tk); write_av_date(tk); file_destroy(&tk->hd); return 0; } int pack_av_by_real_stream(const char (*file)[36]) { return 0; } int pack_av(const char (*file)[36], int type) { if(type == PK_BY_FILE) { tk_para_cfg_t tk; memset(&tk, 0, sizeof(tk)); //video tk.v = (Video_tk_cfg_t *)malloc(sizeof(Video_tk_cfg_t)); memset(tk.v, 0, sizeof(Video_tk_cfg_t)); //audio tk.a = (Audio_tk_cfg_t *)malloc(sizeof(Audio_tk_cfg_t)); memset(tk.a, 0, sizeof(Audio_tk_cfg_t)); pack_av_by_file_stream(file, &tk); free(tk.v); free(tk.a); } else { pack_av_by_real_stream(file); } return 0; } int parse_argv(int argc, void *argv[], char ( *out_files)[36]) { if((argv[1] == NULL) || (argv[2] == NULL) ) { printf("Input file is NULL, exit\n"); return -1; } int i = 1; char *tmp = NULL; while(i < argc) { if((tmp = strrchr(argv[i], '.'))) { tmp++; if( !strcasecmp(tmp, "h264") || !strcasecmp(tmp, "h265")) memcpy(out_files[0], (char *)argv[i], strlen(argv[i])); else if( !strcasecmp(tmp, "aac") ) memcpy(out_files[1], argv[i], strlen(argv[i])); } i++; } char *outf = argv[3] ? argv[3] : "test.mp4"; memcpy(out_files[2], outf, strlen(outf)); return 0; } int main(int argc, void *argv[]) { char files[3][36] = {'\0'}; parse_argv(argc, argv, files); pack_av(files, PK_BY_FILE); return 0; } <file_sep>/readme.txt 利用mp4v2库进行aac + h264 视频封装成MP4格式. ##gcc h264_aac_2_mp4.c -L./lib -lmp4v2 -I./include -o m ####gcc h264_aac_2_mp4.c sps_pps_parser.c -L./lib -lmp4v2 -I./include -o m gcc h264_aac_2_mp4.c sps.c -L./lib -lmp4v2 -I./include -o m<file_sep>/mp4v2_h264.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <mp4v2/mp4v2.h> #define MAX_FRMAES 1024 *256 #define PER_RD_SZ 1024*1024 enum{ SPS_FRAME, PPS_FRAME, I_FRAME, P_FRAME, B_FRAME, }; typedef struct { int frame_pos; //能够记录1024 *256帧的位置. int frame_sz; //记录帧的大小. int frame_type; }frame_inf_t; void print_tnt(char *buf, int len, const char *comment) { int i = 0; printf("\r\n%s start buf:%p len:%d \r\n", comment, buf, len); for(i = 0; i < len; i++) { printf("%02x ", buf[i] & 0xff); //&0xff 是为了防止64位平台中打印0xffffffa0 这样的,实际打印0xa0即可 } printf("\r\n"); } int print_frmae_info(frame_inf_t * inf, int nums) { int i = 0; while( i < nums) { printf("fm_sz:[%d], fm_pos:[%d], fm_type:[%d]\n", inf[i].frame_sz, inf[i].frame_pos, inf[i].frame_type ); i++; } printf("all frame : [%d]\n", nums); } int write2Mp4(char *wbuf, int len, MP4FileHandle pHandle, int *type) { MP4TrackId videoId; unsigned char naluType; int width = 640; int height = 480; int frameRate = 15; int timeScale = 90000; int addStream = 1; char *pNalu = NULL; if (wbuf[0] != 0 || wbuf[1] != 0 || wbuf[2] != 0 || wbuf[3] != 1) return -1; len -= 4; pNalu = wbuf+4; naluType = pNalu[0]&0x1F; switch (naluType) { case 0x07: // SPS *type = SPS_FRAME; if (addStream) { videoId = MP4AddH264VideoTrack (pHandle, timeScale, // 一秒钟多少timescale timeScale/frameRate, // 每个帧有多少个timescale width, // width height, // height pNalu[1], // sps[1] AVCProfileIndication pNalu[2], // sps[2] profile_compat pNalu[3], // sps[3] AVCLevelIndication 3); // 4 bytes length before each NAL unit if (videoId == MP4_INVALID_TRACK_ID) { printf("Error:Can't add track.\n"); return -1; } MP4SetVideoProfileLevel(pHandle, 0x7F); addStream = 0; } MP4AddH264SequenceParameterSet(pHandle, videoId, pNalu, len); break; case 0x08: // PPS *type = PPS_FRAME; MP4AddH264PictureParameterSet(pHandle, videoId, pNalu, len); break; default: wbuf[0] = (len>>24)&0xFF; wbuf[1] = (len>>16)&0xFF; wbuf[2] = (len>>8)&0xFF; wbuf[3] = (len>>0)&0xFF; MP4WriteSample(pHandle, videoId, wbuf, len+4, MP4_INVALID_DURATION, 0, 1); break; } return 0; } int write_h264_nalu(const char *srcFile, const char *dstFile) { int sqe = 0; int sz = 0; int pos = 0; int len = 0; int in_fz = 0; int frames = 0; int remain = 0; int file_sz = 0; char end_flag = 1; char *start = NULL; char wbuf[1024 * 720] = {0}; char *rbuf = malloc(PER_RD_SZ); frame_inf_t frame[MAX_FRMAES]; memset(&frame, 0, sizeof(frame)); struct stat st; lstat(srcFile, &st); in_fz = st.st_size; FILE *infd = fopen(srcFile, "rb"); if(!infd) return -1; //1、create mp4. MP4FileHandle outHandle = MP4Create(dstFile, 0); if(outHandle == MP4_INVALID_FILE_HANDLE) { printf("ERROR:Create mp4 handle fialed.\n"); return -1; } int timeScale = 90000; MP4SetTimeScale(outHandle, timeScale); //2、write h264 frames memset(wbuf, 0, sizeof(wbuf)); while(1) { if(end_flag) { pos = 0; if((len = fread(rbuf, 1, PER_RD_SZ, infd)) <= 0) { perror("ERROR:"); break; } } while(1) { if((rbuf[pos+0] == 0 && rbuf[pos+1] == 0 && rbuf[pos+2] == 0 && rbuf[pos+3] == 1) || (rbuf[pos+0] == 0 && rbuf[pos+1] == 0 && rbuf[pos+2] == 1)) { (rbuf[pos+2] == 1)?(sqe = 3):(sqe = 4); if(!start) { //首次检测到帧. int pos1 = file_sz + pos; frame[frames].frame_pos = pos1; //记录帧的在文件的位置, 便于以后查找. start = &rbuf[pos]; pos += sqe; frames++; end_flag = 0; continue; } else { int type = 0; int pos2 = file_sz + pos; //加上上次read的长度,得到当前在文件中的位置. if(remain > 0) { memcpy(wbuf + remain, &rbuf[0], pos); //加上 上次不完整部分数据. sz = pos + remain; remain = 0; //上次read 剩下的不完整帧. } else { sz = pos2 - frame[frames - 1].frame_pos; memcpy(wbuf, start, sz); } #if 0 if((rbuf[pos+4] == 0x25) || (rbuf[pos+3] == 0x25)) { print_tnt(wbuf, 6, "end:"); printf("--[%d]:[%d]:[%d]==[%d]:[%d]->\n", frames+1, sz, remain, pos2, frame[frames - 1].frame_pos); } #endif write2Mp4(wbuf, sz, outHandle, &type); frame[frames].frame_pos = pos2; frame[frames-1].frame_type = type; frame[frames-1].frame_sz = sz; memset(wbuf, 0, sizeof(sz)); start = &rbuf[pos]; frames++; pos += sqe; end_flag = 0; continue; } } else if( len == pos) {//存下这次read帧中, 剩下的不完整帧数据. remain = file_sz + pos - frame[frames-1].frame_pos; if(remain > 0) { int add = frame[frames-1].frame_pos - file_sz; memset(wbuf, 0, sizeof(sz)); memcpy(wbuf, &rbuf[add] ,remain); if(file_sz + pos == in_fz) { //写最后一帧数据. int type = 0; write2Mp4(wbuf, remain, outHandle, &type); frame[frames-1].frame_type = type; frame[frames-1].frame_sz = remain; } } end_flag = 1; file_sz += len; break; } pos++; } } print_frmae_info(frame, frames); free(rbuf); MP4Close(outHandle, 0); fclose(infd); return 0; } int write_h264(const char *inFile, const char *outFile) { if(inFile == NULL) printf("INput file is NULL, exit\n"); const char *outf = outFile ? outFile : "test.mp4"; write_h264_nalu(inFile, outf); return 0; } int main(int argc, char *argv[]) { if (write_h264(argv[1], argv[2]) ) { printf("Error:Packet to Mp4 fail.\n"); return -1; } return 0; }
f68b0fdce5a6c1f654633840e504b1e55b554c01
[ "C", "Text" ]
4
C
panqc/mp4v2
1d9777fb327698e2460d284903c1b96f02a73607
3d822840b49f4634b3d8d003807f6c8af66d5e00
refs/heads/main
<file_sep>let etapas = [ { titulo: 'VEREADOR', numeros: 5, candidatos: [ { numero: '38111', nome: '<NAME>', partido: 'ABC', fotos: [ {url:'./img/v1.jpg', legenda:'Vereador'} ] }, { numero: '77222', nome: '<NAME>', partido: 'DEFG', fotos: [ {url:'./img/v2.jpg', legenda:'Vereador'} ] }, ] }, { titulo: 'PREFEITO', numeros: 2, candidatos: [ { numero: '17', nome: 'Beltrano', partido: 'PP', fotos: [ {url:'./img/cp1.jpg', legenda:'Prefeito'}, {url:'./img/cp2.jpg', legenda:'Vice-Prefeito', small:true} ] }, { numero: '13', nome: 'PC', partido: 'Metalurgico', fotos: [ {url:'./img/cp3.jpg', legenda:'Prefeito'}, {url:'./img/cp4.jpg', legenda:'Vice-Prefeito', small: true} ] }, ] }, ]
f5ea85fb11415d70214d0741527acce2f01c6785
[ "JavaScript" ]
1
JavaScript
Nery93/urna-eletronica
4dceb1c288d7233732bde9720a5be960db9c360e
70a1c8edd0609c4a6ac4bf85bc06499452b37899
refs/heads/master
<file_sep><Query Kind="Statements"> <Connection> <ID>757a973e-cf10-4c95-a6bd-b82677815f30</ID> <Persist>true</Persist> <Server>.</Server> <Database>eRestaurant</Database> </Connection> </Query> /* These statements are to build a report of income and # customers per day * in a given month/year */ //Get the following from the Bills table for a given month/year: // BillDate, ID, # people served, total amount billed // 0) Set-up info that would be passed in to my BLL var month = DateTime.Today.Month - 1; var year = DateTime.Today.Year; // 1) Get the Bll data for the month/year with a sum of each bill's items var billsInMonth = from info in Bills where info.BillDate.Month == month && info.BillDate.Year == year select new { BillDate = info.BillDate, BillId = info.BillID, NumberOfCustomers = info.NumberInParty, TotalAmount = info.BillItems.Sum(bi => bi.Quantity * bi.SalePrice) }; // TEMP: for exploring" the results billsInMonth.Dump("Raw Bill date for month/year"); billsInMonth.Sum(tb => tb.TotalAmount).Dump("Total Income for month"); billsInMonth.Sum(tb => tb.NumberOfCustomers).Dump("Customers for month"); billsInMonth.Count().Dump("# of bills for month"); var total = billsInMonth.Sum (tb => tb.TotalAmount); var avg = total /billsInMonth.Count(); avg.Dump("Average ammount per bill"); // 2) Build a report form the billsInMonth data var report = from item in billsInMonth group item by item.BillDate.Day into dailySummary //new var created on the fly. select new { Day = dailySummary.Key, DailyCustomers = dailySummary.Sum(grp => grp.NumberOfCustomers), Income = dailySummary.Sum(grp => grp.TotalAmount), BillCount = dailySummary.Count(), AveragePerBill = dailySummary.Sum(grp => grp.TotalAmount) / dailySummary.Count() }; report.OrderBy(r => r.Day).Dump("Daily Income Report") <file_sep><Query Kind="Program"> <Connection> <ID>757a973e-cf10-4c95-a6bd-b82677815f30</ID> <Persist>true</Persist> <Server>.</Server> <Database>eRestaurant</Database> </Connection> </Query> void Main() { var result = from data in Tables select new Stuff() { Table = "Table" + data.TableNumber.ToString(), NotPaid = data.Bills.Any(x=>x.PaidStatus == false), Bill = data.Bills.FirstOrDefault(x=>x.PaidStatus == false), BillID = data.Bills.Any(x=>x.PaidStatus==false) ? data.Bills.SingleOrDefault(x=>x.PaidStatus==false).BillID : 0 }; result.Dump(); } // Define other methods and classes here public class Stuff { public string Table{get;set;} public bool NotPaid {get; set;} public Bills Bill {get; set;} public int BillID {get; set;} public string Name { get { if(BillID == 0) return "nada"; else return Table + "(" + BillID + ")"; } } }<file_sep><Query Kind="Program"> <Connection> <ID>0a036852-c337-4a18-bff2-f4e2ea94a324</ID> <Persist>true</Persist> <Server>.</Server> <Database>eTools</Database> </Connection> </Query> void Main() { var result = from data in Vendors select new Stuff() { Vendor = data.VendorName, OpenOrder = data.PurchaseOrders.Any(x=>x.OrderDate == null), PurchaseOrder = data.PurchaseOrders.FirstOrDefault(x=>x.OrderDate == null), PurchaseOrderID = data.PurchaseOrders.Any(x=>x.OrderDate == null) ? data.PurchaseOrders.SingleOrDefault(x=>x.OrderDate == null).PurchaseOrderID : 0 }; result.Dump(); } public class Stuff { public string Vendor {get; set;} public bool OpenOrder {get; set;} public PurchaseOrders PurchaseOrder {get; set;} public int PurchaseOrderID {get; set;} } // Define other methods and classes here <file_sep><Query Kind="Statements"> <Connection> <ID>757a973e-cf10-4c95-a6bd-b82677815f30</ID> <Persist>true</Persist> <Server>.</Server> <Database>eRestaurant</Database> </Connection> </Query> var month = DateTime.Today.Month - 1; var year = DateTime.Today.Year; var billsInMonth = from info in Bills where info.BillDate.Month == month && info.BillDate.Year == year select new { BillDate = info.BillDate, BillId = info.BillID, TotalAmount = info.BillItems.Sum(bi => bi.Quantity * bi.SalePrice), Waiter = info.WaiterID }; billsInMonth.Dump("Raw Bill date for month/year"); var report = from item in Bills group item by item.Waiter into Waiters //new var created on the fly. select new { Waiter = Waiters.Key, Income = Waiters.Sum(grp => grp.TotalAmount) }; report.Dump("Daily Income Report by Waiter ");
87e5351fac7bf7230b31b69a0fa0075c01dd07ef
[ "C#" ]
4
C#
Shaun83/InClass
1e8aac66a5936d425216a70f8f6ee9a6d7724ba0
68b7ca0f8fc65442b883f75f4f4dc4bb57b6af7d
refs/heads/main
<repo_name>itamar-j-allali/txbit<file_sep>/txbit/tests/test.py from txbit import Txbit, TxbitResponse import unittest class TestTxbit(unittest.TestCase): # def test_error(self): # with self.assertRaises(TypeError): # call_error_function() endpoint = 'https://api.txbit.io/api/' def test_endpoint(self): self.assertEqual(self.endpoint, Txbit.endpoint) def test_expandPathToUrl(self): path = 'test/case' url = Txbit.expandPathToUrl(path) self.assertEqual(url, self.endpoint + path) def test_expandPathToUrl_params(self): path = 'test/case' params = { 'param1': 'test1',\ 'param2': 'test2'\ } url = Txbit.expandPathToUrl(path, params) expected_url = self.endpoint + path + '?' for key in params: expected_url += key + "=" + params[key] + "&" self.assertEqual(url, expected_url) def test_request_bad(self): path = 'test/case' res = Txbit.request(path) self.assertFalse(res.ok) self.assertEqual(404, res.status_code) def test_getMarkets(self): res = Txbit.getMarkets() self.assertTrue(res.success) def test_getCurrencies(self): res = Txbit.getCurrencies() self.assertTrue(res.success) def test_getMarketSummaries(self): res = Txbit.getMarketSummaries() self.assertTrue(res.success) def test_getExchangePairs(self): res = Txbit.getExchangePairs() self.assertTrue(res.success) def test_getOrderBook(self): res = Txbit.getOrderBook('BAN/BTC') self.assertTrue(res.success) def test_getTicker(self): res = Txbit.getTicker('BAN/BTC') self.assertTrue(res.success) def test_getMarketHistory(self): res = Txbit.getMarketHistory('BAN/BTC') self.assertTrue(res.success) def test_getSystemStatus(self): res = Txbit.getSystemStatus() self.assertTrue(res.success) def test_getCurrencyInformation(self): res = Txbit.getCurrencyInformation('BTC') self.assertTrue(res.success) def test_getCurrencyBalanceSheet(self): res = Txbit.getCurrencyBalanceSheet('BTC') self.assertTrue(res.success) if __name__ == '__main__': unittest.main() <file_sep>/txbit/__init__.py from .txbit import Txbit, TxbitResponse __all__ = [ 'Txbit', 'TxbitResponse' ] <file_sep>/txbit/txbit.py import hashlib import hmac import json import requests from time import time class TxbitResponse: def __init__(self, success, message, result): self.success = success self.message = message self.result = result def __str__(self): d = { 'success': self.success,\ 'message': self.message,\ 'result': self.result } return str(json.dumps(d, indent = 4)) class Txbit: """A class to interact with the Txbit.io API Attributes ---------- endpoint : str the base url for API calls APIKey : str key for working with the Market and Account methods Secret : str secret for working with the Market and Account methods Methods ------- expandPathToUrl(path, params={}): adds onto the base url for specific methods request(path, params={}): uses `expandPathToUrl()` to make the API call authenticatedRequest(path, params={}) authenticated API call with APIKey and Secret for Market and Account methods getMarkets(): get the open and available trading markets along with other meta data getCurrencies(): get all supported assets along with other meta data getMarketSummaries(): get the last 24 hour summary of all active markets getExchangePairs(): get list of all pairs that form markets getSystemStatus(): get the system related status for all currencies getOrderBook(market, bookType='both'): get the orderbook for a given market getTicker(market): get current tick values for a market getMarketHistory(market): get the latest trades that have occurred for a specific market getCurrencyInformation(currency): get specific information and metadata about the listed currency getCurrencyBalanceSheet(currency): get solvency information for listed currencies getBalances(): get all balances from your account getBalanceFor(currency): get the balance from your account for a specific asset getDepositAddress(currency): get or generate an address for a specific currency withdraw(currency, quantity, address, paymentid=None): withdraw funds from your account getOrder(uuic): get a single order by uuid getOrderHistory(market): get your order history getWithdrawlHistory(currency): get your withdrawal history getDepositHistory(currency): get your deposit history butLimit(market, quantity, rate): place a Buy Limit order in a specific market sellLimit(market, quantity, rate): place a Sell Limit order in a specific market cancel(uuid): cancel a buy or sell order getOpenOrders(market): get all orders that you currently have opened Notes ----- Public methods can be run without supplying APIKey or Secret Market and Account methods need APIKey and Secret for authentification Market methods need 'ALLOW TRADING' permission set up on the APIKey Account methods need 'ALLOW READING' permission set up on the APIKey For more information, see: https://apidocs.txbit.io/#txbit-io-api """ endpoint = 'https://api.txbit.io/api/' def __init__(self, APIKey, Secret): self.APIKey = APIKey self.Secret = Secret def expandPathToUrl(path, params={}): """adds onto the base url for specific methods""" url = Txbit.endpoint + path url += '?' if params else '' for key in params: url += key + '=' + params[key] + '&' return url def request(path, params={}): """uses `expandPathToUrl()` to make the API call""" url = Txbit.expandPathToUrl(path, params) return requests.get(url) def authenticatedRequest(self, path, params={}): """authenticated API call with APIKey and Secret for Market and Account methods""" params['apikey'] = self.APIKey params['nonce'] = str(int(time())) url = Txbit.expandPathToUrl(path, params) apisign = hmac.new(bytes(self.Secret, 'utf-8'), bytes(url, 'utf-8'), hashlib.sha512).hexdigest().upper() headers = {'apisign': apisign} return requests.get(url, headers=headers) ## PUBLIC FUNCTIONS --------------- def getMarkets(): """(P) get the open and available trading markets along with other meta data""" res = Txbit.request('public/getmarkets') result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getCurrencies(): """(P) get all supported assets along with other meta data""" res = Txbit.request('public/getcurrencies') result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getMarketSummaries(): """(P) get the last 24 hour summary of all active markets""" res = Txbit.request('public/getmarketsummaries') result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getExchangePairs(): """(P) get list of all pairs that form markets""" res = Txbit.getMarketSummaries() res.result = [pair['MarketName'] for pair in res.result] return res def getSystemStatus(): """(P) get the system related status for all currencies""" res = Txbit.request('public/getsystemstatus') result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getOrderBook(market, bookType='both'): """(P) get the orderbook for a given market""" params = {'market': market, 'type': bookType} res = Txbit.request('public/getorderbook', params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getTicker(market): """(P) get current tick values for a market""" params = {'market': market} res = Txbit.request('public/getticker', params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getMarketHistory(market): """(P) get the latest trades that have occurred for a specific market""" params = {'market': market} res = Txbit.request('public/getmarkethistory', params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getCurrencyInformation(currency): """(P) get specific information and metadata about the listed currency""" params = {'currency': currency} res = Txbit.request('public/getcurrencyinformation', params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getCurrencyBalanceSheet(currency): """(P) get solvency information for listed currencies""" params = {'currency': currency} res = Txbit.request('public/getcurrencybalancesheet', params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) ## ACOUNT FUNCTIONS --------------- def getBalances(self): """(A) get all balances from your account""" path = 'account/getbalances' res = self.authenticatedRequest(path) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getBalanceFor(self, currency): """(A) get the balance from your account for a specific asset""" path = 'account/getbalance' params = {'currency': currency} res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getDepositAddress(self, currency): """(A) get or generate an address for a specific currency Notes ----- will return ADDRESS_GENERATING until one is available """ path = 'account/getdepositaddress' params = {'currency': currency} res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def withdraw(self, currency, quantity, address, paymentid=None): """(A) withdraw funds from your account Notes ----- account for txfee """ path = 'account/withdraw' params = {'currency': currency, 'quantity': quantity, 'address': address} if paymentid is not None: params['paymentid'] = paymentid res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getOrder(self, uuid): """(A) get a single order by uuid""" path = 'account/getorder' params = {'uuid': uuid} res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getOrderHistory(self, market=None): """(A) get your order history""" path = 'account/getorderhistory' params = {} if market is not None: params['market'] = market res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getWithdrawlHistory(self, currency=None): """(A) get your withdrawal history""" path = 'account/getwithdrawalhistory' params = {} if currency is not None: params['currency'] = currency res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getDepositHistory(self, currency=None): """(A) get your deposit history""" path = 'account/getdeposithistory' params = {} if currency is not None: params['currency'] = currency res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) ## MARKET FUNCTIONS --------------- def buyLimit(self, market, quantity, rate): """(M) place a Buy Limit order in a specific market""" path = 'market/buylimit' params = {'market': market, 'quantity': quantity, 'rate': rate} res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def sellLimit(self, market, quantity, rate): """(M) place a Sell Limit order in a specific market""" path = 'market/selllimit' params = {'market': market, 'quantity': quantity, 'rate': rate} res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def cancel(self, uuid): """(M) cancel a buy or sell order""" path = 'market/cancel' params = {'uuic': uuic} res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) def getOpenOrders(self, market=None): """(M) get all orders that you currently have opened""" path = 'getopenorders' params = {} if market is not None: params['market'] = market res = self.authenticatedRequest(path, params) result = res.json()['result'] if res.ok and res.json()['success'] else res.status_code return TxbitResponse(res.ok and res.json()['success'], "", result) <file_sep>/README.md # Txbit [![Build Status](https://travis-ci.com/AD-Ventures/txbit.svg?branch=main)](https://travis-ci.com/AD-Ventures/txbit) ![Last Commit](https://img.shields.io/github/last-commit/AD-Ventures/txbit) ![Python Version](https://img.shields.io/badge/python-3.4%2B-green) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/AD-Ventures/txbit/blob/main/LICENSE) A Python3 wrapper for the Txbit API ## Installation ```bash pip3 install txbit ``` ## Usage ```python from txbit import Txbit from secrets import APIKEY, SECRET # api key and secret # public functions (no APIKEY/Secret needed) markets = Txbit.getMarketSummaries().result order = Txbit.getOrderBook('ETH/BTC').result # authenticated market and account functions (require APIKEY/Secret) t = Txbit(APIKEY, SECRET) request = t.getBalance() # check if the API request was successful if request.success: balance = request.result ``` ## Support For any help or questions, please open an issue on GitHub. ## License [MIT](https://github.com/AD-Ventures/txbit/blob/master/LICENSE)
933a372ada671422b794c1a9de8355db83c718e4
[ "Markdown", "Python" ]
4
Python
itamar-j-allali/txbit
09d3639817abe33fac58f12843ef1b3c98b5ada1
75a8b879532b4671ea94e6ad77b0e702308e0cf1
refs/heads/master
<repo_name>DenisZykov19/calculation-zaichkin<file_sep>/calc/CalControllerViewController.swift // // CalControllerViewController.swift // calc // // Created by WSR on 6/20/19. // Copyright © 2019 WSR. All rights reserved. // import UIKit class CalControllerViewController: UIViewController { @IBOutlet weak var result: UILabel! var firstValue = 0.0 var secondValue = 0.0 var operation = "" @IBOutlet var clean: [UIButton]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ //action для цифр @IBAction func action(_ sender: UIButton) { //константа для цифры //берем ее из свойства title вызвавшей этот action кнопки let digit = sender.titleLabel?.text switch digit { case "0": result.text = "0" case "1": result.text = "1" case "2": result.text = "2" case "3": result.text = "3" case "4": result.text = "4" case "5": result.text = "5" case "6": result.text = "6" case "7": result.text = "7" case "8": result.text = "8" case "9": result.text = "9" case "÷": firstValue = Double(result.text!) as! Double operation = "÷" case "x": firstValue = Double(result.text!) as! Double operation = "x" case "-": firstValue = Double(result.text!) as! Double operation = "-" case "+": firstValue = Double(result.text!) as! Double operation = "+" case "%": firstValue = Double(result.text!) as! Double operation = "%" case "C": firstValue = Double(result.text!) as! Double operation = "c" self.firstValue = 0.0 self.secondValue = 0.0 self.result.text = "0" case "+/-": firstValue = Double(result.text!) as! Double let result = -firstValue self.result.text = String(result) case "=": operation(oper: operation) default: break } } func operation(oper: String) { secondValue = Double(self.result.text!) as! Double if oper == "+" { let result = firstValue + secondValue self.result.text = String(result) } if oper == "-" { let result = firstValue - secondValue self.result.text = String(result) } if oper == "÷" { let result = firstValue / secondValue self.result.text = String(result) } if oper == "x" { let result = firstValue * secondValue self.result.text = String(result) } if oper == "%" { let result = firstValue * 100 self.result.text = String(result) } } }
86b018ff434e3d35b525d7302b6af5282a45e173
[ "Swift" ]
1
Swift
DenisZykov19/calculation-zaichkin
488898bba3640859564b4434f61662c7b7e67252
0785a5b899906b91c29769dd26f58099fe6acf74
refs/heads/master
<file_sep>#include <napi.h> #include "helloWorld.h" // Module Inizialization Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "helloWorld"), Napi::Function::New<helloWorld>(env)); return exports; } NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)<file_sep>const testAddon = require('bindings')('test'); //This is an export file. Better leave this file untouched. // Exporting our module module.exports = testAddon; <file_sep>const addon = require('../'); // Calling out function console.log(addon.helloWorld());<file_sep>#ifndef HELLO_WORLD_H_ #define HELLO_WORLD_H_ #include <napi.h> // "Hello World" function Napi::Value helloWorld(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); return Napi::String::New(env, "Hello World!"); } #endif<file_sep>/** * Hello World function * @returns {string} "HelloWorld" */ export function helloWorld(): string;<file_sep># N-API addon This is a project template for [N-API](https://nodejs.org/api/n-api.html) addon. To create a new project based on this template using [degit](https://github.com/Rich-Harris/degit): ```bash npx degit Phamier/napi-addon-template your-napi-project cd your-napi-project ``` *Note that you will need to have [Node.js](https://nodejs.org/) installed.* ## Getting started Installing the depedencies. ```bash npm install ``` ## Building in production `npm install` automatically builds your addon after installing dependencies. There is no need to do anything else. ## Development ### Building If you modify `binding.gyp` or add new source files (`src/*.cpp`), you should run ... ```bash npm run rebuild:dev ``` If you modify an existing source file, `npm run build:dev` will do the job. ```bash npm run build:dev ``` Also there is a cleaning command... ```bash npm run clean ``` ### Declaration reference and JSDoc You can add declarations to `index.d.ts` with JSDoc documentation comments for improved Intellisence and documentaion. Example: ```js /** * Hello World function * @returns {string} "HelloWorld" */ export function helloWorld(): string; ``` ## VS Code Tips and Tricks ### Configure `includePath` for better IntelliSence results If you are using [Microsoft C/C++ extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools), you can add custom `includePath` for your project by modifying [`c_cpp_properties.json`](https://code.visualstudio.com/docs/cpp/c-cpp-properties-schema-reference) : ```json "configurations": [{ ... "includePath": [ "${workspaceFolder}/node_modules/node-addon-api/", "${workspaceFolder}/include/**", "/usr/local/include/**" ], ... ``` ### Debugging *Note: this method was proposed by [<NAME>](https://github.com/a7ul). Basically, this template is an improved version [his](https://github.com/a7ul/basic-node-addon) and I'm using the same debugging method as he does. Check out his [blog post](https://medium.com/@a7ul/debugging-nodejs-c-addons-using-vs-code-27e9940fc3ad) on meduza.com for more information. I will only provide my `launch.json` and `tasks.json` files.*\ `launch.json`: ```json { "version": "0.2.0", "configurations": [ { "type":"lldb", "request": "launch", "name": "Debug", "preLaunchTask": "npm rebuild", "program": "npm", "args": "run test" } ] } ``` `tasks.json`: ```json { "version" : "2.0.0", "tasks": [ { "type": "npm", "script": "rebuild:dev", "problemMatcher": [], "label": "npm rebuild", "detail": "node-gyp rebuild --debug" } ] } ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
f42b2aeafb5926101b112e726d79095461464460
[ "JavaScript", "Markdown", "C", "TypeScript", "C++" ]
6
C++
Phamier/napi-addon-template
a471d48442c320d2eb71f33d5680130c8d18a0f4
13fec251efb01fff47d59b753ce3099a59fc9ad9
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Text; using Adaptador.Clases; using Adaptador.Interfaz; namespace Adaptador.Clases { //Esta es la clase la cual deseamos adaptar, el cliente no la puede usar directamente pues la interfaz que usa es diferente class CalculadoraArray { public double suma(int[] pOperandos) { int n = 0; int r = 0; for (n = 0; n < pOperandos.Length; n++) r += pOperandos[n]; return r; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Adaptador.Interfaz { interface ITarget { int Sumar(int pA, int pB); } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Adaptador.Interfaz; namespace Adaptador.Clases { class Calcu:ITarget { public int Sumar(int pA, int pB) { return pA + pB; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Adaptador.Clases; using Adaptador.Interfaz; namespace Adaptador.Clases { //Esta clase usa la interfaz ITarget la cual es conocida por el cliente. El adaptador comunica al cliente con la clase adaptada class CAdaptador:ITarget { CalculadoraArray adaptado = new CalculadoraArray(); //Haremos la adaptacion de una operación public int Sumar (int pA, int pB) { double r = 0; //Creamos el array que necesita el adaptado //Adaptamos los datos que se envían int[] operadores = { pA, pB }; //realizamos la operación en el adaptado r = adaptado.suma(operadores); //Adaptamos el resultado return (int)r; } } }
01808569c79c3ccd40b1b0c1cd16b73cc6289071
[ "C#" ]
4
C#
diegomera1/PatronAdapter
c418629702d14ade3c36f94292a04f68b6ab52f6
46f713c45e95a601f3da265e4badb95d3547e2f3
refs/heads/master
<file_sep>import Vue from 'vue' import Router from 'vue-router' import Top from 'views/Top' import New from 'views/New' import ItemView from 'views/ItemView' Vue.use(Router) export default new Router({ mode: 'history', routes: [{ path: '/', component: Top }, { path: '/top', component: Top }, { path: '/new', component: New }, { path: '/show/:id', component: ItemView }] })
76c4dbfeb9b9472fd46c834ec40c4e5634ba5b01
[ "JavaScript" ]
1
JavaScript
YUFENGWANG/v2ex-vue-webpack
dedf1f0d93e6a6cf8e34adf4d8e0b995132a94fa
34237cdb9a83f856a7d1e2e769a6d027d41680db
refs/heads/master
<file_sep>var MyClasses = {}; //for creating a new object based on the prototype o if (typeof Object.create !== 'function' ) { Object.create = function(o) { var F = function (){}; F.prototype = o; return new F(); }; } //privode a way to make a method available to all functions Function.prototype.method = function(name, func) { this.prototype[name] = func; return this; }; // for "class" inheritance Function.method("inherits", function(Parent){ this.prototype = new Parent(); return this; }); // Class for player MyClasses.MyAirCraft_Class = function(scene, imgeFile1, imgeFile2, width, height){ var airCraft = new Sprite( scene, imgeFile1, width, height ); var img1 = airCraft.image; var img2 = new Image(); img2.src = imgeFile2; var flag = true; var cnt = 0; airCraft.setPosition( scene.width / 2, scene.height - airCraft.height ); airCraft.update_frame = function(){ cnt += 0.1; if (cnt >= 0.2 ){ cnt = 0; if ( flag === true ){ this.image = img1; } else { this.image = img2; } flag = !flag; } }; var bullet_cnt_time = 0; airCraft.bullet_interval = 3; airCraft.bullet_speed = 30; airCraft.shoot = function( bullets ){ if( airCraft.visible ) { bullet_cnt_time += 1; if ( bullet_cnt_time >= this.bullet_interval ) { bullet_cnt_time = 0; // find a possible bullet to shoot for ( var temp_bullet in bullets ) { if ( bullets[temp_bullet].visible === false ) { // reuse this bullet to shoot bullets[temp_bullet].show(); bullets[temp_bullet].setSpeed( airCraft.bullet_speed ); bullets[temp_bullet].setPosition( this.x, this.y ); //create sound effect file if ( !MyClasses.shootSound) MyClasses.shootSound = new Sound("./sound/shoot.mp3"); MyClasses.shootSound.play(); break; } } } } }; airCraft.update = function() { //update each frame for the airCraft to show animation airCraft.update_frame(); //parent update method this.x += this.dx; this.y += this.dy; this.checkBounds(); if ( this.visible ) { this.draw(); } }; return airCraft; }; //Class for bullets MyClasses.Bullet_Class = function(scene, imageFile, width, height){ var bullet = new Sprite( scene, imageFile, width, height ); bullet.changeMoveAngleBy( -90 ); bullet.setBoundAction( DIE ); bullet.hide(); return bullet; }; //Class for enemy airCraft MyClasses.EnemyClass = function(scene, imageFile, width, height, hp, explodeImageFiles, speed, gotHitImageFile ) { var enemy = new Sprite( scene, imageFile, width, height ); enemy.changeMoveAngleBy( 90 ); enemy.setBoundAction( DIE ); enemy.hide(); enemy.HP = hp; enemy.o_HP = hp; enemy.o_Speed = speed; enemy.originalImage = enemy.image; enemy.setSpeed( speed ); //0 stands for normal status //1 stands for got-hit status enemy.currentStatus= 0; if( gotHitImageFile ){ enemy.gotHitImage = new Image(); enemy.gotHitImage.src = gotHitImageFile; } // number of explosion frames; enemy.explodeFrames = explodeImageFiles.length; enemy.currentExplodeFrame = 0; enemy.explodeImages = []; // acts as a time counter; enemy.explodeCnt = 0; //pre-load images for (var i = 0; i < enemy.explodeFrames; i++) { var temp_image = new Image(); temp_image.src = explodeImageFiles[i]; enemy.explodeImages.push( temp_image ); } enemy.explode = function() { this.setSpeed(0); this.explodeCnt += 1; if ( this.explodeCnt >= 2 ) { this.explodeCnt = 0; this.currentExplodeFrame += 1; if( this.currentExplodeFrame < this.explodeFrames ){ this.image = this.explodeImages[ this.currentExplodeFrame ]; } else { this.hide(); this.currentExplodeFrame = 0; } } }; // set the enemy to its original status enemy.reset = function() { this.HP = this.o_HP; this.image = this.originalImage; this.currentStatus = 0; this.show(); this.setSpeed( this.o_Speed ); }; enemy.showGotHit = function() { if ( this.gotHitImage ) { this.image = this.gotHitImage; } }; enemy.update = function(){ //check if got hit //when HP is less than 0, it will explode, no need to show gotHit status if( this.HP > 0 && this.currentStatus == 1 ) { this.showGotHit(); this.currentStatus = 0; } else if ( this.HP > 0 && this.currentStatus === 0 ) { this.image = this.originalImage; } //check if needed to explode if( this.visible === true && this.HP <= 0 ){ this.explode(); } // parent update method this.x += this.dx; this.y += this.dy; this.checkBounds(); if ( this.visible ){ this.draw(); } }; return enemy; }; MyClasses.FontClass = function( scene, text, size) { this.scene = scene; this.canvas = scene.canvas; this.context = this.canvas.getContext("2d"); this.text = text; this.size = size; this.x = 200; this.y = 200; this.draw = function() { ctx = this.context; ctx.font = this.size + "px Arial"; ctx.strokeText(this.text, this.x, this.y); }; this.update = function() { this.draw(); }; this.setPosition = function( x, y ) { this.x = x; this.y = y; }; };
18d65812fec46ea310d8f1d9c3f9f91d200c9454
[ "JavaScript" ]
1
JavaScript
weimingtom/Shooting-Game
9101f103b804a98b2432a8bcd95ba4e768cce960
fb9ce98a7388c8679663e27c15764818a1c1cbc5
refs/heads/master
<file_sep>package com.wenhua.svr.thread.impl; import com.wenhua.svr.domain.ServerInfo; import com.wenhua.svr.enums.BusinessTypeEnum; import com.wenhua.svr.service.AuthService; import com.wenhua.svr.thread.AbstractThread; public class BarStatisticHandleThread extends AbstractThread { private AuthService authService; private BusinessTypeEnum businessType; private Object data; public BarStatisticHandleThread(AuthService authService,BusinessTypeEnum businessType,Object data){ this.authService=authService; this.businessType=businessType; this.data=data; } @Override protected void execute() { // TODO Auto-generated method stub switch (businessType) { case ServerInfoUpdate: //update server_info ServerInfo info=(ServerInfo)data; this.authService.updateServerInfo(info); break; default: break; } } }
166f25f15eeecd5e7237609a135fe62ceaf7d8e1
[ "Java" ]
1
Java
tigerli216/wenhua
eaefdeee7a68e58f8c7f14b6bfc1b1995312b37f
3920131650cc4ec3cf6d144041aeb7a53a425748
refs/heads/master
<repo_name>FIGS-FESS/DADB_Flywheel_77D<file_sep>/main.c /* Title: SASB Single Axis FLoator Test Code * Author: <NAME> * Purpose: Through use of a PID controller a current sensor and a displacement sensor, the code controls both axis of the top bearings of the flywheel. */ /* * Includes */ #include "F28x_Project.h" //Seems like a nice header file, includes a lot of things so I don't have to /* * Defines */ //Sets the size of the array for the Integral and Derivative previous values #define prev_size 64 //Size of the Memory array in the PID control //Sets the number of Sysclk cycles that the ADC samples for #define sample_cycles (20 - 1) //Note* only change the first number, the 1 accounts for the minimum //Current Bias current for the SADB to help stabilize #define current_bias .5 //Set arbitrarily as a middle point in the range of currents we antisipate to use //Current sensor conversion scale *Calibrated as of 2017/07/20 #define current_scale (10.168070782 * 3.3 / 4096)//Conversion scale for current sensor *(Amps/Volt) //Current sensor conversion offset *Calibrated as of 2017/07/20 #define current_offset -13.45198481 //Conversion offset for current sensor *(Amps) //Displacement sensor sample period #define x1_dt 0.1 //*(MilliSeconds) //Displacement sensor target #define x1_target 1 //Target float level *(Millimeters) //PID constants #define kp_init .5 //Default to 1 for Initial tuning #define ki_init 0 //Default to 0 for initial tuning #define kd_init 0 //Default to 0 for initial tuning /* * Structures */ /*! Position sensor structure */ typedef struct position_sensor_struct{ int *sample_loc; /*!< Sample value pointer */ float sample; /*!< Sample value, *(mm) */ float target; /*!< Target Displacement value *(mm) */ float error; /*!< Error for PID controls *(mm) */ float dt; /*!< Time period for PID control *(ms) */ float kp; /*!< Proportional Constant */ float p; /*!< Proportional calculated value */ float ki; /*!< Integral Constant */ float i; /*!< Integral calculated value */ float kd; /*!< Derivative Constant */ float d; /*!< Derivative calculated value */ float pid_out; /*!< Output of the PID control */ int prev_place; /*!< Current location in the array of previous values */ int prev_last; /*!< Last location in the array, used for Derivative term */ float prev[prev_size]; /*!< Array of previous values, used for calculating the Derivative and Integral terms */ }position; /*! Current Sensor and Coil Control Structure */ typedef struct current_coil_struct{ int *sample_loc; /*!< Sample value pointer */ float sample; /*!< Sample value, (*Amps) */ float target; /*!< Target Displacement value, *(Amps) */ float error; /*!< Error to determine more or less current, *(Amps) **May change later for PWM and/or a PID loop */ float scale; /*!< Scaling constant to convert sensor reading to current, *(Amps/Volt) */ float offset; /*!< Offset constant to convert sensor reading to current, *(Amps) */ float x_influence; /*!< X-axis influence of the coil */ float y_influence; /*!< Y-axis influence of the coil */ float bias; /*!< Individual bias current of the coil **May use in Gauss/De-Gauss process in the future */ int gpio_offset; /*!< Offset in the register to the correct GPIO pin */ }current; /* * Function Prototypes */ //*Note, at some point this should be moved to a header file void SetupPosition(position *sensor); void SetupCoil(current *coil); void Position_PID_Cntrl(position *sensor); void current_target(current *coil,position *x_disp_sensor,position *y_disp_sensor); void Bang_Bang_Cntrl(current *coil); void InitADCPart1(); void InitADCPart2(); void InitEPwm(); void PIEMap(); void EPwmStart(); interrupt void adca1_isr(); interrupt void adcb2_isr(); interrupt void epwm1_isr(); interrupt void epwm2_isr(); /* * Globals */ //Definition of the X1 instance of the position sensor structure position X1; //Variable used to store the PID math variables for the x axis displacement sensor position Y1; //Variable used to store the PID math variables for the y axis displacement sensor //Definition of the current coil structure current C1; //Variable used to store the current control variables for coil 1 current C2; //Variable used to store the current control variables for coil 2 current C3; //Variable used to store the current control variables for coil 3 current C4; //Variable used to store the current control variables for coil 4 //Displacement sensor reading int x1_sample; //Global for x1 displacement sensor reading *(Digitized) int y1_sample; //Global for y1 displacement sensor reading *(Digitized) //Cutoff value for X displacement //*Used for Debug int x1_cutoff = 0; //Debuging purposes, clean out later //Displacement sensor update flag /* Update name to account for more than just x being updated */ int x1_update; //Flag for new displacement sensor readings //Displacement sensor conversion scale //*Make this a define //*Bring this variable into the struct float disp_scale = 1.079757 * 3.3 / 4096; //Conversion scale for displacement sensor *(Millimeters/Volt) //Displacement sensor conversion offset //*Make this a define //*Bring this variable into the struct float disp_offset = 0.0004411644; //Conversion offset for displacement sensor *(Millieters) //Displacement to current ratio //*Make this a define //*First add it into the displacement struct //*Should this change in SADB/DADB? float disp_to_current = 2.2; //Scales the PID output to current *(Meters/Amp) //Current sensors readings int c1_sample; //Global for coil 1 current sensor reading *(Digitized) int c2_sample; //Global for coil 2 current sensor reading *(Digitized) int c3_sample; //Global for coil 3 current sensor reading *(Digitized) int c4_sample; //Global for coil 4 current sensor reading *(Digitized) //Current sensor update flag int c_update; //Flag for new current sensor readings //Maximum Current float current_max = 10; //Max current for operation *(Amps) //Minimum Current float current_min = -10; //Min current for operation *(Amps) /* * Main */ void main(void){ //Main Initialization function for the 77D InitSysCtrl(); //Setup the GPIO pins InitGpio(); //Setup output pins EALLOW; //Pin 89, Used to clock how long the displacement if statement in the main loop takes GpioCtrlRegs.GPBPUD.bit.GPIO40 = 0; //Leaves pull up resistor on pin GpioDataRegs.GPBSET.bit.GPIO40 = 1; //Sets the pin high GpioCtrlRegs.GPBGMUX1.bit.GPIO40 = 0; //Sets the pins to default mux GpioCtrlRegs.GPBDIR.bit.GPIO40 = 1; //Sets the pin to output GpioDataRegs.GPBCLEAR.bit.GPIO40 = 1; //Sets the pin low //PWM_H Pins //Pin 86, PWM_H for C3 GpioCtrlRegs.GPBPUD.bit.GPIO39 = 0; //Leaves the pull up resistor on the pin GpioDataRegs.GPBSET.bit.GPIO39 = 1; //Sets the pin high GpioCtrlRegs.GPBGMUX1.bit.GPIO39 = 0; //Sets the pin to default mux GpioCtrlRegs.GPBDIR.bit.GPIO39 = 1; //Sets the pin to output GpioDataRegs.GPBCLEAR.bit.GPIO39 = 1; //Sets the pin low //Pin 88, PWM_H for C2 GpioCtrlRegs.GPBGMUX1.bit.GPIO34 = 0; //Sets the pin to default mux GpioCtrlRegs.GPBDIR.bit.GPIO34 = 1; //Sets the pin to output GpioDataRegs.GPBCLEAR.bit.GPIO34 = 1; //Sets the pin to low //Pin 90, PWM_H for C3 GpioCtrlRegs.GPBDIR.bit.GPIO44 = 1; //Sets the pin to output GpioDataRegs.GPBCLEAR.bit.GPIO44 = 1; //Sets the pin to low //Pin 92, PWM_H for C4 GpioCtrlRegs.GPBDIR.bit.GPIO45 = 1; //Sets the pin to output GpioDataRegs.GPBCLEAR.bit.GPIO45 = 1; //Sets the pin to low EDIS; //Setup X1 variable SetupPosition(&X1); SetupPosition(&Y1); //Sets the location of the global for each sample X1.sample_loc = &x1_sample; Y1.sample_loc = &y1_sample; //Setup C1 variable SetupCoil(&C1); SetupCoil(&C2); SetupCoil(&C3); SetupCoil(&C4); //Sets the location of the global for each sample C1.sample_loc = &c1_sample; C2.sample_loc = &c2_sample; C3.sample_loc = &c3_sample; C4.sample_loc = &c4_sample; //Displacement sensor influences for each coil C1.x_influence = -1; C2.x_influence = 1; C3.y_influence = -1; C4.y_influence = 1; //GPIO offsets //These are found by mapping between the physical pins and their GPIO address in the GPIO registers C1.gpio_offset = 2; C2.gpio_offset = 7; C3.gpio_offset = 12; C4.gpio_offset = 13; //Disable interrupts? Followed the example of process from the control suite example code DINT; //Initialize PIE control registers InitPieCtrl(); //Disable CPU interrupts IER=0x0000; //Clear CPU Flags IFR=0x0000; //Initialize the PIE vector Table InitPieVectTable(); //Setup PIE Table Mappings PIEMap(); //ADC setup Part 1 InitADCPart1(); //ePWM setup function InitEPwm(); //ADC setup Part 2 InitADCPart2(); //Enable output of ePWM signals to Pins InitEPwm1Gpio(); InitEPwm2Gpio(); //Enable The Interrupts IER |=(M_INT1 | M_INT3 | M_INT10); //Enable Groups 1,3 and 10 //Enable Interrupts in PIE PieCtrlRegs.PIEIER1.bit.INTx1 = 1; //Enable ADCA1 interrupt PieCtrlRegs.PIEIER3.bit.INTx1 = 1; //Enable ePWM1 interrupt PieCtrlRegs.PIEIER3.bit.INTx2 = 1; //Enable ePWM2 interrupt PieCtrlRegs.PIEIER10.bit.INTx6 = 1; //Enable ADCB2 interrupt //Enable interrupts EINT; //Enable Real Time Management? ERTM; //Start ePWM EPwmStart(); //Loop for(;;){ //Current control if statement if(c_update){ c_update = 0; //Bang_Bang_Cntrl(); } //If statement to facilitate the PID calculations, //*Figure out if the current control should still be here if(x1_update){ x1_update = 0 ; GpioDataRegs.GPBTOGGLE.bit.GPIO40 = 1; //Used to clock how long this if statement takes Position_PID_Cntrl(&X1); //PID control for X1 sensor Position_PID_Cntrl(&Y1); //PID control for Y1 sensor current_target(&C1, &X1, &Y1); //Displacement to Current target for coil 1 current_target(&C2, &X1, &Y1); //Displacement to Current target for coil 2 current_target(&C3, &X1, &Y1); //Displacement to Current target for coil 3 current_target(&C4, &X1, &Y1); //Displacement to Current target for coil 4 Bang_Bang_Cntrl(&C1); //Current control function for coil 1 Bang_Bang_Cntrl(&C2); //Current control function for coil 2 Bang_Bang_Cntrl(&C3); //Current control function for coil 3 Bang_Bang_Cntrl(&C4); //Current control function for coil 4 GpioDataRegs.GPBTOGGLE.bit.GPIO40 = 1; //*OLD* Takes 1.0226 micro seconds } } } /* * Setup function for displacement structures */ void SetupPosition(position *sensor){ //Sets up the initial state for the displacement structure variables int i; //Used as a simple loop counter sensor->target = x1_target; //Feeds the position structure the location of sample global sensor->dt = x1_dt; //Feeds in the specific sample period for the sensor sensor->kp = kp_init; //Sets default proportional constant sensor->ki = ki_init; //Sets default integral constant sensor->kd = kd_init; //Sets default derivative constant sensor->prev_place = 0; //Starts the PID progression at 0 sensor->prev_last = prev_size - 1; //Starts the last pointer to the end of the array for(i=0;i<prev_size;i++){ sensor->prev[i]=0; //Step by step through the PID memory array and zero it } } /* * Setup function for coil structure */ void SetupCoil(current *coil){ //Sets up the initial state for the coil structure variables coil->scale = current_scale; //Sets the current conversion scale coil->offset = current_offset; //Sets the current conversion offset coil->x_influence = 0; //Sets the current x value scaling constant to default of zero coil->y_influence = 0; //Sets the current y value scaling constant to default of zero coil->bias = current_bias; //Sets the current bias to the default define } /* * Position PID Control Function */ void Position_PID_Cntrl(position *sensor){ //Read sample into structure sensor->sample = (*(sensor->sample_loc) * disp_scale) + disp_offset; //*(Meters) //Initial error calculation between target and sample values sensor->error = sensor->sample - sensor->target; //Proportional term calculation sensor->p = sensor->error * sensor->kp; //Integral term calculation //This was fun to code, pretty much I subtract out the last value of the array at the same time I add in the new one! sensor->i = sensor->i + ((sensor->error - sensor->prev[sensor->prev_place]) * sensor->dt * sensor->ki); //Derivative term calculation sensor->d = (sensor->error - sensor->prev[sensor->prev_last]) * sensor->kd / sensor->dt; //PID output sensor->pid_out = sensor->p + sensor->i + sensor->d; //*(mm?) //clean up operations to set the array for the next round of PID calculations sensor->prev[sensor->prev_place] = sensor->error; //Places the current rounds error into the memory array sensor->prev_last = sensor->prev_place; //Progresses the placement variable for the "last" location to the current place sensor->prev_place = (prev_size - 1) & (sensor->prev_place + 1); //Progresses the current location variable while using the bitwise math to limit and loop the variable } /* * Current Target Function */ void current_target(current *coil, position *x_disp_sensor, position *y_disp_sensor){ float temp; /* In the next line is where the future addition of the X Y influence will be accounted for */ temp = coil->bias + disp_to_current * ((coil->x_influence * x_disp_sensor->pid_out) + (coil->y_influence * y_disp_sensor->pid_out)); //*(Amps) if(temp > current_max || temp < current_min){ if(temp > current_max){ temp = current_max; //Limits the target current to the max value } else{ temp = current_min; //Limits the target current to the min value } } //Sets the target for the coil coil->target = temp; //*(Amps) } /* * Current Control Function */ void Bang_Bang_Cntrl(current *coil){ //Conversion of ADC current reading into Amps coil->sample = (*(coil->sample_loc) * coil->scale) + coil->offset; //*(Amps) //Initial error calculation between target and sampled current coil->error = coil->sample - coil->target; //Run P_H pin high or low depending on error if(coil->error < 0){ GpioDataRegs.GPBSET.all |= 1 << coil->gpio_offset; //This is Tied to the P_H pin for one of the Pololu's } else{ GpioDataRegs.GPBCLEAR.all |= 1 << coil->gpio_offset; //This is Tied to the P_H pin for one of the Pololu's } } /* * ADC Initialization Functions */ void InitADCPart1(){ //Enable editing of EALLOW registers EALLOW; //Enable The CLk signal for ADC A and B CpuSysRegs.PCLKCR13.bit.ADC_A = 1; CpuSysRegs.PCLKCR13.bit.ADC_B = 1; //Initial setup function for ADCs, calibrates them to factory state /***Find this function in the F2837xD_ADC.c file***/ AdcSetMode(ADC_ADCA, ADC_RESOLUTION_12BIT, ADC_SIGNALMODE_SINGLE); AdcSetMode(ADC_ADCB, ADC_RESOLUTION_12BIT, ADC_SIGNALMODE_SINGLE); //Initialization Settings for ADC A AdcaRegs.ADCCTL1.bit.INTPULSEPOS = 1; //Sets Interrupt pulse to trigger after conversion AdcaRegs.ADCCTL2.bit.SIGNALMODE = 0; //Single Ended, not Differential AdcaRegs.ADCCTL2.bit.RESOLUTION = 0; //Sets resolution to 12 bits, 1=16 bits AdcaRegs.ADCCTL2.bit.PRESCALE = 6; //Sets the Prescale of the ADC, 6=1/4 *Be careful with value, if it is to low, issues with sample value will occur //Initialization Settings for ADC B AdcbRegs.ADCCTL1.bit.INTPULSEPOS = 1; //Sets Interrupt pulse to trigger after conversion AdcbRegs.ADCCTL2.bit.SIGNALMODE = 0; //Single Ended, not Differential AdcbRegs.ADCCTL2.bit.RESOLUTION = 0; //Sets resolution to 12 bits, 1=16 bits AdcbRegs.ADCCTL2.bit.PRESCALE = 6; //Sets the Prescale of the ADC, 6=1/4 *Be careful with value, if it is to low, issues with sample value will occur AdcaRegs.ADCCTL1.bit.ADCPWDNZ = 1; //Powers up all of the analog circuitry AdcbRegs.ADCCTL1.bit.ADCPWDNZ = 1; //Powers up all of the analog circuitry //Delay for 1 ms to allow ADCs to start up DELAY_US(1000); //Required warmup time //Disable editing of EALLOW registers EDIS; } void InitADCPart2(){ EALLOW; //Configuration Settings for ADCA AdcaRegs.ADCSOC0CTL.bit.TRIGSEL = 5; //Set the Trigger for SOC0, 5=ePWM1 AdcaRegs.ADCSOC0CTL.bit.CHSEL = 0; //Set the channel for SOC0 to convert, 0=ADCAIN0 AdcaRegs.ADCSOC0CTL.bit.ACQPS = 19; //Set the sample window size for SOC0, 19=20 SysClkCycles AdcaRegs.ADCSOC1CTL.bit.TRIGSEL = 5; //Set the Trigger for SOC1, 5=ePWM1 AdcaRegs.ADCSOC1CTL.bit.CHSEL = 1; //Set the channel for SOC1 to convert, 0=ADCAIN1 AdcaRegs.ADCSOC1CTL.bit.ACQPS = 19; //Set the sample window size for SOC1, 19=20 SysClkCycles AdcaRegs.ADCSOC2CTL.bit.TRIGSEL = 5; //Set the Trigger for SOC2, 5=ePWM1 AdcaRegs.ADCSOC2CTL.bit.CHSEL = 2; //Set the channel for SOC2 to convert, 0=ADCAIN2 AdcaRegs.ADCSOC2CTL.bit.ACQPS = 19; //Set the sample window size for SOC2, 19=20 SysClkCycles AdcaRegs.ADCSOC3CTL.bit.TRIGSEL = 5; //Set the Trigger for SOC3, 5=ePWM1 AdcaRegs.ADCSOC3CTL.bit.CHSEL = 3; //Set the channel for SOC3 to convert, 0=ADCAIN3 AdcaRegs.ADCSOC3CTL.bit.ACQPS = 19; //Set the sample window size for SOC3, 19=20 SysClkCycles AdcaRegs.ADCINTSEL1N2.bit.INT1SEL = 3; //Set EOCx to trigger ADCINT1, 0=EOC0 AdcaRegs.ADCINTSEL1N2.bit.INT1E = 1; //Enable/Disable ADCINT1 AdcaRegs.ADCINTSEL1N2.bit.INT1CONT = 0; //Enable/Disable Continuous Mode AdcaRegs.ADCINTFLGCLR.bit.ADCINT1 = 1; //Clears ADCINT1 Flag //Configuration Settings for ADCB AdcbRegs.ADCSOC0CTL.bit.TRIGSEL = 8; //Set the Trigger for SOC0, 8=ePWM2 AdcbRegs.ADCSOC0CTL.bit.CHSEL = 0; //Set the channel for SOC0 to convert, 0=ADCBIN0 AdcbRegs.ADCSOC0CTL.bit.ACQPS = 19; //Set the sample window size for SOC0, 19=20 SysClkCycles AdcbRegs.ADCSOC1CTL.bit.TRIGSEL = 8; //Set the Trigger for SOC1, 8=ePWM2 AdcbRegs.ADCSOC1CTL.bit.CHSEL = 1; //Set the channel for SOC1 to convert, 1=ADCBIN1 AdcbRegs.ADCSOC1CTL.bit.ACQPS = 19; //Set the sample window size for SOC1, 19=20 SysClkCycles AdcbRegs.ADCINTSEL1N2.bit.INT2SEL = 1; //Set EOCx to trigger ADCINT2, 1=EOC1 AdcbRegs.ADCINTSEL1N2.bit.INT2E = 1; //Enable/Disable ADCINT2 AdcbRegs.ADCINTSEL1N2.bit.INT2CONT = 0; //Enable/Disable Continuous Mode AdcbRegs.ADCINTFLGCLR.bit.ADCINT2 = 1; //Clears ADCINT2 Flag EDIS; } /* * ePWM Initialization Function */ void InitEPwm(){ EALLOW; CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 0; //Disable the Time Base Clk //Enable Clk for PWM CpuSysRegs.PCLKCR2.bit.EPWM1 = 1; //Enable ePWM1 CLK CpuSysRegs.PCLKCR2.bit.EPWM2 = 1; //Enable ePWM2 CLK //Time Base Controls for ePWM1 EPwm1Regs.TBCTL.bit.PHSEN = 0; //Disable loading Counter register from Phase register EPwm1Regs.TBCTL.bit.PRDLD = 0; //A shadow register is used to write to the Period register EPwm1Regs.TBCTL.bit.HSPCLKDIV = 0; //High speed Time Base Prescale, 0="/1" EPwm1Regs.TBCTL.bit.CLKDIV = 0; //Time Base Clock Prescale, 0="/1" EPwm1Regs.TBCTL.bit.CTRMODE = 3; //Set counter mode, 3=freeze counter //Set ePWM1 counter to 0 EPwm1Regs.TBCTR = 0; //Resets ePWM1 counter register //Set ePWM1 period EPwm1Regs.TBPRD = 1249; //Results in a period of 1/80 kHz //Disable ePWM1 phase sync EPwm1Regs.TBPHS.bit.TBPHS = 0; //Enable ePWM1 event Triggering selection EPwm1Regs.ETSEL.bit.SOCAEN = 0; //Disable the SOCA conversion until ready EPwm1Regs.ETSEL.bit.SOCASEL = 1; //Select SOCA to be triggered by ePWM1 //Enable pulse on first event EPwm1Regs.ETPS.bit.SOCAPRD = 1; //Set the Compare A register EPwm1Regs.CMPA.bit.CMPA = 625; //Sets Compare A to a 50% duty cycle, arbitrary for now //Action qualifier control EPwm1Regs.AQCTLA.bit.CAU = 2; //Action at A going up, 2=set_high EPwm1Regs.AQCTLA.bit.ZRO = 1; //Action at zero, 1=clear //Time Base Controls for ePWM2 EPwm2Regs.TBCTL.bit.PHSEN = 0; //Disable loading Counter register from Phase register EPwm2Regs.TBCTL.bit.PRDLD = 0; //A shadow register is used to write to the Period register EPwm2Regs.TBCTL.bit.HSPCLKDIV = 0; //High speed Time Base Prescale, 0="/1" EPwm2Regs.TBCTL.bit.CLKDIV = 0; //Time Base Clock Prescale, 0="/1" EPwm2Regs.TBCTL.bit.CTRMODE = 3; //Set counter mode, 3=freeze counter //Set ePWM2 counter to 0 EPwm2Regs.TBCTR = 0; //Resets ePWM2 counter register //Set ePWM2 period EPwm2Regs.TBPRD = 9999; //Results in a period of 1/10 kHz //Disable ePWM2 phase sync EPwm2Regs.TBPHS.bit.TBPHS = 0; //Enable ePWM2 event Triggering selection EPwm2Regs.ETSEL.bit.SOCBEN = 0; //Disable the SOCB conversion until ready EPwm2Regs.ETSEL.bit.SOCBSEL = 1; //Select SOCB to be triggered by ePWM2 //Enable pulse on first event EPwm2Regs.ETPS.bit.SOCBPRD = 1; //Set the Compare A register EPwm2Regs.CMPA.bit.CMPA = 5000; //Sets Compare A to a 50% duty cycle, arbitrary for now //Action qualifier control EPwm2Regs.AQCTLA.bit.CAU = 2; //Action at A going up, 2=set_high EPwm2Regs.AQCTLA.bit.ZRO = 1; //Action at zero, 1=clear //CPU clock enable CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 1; //Renable the Time Base Clk EDIS; } /* * PIE Mapping Function */ void PIEMap(){ EALLOW; //PIE mappings for ADC interrupts PieVectTable.ADCA1_INT=&adca1_isr; PieVectTable.ADCB2_INT=&adcb2_isr; //PIE mappings for ePWM interrupts //PieVectTable.EPWM1_INT=&epwm1_isr; //PieVectTable.EPWM2_INT=&epwm2_isr; EDIS; } /* * ePWM Startup Function */ void EPwmStart(){ EALLOW; //Enable SOCs EPwm1Regs.ETSEL.bit.SOCAEN = 1; EPwm2Regs.ETSEL.bit.SOCBEN = 1; //Unfreeze ePWM to up count mode EPwm1Regs.TBCTL.bit.CTRMODE = 0; EPwm2Regs.TBCTL.bit.CTRMODE = 0; EDIS; } /* * ADC1 ISR */ interrupt void adca1_isr(){ //Write the sample to the global variable c1_sample = AdcaResultRegs.ADCRESULT0; //Reads the result register of SOC0 c2_sample = AdcaResultRegs.ADCRESULT1; //Reads the result register of SOC1 c3_sample = AdcaResultRegs.ADCRESULT2; //Reads the result register of SOC2 c4_sample = AdcaResultRegs.ADCRESULT3; //Reads the result register of SOC3 //Set the update flag c_update = 1; //Triggers the if statement in the main loop for Current Control //Clear the interrupt flag AdcaRegs.ADCINTFLGCLR.bit.ADCINT1=1; //Clears ADCA interrupt 1 //Acknowledge the interrupt PieCtrlRegs.PIEACK.all = PIEACK_GROUP1; //Acknowledges the interrupt in the PIE table for ADCA interrupt 1 } /* * ADC2 ISR */ interrupt void adcb2_isr(){ //Write the sample to the global variable x1_sample = AdcbResultRegs.ADCRESULT0; //Reads the result register of SOC0 y1_sample = AdcbResultRegs.ADCRESULT1; //Reads the result register of SOC1 //Set the update flag x1_update = 1; //Triggers the if statement in the main loop for PID operations //Clear the interrupt flag AdcbRegs.ADCINTFLGCLR.bit.ADCINT2=1; //Clears ADCB interrupt 2 //Acknowledge the interrupt PieCtrlRegs.PIEACK.all = PIEACK_GROUP10; //Acknowledges the interrupt in the PIE table for ADCB interrupt 2 } <file_sep>/README.md # DADB_Flywheel_77D Brief: This code utilizes two displacement sensors (X and Y axis) to measure where the rotor is, then regulates the active magnetic bearings to correct the position. Basic Operation: This setup utilizes four coils to provide both a positive and negative stabilization force in the x and y axis. If the sensors detects an offset, the coils will be activated to stabilize to a target position. Pinouts: Current Sensors -> Pin 09 (ADCA CH0) For H-Bridge 1 Coil 1 -> Pin 11 (ADCA CH1) For H-Bridge 2 Coil 2 -> Pin 15 (ADCA CH2) For H-Bridge 3 Coil 3 -> Pin 17 (ADCA CH3) For H-Bridge 4 Coil 4 Displacement Sensor -> Pin 12 (ADCB CH0) -> Pin 14 (ADCB CH1) PWM High -> Pin 86 (GPIO 34) For H-Bridge 1 Coil 1 -> Pin 88 (GPIO 39) For H-Bridge 2 Coil 2 -> Pin 90 (GPIO 44) For H-Bridge 3 Coil 3 -> Pin 92 (GPIO 45) For H-Bridge 4 Coil 4 PWM Low and Dir should be pluged into one of the 3.3V pins on the board to keep them at logic high. This garentees that when the PWM High pin is toggled the Reference Pins: ADCA Clock Signal -> Pin 49 (ePWM1 Compare A) ADCB Clock Signal -> Pin 53 (ePWM2 Compare A) Ussage: After the board is plugged in one should be able to debug the code. Both X and Y have individual PID loops that can be tuned. Each coil has a set bias current that can be changed. Each coil also has variable x/y sensor influences. This allows for moving the sensors without having to rewire or rewrite code. Considerations: Very basic setup, only proportial constants and only a set bias current. When this is properly PID tuned it should be rediculously strong.
75c658a3fbcbb52df30bd30e4fca3c943095e7c0
[ "Markdown", "C" ]
2
C
FIGS-FESS/DADB_Flywheel_77D
ce1b6aac8b91659fa728dfc733f4fd5b725eb28e
be33cd04d380b301a8ab3306d9fe3ddfd748acb2
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> </head> <?php echo $__env->make('login.partials._header', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <body> <div class="login-wrap"> <?php echo $__env->yieldContent('content'); ?> </div> </body> </html><file_sep><?php $__env->startSection('content'); ?> <!-- Main --> <div id="main"> <!-- Post --> <?php $__currentLoopData = $article; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $showArticle): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <article class="post"> <header> <div class="title"> <h2><a href="/read/<?php echo e($showArticle->id); ?>"><?php echo e($showArticle->judul); ?></a></h2> <p><?php echo e($showArticle->isi); ?></p> </div> <div class="meta"> <time class="published" datetime="2015-11-01"><?php echo e($showArticle->tanggal); ?></time> <a href="#" class="author"><span class="name"><?php echo e($showArticle->author_id); ?></span><img src="assets/blog/images/avatar.jpg" alt="" /></a> </div> </header> <a href="#" class="image featured"><img src="<?php echo e(url('img/article/')); ?>/<?php echo e($showArticle->foto); ?>" alt="" /></a> <p><?php echo e($showArticle->isi); ?></p> <footer> <ul class="actions"> <li><a href="/read/<?php echo e($showArticle->id); ?>" class="button big">Continue Reading</a></li> </ul> <ul class="stats"> <li><a href="#">General</a></li> <li><a href="#" class="icon fa-heart">28</a></li> <li><a href="#" class="icon fa-comment">128</a></li> </ul> </footer> </article> <!-- Pagination --> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?> <ul class="actions pagination"> <?php echo e($article->links()); ?> </ul> </div> <?php echo $__env->make('blog.partials._sidebar', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php $__env->stopSection(); ?> <?php echo $__env->make('blog.partials.main', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Article; use DB, Carbon, File; class ArticleController extends Controller { public function index() { $article = Article::paginate(4); return view('article.index', ['article' => $article]); } public function addArticle() { return view('article.add'); } public function addArticleProses(Request $request) { $tanggal = Carbon\Carbon::now()->toDateTimeString(); $data = [ 'judul' => $request->judul, 'isi' => $request->isi, 'kategori' => $request->kategori, 'author_id' => $request->author_id, 'tanggal' => $tanggal ]; if ($request->hasFile('foto')) { $foto = $request->file('foto'); $nama = $foto->getClientOriginalName(); $dir = public_path(). '/img/article/'; $foto->move($dir, $nama); $data['foto'] = $nama; } Article::create($data); return redirect()->route('article'); } public function updateArticle(Request $request) { $id = $request->id; $tanggal = Carbon\Carbon::now()->toDateTimeString(); $data = [ 'judul' => $request->judul, 'isi' => $request->isi, 'kategori' => $request->kategori, 'author_id' => $request->author_id, 'tanggal' => $tanggal ]; if ($request->hasFile('foto')) { $foto = $request->file('foto'); $nama = $foto->getClientOriginalName(); $dir = public_path(). '/img/article/'; $foto->move($dir, $nama); $data['foto'] = $nama; } Article::find($id)->update($data); return redirect()->route('article'); } public function editArticle(Request $request) { $id = $request->id; $article = DB::table('article') ->where('id', $id) ->get(); return view ('article.edit', ['article' => $article]); } public function showArticle() { $article = Article::paginate(2); return view('blog.index',['article' => $article ]); } public function readArticle(Request $request) { $id = $request->id; $article = DB::table('article') ->where('id', $id) ->get(); return view('blog.show', ['article' => $article]); } public function deleteArticle(Request $request) { $id = $request->id; $foto = DB::table('article') ->where('id', $id) ->value('foto'); File::delete('img/article/'.$foto); $article = Article::findOrFail($id)->delete(); return redirect()->route('article'); } } <file_sep> <title>BlogKu</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]--> <link rel="stylesheet" href="<?php echo e(asset('assets/blog/css/main.css')); ?>" /> <!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]--> <!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]--> <file_sep><?php $__env->startSection('content'); ?> <div class="login-html"> <input id="tab-1" type="radio" name="tab" class="sign-in" checked><label for="tab-1" class="tab">Sign In</label> <input id="tab-2" type="radio" name="tab" class="sign-up"><label for="tab-2" class="tab">Sign Up</label> <div class="login-form"> <div class="sign-in-htm"> <form action="<?php echo e(route('login')); ?>" method="post"> <?php echo e(csrf_field()); ?> <div class="group"> <label for="user" class="label">Username</label> <input id="user" name="username" type="text" class="input"> </div> <div class="group"> <label for="pass" class="label">Password</label> <input id="pass" type="<PASSWORD>" name="password" class="input" data-type="password"> </div> <div class="group"> <input id="check" type="checkbox" class="check" checked> <label for="check"><span class="icon"></span> Keep me Signed in</label> </div> <div class="group"> <input type="submit" class="button" value="Sign In"> </div> <div class="hr"></div> <div class="foot-lnk"> <a href="#forgot">Forgot Password?</a> </div> </div> <div class="sign-up-htm"> <div class="group"> <label for="user" class="label">Username</label> <input id="user" type="text" class="input"> </div> <div class="group"> <label for="pass" class="label">Password</label> <input id="pass" type="<PASSWORD>" class="input" data-type="password"> </div> <div class="group"> <label for="pass" class="label">Repeat Password</label> <input id="pass" type="password" class="input" data-type="password"> </div> <div class="group"> <label for="pass" class="label">Email Address</label> <input id="pass" type="text" class="input"> </div> <div class="group"> <input type="submit" class="button" value="Sign Up"> </div> </form> <div class="hr"></div> <div class="foot-lnk"> <label for="tab-1">Already Member?</a> </div> </div> </div> </div> <?php $__env->stopSection(); ?> <?php echo $__env->make('login.partials.main', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ /*Route::get('/', function () { return view('welcome'); });*/ Auth::routes(); Route::get('/', 'ArticleController@showArticle')->name('home'); Route::get('/dashboard','DashboardController@index')->name('dashboard'); Route::get('/read/{id}','ArticleController@readArticle')->name('readArticle'); Route::get('/article', 'ArticleController@index')->name('article'); Route::get('/article/edit/{id}', 'ArticleController@editArticle')->name('editArticle'); Route::post('/updateArticle', 'ArticleController@updateArticle')->name('updateArticle'); Route::get('/article/add', 'ArticleController@addArticle')->name('addArticle'); Route::post('/article/addArticleProses', 'ArticleController@addArticleProses')->name('addArticleProses'); Route::get('/article/delete/{id}', 'ArticleController@deleteArticle')->name('deleteArticle'); <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { protected $table = 'article'; public $timestamps = false; protected $fillable = [ 'judul', 'isi', 'kategori', 'foto', 'author_id','tanggal' ]; } <file_sep><?php use Illuminate\Database\Seeder; class ArticleSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 5; $i++) { DB::table('article')->insert([ 'judul' => 'Belajar Laravel' .$i , 'isi' => 'Belajar Laravel Mudah Menyenangkan', 'kategori' => 'Laravel', 'foto' => 'Laravel.jpg', 'author_id' => '1', 'tanggal' => '2017-02-08 09:53:56' ]); } } } <file_sep><!DOCTYPE html> <html> <head> <?php echo $__env->make('dashboard.partials._header', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> </head> <body> <div class="wrapper"> <?php echo $__env->make('dashboard.partials._navside', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('dashboard.partials._navbar', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->yieldContent('content'); ?> <?php echo $__env->make('dashboard.partials._footer', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> </div> </body> </html>
b653ea93535d1f5963cecec9509cf7402c741cfe
[ "PHP" ]
9
PHP
acidopal/blogku
9787aff11d6ee60f2feeeebf9cc357a324d82a0f
f085c9abe1b1c677203266dc990c3852dbc9aa95
refs/heads/main
<file_sep>{% extends 'index.html' %} {% block content %} <div align="center"> {% for dentist in dentist %} <div align="center" style="float:left;"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp; <img src="{{ dentist.doctor.url }}" width="200" height="200" style="border-radius: 1.8px"><br><br> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;{{ dentist.doctor_name }}<br><br> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;{{ dentist.specilization }}<br><br> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;{{ dentist.rating }}&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;{{ dentist.fee }}<br><br> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;{{ dentist.distance }}<br> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;{{ dentist.avilable_in }} </div> {% endfor %} </div> {% endblock %}<file_sep>from django.db import models # Create your models here. class DoctorsModel(models.Model): doctor_name=models.CharField(max_length=20,null=True) specilization=models.CharField(max_length=30,null=True) rating=models.FloatField(null=True) fee=models.FloatField(null=True) distance=models.CharField(max_length=50,null=True) avilable_in=models.CharField(max_length=100,null=True) doctor=models.ImageField(upload_to='doctors/',null=True) def __str__(self): return self.doctor_name class Next3Dentist(models.Model): doctor_name = models.CharField(max_length=20, null=True) specilization = models.CharField(max_length=30, null=True) rating = models.FloatField(null=True) fee = models.FloatField(null=True) distance = models.CharField(max_length=50, null=True) avilable_in = models.CharField(max_length=100, null=True) doctor = models.ImageField(upload_to='doctors/', null=True) class AnotherNext3Dentist(models.Model): doctor_name = models.CharField(max_length=20, null=True) specilization = models.CharField(max_length=30, null=True) rating = models.FloatField(null=True) fee = models.FloatField(null=True) distance = models.CharField(max_length=50, null=True) avilable_in = models.CharField(max_length=100, null=True) doctor = models.ImageField(upload_to='doctors/', null=True) <file_sep>from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.generic import ListView from .models import DoctorsModel class Homepage(ListView): template_name = 'homepage.html' model = DoctorsModel queryset = DoctorsModel.objects.all() paginate_by = 3 <file_sep>from django.contrib import admin from .models import DoctorsModel,Next3Dentist,AnotherNext3Dentist # Register your models here. admin.site.register(DoctorsModel) admin.site.register(Next3Dentist) admin.site.register(AnotherNext3Dentist)<file_sep># Generated by Django 3.0 on 2020-10-28 16:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Dentalapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='AnotherNext3Dentist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('doctor_name', models.CharField(max_length=20, null=True)), ('specilization', models.CharField(max_length=30, null=True)), ('rating', models.FloatField(null=True)), ('fee', models.FloatField(null=True)), ('distance', models.CharField(max_length=50, null=True)), ('avilable_in', models.CharField(max_length=100, null=True)), ('doctor', models.ImageField(null=True, upload_to='doctors/')), ], ), migrations.CreateModel( name='Next3Dentist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('doctor_name', models.CharField(max_length=20, null=True)), ('specilization', models.CharField(max_length=30, null=True)), ('rating', models.FloatField(null=True)), ('fee', models.FloatField(null=True)), ('distance', models.CharField(max_length=50, null=True)), ('avilable_in', models.CharField(max_length=100, null=True)), ('doctor', models.ImageField(null=True, upload_to='doctors/')), ], ), ] <file_sep># dentalproject this is the Q-dental Project <file_sep> {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Doctor Dentals</title> </head> <body> <pre> </pre> <div align="center"> <h4> Know Your Syntums </h4> </div> <br> <table align="center"> <tr> <th width="200" style="background-color: blanchedalmond"> <img src="{% static 'molar-with-cavity.png' %}" width="150" height="150">&nbsp;&nbsp;&nbsp; <div align="center"> Cavities </div> </th> <th width="200" style="background-color: blanchedalmond"> <img src="{% static 'healthy-tooth.png' %}" width="150" height="150"> <div align="center"> Thoothache </div> </th> <th width="200" style="background-color: blanchedalmond" > <img src="{% static 'broken-tooth.png' %}" width="150" height="150"> <div align="center"> Gingivities </div> </th> <th width="200" style="background-color: blanchedalmond"> <img src="{% static 'cavity.png' %}" width="150" height="150"> <div align="center"> Decay </div> </th> </tr> </table> <pre> </pre> <table align="center"> <tr> <th> Dental Health & You </th> </tr> </table> <pre> </pre> <table align="center" border="2" > <tr> <th width="500"> How To Ceep Cavity Away <br> -Dr.<NAME><br><br> <p> A tooth is one of the hard, white things in the mouth. Teeth (plural) are used to help the mastication process by chewing food. Chew means to break up and crush food so it can be swallowed (pushed down into the stomach). </p> </th> <th width="500"> How To Ceep Cavity Away <br> -Dr.<NAME><br><br> <p> A tooth is one of the hard, white things in the mouth. Teeth (plural) are used to help the mastication process by chewing food. Chew means to break up and crush food so it can be swallowed (pushed down into the stomach). </p> </th> </tr> </table> <table align="center"> <tr> <th> Happy Smiles </th> </tr> </table> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Option 2: jQuery, Popper.js, and Bootstrap JS <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> --> </body> </html>
db02f55dd1bbb64da9e36c27b1c188487c11493b
[ "Markdown", "Python", "HTML" ]
7
HTML
Narayanaraodumpala/dentalproject
46c8211b05cabc5f07a9deac22d574cb9034fd32
ab343f586c5ea5306a977131ae8570e4ffcac8a5
refs/heads/main
<file_sep>import numpy as np def calculate(list): if len(list) < 9: raise ValueError("List must contain nine numbers.") input = np.array(list).reshape(3, 3) calculations = { 'mean': [np.mean(input, axis = 0).tolist(), np.mean(input, axis = 1).tolist(), np.mean(input).tolist()], 'variance': [np.var(input, axis = 0).tolist(), np.var(input, axis = 1).tolist(), np.var(input).tolist()], 'standard deviation': [np.std(input, axis = 0).tolist(), np.std(input, axis = 1).tolist(), np.std(input).tolist()], 'max': [np.max(input, 0).tolist(), np.max(input, 1).tolist(), np.max(input).tolist()], 'min': [np.min(input, 0).tolist(), np.min(input, 1).tolist(), np.min(input).tolist()], 'sum': [np.sum(input, axis = 0).tolist(), np.sum(input, axis = 1).tolist(), np.sum(input).tolist()] } return calculations<file_sep>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Import data df = pd.read_csv("medical_examination.csv") # Add 'overweight' column df['overweight'] = (df.weight / (df.height/100)**2) > 25 df['overweight'] = df['overweight'].map({True: 1, False: 0}) # Normalize data by making 0 always good and 1 always bad. If the value of 'cholestorol' or 'gluc' is 1, make the value 0. If the value is more than 1, make the value 1. normalize = ["cholesterol", "gluc"] for _ in normalize: df[_] = df[_] > 1 df[_] = df[_].map({True: 1, False: 0}) # Draw Categorical Plot def draw_cat_plot(): # Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'. df_cat = pd.melt(df, id_vars = ["cardio"], value_vars = ["active", "alco", "cholesterol", "gluc", "overweight", "smoke"]) # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the collumns for the catplot to work correctly. df_cat = pd.DataFrame(df_cat.value_counts()) df_cat.columns = ["total"] df_cat = df_cat.groupby(["cardio", "variable", "value"])[["total"]].sum() df_cat = df_cat.reset_index() # Draw the catplot with 'sns.catplot()' fig = sns.catplot(x= "variable", y = "total", hue = "value", col = "cardio", data = df_cat, kind = "bar").fig # Do not modify the next two lines fig.savefig('catplot.png') return fig # Draw Heat Map def draw_heat_map(): # Clean the data df_heat = df.copy() df_heat = df_heat.drop(list(df_heat.loc[df["ap_lo"] > df["ap_hi"]].index)) df_heat = df_heat.drop(list(df_heat.loc[df["height"] < df["height"].quantile(0.025)].index)) df_heat = df_heat.drop(list(df_heat.loc[df["height"] > df["height"].quantile(0.975)].index)) df_heat = df_heat.drop(list(df_heat.loc[df["weight"] < df["weight"].quantile(0.025)].index)) df_heat = df_heat.drop(list(df_heat.loc[df["weight"] > df["weight"].quantile(0.975)].index)) # Calculate the correlation matrix corr = df_heat.corr() corr = round(corr, 1) # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr)) # Set up the matplotlib figure fig, ax = plt.subplots(figsize = (11, 10)) # Draw the heatmap with 'sns.heatmap()' sns.heatmap(data = corr, linewidths = .5, center = 0, vmin = -0.16, vmax = 0.32, annot = True, fmt = ".1f", mask = mask, cbar_kws = {"shrink": .5, "ticks": [-0.08, 0.00, 0.08, 0.16, 0.24]}, ax = ax) # Do not modify the next two lines fig.savefig('heatmap.png') return fig <file_sep>import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() # Import data (Make sure to parse dates. Consider setting index column to 'date'.) df = pd.read_csv("fcc-forum-pageviews.csv", index_col = "date", parse_dates = True) # Clean data df_sorted = df.sort_values("value") two_point_five = round(len(df_sorted)*(1/40)) top2point5_index = (df_sorted.head(two_point_five)).index bottom2point5_index = (df_sorted.tail(two_point_five)).index df = df.drop(top2point5_index) df = df.drop(bottom2point5_index) def draw_line_plot(): # Draw line plot fig, axes = plt.subplots(figsize = (18, 6)) axes.plot(df.index, df.value, color = 'red') axes.set_xlabel("Date") axes.set_ylabel("Page Views") axes.set_title("Daily freeCodeCamp Forum Page Views 5/2016-12/2019") # Save image and return fig (don't change this part) fig.savefig('line_plot.png') return fig def draw_bar_plot(): # Copy and modify data for monthly bar plot df_bar = df.copy() df_bar.reset_index(inplace = True) df_bar['Years'], df_bar['Months'] = df_bar['date'].dt.year, df_bar['date'].dt.month df_bar.sort_values('Months', inplace = True) df_bar = pd.DataFrame(df_bar.groupby(['Years', 'Months']).value.mean()) df_bar.rename(columns = {'value': 'AveragePageViews'}, inplace = True) df_bar = df_bar.AveragePageViews df_bar = df_bar.unstack() col = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] df_bar.columns = col df_bar.columns.rename('Months', inplace = True) # Draw bar plot fig, ax = plt.subplots() df_bar.plot(kind = 'bar', figsize = (9, 9), ax = ax) ax.set_xlabel("Years") ax.set_ylabel("Average Page Views") ax.legend() # Save image and return fig (don't change this part) fig.savefig('bar_plot.png') return fig def draw_box_plot(): # Prepare data for box plots (this part is done!) df_box = df.copy() df_box.reset_index(inplace=True) df_box['year'] = [d.year for d in df_box.date] df_box['month'] = [d.strftime('%b') for d in df_box.date] df_box_sorted = df_box.copy() df_box_sorted['month'] = [d.month for d in df_box_sorted.date] df_box_sorted.sort_values(by = 'month', inplace = True) df_box_sorted['month'] = [d.strftime('%b') for d in df_box_sorted.date] # Draw box plots (using Seaborn) fig, axes = plt.subplots(1, 2, figsize = (30, 10)) sns.set_style("whitegrid") sns.boxplot(x = "year", y = 'value', data = df_box, ax = axes[0]) sns.boxplot(x = "month", y = 'value', data = df_box_sorted, ax = axes[1]) axes[0].grid(False) axes[1].grid(False) axes[0].set_xlabel('Year') axes[0].set_ylabel('Page Views') axes[1].set_xlabel('Month') axes[1].set_ylabel('Page Views') axes[0].set_title("Year-wise Box Plot (Trend)") axes[1].set_title("Month-wise Box Plot (Seasonality)") # Save image and return fig (don't change this part) fig.savefig('box_plot.png') return fig <file_sep>import pandas as pd import matplotlib.pyplot as plt from scipy.stats import linregress def draw_plot(): # Read data from file df = pd.read_csv("epa-sea-level.csv", float_precision = 'legacy') # Create scatter plot fig, axes = plt.subplots(figsize = (11, 7)) axes.scatter(df["Year"], df["CSIRO Adjusted Sea Level"]) # Create first line of best fit res1 = linregress(df["Year"], df["CSIRO Adjusted Sea Level"]) through2050 = [1880 + n for n in range(170)] through2050 = pd.Series(through2050) axes.plot(through2050, res1.intercept + res1.slope * through2050, 'r') # Create second line of best fit res2 = linregress(df["Year"][120:], df["CSIRO Adjusted Sea Level"][120:]) from2000 = [2000 + n for n in range(50)] from2000 = pd.Series(from2000) axes.plot(from2000, res2.intercept + res2.slope * from2000, 'g') # Add labels and title axes.set_xlabel("Year") axes.set_ylabel("Sea Level (inches)") axes.set_title("Rise in Sea Level") # Save plot and return data for testing (DO NOT MODIFY) plt.savefig('sea_level_plot.png') return plt.gca()<file_sep># DataAnalysisProjects It consists of five projects that build a good foundational knowledge of data analysis with Python.
41185696d259875927ee77eafa0f747157b538d3
[ "Markdown", "Python" ]
5
Python
muhammadmj/DataAnalysisProjects
a08883d59d74c873213134189644fae41cfa9134
5e72771defe9a383ff027eb760122ab6ad675df1
refs/heads/master
<file_sep>import re import time import sys import os import pandas as pd import requests import random def getArgvDict(argv): optionDict = {} c = 0 for i in argv: if re.match(r'-\D', i): optionDict[i] = argv[c + 1] c += 1 return optionDict def ScrapyTarScan(url, regEx): time.sleep(random.uniform(2.2,4.4)) response = requests.get(url) targetscanFile = response.content targetscanResPage = targetscanFile.decode('utf-8') regObj = re.compile(regEx, re.DOTALL) match = regObj.search(targetscanResPage) if match: scrapyRes = match.group(1) return scrapyRes else: return 'Nothing' def GetTargetScan(miR, out, threshold): baseUrl1 = 'http://www.targetscan.org/cgi-bin/targetscan/vert_72/' baseUrl2 = 'http://www.targetscan.org' searchItem = 'targetscan.cgi?species=Human&gid=&mir_sc=&mir_c=&mir_nc=&mir_vnc=&mirg=' regEx1 = '<A HREF="(.*?)">Download' regEx2 = '<A HREF="(.*?)" download' regEx3 = '(.*)' targetscanUrl = baseUrl1 + searchItem + miR downloadItem = ScrapyTarScan(targetscanUrl, regEx1) if 'Nothing' == downloadItem: print('Warning: This miRNA('+miR+') is not exists in TargetScan v7.2, you may need check this out mannully.') geneList = [] else: downloadUrl = baseUrl1 + downloadItem textItem = ScrapyTarScan(downloadUrl, regEx2) textUrl = baseUrl2 + textItem targetRes = ScrapyTarScan(textUrl, regEx3) t = open(out + 'TargetScan_v7.2/TMP', 'w') t.write(targetRes) t.close() oriTSC = pd.read_table(out + 'TargetScan_v7.2/TMP', header = 0, sep = '\t') tmp1 = oriTSC[oriTSC['Representative miRNA'] == miR] tmp2 = tmp1[tmp1['Cumulative weighted context++ score'] <= float(threshold)] geneList = tmp2['Target gene'].values tmp2.to_csv(out + 'TargetScan_v7.2/TarScan-' + miR + '.tsv', index = False, header = True, sep = '\t') os.remove(outDir + 'TargetScan_v7.2/TMP') return geneList def GetMiRDB(miR, RDB, out, threshold): oriRDB = pd.read_table(RDB, header = 0, sep = '\t') tmp1 = oriRDB[oriRDB['miRNA'] == miR] if len(tmp1) <= 1: print('Warning: This miRNA('+miR+') is not exists in miRDB v6.0, you may need check this out mannully.') geneList = [] else: tmp2 = tmp1[tmp1['score'] >= int(threshold)] geneList = tmp2['Gene'].values tmp2.to_csv(out + 'miRDB_v6.0/miRDB_NM-' + miR + '.tsv', index = False, header = True, sep = '\t') return geneList def GetFinalTarget(miR, tsc, rdb, out): clipdf = pd.read_table('./data/GSE111432_AGO2CLIP_gene.txt', header = None, names=['SYMBOL'], sep = '\t') clipSymbol = clipdf['SYMBOL'].values with open('./data/miRDB_v6.0.hsaOnly.RefSeq2SYMBOL.txt', 'r') as f: cliptxt = f.read() rdb_symbol = [] for i in rdb: match = re.search(i+r'\t(\S+)\n', cliptxt) if match: rdb_symbol.append(match.group(1)) TSC_b_RDB = set(tsc).union(set(rdb_symbol)) TSC_b_RDB_j_CLIP = TSC_b_RDB.intersection(set(clipSymbol)) clip = [s for s in TSC_b_RDB_j_CLIP if s != ''] t = open(out+'final_targets/Targets-' + miR + '.tsv', 'w') t.writelines("\n".join(TSC_b_RDB_j_CLIP)) t.close() if __name__ == '__main__': helpDoc = ''' -H/-h Show this help message and exit. -miRNA The miRNAs list file , one miRNA per line. Please use the complete miRNA name, e.g. hsa-miR-218-5p. [-tarScanScore] Optional. The threshold of cumulative weighted context++ score in TargetScan-V7.2 to filter results. The predicted target with the score great than this threshold will be filtered out. The value range is [-1, 0] (-1 means best prediction). The defult value is -0.2. [-miRDBScore] Optional. The threshold for prediction confidence in miRDB-V6.0 to filter results. The predicted target with the score lower than this threshold will be filtered out. The value range is [50, 100] (100 means best prediction). The defult value is 60. -outputDir A folder will be used to store results. The script will output the following folder/files into -outputDir: TargetScan_v7.2/TarScan-miRNA.tsv, TargetScan results. miRDB_v6.0/miRDB_NM-miRNA.tsv, miRDB results. final_targets/Targets-miRNA.tsv, the union of TargetScan and miRDB results, and filterd by AGO2 CLIP-seq data (osteoblast). ''' argv = sys.argv if re.search('-H|-h', str(argv)): print(helpDoc) sys.exit() try: envDict = getArgvDict(argv) miRFile = envDict['-miRNA'] outDir = envDict['-outputDir'] except KeyError as e: print('ERROR: Incomplete or invalid arg '+str(e)+' ! Please check your input, or use -H/-h flag to get help.') sys.exit() else: tarScanScore = (envDict['-tarScanScore'] if envDict.get('-tarScanScore') else -0.2) miRDBScore = (envDict['-miRDBScore'] if envDict.get('-miRDBScore') else 60) if not os.path.exists(outDir): os.makedirs(outDir) outDir = (outDir if outDir[-1] == '/' else outDir + '/') if not os.path.exists(outDir+'TargetScan_v7.2'): os.makedirs(outDir+'TargetScan_v7.2') if not os.path.exists(outDir+'miRDB_v6.0'): os.makedirs(outDir+'miRDB_v6.0') if not os.path.exists(outDir+'final_targets'): os.makedirs(outDir+'final_targets') miRDBFile = './data/miRDB_v6.0_hsaOnly.txt' with open(miRFile, 'r') as f: miRList = f.readlines() for miR in miRList: miR = miR.strip() print('Predicting the targets of ' + str(miR) + '...') tarListTSC = GetTargetScan(miR, outDir, tarScanScore) tarListRDB = GetMiRDB(miR, miRDBFile, outDir, miRDBScore) GetFinalTarget(miR, tarListTSC, tarListRDB, outDir) localtime = time.asctime(time.localtime(time.time())) print('Done. Finish time: '+ localtime + '\n') <file_sep># Osteo-miRNA-Target-Prediction-Tool This is an easily-to-use tool for users to predict human osteoblast-specific target genes of human miRNA of interest. The TargetScan v7.2 and miRDB v6.0 are jointly used to form a putative targets pool with the given thresholds, the AGO2 CLIP-seq data is used to fliter false postive targets. User could just input a list of miRNA in local. Use the follow command to download: $ git clone https://github.com/WeiYang-BAI/Osteo-miRNA-Target-Prediction-Tool.git The miRDB data used in the tool was gziped, please unzip it before use: $ cd data $ gunzip miRDB_v6.0_hsaOnly.txt.gz Run the follow command to see the help message: $ cd .. $ python ./miRNA_Target_Prediction.py -H Arguments: -H/-h Show this help-doc. -miRNA The miRNAs list file , one miRNA per line. Please use the complete miRNA name, e.g. hsa-miR-218-5p. [-tarScanScore] Optional. The threshold of cumulative weighted context++ score in TargetScan v7.2 to filter results. The predicted target with the score great than this threshold will be filtered out. The value range is [-1, 0] (-1 means best prediction). The defult value is -0.2. [-miRDBScore] Optional. The threshold for prediction confidence in miRDB-V6.0 to filter results. The predicted target with the score lower than this threshold will be filtered out. The value range is [50, 100] (100 means best prediction). The defult value is 60. -outputDir A folder will be used to store results. An example is given, run it in the command line for details: $ sh example.sh Output folder/files into -outputDir: TargetScan_v7.2/TarScan-miRNA.tsv, prediction of TargetScan results. miRDB_v6.0/miRDB_NM-miRNA.tsv, prediction of miRDB results. final_targets/Targets-miRNA.tsv, the union of TargetScan and miRDB results, and filterd by AGO2 CLIP-seq data. <file_sep>#!/bin/sh python \ ./miRNA_Target_Prediction.py \ -miRNA ./example/example-miR.txt \ -tarScanScore -0.2 \ -miRDBScore 60 \ -outputDir ./example/prediction_results
f6439edddf6567e0753f5793428fe3aa84e4f046
[ "Markdown", "Python", "Shell" ]
3
Python
WeiYang-BAI/Osteo-miRNA-Target-Prediction-Tool
144b118653893c43eb00f8d1fc188cc3d9dd72fa
de1eee657f70e10c766d518e531f7a43ded4828d
refs/heads/master
<repo_name>OscarCode9/oscarCodePythonApi<file_sep>/userMode.sql CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstName VARCHAR(30) NOT NULL, lastName VARCHAR(30) NOT NULL, email VARCHAR(50), password varchar(150), username varchar(50) NOT NULL UNIQUE )<file_sep>/api.py from flask import Flask, request, jsonify, make_response from flask_sqlalchemy import SQLAlchemy import uuid import json import jwt import datetime import os from werkzeug.security import generate_password_hash, check_password_hash from sqlalchemy.ext.declarative import DeclarativeMeta from functools import wraps from validate_email import validate_email app = Flask(__name__) app.config['SECRET_KEY'] = 'thisismySewcretKay' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////home/oscarcode/Documents/pythonAPI/todo.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False from flaskext.mysql import MySQL mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = os.environ['MYSQL_DATABASE_USER'] app.config['MYSQL_DATABASE_PASSWORD'] = os.environ['MYSQL_DATABASE_PASSWORD'] app.config['MYSQL_DATABASE_DB'] = os.environ['MYSQL_DATABASE_DB'] app.config['MYSQL_DATABASE_HOST'] = os.environ['MYSQL_DATABASE_HOST'] mysql.init_app(app) db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.String(50), unique=True) name = db.Column(db.String(50)) password = db.Column(db.String(80)) admin = db.Column(db.Boolean) class Todo(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(50)) complete = db.Column(db.Boolean) user_id = db.Column(db.Integer) def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = None if 'x-access-token' in request.headers: token = request.headers['x-access-token'] if not token: return jsonify({'message': 'Token is missing'}), 401 try: data = jwt.decode(token, app.config['SECRET_KEY']) current_user = User.query.filter_by( public_id=data['public_id']).first() except: return jsonify({'message': 'Token is invalid'}) return f(current_user, *args, **kwargs) return decorated class AlchemyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj.__class__, DeclarativeMeta): # an SQLAlchemy class fields = {} for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']: data = obj.__getattribute__(field) try: # this will fail on non-encodable values, like other classes json.dumps(data) fields[field] = data except TypeError: fields[field] = None # a json-encodable dict return fields return json.JSONEncoder.default(self, obj) # delete a user by username @app.route('/api/v1/user/<username>', methods=['DELETE']) def mysql_delete_one_user(username): conn = mysql.connect() cursor = conn.cursor() sql_query = """DELETE FROM Users WHERE username = %s""" r = cursor.execute(sql_query, (username)) if r == 1: conn.commit() conn.close() return jsonify({ 'message': 'A user has been deleted', 'error': False }) else: conn.close() return jsonify({ 'message': 'User hasn\'t been deleted, we can\'t find this user', 'error': True }) # get user by username @app.route('/api/v1/user/<username>', methods=['GET']) def mysql_get_one(username): conn=mysql.connect() cursor=conn.cursor() sql_query="""SELECT * FROM Users WHERE username = %s""" cursor.execute(sql_query, (username)) user=cursor.fetchone() if not user: return make_response(jsonify({ 'message': 'we can\'t find this user', 'error': True }), 404) user_object={} user_object['id']=user[0] user_object['firstName']=user[1] user_object['lastName']=user[2] user_object['email']=user[3] user_object['username']=user[5] conn.close() return jsonify({'user': user_object}) @app.route('/api/v1/user/<username>', methods=['PUT']) def mysql_update_one_user(username): conn = mysql.connect() cursor = conn.cursor() data=request.get_json() sql_query="""SELECT * FROM Users WHERE username = %s""" cursor.execute(sql_query, (username)) user=cursor.fetchone() if not user: return make_response(jsonify({ 'message': 'we can\'t find this user', 'error': True }), 404) sql_query = """ UPDATE Users SET firstName = %s, lastName = %s, email = %s, username = %s WHERE username = %s;""" firstName=data['firstName'] lastName=data['lastName'] email=data['email'] newusername=data['username'] cursor.execute(sql_query, (firstName, lastName, email, newusername, username)) sql_select_by_id="""SELECT * FROM Users WHERE username = %s """ cursor.execute(sql_select_by_id, (newusername)) user=cursor.fetchone() user_object={} if not user: return make_response(jsonify({ 'message': 'Error is the database', 'error': True }), 404) user_object['id']=user[0] user_object['firstName']=user[1] user_object['lastName']=user[2] user_object['email']=user[3] user_object['username']=user[5] conn.commit() conn.close() return jsonify({ 'user': user_object, 'message': 'This user has been updated', 'error': False }) @app.route('/api/v1/users', methods=['GET']) def mysql_get_all_users(): conn=mysql.connect() cursor=conn.cursor() cursor.execute("SELECT * from Users") users=cursor.fetchall() output=[] for user in users: user_data={} user_data['id']=user[0] user_data['firstName']=user[1] user_data['lastName']=user[2] user_data['email']=user[3] user_data['password']=user[4] user_data['username']=user[5] output.append(user_data) conn.close() return jsonify({'users': output}) @app.route('/api/v1/user', methods=['POST']) def mysql_create_user(): conn=mysql.connect() cursor=conn.cursor() data=request.get_json() sql_query="""INSERT INTO Users (id, firstName, lastname, email , password, username) VALUES (null,%s,%s,%s,%s,%s)""" hash_password=generate_password_hash(data['password'], method='sha256') firstName=data['firstName'] lastName=data['lastName'] email=data['email'] username=data['username'] is_email=validate_email(email) if not is_email: return make_response(jsonify({ 'message': 'Email is not validate', 'error': True }), 401) cursor.execute(sql_query, (firstName, lastName, email, hash_password, username)) sql_select_by_id="""SELECT * FROM Users WHERE username = %s """ cursor.execute(sql_select_by_id, (username)) user=cursor.fetchone() user_object={} if not all(user): return make_response(jsonify({ 'message': 'Error is the database', 'error': True }), 404) user_object['id']=user[0] user_object['firstName']=user[1] user_object['lastName']=user[2] user_object['email']=user[3] user_object['username']=user[5] conn.commit() conn.close() return jsonify({ 'user': user_object, 'message': 'A new user has been inserted in the datebase', 'error': False }) @app.route('/users', methods=['GET']) @token_required def get_all_users(current_user): if not current_user.admin: return jsonify({'message': 'Cannot perform that function!'}) users=User.query.all() output=[] for user in users: user_data={} user_data['public_id']=user.public_id user_data['name']=user.name user_data['password']=<PASSWORD> user_data['admin']=user.admin output.append(user_data) return jsonify({'users': output}) @app.route('/user/<public_id>', methods=['GET']) def get_one_user(public_id): user=User.query.filter_by(public_id=public_id).first() if not user: return jsonify({ 'message': 'No user found!' }) user_data={} user_data['public_id']=user.public_id user_data['name']=user.name user_data['password']=<PASSWORD> user_data['admin']=user.admin return jsonify({'user': user_data}) @app.route('/user', methods=['POST']) def create_user(): data=request.get_json() hash_password=generate_password_hash(data['password'], method='sha256') new_user=User(public_id=str(uuid.uuid4()), name=data['name'], password=<PASSWORD>, admin=False) db.session.add(new_user) db.session.commit() new_user=json.dumps(new_user, cls=AlchemyEncoder) return jsonify({'message': 'A new user has been created', 'user': new_user}) @app.route('/user/<public_id>', methods=['PUT']) def promote_user(public_id): data=request.get_json() user=User.query.filter_by(public_id=public_id).first() if not user: return jsonify({'message': 'No user found!'}) hash_password=generate_password_hash(data['password'], method='sha256') user.name=data['name'] user.password=<PASSWORD> user.admin=data['admin'] db.session.commit() return jsonify({'message': 'The user has been promoted!'}) @app.route('/user/<public_id>', methods=['DELETE']) def delete_user(public_id): user=User.query.filter_by(public_id=public_id).first() if not user: return jsonify({'message': 'No user found!'}) db.session.delete(user) db.session.commit() return jsonify({'message': 'The user has been deleted'}) @app.route('/login') def login(): auth=request.authorization if not auth or not auth.username or not auth.password: return make_response('Could no verify', 401, {'WWW-Authenticate': 'Basic realm="login required!"'}) user=User.query.filter_by(name=auth.username). first() if not user: return make_response('Could no verify', 401, {'WWW-Authenticate': 'Basic realm="login required!"'}) if check_password_hash(user.password, auth.password): token=jwt.encode({'public_id': user.public_id, 'exp': datetime.datetime.utcnow( ) + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY']) return jsonify({'token': token.decode('UTF-8')}) return make_response('Could no verify', 401, {'WWW-Authenticate': 'Basic realm="login required!"'}) if __name__ == '__main__': app.run(debug=True) <file_sep>/Readme.txt # sudo apt-get install python3-pip # sudo pip3 install Flask # sudo pip3 install flask_sqlalchemy
09c661dd64189890f0923278bbd92ef7cf3ffe34
[ "SQL", "Python", "Text" ]
3
SQL
OscarCode9/oscarCodePythonApi
c0875dde59316ade4f8c87b8a036be294b9df1f6
96c9bf6bbff99119953d7eca255fbdec9b53f144
refs/heads/master
<file_sep>puts "Which month of the year is your birthday in?" month = gets month = month.to_i if month < 0 puts "Hey! That's not even a month!" elsif month > 0 if month == 1 puts "Brr. Your birthday is in the winter." elsif month == 2 puts "Brr. Your birthday is in the winter." elsif month > 2 if month < 6 puts "Celebrate another year and the coming of warm weather." elsif month < 9 puts "Birthdays are best held outside in this weather." else if month > 11 if month <= 12 puts "Brr. Your birthday is in the winter." else puts "Hey! That's not even a month!" end else puts "The leaves are changing colour and you're celebrating." end end end else puts "Hey! That's not even a month!" end
f88f951b40979450fe11ada6ae109413bda78317
[ "Ruby" ]
1
Ruby
chrisnicola/llc-ruby
173bc2f1008802492af370c42399adf186e4e3a0
ceeb0c6bf407fa63396410b2f60a753bb1c97206
refs/heads/master
<file_sep># HackTJ This is the code that I used in our hackathon project, ExpressCheck. The code allowed me to create a grocery shopping reccomendation system to help shoppers. <file_sep>import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel df = pd.read_csv("/Users/Rohkal/Desktop/final_dataset.csv") textVector = TfidfVectorizer(stop_words="english") df["Description"] = df["Description"].fillna(" ") textVectorM = textVector.fit_transform(df["Description"]) similarity_score = linear_kernel(textVectorM, textVectorM) array_of_indices = pd.Series(df.index, index=df['Name']).drop_duplicates() def recommended_item(name, similarity_score=similarity_score): name.lower() index = array_of_indices[name] list_of_similar_items = list(enumerate(similarity_score[index])) list_of_similar_items = sorted(list_of_similar_items, key=lambda x: x[1], reverse=True) list_of_similar_items = list_of_similar_items[1:2] grocery_indices = [i[0] for i in list_of_similar_items] first_string = str(df['Name'].iloc[grocery_indices]) # print(first_string[7:]) second_string = str(df['Location'].iloc[grocery_indices]) # print(second_string[7:]) return first_string[5:] + "\n" + second_string[5:] def main(): fileIn = open("input.txt", "r") fileOut = open("output.txt", "w") for line in fileIn: if "\n" in line: line = line.replace("\n", "") fileOut.write(str(line) + ", ") fileOut.write("" + str(recommended_item(line))) fileOut.write("\n") fileOut.close() fileA = open("output.txt", "r") lines = fileA.readlines() fileA.close() fileA = open("output.txt", "w") for line in lines: if line != "Name: Location, dtype: object" + "\n": fileA.write(line) fileA = open("output.txt", "r") lines = fileA.readlines() fileA.close() fileA = open("output.txt", "w") for line in lines: if line != "Name: Name, dtype: object" + "\n": fileA.write(line) if __name__ == "__main__": main()
f7b0c65dc880129ca91f0ad2b5b2ec434e39a348
[ "Markdown", "Python" ]
2
Markdown
rohkalra/HackTJ
0becafc4ac38572f90a999c5d299f968848d63de
60892d1b6eb10e22c1a68b2a4a86959ceb395930
refs/heads/master
<file_sep>#!/usr/bin/env python3 import click from Crypto.PublicKey import RSA import base64 import pyotp import qrcode import qrcode.image.svg import requests from urllib import parse from urllib.parse import urlparse # this function is from https://github.com/WillForan/duo-hotp def qr_url_to_activation_url(qr_url): "Create request URL" # get ?value=XXX data = parse.unquote(qr_url.split("?value=")[1]) # first half of value is the activation code code = data.split("-")[0].replace("duo://", "") # second half of value is the hostname in base64 hostb64 = data.split("-")[1] # Same as "api-e4c9863e.duosecurity.com" host = base64.b64decode(hostb64 + "=" * (-len(hostb64) % 4)) # this api is not publicly known activation_url = "https://{host}/push/v2/activation/{code}".format( host=host.decode("utf-8"), code=code ) print(activation_url) return activation_url def get_secret(activation_uri): if "frame/qr" in activation_uri: activation_uri = qr_url_to_activation_url(activation_uri) parsed = urlparse(activation_uri) subdomain = parsed.netloc.split(".")[0] host_id = subdomain.split("-")[-1] slug = parsed.path.split("/")[-1] headers = { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Host": f"api-{host_id}.duosecurity.com", "Connection": "Keep-Alive", "Accept-Encoding": "gzip", "User-Agent": "okhttp/4.0.0", } params = {"customer_protocol": "1"} data = { "touchid_status": "not_supported", "jailbroken": False, "architecture": "arch64", "region": "US", "app_id": "com.duosecurity.duomobile", "full_disk_encryption": True, "passcode_status": True, "platform": "Android", "pkpush": "rsa-sha512", "pubkey": RSA.generate(2048).publickey().export_key().decode(), "app_version": "3.28.1", "app_build_number": 328104, "version": "9.0.0", "manufacturer": "Samsung", "language": "en", "model": "Samsung Smart Fridge", "security_patch_level": "2019-07-05", } address = f"https://{parsed.netloc}/push/v2/activation/{slug}" request = requests.post(address, headers=headers, params=params, data=data) request.raise_for_status() hotp_secret = request.json()["response"]["hotp_secret"] return base64.b32encode(hotp_secret.encode()) @click.command() @click.argument("activation-uri") @click.option("--output-file") def duolibre(activation_uri, output_file): secret = get_secret(activation_uri) print(f"Fetched secret: {secret}") hotp = pyotp.hotp.HOTP(secret) uri = hotp.provisioning_uri("Duolibre", initial_count=1) print(f"Provisioning URI is: {uri}") if output_file: factory = qrcode.image.svg.SvgPathImage image = qrcode.make(uri, image_factory=factory) image.save(output_file) print(f"Wrote provisioning QR code to {output_file}") else: print("No output file specified, printing QR code to terminal...") qr = qrcode.QRCode() qr.add_data(uri) qr.print_tty() if __name__ == "__main__": duolibre() <file_sep># Duolibre Duolibre lets you authenticate to Duo 2FA systems without the proprietary Duo Mobile app. It forges an activation request from Duo Mobile to Duo's servers and hands the resulting HOTP secret over to you. You can use this secret to generate HOTP codes programmatically, or import it into the two-factor authenticator of your choice; for Android users, I recommend [Aegis](https://f-droid.org/app/com.beemdevelopment.aegis) or [FreeOTP+](https://f-droid.org/app/org.liberty.android.freeotpplus) from F-Droid. Note that Duolibre doesn't provide a reverse-engineered alternative to Duo Push, so you'll have to use one-time passwords. ## Getting started Install from PyPI: ``` pip install --user duolibre ``` Run Duolibre against the activation URL that was sent to your phone via SMS, or the URL of the QR code displayed on the web interface: ``` duolibre https://m-XXXXXXXX.duosecurity.com/android/XXXXXXXXXXXXXXXXXXXX ``` If you'd rather save the generated provisioning QR code to an SVG file instead of printing it to the terminal, pass `--output-file`: ``` duolibre https://m-XXXXXXXX.duosecurity.com/android/XXXXXXXXXXXXXXXXXXXX --output-file ./qr-code.svg ``` ## Background The Duo Mobile app [collects](https://help.duo.com/s/article/2939?language=en_US) a considerable amount of analytics data from its users. Privacy-conscious folks and those who simply do not wish to run proprietary software on their phones should have a way to opt-out without special intervention from their organization. Duolibre makes it easy to use an alternative authenticator that's more respectful of one's privacy and freedoms. I developed Duolibre by man-in-the-middling communication between the Duo Mobile client and Duo's servers. Duo Mobile for Android implements certificate pinning to defend against this reverse-engineering technique, but I was able to circumvent that using the Xposed module [JustTrustMe](https://github.com/Fuzion24/JustTrustMe). ## Usage ``` Usage: duolibre [OPTIONS] ACTIVATION_URI Options: --output-file TEXT --help Show this message and exit. ``` ## License [The Unlicense](https://unlicense.org) <file_sep>click pycryptodome pyotp qrcode requests <file_sep>#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name="duolibre", version="1.0.1", description="Authenticate to Duo 2FA systems without the proprietary Duo Mobile app", url="https://github.com/evan-goode/duolibre", author="<NAME>", author_email="<EMAIL>", license="The Unlicense", install_requires=["Click", "pycryptodome", "pyotp", "qrcode", "requests"], packages=find_packages(), entry_points={"console_scripts": ["duolibre=duolibre.duolibre:duolibre"]}, )
ad7b8a5661e3e186c5258c0c58c8991d101558f3
[ "Markdown", "Python", "Text" ]
4
Python
evan-goode/duolibre
736ce53288d3277bb10a57a9622cbcde3a5296d6
5db213400c51eafa9309f09148ee7060a6fe799e
refs/heads/master
<repo_name>biodataprog/GEN220_2019_examples<file_sep>/Bioinformatics_2/parse_orthofinder.py #!/usr/bin/env python3 import csv orthogroups = "Orthogroups.csv" groups = {} with open(orthogroups,"r") as ortho, open("Orthogroups_counts.tab","w") as ogout: rdr = csv.reader(ortho,delimiter="\t") wrt = csv.writer(ogout,delimiter="\t") header = next(rdr) header[0] = "FAMILY" wrt.writerow(header) for row in rdr: name = row[0] # initialize a row 0s -with as many cols as we need # its -1 because the first col in the row is the name # of the ortholog group groups[name] = [0] * (len(row)-1) for i in range(1,len(row)): col = row[i] genes = col.split(", ") groups[name][i-1] = 0 for gene in genes: if len(gene): groups[name][i-1] += 1 wrt = csv.writer(ogout,delimiter="\t") for group in groups: row = [group] row.extend(groups[group]) wrt.writerow(row) <file_sep>/Bioinformatics_5/plot_lengths.R transposons = read.csv("transposon.tab",sep="\t",header=TRUE) summary(transposons) mRNAs = read.csv("mRNA.tab",sep="\t",header=TRUE) summary(mRNAs) hist(transposons$Length,100,main="Histogram of TE lengths") hist(log(mRNAs$Length),100,main="Histogram of mRNA lengths") boxplot(mRNAs$Length) boxplot(transposons$Length) short = subset(mRNAs,mRNAs$Length < 10000) summary(short) boxplot(short$Length) <file_sep>/Python_2/species_count.py import csv datafile = 'species.csv' genera = {} with open(datafile,"r") as fh: reader = csv.reader(fh,delimiter=",") header = next(reader) # take the first line off for row in reader: key = row[1] if key == "": # skip an entry that is empty continue if key in genera: genera[key] += 1 else: genera[key] = 1 for genus in genera: print(genus,genera[genus]) <file_sep>/Python_4/parse_fasta.py #!/usr/bin/env python3 import sys import Bio from Bio import SeqIO from Bio.Seq import Seq # seqfile filename = "/bigdata/gen220/shared/data/E3Q6S8.fasta" # alternatively the file is located in this folder filename = "E3Q6S8.fasta" for seq_record in SeqIO.parse( filename , "fasta"): print(seq_record.id) print(repr(seq_record.seq)) print(seq_record.seq) print(len(seq_record)) <file_sep>/Bioinformatics_1/run.sh #!/usr/bin/bash #SBATCH --ntasks 8 --mem 8G module load ncbi-blast module load orthofinder module load miniconda2 CPU=8 mkdir -p cyanobacteria cd cyanobacteria #curl -L -O ftp://ftp.ensemblgenomes.org/pub/bacteria/release-45/fasta/bacteria_10_collection/oscillatoriales_cyanobacterium_jsc_12/pep/Oscillatoriales_cyanobacterium_jsc_12.ASM30994v1.pep.all.fa.gz #curl -L -O ftp://ftp.ensemblgenomes.org/pub/bacteria/release-45/fasta/bacteria_0_collection/nostoc_punctiforme_pcc_73102/pep/Nostoc_punctiforme_pcc_73102.ASM2002v1.pep.all.fa.gz #curl -L -O ftp://ftp.ensemblgenomes.org/pub/bacteria/release-45/fasta/bacteria_4_collection/cyanobacterium_aponinum_pcc_10605/pep/Cyanobacterium_aponinum_pcc_10605.ASM31767v1.pep.all.fa.gz for file in *.fa.gz do m=$(basename $file .pep.all.fa.gz) pigz -dc $file > $m.fasta done cd .. orthofinder.py -a $CPU -f cyanobacteria <file_sep>/Python_4/url_parse_direct.py #!/usr/bin/env python3 from urllib.request import urlopen from io import TextIOWrapper from Bio import SeqIO url="https://www.uniprot.org/uniprot/P10127.fasta" handle = TextIOWrapper(urlopen(url)) sequences = SeqIO.parse(handle, "fasta") for seq in sequences: print("seq is ",seq.id, " ", seq.seq) <file_sep>/README.md # GEN220_2019_examples Examples from class <file_sep>/Python_4/parse_gff.py #!/usr/bin/env python3 import os gffurl="https://fungidb.org/common/downloads/release-45/ScerevisiaeS288c/gff/data/FungiDB-45_ScerevisiaeS288c.gff" in_file = os.path.basename(gffurl) if not os.path.exists(in_file): os.system("curl -O "+gffurl) from BCBio import GFF limit_info = dict( gff_id = ["BK006934"], gff_type = ["CDS"], gff_source = ["EuPathDB"]) in_handle = open(in_file) for rec in GFF.parse(in_handle, limit_info=limit_info): for feat in rec.features: print(feat) break in_handle.close() in_handle = open(in_file) for rec in GFF.parse(in_handle): for feat in rec.features: print(feat) break in_handle.close() <file_sep>/Bioinformatics_8/run_bwa.sh #!/usr/bin/bash #SBATCH -p short -N 1 -n 8 --mem 8gb module load bwa module load samtools CPU=16 mkdir -p fastq ln -s /bigdata/gen220/shared/data/S_enterica/*.fastq.gz fastq ln -s /bigdata/gen220/shared/data/S_enterica/S_enterica_CT18.fasta ln -s /bigdata/gen220/shared/data/S_enterica/acc.txt GENOME=S_enterica_CT18.fasta if [ ! -f $GENOME.sa ]; then bwa index $GENOME fi for acc in $(cat acc.txt) do FWDREAD=fastq/${acc}_1.fastq.gz REVREAD=fastq/${acc}_2.fastq.gz bwa mem -t $CPU $GENOME $FWDREAD $REVREAD > ${acc}.sam samtools fixmate -O bam ${acc}.sam ${acc}_fixmate.bam samtools sort --threads $CPU -O BAM -o ${acc}.bam ${acc}_fixmate.bam samtools index ${acc}.bam done <file_sep>/Python_5/regex_2.py #!/usr/bin/env python3 import re text=[ "ABC\t10..30", "ABC 30..40"] for r in text: m = re.match(r'(\S+)\s+(\S+)',r) if m: print("\t".join([m.group(1),m.group(2)])) <file_sep>/Bioinformatics_5/plot_lengths.Rmd ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r TEs} transposons = read.csv("transposon.tab",sep="\t",header=TRUE) summary(transposons) mRNAs = read.csv("mRNA.tab",sep="\t",header=TRUE) summary(mRNAs) ``` ## Including Plots You can also embed plots, for example: ```{r plots, echo=FALSE} hist(transposons$Length,100,main="Histogram of TE lengths") hist(log(mRNAs$Length),100,main="Histogram of mRNA lengths") boxplot(mRNAs$Length) boxplot(transposons$Length) short = subset(mRNAs,mRNAs$Length < 10000) summary(short) boxplot(short$Length) ``` ```{r genelens, echo=FALSE} fungi = read.csv("fungi_genome_stats.csv",header=TRUE,sep=",") #summary(fungi) plot(fungi$GENOME_SIZE,fungi$GC) cor(fungi$GENOME_SIZE,fungi$GC) plot(fungi$GENOME_SIZE,fungi$mRNA.mean) ```<file_sep>/Bioinformatics_5/seq_lengths.py #!/usr/bin/env python3 import sys from Bio import SeqIO from Bio.Seq import Seq # seqfile if len(sys.argv) != 2: print("argument should be\n","sequence_length.py FILE.fasta") exit() filename = sys.argv[1] print("%s\t%s"%("Name","Length")) for seq_record in SeqIO.parse( filename , "fasta"): print("%s\t%d"%(seq_record.id,len(seq_record))) <file_sep>/Bioinformatics_5/download_worm_seqs.sh #!/usr/bin/bash curl -L ftp://ftp.wormbase.org/pub/wormbase/species/c_elegans/sequence/transcripts/c_elegans.PRJNA13758.WS260.transposon_transcripts.fa.gz > transposon.fa.gz curl -L ftp://ftp.wormbase.org/pub/wormbase/species/c_elegans/sequence/transcripts/c_elegans.PRJNA13758.WS260.mRNA_transcripts.fa.gz > mRNA.fa.gz gunzip *.gz <file_sep>/Bioinformatics_3/run_kallisto.sh #!/usr/bin/bash #SBATCH -p short -N 1 -n 8 module load kallisto mkdir -p output if [ ! -f Scer.idx ]; then kallisto index -i Scer.idx S_cerevisiae.fasta fi cat samples.tsv | while read ACC COND REP do OUT=output/$COND.$REP kallisto quant -t 8 --single -l 300 -s 20 -i Scer.idx -o $OUT data/${ACC}_1.fastq.gz # if paired end # kallisto quant -t 8 -i Scer.idx -o $OUT data/${ACC}_1.fastq.gz data/${ACC}_2.fastq.gz done <file_sep>/Python_1/gene_name_processing.py #!/usr/bin/python # test strings with the gene name in them gene1 = "Atchr12gene6" gene2 = "Atchr3gene4" match_length = len("chr") print("substring length is ",match_length) start_cut = gene1.find("chr") + match_length end_cut = gene1.find("gene") chrom = gene1[start_cut:end_cut] print "the chrom for", gene1, "is", chrom start_cut = gene2.find("chr") + match_length end_cut = gene2.find("gene") chrom = gene2[start_cut:end_cut] print("the chrom for",gene2,"is",chrom) <file_sep>/Python_2/fasta_count_seqs_codons.py import itertools, sys, re # define what a header looks like in FASTA format def isheader(line): return line[0] == '>' def aspairs(f): seq_id = '' sequence = '' for header,group in itertools.groupby(f, isheader): if header: line = next(group) seq_id = line[1:].split()[0] else: sequence = ''.join(line.strip() for line in group) yield seq_id, sequence filename="/bigdata/gen220/shared/data_files/S_cerevisiae_ORFs.fasta" #filename="S_cerevisiae_ORFs.fasta" with open(filename,"r") as f: seqs = dict(aspairs(f)) first_codon = {} last_codon = {} sequence_count = 0 strand_count = {} for seqname in seqs: sequence_count += 1 firstcodon = seqs[seqname][0:3] lastcodon = seqs[seqname][-3:] if firstcodon in first_codon: first_codon[firstcodon] +=1 else: first_codon[firstcodon] = 1 if lastcodon in last_codon: last_codon[lastcodon] +=1 else: last_codon[lastcodon] = 1 # print(firstcodon,lastcodon) last_char = seqname[-1] # print(last_char, " in ", seqname) if last_char in strand_count: strand_count[last_char] += 1 else: strand_count[last_char] = 1 print("1.") print("There are %d sequences in the file"%(sequence_count)) print("2.") print("The distribution of first codons is:") for codon in first_codon: print("%s => %d (%.1f%%)" % (codon, first_codon[codon], 100.0 * first_codon[codon] / sequence_count)) print("The distribution of last codons is:") for codon in last_codon: print("%s => %d (%.1f%%)" % (codon, last_codon[codon], 100.0 * last_codon[codon] / sequence_count)) print("There are %s genes on the Watson (+) strand"%(strand_count['W'])) print(" %s genes on the Crick (-) strand"%(strand_count['C'])) print("3.") print("There are %s genes on the Watson (+) strand"%(strand_count['W'])) print(" %s genes on the Crick (-) strand"%(strand_count['C'])) <file_sep>/Python_1/list_ofList.py #!/usr/bin/python matrix = [ [ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8] ] print(matrix) print(matrix[2]) print(matrix[2][0]) <file_sep>/Bioinformatics_4/search_SOD1.sh #!/usr/bin/bash #SBATCH -p short -N 1 -n 4 module load hmmer module load db-pfam QUERY=query_SOD1.fa OUT=SOD1_search.hmmscan hmmscan --cut_ga --cpu 4 --domtbl SOD1_search.domtbl $PFAM_DB/Pfam-A.hmm $QUERY > SOD1_search.hmmscan <file_sep>/Bioinformatics_2/parse_blast.py #!/usr/bin/env python3 import re from Bio import SeqIO protein_file = "E_coli_K12.pep" blast_file = "Ecoli-vs-Senterica.BLASTP.tab" seqlengths = {} # the BLAST columns are documented for the default columns that come out of tabular format (-m9/-m8) # http://www.pangloss.com/wiki/Blast # this function returns just the accession number from a long # sequence name like gi|1234|ref|YP_1234.1| def clean_name(id): split_name = id if re.search(r'\|',id): split_name = id.split("|") return split_name[3] # with open(protein_file, "r") as handle: for record in SeqIO.parse(handle, "fasta"): # print(record.id) seqlengths[record.id] = len(record) # REMEMBER we could get the sequence in this record # like this: # record[22:712] # print(record.id,len(record)) # break print("there are %d sequences stored"%(len(seqlengths))) # this is the headers for the output file print("\t".join(["QUERY","SUBJECT","PERCENT_ALIGNED","PERCENT_ID"])) with open(blast_file,"r") as blast: for line in blast: row = line.strip().split("\t") qname = row[0] # query name is in slot 0 hname = row[1] # hit/subject name percent_id = row[2] # percent ID col query_aln_start = row[6] # query start align is in 6 query_aln_end = row[7] # "" in slot 7 query_aln_len = int(row[7]) - int(row[6]) + 1 frac_query_aln = query_aln_len / seqlengths[qname] # print(row[0],row[10]) # print(row) print("\t".join([clean_name(qname),clean_name(hname), "%.2f"%(frac_query_aln * 100), percent_id ])) <file_sep>/Python_5/regex_1.py #!/usr/bin/env python3 import re pat = re.compile(r'>([^\|]+)\|([^\|]+)\|gi\|(\d+)\s+GENE=(\S+)\s+DESC=\"([^\"]+)\"') with open("sequences.fas","r") as fh: for line in fh: if line.startswith(">"): m = pat.match(line) print(line.strip()) if m: species=m.group(1) acc =m.group(2) gi =m.group(3) gene =m.group(4) Desc =m.group(5) print("species = ",species) print("accession = ",acc) print("gi. = ",gi) print("Gene name = ",gene) print("Desc is. = '{}'".format(Desc)) <file_sep>/Python_4/url_parse.py #!/usr/bin/env python3 import urllib.request url="https://www.uniprot.org/uniprot/P10127.fasta" seqdata = urllib.request.urlopen(url) for line in seqdata: linestrip = line.decode('UTF-8').strip() print(linestrip) <file_sep>/Python_4/use_dictionary.py #!/usr/bin/env python3 from Bio import SeqIO infile="/bigdata/gen220/shared/data/vector" handle = open(infile, "rU") record_dict = SeqIO.to_dict(SeqIO.parse(handle, "fasta")) print(record_dict.keys) handle.close() print(record_dict["gi|1052556|emb|Z50149.1|"]) #use any record ID <file_sep>/Bioinformatics_2/download_2.sh curl -O https://biodataprog.github.io/GEN220/Bioinformatics/data/Orthogroups.csv <file_sep>/Bioinformatics_2/download.sh curl -O https://biodataprog.github.io/GEN220/Bioinformatics/data/E_coli_O157_H7.pep.gz curl -O https://biodataprog.github.io/GEN220/Bioinformatics/data/E_coli_K12.pep.gz curl -O https://biodataprog.github.io/GEN220/Bioinformatics/data/S_enterica.pep.gz curl -O https://biodataprog.github.io/GEN220/Bioinformatics/data/Ecoli-vs-Senterica.BLASTP.tab.gz gunzip *.gz <file_sep>/Python_3/regex1.py #!/usr/bin/env python import re m = re.search("((AB)+)C.{2}","BLAHABABABCDED") if m: print("Group 0",m.group(0)) print("Group 1",m.group(1)) print("Group 2",m.group(2)) <file_sep>/Python_2/exon_stats.py #!/usr/bin/env python filename="/bigdata/gen220/shared/simple/rice_random_exons.bed" with open(filename,"r") as fh: exon_count = 0 total_exon_length = 0 for line in fh: list = line.strip().split("\t") # print(list) start = int(list[1]) # convert string to number with int() end = int(list[2]) exonlen = end - start + 1 exon_count += 1 total_exon_length += exonlen # print(exonlen) print("There are",exon_count, "exons, and",total_exon_length,"coding bases") <file_sep>/Bioinformatics_4/search_Cgla.sh #!/usr/bin/bash #SBATCH -p short -N 1 -n 24 module load hmmer module load db-pfam QUERY=/bigdata/gen220/shared/data/C_glabrata_ORFs.pep OUT=Cgla_search hmmscan --cut_ga --cpu 24 --domtbl $OUT.domtbl $PFAM_DB/Pfam-A.hmm $QUERY > $OUT.hmmscan <file_sep>/Bioinformatics_8/run_bcftools.sh #!/usr/bin/bash #SBATCH -p batch -N 1 -n 4 --mem 16gb module unload perl module load samtools module load bcftools GENOME=S_enterica_CT18.fasta # need to make a string which is all the bam files you want to process # but if we do *.bam it will catch the intermediate bam files that are in the folder for a in $(cat acc.txt) do m="$a.bam $m" done VCF=Salmonella.vcf.gz FILTERED=Salmonella.filtered.vcf.gz LOWQUAL="FAIL" bcftools mpileup -Ou -f $GENOME $m | bcftools call --ploidy 1 -vmO z -o $VCF tabix -p vcf $VCF bcftools stats -v -F $GENOME -s - $VCF > $VCF.stats mkdir -p plots plot-vcfstats -p plots/ $VCF.stats bcftools filter -O z -o $FILTERED -s $LOWQUAL -i'%QUAL>10' $VCF <file_sep>/Python_4/convert.py #!/usr/bin/env python3 from Bio import SeqIO input_handle = open("cor6_6.gbk", "rt") output_handle = open("cor6_6.fasta", "w") sequences = SeqIO.parse(input_handle, "genbank") count = SeqIO.write(sequences, output_handle, "fasta") output_handle.close() input_handle.close() <file_sep>/Python_4/parse_genbank.py #!/usr/bin/env python3 import sys import Bio from Bio import SeqIO from Bio.Seq import Seq # seqfile filename = "/bigdata/gen220/shared/data/AJ240084.gbk" # alternatively the file is in this folder filename = "AJ240084.gbk" for seq_record in SeqIO.parse( filename , "genbank"): print(seq_record.id) print(repr(seq_record.seq)) print(seq_record.seq) print(len(seq_record)) <file_sep>/Bioinformatics_3/README.md You will need to do: ``` ln -s /bigdata/gen220/shared/data-examples/rnaseq/kallisto/data ln -s /bigdata/gen220/shared/data-examples/rnaseq/yeast_genome/S_cerevisiae.gff3 ln -s /bigdata/gen220/shared/data-examples/rnaseq/yeast_genome/S_cerevisiae.fasta ln -s /bigdata/gen220/shared/data-examples/rnaseq/yeast_genome/S_cerevisiae.ORFs.fasta ```
6eb42cc13d2fa09b5df0831b843cf1ee0843417a
[ "Markdown", "Python", "R", "RMarkdown", "Shell" ]
31
Python
biodataprog/GEN220_2019_examples
0756569a8cc855341b1bfa85a8d14fce19be22d8
b6ef70fbf4d1169a0cc12a1ca74b2c70ff9af7fe
refs/heads/main
<repo_name>ishani1124/gfg<file_sep>/array/appearsOnce.cpp /* Find the element that appears once Given a sorted array A[] of N positive integers having all the numbers occurring exactly twice, except for one number which will occur only once. Find the number occurring only once. */ #include <bits/stdc++.h> using namespace std; class Solution{ public: int search(int A[], int N){ int res=0; for(int i=0;i<N;i++) res = res^A[i]; return res; } }; int main() { int t,len; cin>>t; while(t--) { cin>>len; int arr[len]; for(int i=0;i<len;i++){ cin>>arr[i]; } Solution ob; cout<<ob.search(arr, len)<<'\n'; } return 0; }
8dd79378c518bac1864cddfa9012851e7374ad9d
[ "C++" ]
1
C++
ishani1124/gfg
78cf3509ff46306724df746107e2d06e30baa70c
5e2bc59982ffba3669b9981e6c6e6118b9fbb8e2
refs/heads/master
<file_sep>var server = require('karma-server-side') var expect = require('chai').expect var isBrowser = !require('is-node') function isSupportedBrowser () { if (isBrowser) { var browser = require('detect-browser') if (browser.name === 'ie' && parseInt(browser.version.match(/(\d+)./)[1]) <= 10) { return false } return true } } if (isSupportedBrowser()) { testMount('angular', require('./app/angular'), require('../angular')) testMount('hyperdom', new (require('./app/hyperdom'))(), require('../hyperdom')) testMount('react', new (require('./app/react'))(), require('../react')) context('iframe', () => { var app before(() => { return server.run(function () { var express = serverRequire('express') // eslint-disable-line app = express() app.get('/', (req, res) => { res.send(`<form action="/iframe-test/click"> <button type="submit">press me</button> <div class="message">default</div> </div>`) }) app.get('/click', (req, res) => { res.send('<div class="message">hello browser-monkey</div>') }) var self = this return new Promise(function (resolve) { self.server = app.listen(4572, function () { resolve() }) }) }) }) after(() => { return server.run(function () { var self = this return new Promise(function (resolve) { self.server.close(resolve) }) }) }) testMount('iframe', window.location.origin + '/iframe-test/', require('../iframe')) }) } function testMount (appType, app, monkeyBuilder) { describe(`mount ${appType}`, () => { var monkey beforeEach(() => { monkey = monkeyBuilder(app) }) afterEach(() => monkey.get('mount').stop()) it('loads some data', () => { return monkey.find('.message').shouldHave({text: 'default'}).then(() => { return monkey.find('button').click() }).then(() => { return monkey.find('.message').shouldHave({text: 'hello browser-monkey'}) }) }) it('exposes the app', () => { expect(monkey.get('app')).to.equal(app) }) }) }
df8925a4f7fe91a3c54bad4d82f02dc05895c14d
[ "JavaScript" ]
1
JavaScript
esme-noodle/browser-monkey
cea7cdc06ade89b13fa7918457b3ab461865c169
1fab982c5ce14ee09a4252c335ade3c0e3b6a03e
refs/heads/master
<file_sep>using System.Collections.Generic; using System.Linq; public class GradeSchool { private List<(int Year, string Name)> register = new List<(int, string)>(); public void Add(string student, int grade) { register.Add((grade, student)); register.Sort(); } public IEnumerable<string> Roster() { return register.Select(r => r.Name); } public IEnumerable<string> Grade(int grade) { return register.Where(r => r.Year == grade).Select(r => r.Name); } } <file_sep>const GIGASECOND_IN_MS = 10 ** 12; export const gigasecond = (moment) => { return new Date(moment.getTime() + GIGASECOND_IN_MS); }; <file_sep>using System; using System.Linq; public static class Hamming { public static int Distance(string firstStrand, string secondStrand) { if (firstStrand.Length != secondStrand.Length) { throw new ArgumentException("Strands must be the same length."); } return firstStrand.Zip(secondStrand).Count(pair => pair.First != pair.Second); } } <file_sep>LETTERS = ( (1, ('A','E','I','O','U','L','N','R','S','T')), (2, ('D','G')), (3, ('B','C','M','P')), (4, ('F','H','V','W','Y')), (5, 'K'), (8, ('J','X')), (10,('Q','Z')), ) TILES = {x:k for k,v in LETTERS for x in v} def score(word): """Compute the scrabble score for a word.""" return sum(TILES[x] for x in word.upper()) <file_sep>using System.Linq; using System.Text.RegularExpressions; public static class Acronym { public static string Abbreviate(string phrase) { MatchCollection result = Regex.Matches(phrase.ToUpper(), "[A-Z']+"); return string.Join("", result.Select(m => m.Value[0])); } } <file_sep>using System.Linq; public static class Bob { public static string Response(string statement) { if (statement.IsSilent()) { return "Fine. Be that way!"; } if (statement.IsShouted()) { return statement.IsQuestion() ? "Calm down, I know what I'm doing!" : "Whoa, chill out!"; } return statement.IsQuestion() ? "Sure." : "Whatever."; } private static bool IsSilent(this string statement) => string.IsNullOrWhiteSpace(statement); private static bool IsShouted(this string statement) => statement.Any(char.IsLetter) && !statement.Any(char.IsLower); private static bool IsQuestion(this string statement) => statement.TrimEnd().EndsWith('?'); } <file_sep>public static class BinarySearch { public static int Find(int[] input, int value) { var low = 0; var high = input.Length - 1; while (low <= high) { var middle = (low + high) / 2; var check = input[middle]; if (check == value) { return middle; } if (check < value) { low = middle + 1; } else { high = middle - 1; } } return -1; } } <file_sep>using System.Collections.Generic; public class SpaceAge { private const double EarthYear = 31557600; private readonly Dictionary<string, double> orbit = new Dictionary<string, double> { ["Mercury"] = 0.2408467, ["Venus"] = 0.61519726, ["Mars"] = 1.8808158, ["Jupiter"] = 11.862615, ["Saturn"] = 29.447498, ["Uranus"] = 84.016846, ["Neptune"] = 164.79132, }; private double earthYears; public SpaceAge(int seconds) { earthYears = seconds / EarthYear; } public int Seconds { set => earthYears = value / EarthYear; } public double OnEarth() => earthYears; public double OnMercury() => earthYears / orbit["Mercury"]; public double OnVenus() => earthYears / orbit["Venus"]; public double OnMars() => earthYears / orbit["Mars"]; public double OnJupiter() => earthYears / orbit["Jupiter"]; public double OnSaturn() => earthYears / orbit["Saturn"]; public double OnUranus() => earthYears / orbit["Uranus"]; public double OnNeptune() => earthYears / orbit["Neptune"]; } <file_sep>using System.Collections.Generic; using System.Linq; public static class MatchingBrackets { private const string OpeningBrackets = "{[("; private const string ClosingBrackets = "}])"; public static bool IsPaired(string input) { Stack<char> unpairedBrackets = new(); foreach (char character in input) { if (OpeningBrackets.Contains(character)) { unpairedBrackets.Push(character); } else if (ClosingBracketsContains(character, out int closingBracketIndex)) { if (BracketsMatch(closingBracketIndex, unpairedBrackets)) { unpairedBrackets.Pop(); } else { return false; } } } return !unpairedBrackets.Any(); } private static bool ClosingBracketsContains(char character, out int closingBracketIndex) { closingBracketIndex = ClosingBrackets.IndexOf(character); return closingBracketIndex != -1; } private static bool BracketsMatch(int closingBracketIndex, Stack<char> unpairedBrackets) { char openingBracket = OpeningBrackets[closingBracketIndex]; return unpairedBrackets.TryPeek(out char stackTop) && stackTop == openingBracket; } } <file_sep>import re U_LIST = r"(<li>.*</li>)" LIST_ITEMS = r"^\* (.*)" EMPHASIS = "_(.*)_" STRONG = "__(.*)__" HEADING_TYPES = ["#" * num for num in range(1, 7)] def parse(text): """Parse string with Markdown syntax and return HTML.""" for heading_type in HEADING_TYPES: n = len(heading_type) headings = f"^{heading_type} (.*)" text = re.sub(headings, fr"<h{n}>\1</h{n}>", text, flags=re.M) text = re.sub(STRONG, r"<strong>\1</strong>", text) text = re.sub(EMPHASIS, r"<em>\1</em>", text) text = re.sub(LIST_ITEMS, r"<li>\1</li>", text, flags=re.M) text = re.sub(U_LIST, r"<ul>\1</ul>", text, flags=re.S).splitlines() text = [x if "<h" in x or "<l" in x else f"<p>{x}</p>" for x in text] return "".join(text) <file_sep>using System; using System.Collections.Generic; using System.Linq; public static class NucleotideCount { private static readonly HashSet<char> NucleotideSymbols = new HashSet<char>("ACGT"); public static IDictionary<char, int> Count(string sequence) { var nucleotideCount = NucleotideSymbols.ToDictionary(c => c, c => 0); foreach (char nucleotide in sequence) { CheckNucleotideIsValid(nucleotide); nucleotideCount[nucleotide]++; } return nucleotideCount; } private static void CheckNucleotideIsValid(char nucleotide) { if (!NucleotideSymbols.Contains(nucleotide)) { throw new ArgumentException($"{nucleotide} is not a valid nucleotide."); } } } <file_sep>from re import findall def abbreviate(words): """Convert a phrase to its acronym.""" rx = r"(?:\b|(?<=_))(?<!')[^_\W]" return "".join(findall(rx, words.upper())) <file_sep>using System.Collections.Generic; using System.Linq; public static class ScrabbleScore { private static readonly Dictionary<char, int> Scores = new Dictionary<char, int> { ['A'] = 1, ['E'] = 1, ['I'] = 1, ['O'] = 1, ['U'] = 1, ['L'] = 1, ['N'] = 1, ['R'] = 1, ['S'] = 1, ['T'] = 1, ['D'] = 2, ['G'] = 2, ['B'] = 3, ['C'] = 3, ['M'] = 3, ['P'] = 3, ['F'] = 4, ['H'] = 4, ['V'] = 4, ['W'] = 4, ['Y'] = 4, ['K'] = 5, ['J'] = 8, ['X'] = 8, ['Q'] = 10,['Z'] = 10, }; public static int Score(string input) { return input.ToUpperInvariant().Sum(c => GetScore(c)); } private static int GetScore(char c) { return Scores.TryGetValue(c, out int val) ? val : 0; } } <file_sep>using System.Text; public static class RotationalCipher { public static string Rotate(string text, int shiftKey) { StringBuilder cipherText = new StringBuilder(); foreach (char c in text) { if (char.IsLetter(c)) { int start = char.IsLower(c) ? 'a' : 'A'; int final = (((c + shiftKey) - start) % 26) + start; cipherText.Append((char)final); } else { cipherText.Append(c); } } return cipherText.ToString(); } } <file_sep>using System; using System.Linq; public class Anagram { private readonly string wordUpper; private readonly string sortedWordUpper; public Anagram(string baseWord) { wordUpper = baseWord.ToUpper(); sortedWordUpper = SortString(baseWord); } public string[] FindAnagrams(string[] potentialMatches) { return potentialMatches .Where(p => p.ToUpper() != wordUpper) .Where(p => SortString(p) == sortedWordUpper) .ToArray(); } private string SortString(string word) { char[] chars = word.ToUpper().ToCharArray(); Array.Sort(chars); return new string(chars); } } <file_sep>using System; using System.Linq; [Flags] public enum Allergen : byte { Eggs = 0b_0000_0001, Peanuts = 0b_0000_0010, Shellfish = 0b_0000_0100, Strawberries = 0b_0000_1000, Tomatoes = 0b_0001_0000, Chocolate = 0b_0010_0000, Pollen = 0b_0100_0000, Cats = 0b_1000_0000, } public class Allergies { public Allergies(int mask) => Mask = mask; public int Mask { get; set; } public bool IsAllergicTo(Allergen allergen) { return (Mask & (byte)allergen) != 0; } public Allergen[] List() { return (from Allergen allergen in Enum.GetValues(typeof(Allergen)) where IsAllergicTo(allergen) select allergen).ToArray(); } } <file_sep>using System.Collections.Generic; using System.Linq; public static class Isogram { public static bool IsIsogram(string word) { var set = new HashSet<char>(); return word.ToLower().Where(char.IsLetter).All(set.Add); } } <file_sep>from re import findall from collections import Counter def count_words(sentence): """Count how many times each word occurs in a sentence.""" return Counter(findall("(?!')[a-z0-9']+(?<!')", sentence.lower())) <file_sep>from collections import defaultdict from operator import itemgetter HEADINGS = ("Team".ljust(30), "MP", " W", " D", " L", " P") SEP = " | " HEADER_ROW = SEP.join(HEADINGS) def tally(rows): """Tallies the results of a football competition.""" rows_split = split_rows(rows) individual_scores = convert_rows(rows_split) grouped_scores = group_scores(individual_scores) overall_stats = calculate_stats(grouped_scores) overall_stats = order_stats(overall_stats) return format_table(overall_stats) def split_rows(rows): for row in rows: yield row.split(";") def convert_rows(rows_split): """Converts rows into individual scores for each team.""" for team_one, team_two, result in rows_split: if result == "win": yield (team_one, 3) yield (team_two, 0) elif result == "draw": yield (team_one, 1) yield (team_two, 1) else: yield (team_one, 0) yield (team_two, 3) def group_scores(individual_scores): """Groups individual scores together by team.""" grouped_scores = defaultdict(list) for team, score in individual_scores: grouped_scores[team].append(score) for row in grouped_scores.items(): yield row def calculate_stats(grouped_scores): """Calculates team statistics based on grouped scores.""" overall_stats = [] for team, scores in grouped_scores: team_stats = [team.ljust(30)] # Team Name team_stats.extend( ( len(scores), # Matches Played scores.count(3), # Wins scores.count(1), # Draws scores.count(0), # Losses sum(scores), # Points ) ) overall_stats.append(team_stats) return overall_stats def order_stats(overall_stats): """ Sorts team statistics by points in descending order, and alphabetically if points are tied. """ overall_stats.sort() overall_stats.sort(key=itemgetter(5), reverse=True) for row in overall_stats: yield row def format_table(overall_stats): """Formats statistics into table with headings.""" formatted_table = [HEADER_ROW] for row in overall_stats: justified_text = (f"{element:2}" for element in row) formatted_row = SEP.join(justified_text) formatted_table.append(formatted_row) return formatted_table <file_sep>using System; using System.Collections.Generic; using System.Linq; public enum Plant { Violets, Radishes, Clover, Grass } public class KindergartenGarden { private static readonly string[] Names = { "Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry", }; private readonly Plant[] plantRowOne; private readonly Plant[] plantRowTwo; public KindergartenGarden(string diagram) { string[] diagramSplit = diagram.Split('\n'); plantRowOne = ConvertRow(diagramSplit[0]); plantRowTwo = ConvertRow(diagramSplit[1]); } public IEnumerable<Plant> Plants(string student) { int leftPlantPosition = Array.IndexOf(Names, student) * 2; int rightPlantPosition = leftPlantPosition + 1; yield return plantRowOne[leftPlantPosition]; yield return plantRowOne[rightPlantPosition]; yield return plantRowTwo[leftPlantPosition]; yield return plantRowTwo[rightPlantPosition]; } private static Plant[] ConvertRow(string row) { return row.Select(ConvertLetter).ToArray(); } private static Plant ConvertLetter(char letter) { return letter switch { 'V' => Plant.Violets, 'R' => Plant.Radishes, 'C' => Plant.Clover, 'G' => Plant.Grass, _ => throw new ArgumentException($"Invalid letter: {letter}."), }; } } <file_sep>BRACKETS = {"{": "}", "[": "]", "(": ")"} OPENING = set(BRACKETS) CLOSING = set(BRACKETS.values()) def is_paired(input_string): """Verify that bracket pairs are matched and nested correctly.""" unpaired = [] for char in input_string: if char in OPENING: unpaired.append(char) elif char in CLOSING: if not unpaired or BRACKETS[unpaired.pop()] != char: return False return not unpaired <file_sep># exercism-solutions My solutions to exercism.io coding exercises. <file_sep>STUDENTS = ( 'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry', ) PLANTS = { 'C': 'Clover', 'G': 'Grass', 'R': 'Radishes', 'V': 'Violets', } class Garden: """Class to represent a kindergarten garden.""" def __init__(self, diagram, students=STUDENTS): self.rows = diagram.split() kids = sorted(students) sets = zip(*([iter(self.rows[0])]*2 + [iter(self.rows[1])]*2)) self.cups = {s:p for s,p in zip(kids, sets)} def plants(self, student): """Returns the plants a student is responsible for.""" return [PLANTS[plant] for plant in self.cups[student]] def plants_all_students(self): """Returns all student plant responsibilities.""" return {s:[PLANTS[p] for p in self.cups[s]] for s in self.cups} def plants_in_row(self, row=1): """Returns all the plants present in a row.""" return [PLANTS[plant] for plant in self.rows[row-1]] def count_plant(self, plant='C'): """Returns how many times a plant has been planted.""" return (PLANTS[plant], sum(row.count(plant) for row in self.rows)) <file_sep>using System; using System.Collections.Generic; public class Robot { private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private const int MaximumNumberOfRobots = 675_000; private static readonly Random Rand = new Random(); private static HashSet<string> names = new HashSet<string>(); public Robot() { Reset(); } public string Name { get; private set; } public void Reset() { LimitNumberOfRobotNames(); do { GenerateRandomRobotName(); } while (!names.Add(Name)); } private void LimitNumberOfRobotNames() { if (names.Count > MaximumNumberOfRobots) { throw new InvalidOperationException( "Factory settings could not be applied " + "because it wasn't possible to generate " + "a new robot name. Please contact the " + "manufacturer for assistance."); } } private void GenerateRandomRobotName() { Name = Alphabet[Rand.Next(26)].ToString(); Name += Alphabet[Rand.Next(26)]; Name += Rand.Next(1000).ToString("D3"); } } <file_sep>class School: """Class to represent a school roster.""" def __init__(self): self._students = [] def add_student(self, name, grade): """Adds a student's grade and name to the school roster.""" if grade not in range(1, 8): raise ValueError("Grade can't be below 1 or above 7.") self._students.append((grade, name)) self._students.sort() def roster(self): """Returns the full roster for the school.""" return [name for grade, name in self._students] def grade(self, grade_number): """Returns the roster for a single grade.""" return [name for grade, name in self._students if grade == grade_number] <file_sep>day = ( "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth", ) end = ( "a Partridge in a Pear Tree", "two Turtle Doves", "three French Hens", "four Calling Birds", "five Gold Rings", "six Geese-a-Laying", "seven Swans-a-Swimming", "eight Maids-a-Milking", "nine Ladies Dancing", "ten Lords-a-Leaping", "eleven Pipers Piping", "twelve Drummers Drumming", ) def recite(start_verse, end_verse): """Output the lyrics to 'The Twelve Days of Christmas'.""" carol = [] for verse_num in range(start_verse, end_verse+1): gifts = (f"{', '.join(end[verse_num-1:0:-1])}, and {end[0]}" if verse_num-1 else end[0]) verse = (f"On the {day[verse_num-1]} day of Christmas " f"my true love gave to me: {gifts}.") carol.append(verse) return carol <file_sep>from typing import Iterator, List BOOK_COST = 800 DISCOUNTS = (1, .95, .9, .8, .75) PRICES = { size: BOOK_COST * discount * size for size, discount in zip(range(1, 6), DISCOUNTS) } def total(basket: List[int]) -> float: """ Calculates the lowest price of a shopping basket containing books from the same series. """ if (basket_size := len(basket)) == 1: return BOOK_COST book_group_sizes = configure(basket) if basket_size < 8: return cheapest_deal(book_group_sizes) replaced_sizes = replace(book_group_sizes) return cheapest_deal(replaced_sizes) def configure(basket: List[int]) -> Iterator[int]: """ Configures basket into groups of unique books, and yields the book group sizes. """ basket_copy = basket[:] while book_group := set(basket_copy): yield len(book_group) for book in book_group: basket_copy.remove(book) def replace(sizes: Iterator[int]) -> Iterator[int]: """ Replaces groups of three and five with two groups of four, which is cheaper. """ size_list = list(sizes) while {3, 5}.issubset(size_list): size_list.remove(3) size_list.remove(5) yield from (4, 4) yield from size_list def cheapest_deal(sizes: Iterator[int]) -> float: """Returns the cost of the cheapest deal.""" return sum(PRICES[size] for size in sizes) <file_sep>from collections import deque PARENS = ("(", ")") BRACKETS = ("[", "]") CHARS = ("", ";", " ", "\\", "\t") EMPTY, SEMICOLON, SPACE, SLASH, TAB = CHARS VALIDATION = { "tree": "tree missing", "node": "tree with no nodes", "delimiter": "properties without delimiter", "uppercase": "property must be in uppercase", } class SgfTree: def __init__(self, properties=None, children=None): self.properties = properties or {} self.children = children or deque() def __eq__(self, other): if not isinstance(other, SgfTree): return False for k, v in self.properties.items(): if k not in other.properties: return False if other.properties[k] != v: return False for k in other.properties.keys(): if k not in self.properties: return False if len(self.children) != len(other.children): return False for a, b in zip(self.children, other.children): if a != b: return False return True def __ne__(self, other): return not self == other def parse(input_string): """parse an SGF string and return a tree structure of properties.""" _validate_is_tree_with_node(input_string) stack = list(input_string) tree = SgfTree() prop = {} value = deque() is_value = False while stack: current = stack.pop() _validate_delimiters(value, is_value, current) if current in PARENS: continue elif current == SEMICOLON: _add_node(tree, prop) elif is_value and current != BRACKETS[0]: current = _replace_slashes_and_tabs(current) if current: _add_current_to_value(stack, value, current) elif current in BRACKETS: is_value = not is_value else: _validate_property_is_uppercase(current) _add_property(prop, value, current) return tree def _add_node(tree, prop): if not tree.properties: tree.properties = prop.copy() else: tree.children.appendleft(SgfTree(tree.properties)) tree.properties = prop.copy() prop.clear() def _replace_slashes_and_tabs(current): if current == SLASH: current = EMPTY elif current == TAB: current = SPACE return current def _add_current_to_value(stack, value, current): if stack and stack[-1] != BRACKETS[0] and value: value[0] = current + value[0] else: value.appendleft(current) def _add_property(prop, value, current): prop[current] = list(value) value.clear() def _validate_is_tree_with_node(input_string): if input_string in CHARS[:2]: raise ValueError(VALIDATION["tree"]) elif input_string == "".join(PARENS): raise ValueError(VALIDATION["node"]) def _validate_delimiters(value, is_value, current): if not value and not is_value and current.isalpha(): raise ValueError(VALIDATION["delimiter"]) def _validate_property_is_uppercase(current): if not current.isupper(): raise ValueError(VALIDATION["uppercase"]) <file_sep>class Luhn: """Class to represent an identification number checker.""" def __init__(self, card_num): self.card_num = card_num def valid(self): """Checks number validity as per the Luhn formula.""" number = self.card_num.replace(' ', '') if len(number) > 1 and number.isdigit(): return sum(self._parsed(number)) % 10 == 0 return False def _parsed(self, number): """Parses number's digits in reverse order.""" result = [] for idx, char in enumerate(reversed(number)): digit = int(char) if idx % 2 == 0: result.append(digit) continue digit += digit if digit < 9: result.append(digit) continue result.append(digit - 9) return result <file_sep>using System.Linq; public class Pangram { private const string Alphabet = "abcdefghijklmnopqrstuvwxyz"; public static bool IsPangram(string input) { return Alphabet.All(input.ToLower().Contains); } } <file_sep>using System; public struct Clock { private const int HoursInDay = 24; private const int MinsInHour = 60; public Clock(int hours, int minutes) { double quotient = Math.Floor((double)minutes / MinsInHour); Hours = Mod(hours + quotient, HoursInDay); Minutes = Mod(minutes, MinsInHour); } public int Hours { get; } public int Minutes { get; } public override string ToString() => $"{Hours:00}:{Minutes:00}"; public Clock Add(int minsToAdd) => new Clock(Hours, Minutes + minsToAdd); public Clock Subtract(int minsToSubtract) => Add(-minsToSubtract); private static int Mod(double amt, int un) => (((int)amt % un) + un) % un; } <file_sep>using System; using System.Collections.Generic; using System.Linq; public static class ProteinTranslation { public static string[] Proteins(string strand) { return Chunks(strand) .Select(Translate) .TakeWhile(protein => protein != "STOP") .ToArray(); } private static IEnumerable<string> Chunks(string strand) { if (strand.Length is var length && length % 3 != 0) { throw new ArgumentException($"Invalid strand length: {length}."); } for (int i = 0; i < length; i += 3) { yield return strand.Substring(i, 3); } } private static string Translate(string codon) { return codon switch { "AUG" => "Methionine", "UUC" or "UUU" => "Phenylalanine", "UUA" or "UUG" => "Leucine", "UCU" or "UCC" or "UCA" or "UCG" => "Serine", "UAU" or "UAC" => "Tyrosine", "UGU" or "UGC" => "Cysteine", "UGG" => "Tryptophan", "UAA" or "UAG" or "UGA" => "STOP", _ => throw new ArgumentException($"Invalid codon: {codon}."), }; } } <file_sep>def is_isogram(string): """Determine if word or phrase is isogram.""" return not any(string.lower().count(c) > 1 for c in string if c.isalpha()) <file_sep>def distance(strand_a, strand_b): """Calculate Hamming distance between DNA strands""" if len(strand_a) != len(strand_b): raise ValueError('Strands must be equal length') return sum(1 for a, b in zip(strand_a, strand_b) if a != b) <file_sep>from string import ascii_letters, punctuation INVALID_NUMBERS = {"0": "zero", "1": "one"} INVALID_PUNCTUATION = set(punctuation) - set("+.()-") INVALID_LETTERS = set(ascii_letters) VALIDATION = { "punctuation": "punctuations not permitted", "letters": "letters not permitted", "long": "more than 11 digits", "short": "incorrect number of digits", "country": "11 digits must start with 1", "code": "code cannot start with", } class PhoneNumber: """Class to validate and format American phone numbers.""" def __init__(self, phone_number): self.number = self._clean_number(phone_number) self.area_code = self.number[:3] self.exchange_code = self.number[3:6] self.subscriber = self.number[6:] def pretty(self): """Return formatted phone number.""" return f"({self.area_code})-{self.exchange_code}-{self.subscriber}" def _clean_number(self, phone_number): # Return cleaned number if it's valid self._validate_chars(phone_number) stripped = "".join(x for x in phone_number if x.isdigit()) length = len(stripped) self._validate_length(length) if length == 11: self._validate_country(stripped) stripped = stripped[1:] self._validate_codes(stripped) return stripped def _validate_chars(self, phone_number): # Raise error if phone number contains letters or invalid punctuation unique_chars = set(phone_number) if unique_chars & INVALID_PUNCTUATION: raise ValueError(VALIDATION["punctuation"]) if unique_chars & INVALID_LETTERS: raise ValueError(VALIDATION["letters"]) def _validate_length(self, length): # Raise error if phone number's length is invalid if length > 11: raise ValueError(VALIDATION["long"]) if length < 10: raise ValueError(VALIDATION["short"]) def _validate_country(self, stripped): # Raise error if phone number has invalid country code if not stripped.startswith("1"): raise ValueError(VALIDATION["country"]) def _validate_codes(self, stripped): # Raise error if area or exchange code starts with invalid digit first, _, _, fourth = stripped[:4] for digit, code_type in ((first, "area"), (fourth, "exchange")): if digit in INVALID_NUMBERS: raise ValueError( f"{code_type} {VALIDATION['code']} {INVALID_NUMBERS[digit]}" )
e6e82f6f3e7887917698ad99e506d73772aa3965
[ "JavaScript", "C#", "Python", "Markdown" ]
35
C#
jonboland/exercism-solutions
59047bc3fc9c64a1380f393fa5be31a9f7d7d166
7db073a9329efa83d9c7630d69d437ec61873fda
refs/heads/master
<repo_name>m42cococa/RepData_PeerAssessment1<file_sep>/PA1_template.Rmd --- title: "Reproducible Research: Peer Assessment 1" output: html_document: keep_md: true --- ## Loading and preprocessing the data This also includes loading dependent packages. ```{r} library(ggplot2); library(plyr); #Read activity file activity <- read.csv("./activity.csv");activity <- read.csv("./activity.csv"); #Activity_withoutNA has no NA records activity_wtna <- na.omit(activity,cols=("steps")); ``` ## What is mean total number of steps taken per day? ```{r} dsteps <- ddply(activity_wtna, .(date), summarize, steps=sum(steps)); hist(dsteps$steps,main="Histogram of total steps per day",xlab="Steps per day"); mean <- format(mean(dsteps$steps),digit=7); median <- median(dsteps$steps); ``` The mean when ignoring NA records is `r mean` The median when ignoring NA records is `r median` ## What is the average daily activity pattern? ```{r} #Summarize data isteps <- ddply(activity_wtna, .(interval), summarize, msteps=mean(steps,na.rm=TRUE)); #Plot time series plot(isteps$interval,isteps$msteps,type="l",xlab="Interval",ylab="Steps",main="Average number of steps by interval"); #Interval with the max avg steps across all days minterval <- isteps[isteps$msteps == max(isteps$msteps,na.rm=TRUE),]$interval; maxmsteps <- format(isteps[isteps$interval == minterval,]$msteps,digit=5); ``` The maximum interval is `r minterval` with `r maxmsteps` steps. ## Imputing missing values The code below use data frame merge to populate a msteps colum. The msteps (mean of steps for interval i) column populates the steps column if its value is NA. ```{r} # Count of NA values nrow(activity[is.na(activity$steps),]); #Fill NA by merging with isteps (average steps by interval) activity_backfill <- merge(activity,isteps); activity_backfill[is.na(activity_backfill$step),]$steps <- activity_backfill[is.na(activity_backfill$step),]$msteps; activity_backfill$msteps <- NULL; #Create histogram of daily steps dsteps_backfill <- ddply(activity_backfill, .(date), summarize, steps=sum(steps)); hist(dsteps_backfill$steps,main="Histogram of total steps per day",xlab="Steps per day"); mean_backfill <- format(mean(dsteps_backfill$steps),digit=7); median_backfill <- format(median(dsteps_backfill$steps),digit=7); ``` The mean when ignoring NA records is `r mean` The median when ignoring NA records is `r median` The mean with backfill of NA data is `r mean_backfill` The median with backfill of NA data is `r median_backfill` After backfill, the mean stays the same and the median increases slightly. ## Are there differences in activity patterns between weekdays and weekends? The code below use the qplot function of the ggplot2 package. I use the $day property of the POSIXlt object to test if the day is a Sunday (0) or a Saturday (6) and generate a factor column added to the activity dataframe. ```{r} # Create a boolean vector - TRUE means this is a week end Wend <- (as.POSIXlt(activity_backfill$date)$wday == 0 ) | (as.POSIXlt(activity_backfill$date)$wday == 6 ); Wend <- as.data.frame(Wend); #This function turn the boolen into either weekend or weekday Wdayend <- function(x) { if (x == TRUE) {return ("weekend")} else { return("weekday")} } #A column is added & converted into a factor activity_backfill$Wend <- apply(Wend,1,Wdayend); activity_backfill$Wend <- as.factor(activity_backfill$Wend); #Summarize data by interval and Wend column (factor with "weekend" and "weekday" values) isteps <- ddply(activity_backfill, .(interval,Wend), summarize, msteps=mean(steps,na.rm=TRUE)); #Plot time series qplot(interval,msteps,data=isteps,facets= Wend~., geom=c("line"), main="Comparison of mean steps by interval for Weekend and weekdays", ylab="Avg number of steps by interval"); ``` <file_sep>/PA1_template.md # Reproducible Research: Peer Assessment 1 ## Loading and preprocessing the data This also includes loading dependent packages. ```r library(ggplot2); library(plyr); #Read activity file activity <- read.csv("./activity.csv");activity <- read.csv("./activity.csv"); #Activity_withoutNA has no NA records activity_wtna <- na.omit(activity,cols=("steps")); ``` ## What is mean total number of steps taken per day? ```r dsteps <- ddply(activity_wtna, .(date), summarize, steps=sum(steps)); hist(dsteps$steps,main="Histogram of total steps per day",xlab="Steps per day"); ``` ![](PA1_template_files/figure-html/unnamed-chunk-2-1.png) ```r mean <- format(mean(dsteps$steps),digit=7); median <- median(dsteps$steps); ``` The mean when ignoring NA records is 10766.19 The median when ignoring NA records is 10765 ## What is the average daily activity pattern? ```r #Summarize data isteps <- ddply(activity_wtna, .(interval), summarize, msteps=mean(steps,na.rm=TRUE)); #Plot time series plot(isteps$interval,isteps$msteps,type="l",xlab="Interval",ylab="Steps",main="Average number of steps by interval"); ``` ![](PA1_template_files/figure-html/unnamed-chunk-3-1.png) ```r #Interval with the max avg steps across all days minterval <- isteps[isteps$msteps == max(isteps$msteps,na.rm=TRUE),]$interval; maxmsteps <- format(isteps[isteps$interval == minterval,]$msteps,digit=5); ``` The maximum interval is 835 with 206.17 steps. ## Imputing missing values The code below use data frame merge to populate a msteps colum. The msteps (mean of steps for interval i) column populates the steps column if its value is NA. ```r # Count of NA values nrow(activity[is.na(activity$steps),]); ``` ``` ## [1] 2304 ``` ```r #Fill NA by merging with isteps (average steps by interval) activity_backfill <- merge(activity,isteps); activity_backfill[is.na(activity_backfill$step),]$steps <- activity_backfill[is.na(activity_backfill$step),]$msteps; activity_backfill$msteps <- NULL; #Create histogram of daily steps dsteps_backfill <- ddply(activity_backfill, .(date), summarize, steps=sum(steps)); hist(dsteps_backfill$steps,main="Histogram of total steps per day",xlab="Steps per day"); ``` ![](PA1_template_files/figure-html/unnamed-chunk-4-1.png) ```r mean_backfill <- format(mean(dsteps_backfill$steps),digit=7); median_backfill <- format(median(dsteps_backfill$steps),digit=7); ``` The mean when ignoring NA records is 10766.19 The median when ignoring NA records is 10765 The mean with backfill of NA data is 10766.19 The median with backfill of NA data is 10766.19 After backfill, the mean stays the same and the median increases slightly. ## Are there differences in activity patterns between weekdays and weekends? The code below use the qplot function of the ggplot2 package. I use the $day property of the POSIXlt object to test if the day is a Sunday (0) or a Saturday (6) and generate a factor column added to the activity dataframe. ```r # Create a boolean vector - TRUE means this is a week end Wend <- (as.POSIXlt(activity_backfill$date)$wday == 0 ) | (as.POSIXlt(activity_backfill$date)$wday == 6 ); Wend <- as.data.frame(Wend); #This function turn the boolen into either weekend or weekday Wdayend <- function(x) { if (x == TRUE) {return ("weekend")} else { return("weekday")} } #A column is added & converted into a factor activity_backfill$Wend <- apply(Wend,1,Wdayend); activity_backfill$Wend <- as.factor(activity_backfill$Wend); #Summarize data by interval and Wend column (factor with "weekend" and "weekday" values) isteps <- ddply(activity_backfill, .(interval,Wend), summarize, msteps=mean(steps,na.rm=TRUE)); #Plot time series qplot(interval,msteps,data=isteps,facets= Wend~., geom=c("line"), main="Comparison of mean steps by interval for Weekend and weekdays", ylab="Avg number of steps by interval"); ``` ![](PA1_template_files/figure-html/unnamed-chunk-5-1.png) <file_sep>/PA1.R library(ggplot2); library(plyr); #Read activity file activity <- read.csv("./activity.csv"); #activity$date <- as.Date(activity$date, "%Y-%m-%d"); #Historam of number of steps tsteps <- ddply(activity, .(date), summarize, steps=sum(steps,na.rm=TRUE)); hist(tsteps$steps,main="Histogram of total steps per day",xlab="Steps per day"); print(mean(tsteps$steps,na.rm=TRUE)); median(tsteps$steps,na.rm=TRUE);
122e66ec6df57a6065ed2788a245b2d9c56fe0e3
[ "Markdown", "R", "RMarkdown" ]
3
RMarkdown
m42cococa/RepData_PeerAssessment1
e1c51d1808c9d0c37036d1e413f2ccaa341e7893
5cde23203c82dad673c34294307daad97302cc0d
refs/heads/master
<repo_name>Karim-Johnson/projet_cv<file_sep>/crud/formation/about.php <?php include_once '../../config/database.php'; $reponse = $database->query("SELECT * FROM formation ORDER BY id DESC"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>About database</title> <!-- Bootstrap core CSS --> <link href="../../style/bootstrap.min.css" rel="stylesheet"> <link href="../../style/main.css" rel="stylesheet"> </head> <body> <?php include '../../header.php'; if ($reponse->rowCount() > 0) { ?> <div class="container"> <h1 id="entete-tableau"> Table de formations :</h1> <table> <tr> <td idden>id</td> <td>nomFormation</td> <td>ecole</td> <td>anneeDiplome</td> <td>descriptions</td> <td>utilisateur</td> </tr> <?php while($row = $reponse->fetch()) { $lienSuppression ='href="supprimer.php?id='.$row["id"]; ?> <tr> <td><?php echo $row["id"]; ?></td> <td><?php echo $row["nomFormation"]; ?></td> <td><?php echo $row["ecole"]; ?></td> <td><?php echo $row["anneeDiplome"]; ?></td> <td><?php echo $row["description"]; ?></td> <td><?php echo $row["utilisateur"]; ?></td> <td><?php echo '<a class="btn btn-success" href="modifier.php?id='.$row["id"].'">modifier</a>'?></td> <td><?php echo '<a class="btn btn-danger" href="supprimer.php?id='.$row["id"].'">supprimer</a>'?></td> </tr> <?php } $reponse->closeCursor(); ?> </table> <?php } else{ echo "No result found"; } ?> <a class="btn btn-primary" id="bouton-ajouter" href="ajouter.php">Ajouter une formation</a> </div> </body> </html><file_sep>/functions.php <?php function somme($premierElement, $secondElement) { return $premierElement + $secondElement; } function difference($premierElement=100, $secondElement=50) { $resultat = $premierElement - $secondElement; return $resultat; } ?><file_sep>/login.php <?php session_start(); include_once 'config/database.php'; if(isset($_POST['submit'])){ if( isset($_POST['email']) && isset($_POST['password'])){ $email = $_POST['email']; $password = $_POST['password']; if(!empty($email) && !empty($password)){ $sqlRe = $database->query("SELECT * FROM utilisateur"); while ($row = $sqlRe->fetch()){ if($email == $row['email'] && $password == $row['password']){ $_SESSION['email'] = $row['email']; $_SESSION['nom'] = $row['nom']; header("Location: index.php"); }else{ $erreur = 1; } } } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Bare - Start Bootstrap Template</title> <!-- Bootstrap core CSS --> <link href="style/bootstrap.min.css" rel="stylesheet"> <link href="style/main.css" rel="stylesheet"> <link href="login.css" rel="stylesheet"> <link href="css/styles.css" rel="stylesheet" /> </head> <body> <?php include("_navbar.php"); ?> <!-- session avec le login --> <!-- // if(!isset($_SESSION)) // { // session_start(); // } --> <!-- Page Content --> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="wrapper fadeInDown"> <div id="formContent"> <!-- Tabs Titles --> <!-- Icon --> <!-- <div class="fadeIn first"> <img src="http://danielzawadzki.com/codepen/01/icon.svg" id="icon" alt="User Icon" /> </div> --> <!-- email Form --> <!--form action="php echo htmlspecialchars($_SERVEUR['PHP_SELF']);?> " method="post"> --> <form action="login.php" class="mt-5" method="post"> <input type="text" id="email" class="fadeIn second" name="email" placeholder="email"> <input type="<PASSWORD>" id="password" class="fadeIn third" name="password" placeholder="<PASSWORD>"> <input type="submit" class="fadeIn fourth" value="Log In" name="submit"> </form> <?php if(isset($erreur)){ echo $erreur; } ?> <!-- Remind Passowrd --> <div id="formFooter"> <a class="underlineHover" href="#">Forgot Password?</a> </div> </div> </div> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.slim.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <?php include("_footer.php"); ?> </body> </html> <file_sep>/crud/utilisateur/ajouter.php <?php include_once '../config/database.php'; if(isset($_GET['nomFormation']) && isset($_GET['ecole']) && isset($_GET['anneeDiplome']) && isset($_GET['description']) && isset($_GET['utilisateur'])){ $sqlRe = "INSERT INTO formation(ecole, anneeDiplome, description, utilisateur) VALUES(:Nomformation, :nomEcole, :dateAnneeDiplome, :textDescription, :nbreUtilisateur)"; try{ $req = $database->prepare($sqlRe); $req->execute(array( Nomformation=>$_GET['nomFormation'], nomEcole=> $_GET['ecole'], dateAnneeDiplome=>$_GET['anneeDiplome'], textDescription=>$_GET['description'], nbreUtilisateur=>$_GET['utilisateur'])); echo "New record created successfully"; header("Location:../about.php"); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Ajouter une formation</title> <!-- Bootstrap core CSS --> <link href="../style/bootstrap.min.css" rel="stylesheet"> <link href="../style/main.css" rel="stylesheet"> <link href="../../css/styles.css" rel="stylesheet" /> </head> <body> <?php include '../header.php'; ?> <div class="form-container"> <form action="ajouter.php" method="get" name="formulaire"> <div class="container"> <div class="form-group"> <label for="nomFormation"><b>Nom de la formation</b></label> <input class="form-control" id="nomFormation" type="text" name="nomFormation" required> </div> <div class="form-group"> <label for="ecole"><b>Nom de l'ecole</b></label> <input class="form-control" id="ecole" type="text" name="ecole" required> </div> <div class="form-group"> <label for="anneeDiplome"><b>Année d'obtention</b></label> <input class="form-control" id="anneeDiplome" type="Number" step="0.01" name="anneeDiplome" required> </div> <div class="form-group"> <label for="description"><b>Description de la formation</b></label> <input class="form-control" id="descriptiont" type="text" name="description" required> </div> <div class="form-group"> <label for="utilisateur"><b>nombre</b></label> <input class="form-control" id="utilisateur" type="Number" step="0.01" name="utilisateur" required> </div> <button type="submit" id="bouton-ajouter" class="btn btn-primary">Submit</button> </div> </form> </div> </body> </html> <file_sep>/crud/formation/detail.php <?php include_once '../../config/database.php'; // if(isset($_GET['id'])){ // $sqlRe = 'SELECT * FROM experience WHERE id= :?'; // try{ // $req = $database->prepare($sqlRe); // $req->execute(array(':?' => $_GET['id'])); // } catch(PDOException $e) { // echo $sqlRe . "<br>" . $e->getMessage(); // } // } if (!empty($_GET['id'])); { $id = checkInput(($_GET['id'])); } $sqlRe = "SELECT * FROM formation WHERE id = ?"; $req = $database->prepare($sqlRe); $req->execute(array($id)); $row =$req->fetch(); function checkInput($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars_decode($data); return $data; } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Modifier une formation</title> <!-- Font Awesome icons (free version)--> <script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js" crossorigin="anonymous"></script> <!-- Google fonts--> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" /> <!-- Bootstrap core CSS --> <link href="../../style/bootstrap.min.css" rel="stylesheet"> <link href="../../style/main.css" rel="stylesheet"> <link href="../../css/styles.css" rel="stylesheet" /> <link href="../../formulaire.css" rel="stylesheet" /> </head> <body> <?php include '../../header.php'; $lienSuppression ='href="supprimer.php?id='.$row["id"]; ?> <div class="container mt-5"> <form> <!-- " &nbsp" permet de creer l'espace entre deux mots --> <div id="font"> <div class="form-group" > <label><strong>Nom de la formation: &nbsp &nbsp</strong></label> <?php echo ' ' .$row["nomFormation"]; ?> </div> <div class="form-group" > <label><strong>Nom de l'école: &nbsp &nbsp</strong></label> <?php echo ' ' .$row["ecole"]; ?> </div> <div class="form-group" > <label><strong>Année d'obtention du diplôme: &nbsp &nbsp</strong></label> <?php echo ' ' .$row["anneeDiplome"]; ?> </div> <div class="form-group" > <label><strong>Description de la formation: &nbsp &nbsp</strong></label> <?php echo ' ' .$row["description"]; ?> </div> <div class="form-group" > <label><strong>Utilisateur: &nbsp &nbsp</strong></label> <?php echo ' ' .$row["utilisateur"]; ?> </div> </div> <?php echo '<a class="btn btn-success" href="modifier.php?id='.$row["id"].'">modifier</a>'?> <?php echo '<a class="btn btn-danger" href="supprimer.php?id='.$row["id"].'">supprimer</a>'?> <form> </div> <?php include("../../_footer.php"); ?> </body> <html> <file_sep>/index.php <?php include_once 'config/database.php'; session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Devéloppeur Web</title> <!-- Favicon--> <link rel="icon" type="image/x-icon" href="assets/img/favicon.ico" /> <!-- Font Awesome icons (free version)--> <script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js" crossorigin="anonymous"></script> <!-- Google fonts--> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" /> <!-- Core theme CSS (includes Bootstrap)--> <link href="css/styles.css" rel="stylesheet" /> </head> <body id="page-top"> <!-- Navigation--> <?php include("_navbar.php"); ?> <!-- Masthead--> <header class="masthead bg-primary text-white text-center"> <div class="container d-flex align-items-center flex-column"> <!-- Masthead Avatar Image--> <img class="rounded-circle" src="karim.png" alt="" /> <!-- Masthead Heading--> <h1 class="masthead-heading text-uppercase mb-0">QUI SUIS - JE ?</h1> <!-- Icon Divider--> <div class="divider-custom divider-light"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Masthead Subheading--> <p class="masthead-subheading font-weight-light mb-0">Développeur Junior Web: HTML5, CSS3, JAVASCRIPT, PHP</p> </div> </header> <!-- Portfolio Section--> <?php $reponse = $database->query("SELECT * FROM formation ORDER BY id ASC"); ?> <section class="page-section portfolio" id="portfolio"> <div class="container"> <!-- Portfolio Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Mes formations</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Portfolio Grid Items--> <div class="row justify-content-center"> <?php while($row = $reponse->fetch()) { echo'<a href= "crud/formation/detail.php?id='.$row["id"].'" class="col-md-6 col-lg-4 mb-5"> <div class="portfolio-item mx-auto" data-toggle="modal" data-target="#portfolioModal1"> <div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100"> <div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div> </div> <img class="img-fluid" src="assets/img/portfolio/forma.png" alt="" /> <div class= "taille_formation">'.$row["nomFormation"].'</div> </div>'; } $reponse->closeCursor(); ?> </div> </div> <div class="boutonAjouter1"> <a class="btn btn-primary" id="bouton-ajouter" href="crud/formation/ajouter.php" style="opacity: <?= isset($_SESSION['email']) ? '1':'0' ?>;">Ajouter une formation</a> </div> </section> <!-- About Section--> <section class="page-section bg-primary1 text-white mb-0" id="about"> <?php $reponse = $database->query("SELECT * FROM experience"); ?> <section class="page-section portfolio" id="portfolio"> <div class="container"> <!-- Portfolio Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Mes expériences</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Portfolio Grid Items--> <div class="row justify-content-center"> <?php while($row = $reponse->fetch()) { echo'<a href= "crud/experience/detail.php?id='.$row["id"].'" class="col-md-6 col-lg-4 mb-5"> <div class="portfolio-item mx-auto" data-toggle="modal" data-target="#portfolioModal1"> <div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100"> <div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div> </div> <img class="img-fluid" src="assets/img/portfolio/exp.png" alt="" /> <div class= "taille_formation">'.$row["posteOccupe"].'</div> </div>'; } $reponse->closeCursor(); ?> </div> </div> <!-- le bouton apparait lorrsque un visiteur est connecté il disparait lorsqu'il est déconnecté --> <a class="btn btn-primary" id="bouton-ajouter" href="crud/experience/ajouter.php" style="opacity: <?= isset($_SESSION['email']) ? '1':'0' ?>;">Ajouter une Expérience</a> </div> </section> </section> <!-- Contact Section--> <?php include("contact.php"); ?> <!-- footer --> <?php include("_footer.php"); ?> <!-- footer --> <!-- Scroll to Top Button (Only visible on small and extra-small screen sizes)--> <!-- Bootstrap core JS--> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <!-- Third party plugin JS--> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script> <!-- Contact form JS--> <script src="assets/mail/jqBootstrapValidation.js"></script> <script src="assets/mail/contact_me.js"></script> <!-- Core theme JS--> <script src="js/scripts.js"></script> </body> </html> <file_sep>/contact.php <?php // première fois ou l utilisateur n a pas soumis les donnees $Name = $email = $phone = $message = ""; $NameError = $emailError = $phoneError = $messageError = ""; $isSuccess = "false"; $emailTo = "<EMAIL>"; // deuxième fois ou l utilisateur soumis les donnees if($_SERVER['REQUEST_METHOD'] == 'POST') { $Name = verifyInput($_POST["Name"]); $email = verifyInput($_POST["email"]); $phone = verifyInput($_POST["phone"]); $message = verifyInput($_POST["message"]); $isSuccess = "true"; $emailText = " "; if (empty($Name)) { $NameError = "je veux connaitre ton nom"; $isSuccess = "false"; } else { $emailText .= "Name: $Name\n"; } if(empty($message)) { $message = "qu'est ce que tu veux me dire"; $isSuccess = "false"; } else { $emailText .= "message: $message\n"; } if(!isEmail($email)) { $emailError = "je veux connaitre ton mail"; $isSuccess = "false"; } else { $emailText .= "email: $email\n"; } if(!isPhone($phone)) { $phoneError = "je veux connaitre ton numéro de téléphone"; $isSuccess = "false"; } else { $emailText .= "phone: $phone\n"; } if ($isSuccess) { $headers = "From: $firstname $Name <$email>\r\nReply-To: $email"; mail($emailTo, "un message de votre site", $emailText, $headers); $Name = $email = $phone = $message = ""; } } // fonction qui permet de valider un numéro de telephone function isPhone($var) { return preg_match("/^[0-9 ]*$/", $var); } // fonction qui permet de valider un email, elle repose sur une autre fonction FILTER_VALIDATE_EMAIL. Cette fonction renvoie true si le mail est valide et false dans le cas contraire. function isEmail($var) { return filter_var($var, FILTER_VALIDATE_EMAIL); } // fonction permettant de verifiant l input ie, ce que l utilisateur entre dans le formulaire. function verifyInput($var) { // le but de la fonction trim permet de d enlever tout ce qui est espace supplementaire, tab, $var = trim($var); // le but de la fonction stripslashes enleve tous les antislahe $var = stripslashes($var); // le but de la fonction htmlspecialchars permet de convertir les caractere en html $var = htmlspecialchars($var); return $var; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Devéloppeur Web</title> <!-- Favicon--> <link rel="icon" type="image/x-icon" href="assets/img/favicon.ico" /> <!-- Font Awesome icons (free version)--> <script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js" crossorigin="anonymous"></script> <!-- Google fonts--> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" /> <!-- Core theme CSS (includes Bootstrap)--> <link href="css/styles.css" rel="stylesheet" /> </head> <body> <!-- Page Content --> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Contact Section Form--> <div class="new"> <div class="col-lg-8 mx-auto"> <!-- To configure the contact form email address, go to mail/contact_me.php and update the email address in the PHP file on line 19.--> <form id="contactForm" name="sentMessage" method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>" novalidate="novalidate"> <div class="control-group"> <div class="form-group floating-label-form-group controls mb-0 pb-2"> <label>Email Address</label> <input class="form-control" id="email" type="email" placeholder="Email Address" required="required" data-validation-required-message="Please enter your email address." value=" <?php echo $email; ?>" /> <p class="help-block text-danger"></p> <p class="comments"><?php echo $emailError; ?></p> </div> </div> <div class="control-group"> <div class="form-group floating-label-form-group controls mb-0 pb-2"> <label>Name</label> <input class="form-control" id="name" type="text" placeholder="Name" required="required" data-validation-required-message="Please enter your name." value=" <?php echo $Name; ?>" /> <p class="help-block text-danger"></p> <p class="comments"><?php echo $NameError; ?></p> </div> </div> <div class="control-group"> <div class="form-group floating-label-form-group controls mb-0 pb-2"> <label>Phone Number</label> <input class="form-control" id="phone" type="tel" placeholder="Phone" required="required" data-validation-required-message="Please enter your phone number." value=" <?php echo $phone; ?>" /> <p class="help-block text-danger"></p> <p class="comments"><?php echo $phoneError; ?></p> </div> </div> <div class="control-group"> <div class="form-group floating-label-form-group controls mb-0 pb-2"> <label>Message</label> <textarea class="form-control" id="message" rows="5" placeholder="message" required="required" data-validation-required-message="Please enter a message." value=" <?php echo $message; ?>" ></textarea> <p class="help-block text-danger"></p> <p class="comments"><?php echo $messageError; ?></p> </div> </div> <br /> <div id="success"></div> <div class="form-group"><button class="btn btn-primary btn-xl" id="sendMessageButton" type="submit">Envoyer</button></div> </form> </div> </div> </div> </section> <?php // if(isset($_POST) && !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['phone']) && !empty($_POST['message'])){ // extract($_POST); // $destinataire = "<EMAIL>" // $expediteur = $name.'<'.$email.'>'; // $mail = mail($destinataire, $name, $message, $expediteur ': nomexpediteur: Mail de test'); // if($mail) echo'Email envoyé avec succès!'; else 'echec d envoie de Mail'; // }else{ // echo "formulaire non soumi ou des champs sont vides"; // } ?> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.slim.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> </body> </html> <file_sep>/crud/formation/supprimer.php <!-- $action = mysql_real_escape_string('insert php code for button here'); --> <?php include_once '../../config/database.php'; if(isset($_GET['id'])){ $sqlRe = 'DELETE FROM formation WHERE id= :id'; try{ $req = $database->prepare($sqlRe); $req->execute(array(id=> $_GET['id'])); echo " delete execute"; header("Location:../../index.php"); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } } ?><file_sep>/README.md # Création d'un site Web dynamique ## Prérequis techniques -bootstrap3 -Mysql ## Fonctionnalités implémentées -page de connexion qui après soumission du formulaire s’il existe un utilisateur en BDD qui a les identifiants rentrés, alors On est redirigé vers la page d’accueil. Le login est enregistré en session Le menu « connexion » disparait Le menu « déconnexion » apparait à la place du menu « connexion » Au clic sur « déconnexion » l’inverse se produit et on efface le login de la session et on détruit la session -La page d'accueil constituée de quatre blocs: * un bloc présentation; * un bloc formations; * un bloc expériences; * un bloc formulaire de contact -La page présentant les détails d'une formation -La page présentant les détails d'une expérience -La page permettant d'ajouter une formation -La page permettant d'ajouter une expérience -La parge permettant de modifier ou de supprimer une fomation -La parge permettant de modifier ou de supprimer une expérience ### Le bloc présentation Contient ma photo et ce qui me caractérise #### Le bloc formations Contient toute les formations se trouvant dans la BD et au clic sur une formation, on est dirigé vers une modale qui présente les détails de la formation. ### Le bloc expériences Contient toute les formations se trouvant dans la BD et au clic sur une formation, on est dirigé vers une modale qui présente les détails de la formation. ### Le bloc formulaire de contact contient un formulaire permettant de me contacter pour un service. <file_sep>/crud/formation/liste.php <!-- connexion avec la base --> <?php include_once '../../config/database.php'; $reponse = $database->query("SELECT * FROM formation"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>About database</title> <!-- Font Awesome icons (free version)--> <script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js" crossorigin="anonymous"></script> <!-- Google fonts--> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" /> <!-- Core theme CSS (includes Bootstrap)--> <!-- Bootstrap core CSS --> <link href="../../css/styles.css" rel="stylesheet"> </head> <body> <?php include '../../header.php';?> <section class="page-section portfolio" id="portfolio"> <div class="container"> <!-- Portfolio Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Portfolio</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Portfolio Grid Items--> <div class="row justify-content-center"> <?php while($row = $reponse->fetch()) { echo'<a href= "detail.php?id='.$row["id"].'" class="col-md-6 col-lg-4 mb-5"> <div class="portfolio-item mx-auto" data-toggle="modal" data-target="#portfolioModal1"> <div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100"> <div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div> </div> <img class="img-fluid" src="../../assets/img/portfolio/cabin.png" alt="" /> <div>'.$row["nomFormation"].'</div> </div>'; } $reponse->closeCursor(); ?> </div> </div> </section> <a class="btn btn-primary" id="bouton-ajouter" href="crud/formation/ajouter.php">Ajouter une Expérience</a> </body> </html><file_sep>/crud/utilisateur/modifier.php <?php include_once '../../config/database.php'; if(isset($_GET['id'])){ $sqlRe = 'SELECT * FROM formation WHERE id =:identifiant'; try{ $req = $database->prepare($sqlRe); $req->execute(array(':identifiant' => $_GET['id'])); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } } else{ if(isset($_POST['nomFormation']) && isset($_POST['ecole']) && isset($_POST['anneeDiplome']) && isset($_POST['description']) && isset($_POST['utilisateur'])){ $sqlRe = "UPDATE formation SET nomFormation= :nomFormation, ecole= :ecole, anneeDiplome= :anneeDiplome, description= :description, utilisateur= :utilisateur WHERE id= :id"; try{ $req = $database->prepare($sqlRe); $req->execute(array(':nomFormation'=>$_POST['nomFormation'], ':ecole'=> $_POST['ecole'], ':anneeDiplome'=>$_POST['anneeDiplome'], ':description'=>$_POST['description'], ':utilisateur'=>$_POST['utilisateur'], ':id'=>$_POST['identifiant'])); echo "New record created successfully"; header("Location:about.php"); } catch(PDOException $e) { echo $sqlRe . "<br>" . $e->getMessage(); } } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Modifier une formation</title> <!-- Bootstrap core CSS --> <link href="../../style/bootstrap.min.css" rel="stylesheet"> <link href="../../style/main.css" rel="stylesheet"> </head> <body> <?php include '../../header.php'; ?> <div class="form-container"> <form action="modifier.php" method="post" name="formulaire"> <?php $row = $req->fetch(); ?> <div class="container"> <div class="form-group" hidden> <label for="id"><b>id</b></label> <input class="form-control" id="nomFormation" type="text" name="nomFormation" value="<?php echo $row["nomFormation"]; ?>" required> </div> <div class="form-group"> <label for="nomFormation"><b>identifiant</b></label> <input class="form-control" id="identifiant" type="Number" name="identifiant" value="<?php echo $row["id"]; ?>" required> </div> <div class="form-group"> <label for="ecole"><b>Nom de l'ecole</b></label> <input class="form-control" id="ecole" type="text" name="ecole" value="<?php echo $row["ecole"]; ?>" required> </div> <div class="form-group"> <label for="anneeDiplome"><b>Année d'obtention</b></label> <input class="form-control" id="anneeDiplome" type="Number" name="anneeDiplome" value="<?php echo $row["anneeDiplome"]; ?>" required> </div> <div class="form-group"> <label for="description"><b>Description de la formation</b></label> <input class="form-control" id="descriptions" type="text" name="description" value="<?php echo $row["description"]; ?>" required> </div> <div class="form-group"> <label for="utilisateur"><b>Nombre</b></label> <input class="form-control" id="utilisateur" type="Number" name="utilisateur" value="<?php echo $row["utilisateur"]; ?>" required> </div> <button type="submit" id="bouton-ajouter" class="btn btn-primary">Submit</button> </div> </form> </div> </body> </html> <file_sep>/crud/experience/about.php <?php include_once '../../config/database.php'; $reponse = $database->query("SELECT * FROM experience ORDER BY id DESC"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>About database</title> <!-- Bootstrap core CSS --> <link href="../../style/bootstrap.min.css" rel="stylesheet"> <link href="../../style/main.css" rel="stylesheet"> </head> <body> <?php include '../../header.php'; if ($reponse->rowCount() > 0) { ?> <div class="container"> <h1 id="entete-tableau"> Table des expériences :</h1> <table> <tr> <td idden>id</td> <td>posteOccupe</td> <td>nomEntreprise</td> <td>dateDebut</td> <td>dateDefin</td> <td>descriptionPoste</td> <td>utilisateur</td> </tr> <?php while($row = $reponse->fetch()) { $lienSuppression ='href="supprimer.php?id='.$row["id"]; ?> <tr> <td><?php echo $row["id"]; ?></td> <td><?php echo $row["posteOccupe"]; ?></td> <td><?php echo $row["nomEntreprise"]; ?></td> <td><?php echo $row["dateDebut"]; ?></td> <td><?php echo $row["dateDefin"]; ?></td> <td><?php echo $row["descriptionPoste"]; ?></td> <td><?php echo $row["utilisateur"]; ?></td> <td><?php echo '<a class="btn btn-success" href="modifier.php?id='.$row["id"].'">modifier</a>'?></td> <td><?php echo '<a class="btn btn-danger" href="supprimer.php?id='.$row["id"].'">supprimer</a>'?></td> </tr> <?php } $reponse->closeCursor(); ?> </table> <?php } else{ echo "No result found"; } ?> </div> </body> </html><file_sep>/effacer.php <?php try { $database = new PDO('mysql:host=localhost;dbname=job_board','root',''); $database->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); } catch (Excepttion $e) { die('ERROR: ' .$e->getMessage()); } $pdo = new PDO('mysql:host=localhost;dbname=job_board', 'root', ''); $statement = $pdo->query("SELECT PRIX FROM stock"); while($row = $statement->fetch()) { echo ($row['PRIX']).'<br><br><br>'; } ?> <?php include '../header.php'; ?><file_sep>/crud/experience/ajouter.php <?php include_once '../../config/database.php'; session_start(); if(isset($_POST['posteOccupe']) && isset($_POST['nomEntreprise']) && isset($_POST['dateDebut']) && isset($_POST['dateDefin']) && isset($_POST['descriptionPoste']) && isset($_POST['utilisateur'])){ $sqlRe = "INSERT INTO experience(posteOccupe, nomEntreprise, dateDebut, dateDefin, descriptionPoste, utilisateur) VALUES(:posteOccupe, :nomEntreprise, :dateDebut, :dateDefin, :descriptionPoste, :utilisateur)"; try{ $req = $database->prepare($sqlRe); $req->execute(array(':posteOccupe'=>$_POST['posteOccupe'], ':nomEntreprise'=>$_POST['nomEntreprise'], ':dateDebut'=> $_POST['dateDebut'], ':dateDefin'=> $_POST['dateDefin'], ':descriptionPoste'=>$_POST['descriptionPoste'], ':utilisateur'=>$_POST['utilisateur'])); echo "New record created successfully"; header("Location:../../index.php"); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } } // $result = mysqli_query( $con, $query ); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Ajouter une expérience</title> <!-- Bootstrap core CSS --> <link href="../../style/bootstrap.min.css" rel="stylesheet"> <link href="../../style/main.css" rel="stylesheet"> </head> <body> <?php include '../../header.php'; ?> <div class="form-container"> <form action="ajouter.php" method="post" name="formulaire"> <div class="container"> <div class="form-group"> <label for="posteOccupe"><b>Nom du poste occupé</b></label> <input class="form-control" id="posteOccupe" type="text" name="posteOccupe" required> </div> <div class="form-group"> <label for="nomEntreprise"><b>Nom de l'entreprise</b></label> <input class="form-control" id="nomEntreprise" type="text" name="nomEntreprise" required> </div> <div class="form-group"> <label for="dateDebut"><b>Date de début</b></label> <input class="form-control" id="dateDebut" type="date" name="dateDebut" required> </div> <div class="form-group"> <label for="dateDefin"><b>Date de fin</b></label> <input class="form-control" id="dateDefin" type="date" name="dateDefin" required> </div> <div class="form-group"> <label for="descriptionPoste"><b>Description du poste</b></label> <input class="form-control" id="descriptionPoste" type="text" name="descriptionPoste" required> </div> <div class="form-group"> <label for="utilisateur"><b>Nombre</b></label> <input class="form-control" id="utilisateur" type="Number" name="utilisateur" required> </div> <button type="submit" id="bouton-ajouter" class="btn btn-primary">Submit</button> </div> </form> </div> </body> </html>
abff33d0ba3b26e52c24775d29d779c95270cbd2
[ "Markdown", "PHP" ]
14
PHP
Karim-Johnson/projet_cv
20bb5e5fe031c196e3d4770cafb250fe7625a649
00814a620e46f927acadcf6b7e68c6e450d4e0d1