branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import logging import os MYDIR = os.path.abspath(os.path.dirname( os.path.dirname('__file__') )) ANSI2HTML = os.path.join( MYDIR, "share/ansi2html.sh" ) LOG_FILE = os.path.join( MYDIR, 'log/main.log' ) FILE_QUERIES_LOG = os.path.join( MYDIR, 'log/queries.log' ) TEMPLATES = os.path.join( MYDIR, 'share/templates' ) STATIC = os.path.join( MYDIR, 'share/static' ) PATH_TLDR_PAGES = "/home/igor/.tldr/cache/pages/*/*.md" PATH_CHEAT_PAGES = "/usr/local/lib/python2.7/dist-packages/cheat/cheatsheets/*" PATH_CHEAT_SHEETS = "/home/igor/cheat.sheets/sheets/" PATH_CHEAT_SHEETS_SPOOL = "/home/igor/cheat.sheets/spool/" def error(text): if not text.startswith('Too many queries'): print text logging.error("ERROR "+text) raise RuntimeError(text) def log(text): if not text.startswith('Too many queries'): print text logging.info(text) <file_sep>## Usage ``` printf "flag{df3408fsdn254uv0345}" | curl -F-=\<- qrenco.de |lolcat -F 0.3 ``` ![](qr.jpg) [![asciicast](https://asciinema.org/a/wq5HyXt29kGFHKSAM7UDuUmlV.png)](https://asciinema.org/a/wq5HyXt29kGFHKSAM7UDuUmlV) The service is used to generate QR-codes for strings in a UNIX/Linux console using curl/httpie/wget or similar tools. ![qrenco.de usage](http://igor.chub.in/download/qrenco.de.png) The service can be used in a browser also. Just add `qrenco.de/` before the URL. ![qrenco.de in browser](http://igor.chub.in/download/qrenco.de-browser.png) The service uses [libqrencode](https://github.com/fukuchi/libqrencode) to generate QR-codes. ## Installation You don't need to install the service for using it (just try curl qrenco.de), but if you want to install it locally, do the following steps: ``` $ git clone https://github.com/chubin/qrenco.de        $ cd qrenco.de $ pip install virtualenv $ virtualenv ve $ ve/bin/pip install -r requirements.txt $ sudo apt-get install libqrenv $ ve/bin/python bin/srv.py ``` If you want to use a HTTP-frontend for the service, configure it this way: ``` server { listen 80; listen [::]:80; server_name qrenco.de *.qrenco.de; access_log /var/log/nginx/qrenco.de-access.log; error_log /var/log/nginx/qrenco.de-error.log; location / { proxy_pass http://1192.168.127.12:8003; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; expires off; } } ``` <file_sep>import gevent from gevent.monkey import patch_all from gevent.subprocess import Popen, PIPE, STDOUT patch_all() import sys import os MYDIR = os.path.abspath(os.path.dirname( os.path.dirname('__file__') )) sys.path.append("%s/lib/" % MYDIR) from buttons import GITHUB_BUTTON_FOOTER INTERNAL_TOPICS = [':firstpage'] def github_button(button): repository = { "qrenco.de" : 'chubin/qrenco.de', "libqrencode": 'fukuchi/libqrencode', } full_name = repository.get(button, '') if not full_name: return '' short_name = full_name.split('/',1)[1] button = ( "<!-- Place this tag where you want the button to render. -->" '<a aria-label="Star %(full_name)s on GitHub" data-count-aria-label="# stargazers on GitHub"' ' data-count-api="/repos/%(full_name)s#stargazers_count"' ' data-count-href="/%(full_name)s/stargazers"' ' data-icon="octicon-star"' ' href="https://github.com/%(full_name)s"' ' class="github-button">%(short_name)s</a>' ) % locals() return button def html_wrapper(answer): style = 'background-color: black; color: white;' buttons = "".join(github_button(x) for x in ['qrenco.de', 'libqrencode']) buttons += GITHUB_BUTTON_FOOTER return ( "<html>" "<head>" "<title>qrenco.de</title>" "</head>" "<body style='%s'><pre>%s</pre>%s</body>" "</html>" )% (style, answer, buttons) def get_internal(topic): return open(os.path.join(MYDIR, "share", topic[1:]+".txt"), "r").read() def qrencode_wrapper(query_string="", request_options=None, html=False): if query_string == "": query_string = ":firstpage" if query_string in INTERNAL_TOPICS: answer = get_internal(query_string) else: answer = query_string + "\n" cmd = ["qrencode", "-t", "UTF8", "-o", "-"] p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT) answer = p.communicate(answer.encode('utf-8'))[0] if html: return html_wrapper(answer), True else: return answer, True
b03ff74737abd7d4abf4761fdc0f46ec01b9ac58
[ "Markdown", "Python" ]
3
Python
jas502n/qrenco.de
1b85acdfdde39de9c54059001b5a8affd207237e
651f178d3aaad72dd42977daf0f51f3d430aed06
refs/heads/master
<repo_name>hamid42643/Rational<file_sep>/Rational.cpp #include <iostream> //for string manipulation #include <string> #include <vector> #include <functional> using namespace std; class Rational{ private: int numerator; //soorat int denominator; //makhraj string input; public: int dontPrintDen; int error; Rational(); Rational(int, int); Rational(int); // Rational::Rational(int, const 1); bool Rational::anyError(); bool isNumber(const std::string& ); void Rational::normalize(bool); //Overloaded operator functions Rational operator + (const Rational &); Rational operator - (const Rational &); Rational operator / (const Rational &); Rational operator * (const Rational &); bool Rational:: operator == (const Rational &); bool Rational:: operator > (const Rational &); bool Rational:: operator < (const Rational &); /* function prototypes for overloaded stream operators Both functions attempt to directly access the Rational object's private members. Because These functions aren't themselves members of the Rational class, they don't have this type Of access so the operators should be friend of the Rational class. */ friend ostream &operator << (ostream & , Rational &); friend istream &operator >> (istream & , Rational &); }; //---------------------------------------------- //default constructor Rational::Rational(){ numerator = 0; denominator = 1; } //first constructor Rational::Rational(int n, int d){ numerator = n; denominator = d; } //second constructor Rational::Rational(int n){ numerator = n; denominator = 1; } /* checkes the private varible error if its set to 1 the function returns true */ bool Rational::anyError(){ if(this->error==1){ this->error=0; return true; } else{ return false; } } /* ths function first counts the numbers of '/' '-' and '+' if it is more than 1 or 2 it returns false. also if after '+' or '-' there is a non-degit character or a '0' it returns false(ex -+23/33) also if there is any none-digit character in the string array it returns false */ bool isNumber(const std::string& s) { int countSlash=0; int countPlus=0; int countMinus=0; if(s[0]=='0'){ return false; } for (unsigned int i = 0; i < s.length(); i++) { if((s[i]=='/')) { countSlash++; if(s[i+1]=='0'){ return false; } } else if((s[i]=='+')) { countPlus++; if((!isdigit(s[i+1]))||(s[i+1]=='0')){ return false; } } else if((s[i]=='-')) { countMinus++; if((!isdigit(s[i+1]))||(s[i+1]=='0')){ return false; } } else if(!isdigit(s[i])) { return false; } } if(countSlash>1){ return false; } if(countPlus>2){ return false; } if(countMinus>2){ return false; } return true; } /* this function fix the sign(for example -4/-3 becomes 4/3), and also find the greater common devisor and divides the numerator and denominator by it. if the boolean i is set to 1 it only tries to fix the sign. */ void Rational::normalize(bool i=0){ int a = numerator; int b = denominator; int sign = 1; if (a < 0) { sign = sign * -1; numerator = -numerator; a=-a;} if (b < 0) { sign = sign * -1; denominator = -denominator; b=-b;} if((i==0)) { if((b!=0)&&(a!=0))//if eighter numerator or denominator are not zeros { int tmp, rem=1, gcd; if(a>b){ tmp=a; a=b; b=tmp; } while(rem>0){ rem=b%a; b=a; gcd=a; a=rem; } numerator = sign*(numerator/gcd); denominator = denominator/gcd; if(denominator==1){//updated dontPrintDen=1; } }else{ numerator = sign*(numerator); denominator = denominator; dontPrintDen=1; } }else{ numerator = sign*(numerator); denominator = denominator; } } /* Overloading + operator This function is called anytime the + operator is used with two Rational objects. This function has one parameter: a constant reference object named 'right'. This parameter references the object on the right side of the operator, For example, when the following statement is executed, right will reference the b object: a + b */ Rational Rational::operator +(const Rational &right){ Rational temp; temp.numerator = (numerator * right.denominator) + (right.numerator * denominator); temp.denominator = denominator * right.denominator; temp.normalize(); return temp; } //Overloading - operator Rational Rational::operator - (const Rational &right) { Rational temp; temp = Rational(numerator*right.denominator - right.numerator*denominator, denominator*right.denominator); temp.normalize(); return temp; } //Overloading * operator Rational Rational::operator * (const Rational &right) { Rational temp; temp = Rational(numerator * right.numerator, denominator * right.denominator); temp.normalize(); return temp; } //Overloading / operator Rational Rational::operator / (const Rational &right) { Rational temp; temp = Rational(numerator * right.denominator, denominator * right.numerator); temp.normalize(); return temp; } //Overloading == operator bool Rational:: operator == (const Rational &right) { return (numerator * right.denominator == denominator * right.numerator); } //Overloading > operator bool Rational:: operator > (const Rational &right) { bool c (numerator * right.denominator > denominator * right.numerator); return c; } //Overloading < operator bool Rational:: operator < (const Rational &right) { bool c = (numerator * right.denominator < denominator * right.numerator); return c; } /* Overloading << operator, This function tells C++ how to handle any expression that has the Following form: Left Right ostreamObject << RationalObject When the return strm; statement executes, it doesn’t return a copy of strm, but a reference to it. This allows to chain together several expressions using the overloaded operator NOTE: Do not confuse the address operator(pointers chapter) with the & symbol used when defining a refrence */ ostream &operator << (ostream &strm, Rational &right){ if(right.dontPrintDen==1){ cout << right.numerator; right.normalize(1); return strm; }else{ cout << right.numerator << "/" << right.denominator; right.normalize(1); return strm; } } //Overloading >> operator, this function gets user input istream &operator >> (istream &strm, Rational &right){ //char slash; //strm >> right.numerator >> slash >> right.denominator; //cout << "enter the rational number: "; char line[233]; cin.getline(line,233); if(isNumber(line)){ // check if input is valid right.input = line; int slashPos = right.input.find("/"); int num,den; if(slashPos!=-1){ //if '/' exists string n = right.input.substr(0, slashPos); string d = right.input.substr(slashPos+1); num = atoi(n.c_str()); den = atoi(d.c_str()); } else{// if '/' doesnt exist we suppose users entering rational number as whole(ex 5 instead of 5/1) string n = right.input; num = atoi(n.c_str()); den=0; } if(num==0){ // if numerator doesn't exist or it's not a number right.error=1; return strm; }else if(den==0) // if denominator doesn't exist or it's not a number { if(slashPos==-1){ //// if '/' doesn't exist right.numerator = num; right.denominator = 1; right.normalize(1); //right.dontPrintDen=1; return strm; }else{ right.error=1; return strm; } }else{ // if both numerator and denominator exist and both are numbers right.numerator = num; right.denominator = den; right.normalize(1); return strm; } }else{ right.error=1; return strm; } } void main(){ /* Rational a(2); Rational b(-1,-3); a.normalize(a,1); b.normalize(b,1); */ while(1){ bool error=1; Rational a,b; while(error==1){ //Rational a; cout << "enter the first rational number: "; cin >> a; if(a.anyError()){ error=1; cout << "\nfirst rational number is invalid!\n"; }else{ break; } } while(error==1){ //Rational b; cout << "enter the second rational number: "; cin >> b; if(b.anyError()){ error=1; cout << "\nsecond rational number is invalid!\n"; }else{ break; } } if(a == b){ cout << a << " = " << b << endl; }else{ cout << a << " is not = " << b << endl; } if(a > b){ cout << a << " > " << b << endl; }else{ cout << a << " is not > " << b << endl; } if(a < b){ cout << a << " < " << b << endl; }else{ cout << a << " is not < " << b << endl; } cout << "(" << a << ")" << " + " << "(" << b << ")" <<" = " << a + b << endl; cout << "(" << a << ")" << " - " << "(" << b << ")" <<" = " << a - b << endl; cout << "(" << a << ")" << " * " << "(" << b << ")" <<" = " << a * b << endl; cout << "(" << a << ")" << " / " << "(" << b << ")" <<" = " << a / b << endl; getchar(); } } <file_sep>/readme.txt A simple class written in C++, defining rational numbers, and operations with rational numbers.
a9ddd5541f8322b136feba12c64608e05b845f19
[ "Text", "C++" ]
2
C++
hamid42643/Rational
eca3757496202dc7b5609d041afacb9d6238dd2c
7a833e5166655396753c89bb2047b353a751e6c0
refs/heads/master
<repo_name>okunishinishi/node-taggit<file_sep>/test/taggit_test.js /** * Test for taggit. * Runs with mocha */ 'use strict' const taggit = require('../lib/taggit') const injectmock = require('injectmock') const co = require('co') const assert = require('assert') const childProcess = require('child_process') describe('taggit', function () { before(async () => { injectmock(childProcess, 'spawn', function mockSpawn() { return { stdout: { pipe() { } }, stderr: { pipe() { } }, on(event, callback) { setTimeout(function () { callback(0) }, 2) } } }) injectmock(childProcess, 'exec', function mockExec(comand, callback) { callback(null, null) }) }) after(async () => { injectmock.restoreAll() }) it('Do tag git.', async () => { await taggit({}) }) }) /* global describe, before, after, it */ <file_sep>/lib/taggit.js /** * Create remote git tag. * @function taggit * @param {object} [options] - Optional settings. * @param {string} [options.tag=('v'+pkg.version)] - Name of tag on git. By default, name is resolved form package.json. * @param {string} [options.cwd=process.cwd()] - Working directory path. * @param {function} callback - Callback when done. */ 'use strict' const argx = require('argx') const execcli = require('execcli') const _tagExists = require('./_tag_exists') const _tagName = require('./_tag_name') /** @lends taggit */ async function taggit(options = {}) { let args = argx(arguments) if (args.pop('function')) { throw new Error('Callback is no longer supported. Use promise interface instead.') } options = args.pop('object') || {} let cwd = options.cwd || process.cwd() let tagName = options.tag || _tagName(cwd) if (!tagName) { throw new Error('Failed to find tag name.') } let exists = await _tagExists(tagName) if (exists) { throw new Error('Tag already exists: ' + tagName) } await execcli('git', ['tag', tagName]) await execcli('git', ['push', '--tags']) } module.exports = taggit <file_sep>/example/example-taggit.js 'use strict' let basedir = __dirname; process.chdir(basedir) //Move to project root. const taggit = require('taggit') // Create remote git tag named with package.json version. (eg. v1.0.0) taggit({ // Options }, (err) => { /*...*/ }) <file_sep>/lib/_tag_exists.js /** * @function _tagExists * @private */ 'use strict' const childProcess = require('child_process') /** @lends _tagExists */ async function _tagExists(tagName) { const command = `git tag -l ${tagName}` const stdOut = await new Promise((resolve, reject) => childProcess.exec(command, (err, stdOut, stdErr) => (err || stdErr) ? reject(err || stdErr) : resolve(stdOut) ) ) return !!stdOut } module.exports = _tagExists <file_sep>/lib/index.js /** * Create a tag on remote git with version number in package.json (or bower.json) * @module taggit * @version 2.0.3 */ 'use strict' const taggit = require('./taggit.js') const pkg = require('../package.json') let lib = taggit.bind(taggit) Object.assign(lib, taggit, { taggit, version: pkg.version }) module.exports = lib<file_sep>/bin/taggit #!/usr/bin/env node /** * Command line interface of taggit. * This file is auto generated by ape-tmpl. */ 'use strict' const program = require('commander') const pkg = require('../package') const taggit = require('../lib') program .version(pkg[ 'version' ]) .usage('[options] ') .description(pkg[ 'description' ]) .option('-t, --tag <tag>', 'Name of tag. By default, name is resolved form package.json.') .option('-c, --cwd <cwd>', 'Working directory path.') program.parse(process.argv) // Run main command taggit.apply(taggit, program.args.concat({ tag: program.tag, cwd: program.cwd}) ).catch(handleError) // Handlers /** Handle error */ function handleError (err) { console.error(err) process.exit(1) } <file_sep>/lib/_tag_name.js /** * @private * @function _tagName */ 'use strict' const fs = require('fs') const path = require('path') /** @lends _tagName */ function _tagName (cwd) { let filenames = [ 'package.json', 'bower.json' ] for (let i = 0; i < filenames.length; i++) { try { let filename = require.resolve(path.resolve(cwd || process.cwd(), filenames[ i ])) let content = JSON.parse(fs.readFileSync(filename)) return 'v' + content.version } catch (e) { // Do nothing. } } return null } module.exports = _tagName
2f0bb3258ce871e8ac450d8d0b2a6d58f84e20e0
[ "JavaScript" ]
7
JavaScript
okunishinishi/node-taggit
73b5805fe77b48e4b0a9c64ee8ae8cbd5952908d
dfb6043bf271f03e722535f6985db356c4cf1523
refs/heads/master
<repo_name>BRACU-DICHARI/pyMaxon<file_sep>/setup.py from distutils.core import setup setup( name='pyMaxon', version='0.0.1', packages=['pyMaxon'], url='', license='MIT', author='Riccardo', author_email='<EMAIL>', description='Wrapper for Maxon Library' ) <file_sep>/pyMaxon/pyMaxon.py from ctypes import cdll, CDLL, c_uint, c_char_p, c_bool, byref class Maxon(): def __init__(self, path_lib, model, type_comm, conn, port_conn): self.path = path_lib cdll.LoadLibrary(self.path) self.epos = CDLL(self.path) self.p_error_code = c_uint(0) self.key_handle = 0 self.node_id = 1 self.model = c_char_p(model.encode('ascii')) self.type_comm = c_char_p(type_comm.encode('ascii')) self.conn = c_char_p(conn.encode('ascii')) self.port_conn = c_char_p(port_conn.encode('ascii')) self.velox = c_uint(0) self.accel = c_uint(0) self.decel = c_uint(0) self.ret_val = c_bool(False) self.pos_reached = c_bool(False) self.p_baud_rate = c_uint(0) # Controllare che il tipo va bene self.p_time_out = c_uint(0) # Controllare che il tipo va bene def open_device(self): self.key_handle = self.epos.VCS_OpenDevice(self.model, self.type_comm, self.conn, self.port_conn, byref(self.p_error_code)) # check key_handle and p_error_code value # According to documentation key_handle must be != 0 if success if self.key_handle == 0: raise Exception("Error! Can't open device") if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) def set_protocol_stack_settings(self, baud_rate, timeout): self.ret_val = self.epos.VCS_SetProtocolStackSettings(self.key_handle, baud_rate, timeout, byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return 0 def get_protocol_stack_settings(self): self.ret_val = self.epos.VCS_GetProtocolStackSettings(self.key_handle, byref(self.p_baud_rate), byref(self.p_time_out), byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return self.p_baud_rate.value, self.p_time_out.value def close_all_devices(self): self.ret_val = self.epos.VCS_CloseAllDevices(byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return 0 def close_device(self): self.ret_val = self.epos.VCS_CloseDevice(self.key_handle, byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return 0 def open_sub_device(self, device_name, protocol_stack_name): sub_key_handle = 0 sub_p_error_code = c_uint(0) sub_device_name = c_char_p(device_name.encode('ascii')) sub_protocol_stack_name = c_char_p(protocol_stack_name.encode('ascii')) sub_key_handle = self.epos.OpenSubDevice(self.key_handle, sub_device_name, sub_protocol_stack_name, byref(sub_p_error_code)) if sub_key_handle == 0: raise Exception("Error! Can't open device") if sub_p_error_code != 0: return sub_p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return sub_key_handle # TODO check if is correct def set_gateway_settings(self, baud_rate): self.ret_val = self.epos.VCS_SetGatewaySettings(self.key_handle, c_uint(baud_rate), byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return 0 def get_gateway_settings(self): p_baud_rate = c_uint(0) self.ret_val = self.epos.VCS_GetGatewaySettings(self.key_handle, byref(p_baud_rate), self.p_error_code) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return p_baud_rate.value def close_all_sub_devices(self): self.ret_val = self.epos.VCS_CloseAllSubDevices(self.key_handle, byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) def close_all_sub_device(self): self.ret_val = self.epos.VCS_CloseSubDevice(self.key_handle, byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) def get_error_info(self, error_code_value, max_str_size): """error_code_value deve essere di tipo DWORD (sistema il tipo) max_str_size deve essere di tipo WORD (sistema il tipo)""" p_error_info = c_char_p("".encode('ascii')) self.ret_val = self.epos.VCS_GetErrorInfo(error_code_value, p_error_info, max_str_size) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) def get_driver_info(self, max_str_name_size, max_str_version_size): p_library_name = c_char_p("".encode('ascii')) p_library_version = c_char_p("".encode('ascii')) self.ret_val = self.epos.VCS_GetDriverInfo(p_library_name, max_str_name_size, p_library_version, max_str_version_size) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return p_library_name, p_library_version def get_version(self): p_hw_version = c_uint(0) p_sw_version = c_uint(0) p_application_number = c_uint(0) p_application_version = c_uint(0) self.ret_val = self.epos.VCS_GetVersion(self.key_handle, self.node_id, byref(p_hw_version), byref(p_sw_version), byref(p_application_number), byref(p_application_version), byref(self.p_error_code)) if not self.ret_val: return -1 if self.p_error_code != 0: return self.p_error_code # TODO ritorna l'errore in base al numero restituito (crea una funzione apposita) return p_hw_version, p_sw_version, p_application_number, p_application_version
025aef748c72d3f9135d67a1c67c8d408f7f48ce
[ "Python" ]
2
Python
BRACU-DICHARI/pyMaxon
69a040a48219a85b1f3d0fd4d8c9d3728a50e669
85a52325f13fbd860b33bd833f862db7bdfcc63c
refs/heads/master
<file_sep>import ItemTemplate from '../ItemTemplate.js' import {Bar} from "../ResourceItems/resourceItems" import {playerArmor} from "../../../Animations/images" let BronzeArmor = [ { info : new ItemTemplate({ name: "Bronze Helm", price: 10000, animation: false, img: playerArmor.bronzeHelm, use : function(playerArmor) { this.bonus = 12; return playerArmor.addHelm(this); }, recipe : [ {item: Bar[0].info, quantity: 30} ] }) }, { info : new ItemTemplate({ name: "Bronze Chest", price: 15000, animation: false, img: playerArmor.bronzeChest, use : function(playerArmor) { this.bonus = 18; return playerArmor.addChest(this) }, recipe : [ {item: Bar[0].info, quantity: 50} ] }) }, { info : new ItemTemplate({ name: "Bronze Legs", price: 13000, animation: false, img: false, use : function(playerArmor) { this.bonus = 16; return playerArmor.addLegs(this) }, recipe : [ {item: Bar[0].info, quantity: 40} ] }) }, { info : new ItemTemplate({ name: "Bronze Boots", price: 9000, animation: false, img: false, use : function(playerArmor) { this.bonus = 10; return playerArmor.addFeet(this); }, recipe : [ {item: Bar[0].info, quantity: 20} ] }) }, { info : new ItemTemplate({ name: "Bronze Shield", price: 13000, animation: false, img: playerArmor.bronzeShield, use : function(playerArmor) { this.bonus = 19; return playerArmor.addShield(this); }, recipe : [ {item: Bar[0].info, quantity: 30} ] }) }, ] let IronArmor = [ { info : new ItemTemplate({ name: "Iron Helm", price: 50000, animation: false, img: playerArmor.ironHelm, use : function(playerArmor) { this.bonus = 27; return playerArmor.addHelm(this) }, recipe : [ {item: Bar[1].info, quantity: 50} ] }) }, { info : new ItemTemplate({ name: "Iron Chest", price: 65000, animation: false, img: playerArmor.ironChest, use : function(playerArmor) { this.bonus = 34; return playerArmor.addChest(this) }, recipe : [ {item: Bar[1].info, quantity: 80} ] }) }, { info : new ItemTemplate({ name: "Iron Legs", price: 60000, animation: false, img: false, use : function(playerArmor) { this.bonus = 32; return playerArmor.addLegs(this) }, recipe : [ {item: Bar[1].info, quantity: 70} ] }) }, { info : new ItemTemplate({ name: "Iron Boots", price: 40000, animation: false, img: false, use : function(playerArmor) { this.bonus = 25; return playerArmor.addFeet(this); }, recipe : [ {item: Bar[1].info, quantity: 40} ] }) }, { info : new ItemTemplate({ name: "Iron Shield", price: 60000, animation: false, img: playerArmor.ironShield, use : function(playerArmor) { this.bonus = 29; return playerArmor.addShield(this) }, recipe : [ {item: Bar[1].info, quantity: 60} ] }) }, ] let GoldArmor = [ { info : new ItemTemplate({ name: "Gold Helm", price: 100000, animation: false, img: playerArmor.goldHelm, use : function(playerArmor) { this.bonus = 47; return playerArmor.addHelm(this) }, recipe : [ {item: Bar[2].info, quantity: 50} ] }) }, { info : new ItemTemplate({ name: "Gold Chest", price: 120000, animation: false, img: playerArmor.goldChest, use : function(playerArmor) { this.bonus = 56; return playerArmor.addChest(this) }, recipe : [ {item: Bar[2].info, quantity: 80} ] }) }, { info : new ItemTemplate({ name: "Gold Legs", price: 110000, animation: false, img: false, use : function(playerArmor) { this.bonus = 52; return playerArmor.addLegs(this) }, recipe : [ {item: Bar[2].info, quantity: 70} ] }) }, { info : new ItemTemplate({ name: "Gold Boots", price: 90000, animation: false, img: false, use : function(playerArmor) { this.bonus = 48; return playerArmor.addFeet(this); }, recipe : [ {item: Bar[2].info, quantity: 40} ] }) }, { info : new ItemTemplate({ name: "Gold Shield", price: 112000, animation: false, img: playerArmor.goldShield, use : function(playerArmor) { this.bonus = 51; return playerArmor.addShield(this) }, recipe : [ {item: Bar[2].info, quantity: 60} ] }) }, ] let PlatinumArmor = [ { info : new ItemTemplate({ name: "Platinum Helm", price: 200000, animation: false, img: playerArmor.platinumHelm, use : function(playerArmor) { this.bonus = 68; return playerArmor.addHelm(this) }, recipe : [ {item: Bar[3].info, quantity: 50} ] }) }, { info : new ItemTemplate({ name: "Platinum Chest", price: 250000, animation: false, img: playerArmor.platinumChest, use : function(playerArmor) { this.bonus = 75; return playerArmor.addChest(this) }, recipe : [ {item: Bar[3].info, quantity: 80} ] }) }, { info : new ItemTemplate({ name: "Platinum Legs", price: 225000, animation: false, img: false, use : function(playerArmor) { this.bonus = 72; return playerArmor.addLegs(this) }, recipe : [ {item: Bar[3].info, quantity: 70} ] }) }, { info : new ItemTemplate({ name: "Platinum Boots", price: 190000, animation: false, img: false, use : function(playerArmor) { this.bonus = 69; return playerArmor.addFeet(this); }, recipe : [ {item: Bar[3].info, quantity: 40} ] }) }, { info : new ItemTemplate({ name: "Platinum Shield", price: 230000, animation: false, img: playerArmor.platinumShield, use : function(playerArmor) { this.bonus = 70; return playerArmor.addShield(this) }, recipe : [ {item: Bar[3].info, quantity: 60} ] }) }, ] let DiamondArmor = [ { info : new ItemTemplate({ name: "Diamond Helm", price: 500000, animation: false, img: playerArmor.diamondHelm, use : function(playerArmor) { this.bonus = 88; return playerArmor.addHelm(this) }, recipe : [ {item: Bar[4].info, quantity: 100} ] }) }, { info : new ItemTemplate({ name: "Diamond Chest", price: 750000, animation: false, img: playerArmor.diamondChest, use : function(playerArmor) { this.bonus = 95; return playerArmor.addChest(this) }, recipe : [ {item: Bar[4].info, quantity: 150} ] }) }, { info : new ItemTemplate({ name: "Diamond Legs", price: 600000, animation: false, img: false, use : function(playerArmor) { this.bonus = 91; return playerArmor.addLegs(this) }, recipe : [ {item: Bar[4].info, quantity: 130} ] }) }, { info : new ItemTemplate({ name: "Diamond Boots", price: 450000, animation: false, img: false, use : function(playerArmor) { this.bonus = 86; return playerArmor.addFeet(this); }, recipe : [ {item: Bar[4].info, quantity: 80} ] }) }, { info : new ItemTemplate({ name: "Diamond Shield", price: 610000, animation: false, img: playerArmor.diamondShield, use : function(playerArmor) { this.bonus = 90; return playerArmor.addShield(this) }, recipe : [ {item: Bar[4].info, quantity: 120} ] }) }, ] export { BronzeArmor, IronArmor, GoldArmor, PlatinumArmor, DiamondArmor } <file_sep>import ItemTemplate from '../ItemTemplate.js' import {plants} from "../ConsumeableItems/food" import {farmPlants, itemImages} from "../../../Animations/images" import ResourceAnimation from "../../../Animations/resourceAnimation" let Ore = [ { info : new ItemTemplate({ name: "Ore (T)", img: itemImages.ore.tin, use : function() { return ({description: "Used to Craft Armor and Weapons", used: false}); } }) }, { info : new ItemTemplate({ name: "Ore (C)", img: itemImages.ore.copper, use : function() { return ({description: "Used to Craft Armor and Weapons", used: false}); } }) }, { info : new ItemTemplate({ name: "Ore (I)", img: itemImages.ore.iron, use : function() { return ({description: "Used to Craft Armor and Weapons", used: false}); } }) }, { info : new ItemTemplate({ name: "Ore (G)", img: itemImages.ore.gold, use : function() { return ({description: "Used to Craft Armor and Weapons", used: false}); } }) }, { info : new ItemTemplate({ name: "Ore (P)", img: itemImages.ore.platinum, use : function() { return ({description: "Used to Craft Armor and Weapons", used: false}); } }) }, { info : new ItemTemplate({ name: "Diamond", img: itemImages.ore.diamond, use : function() { return ({description: "Used To Craft The Best Armor and Weapons", used: false}); } }) }, ] let Bar = [ { info : new ItemTemplate({ name: "Bar (B)", img: itemImages.bar.bronze, use : function() { return ({description: "Used To Create Armor and Weapons", used: false}); }, recipe: [{item: Ore[0].info, quantity:5}, {item: Ore[1].info, quantity:5}] }) }, { info : new ItemTemplate({ name: "Bar (I)", img: itemImages.bar.iron, use : function() { return ({description: "Used To Create Armor and Weapons", used: false}); }, recipe: [{item: Ore[2].info, quantity: 10}] }) }, { info : new ItemTemplate({ name: "Bar (G)", img: itemImages.bar.gold, use : function() { return ({description: "Used To Create Armor and Weapons", used: false}); }, recipe: [{item: Ore[3].info, quantity: 10}] }) }, { info : new ItemTemplate({ name: "Bar (P)", img: itemImages.bar.platinum, use : function() { return ({description: "Used To Create Armor and Weapons", used: false}); }, recipe: [{item: Ore[4].info, quantity: 10}] }) }, { info : new ItemTemplate({ name: "Diamond Brick", img: itemImages.bar.diamond, use : function() { return ({description: "Used To Craft Diamond Armor", used: false}); }, recipe: [{item: Ore[5].info, quantity:10}] }) }, ] let Wood = [ { info : new ItemTemplate({ name: "Log (O)", img: itemImages.wood.oak, use : function() { return ({description: "Used to Fletch weapon Handles", used: false}); } }) }, { info : new ItemTemplate({ name: "Log (M)", img: itemImages.wood.maple, use : function() { return ({description: "Used to Fletch weapon Handles", used: false}); } }) }, { info : new ItemTemplate({ name: "Log (MO)", img: itemImages.wood.mahogony, use : function() { return ({description: "Used to Fletch weapon Handles", used: false}); } }) }, { info : new ItemTemplate({ name: "Log (MA)", img: itemImages.wood.magic, use : function() { return ({description: "Used to Fletch weapon Handles", used: false}); } }) }, { info : new ItemTemplate({ name: "Log (SU)", img: itemImages.wood.super, use : function() { return ({description: "Used to Fletch weapon Handles", used: false}); } }) }, ] let Seeds = [ { info : new ItemTemplate({ name: "Seeds (C)", animation: new ResourceAnimation(farmPlants.carrot), img: itemImages.seed.carrot, use : function() { let item = plants[0].info.copy(); item.quantity = 10; return ({item : item, description: "Used For Farming carrots", used: false}); } }) }, { info : new ItemTemplate({ name: "Seeds (P)", animation: new ResourceAnimation(farmPlants.potatoe), img: itemImages.seed.potato, use : function() { let item = plants[1].info.copy(); item.quantity = 10; return ({item : item, description: "Used For Farming Potatoes", used: false}); } }) }, { info : new ItemTemplate({ name: "Seeds (CO)", animation: new ResourceAnimation(farmPlants.corn), img: itemImages.seed.corn, use : function() { let item = plants[2].info.copy(); item.quantity = 10; return ({item : item, description: "Used For Farming Corn", used: false}); } }) }, { info : new ItemTemplate({ name: "Seeds (CU)", animation: new ResourceAnimation(farmPlants.cucumber), img: itemImages.seed.cucumber, use : function() { let item = plants[3].info.copy(); item.quantity = 10; return ({item : item, description: "Used For Farming Cucumber", used: false}); } }) }, { info : new ItemTemplate({ name: "Seeds (T)", animation: new ResourceAnimation(farmPlants.tomato), img: itemImages.seed.tomato, use : function() { let item = plants[4].info.copy(); item.quantity = 10; return ({item : item, description: "Used For Farming Tomatoes", used: false}); } }) }, { info : new ItemTemplate({ name: "Seeds (A)", animation: new ResourceAnimation(farmPlants.artichoke), img: itemImages.seed.artichoke, use : function() { let item = plants[5].info.copy(); item.quantity = 10; return ({item : item, description: "Used For Farming Artichoke", used: false}); } }) }, ] export { Ore, Bar, Wood, Seeds } <file_sep>import ItemTemplate from '../ItemTemplate.js' import {itemImages} from "../../../Animations/images" let drinks = [ { info : new ItemTemplate({ name: "Water (T)", img: itemImages.water.tiny, use: function(skill) { skill.thirst.giveLimit(1) skill.thirst.addXp(1) return ({skill: skill, description: "Drink Up", used: true}); } }) }, { info : new ItemTemplate({ name: "Water (S)", img: itemImages.water.small, use: function(skill) { skill.thirst.giveLimit(2) skill.thirst.addXp(2) return ({skill: skill, description: "Drink Up", used: true}); } }) }, { info : new ItemTemplate({ name: "Water (M)", img: itemImages.water.medium, use: function(skill) { skill.thirst.giveLimit(4) skill.thirst.addXp(4) return ({skill: skill, description: "Drink Up", used: true}); } }) }, { info : new ItemTemplate({ name: "Water (L)", img: itemImages.water.large, use: function(skill) { skill.thirst.giveLimit(8) skill.thirst.addXp(8) return ({skill: skill, description: "Drink Up", used: true}); } }) }, { info : new ItemTemplate({ name: "Water (G)", img: itemImages.water.giant, use: function(skill) { skill.thirst.giveLimit(16) skill.thirst.addXp(16) return ({skill: skill, description: "Drink Up", used: true}); } }) }, { info : new ItemTemplate({ name: "Water (GD)", img: itemImages.water.god, use: function(skill) { skill.thirst.giveLimit(32) skill.thirst.addXp(32) return ({skill: skill, description: "Drink Up", used: true}); } }) }, ] export default drinks <file_sep>import Category from "./itemCategory" import ItemTemplate from './Types/ItemTemplate.js' import potions from "./Types/ConsumeableItems/potions" import {food, cookedFood, plants} from "./Types/ConsumeableItems/food" import drinks from "./Types/ConsumeableItems/drinks" import { BronzeArmor, IronArmor, GoldArmor, PlatinumArmor, DiamondArmor } from "./Types/PlayerItems/armorItems" import { BronzeWeapons, IronWeapons, GoldWeapons, PlatinumWeapons, DiamondWeapons, rangeWeapons, arrows } from "./Types/PlayerItems/weaponItems" import { magicItems } from "./Types/PlayerItems/magicItems" import { Wood, Ore, Bar, Seeds } from "./Types/ResourceItems/resourceItems" import {randomInt} from "../../Helpers/functions" export default class Items { constructor() { this.categoryIndex = 0; this.subCategoryIndex = 0; this.itemIndex = 0; this.totalCategories = 0; this.totalSubCategories = 0; this.totalItems = 0; this.categories = []; this.createCategories() this.createSubCategories(); this.addConsumeableItemsToSubcategory() this.addArmorItemsToSubcategory() this.addWeaponItemsToSubcategory() this.addResourceItemsToSubcategory() this.addMagicItemsToSubcategory(); } nextCategory() { this.categoryIndex++; } prevCategory() { this.categoryIndex--; } nextSubCategory() { this.subCategoryIndex++; } prevSubCategory() { this.subCategoryIndex--; } getItemFromClick(index) { return (this.categories[this.categoryIndex].subcategory[this.subCategoryIndex].items[index].info.copy); } none() { let noItem = new ItemTemplate({ name: "None", use: function(skill) { return ("No Item to Use"); } }) noItem.setId(-1); return (noItem); } randomItemDrop(level) { let chance = randomInt(1, 100); if (chance > 100) { return this.none(); } let potions = this.returnItems(0,0); let seeds = this.returnItems(1,2); let magicStones = this.returnItems(4,0); // consumable or resources // choose random category, select level of item chance = randomInt(0, 50); let currentItems = potions; if (chance <= 8) { currentItems = potions; } else if (chance > 10 && chance <= 40){ currentItems = seeds } else if (chance > 40 && chance <= 43) { currentItems = magicStones return currentItems[randomInt(0, currentItems.length - 1)] } else { return this.none(); } let itemIndex = 0; if (level >= 0 && level < 20) { itemIndex = 0; } else if (level >= 20 && level < 40) { itemIndex = randomInt(0, 1); } else if (level >= 40 && level < 60) { itemIndex = randomInt(0, 2); } else if (level >= 60 && level < 80) { itemIndex = randomInt(0, 3); } else if (level >= 80 && level < 100) { itemIndex = randomInt(0, 4); } else { itemIndex = randomInt(0, currentItems.length - 1); } return (currentItems[itemIndex]); } randomWeapon(level) { // consumable or resources // choose random category, select level of item let categoryIndex = 3 let subCategoryIndex = 0; let itemIndex = randomInt(0, 1); if (level >= 0 && level < 20) { subCategoryIndex = 0; } else if (level >= 20 && level < 40) { subCategoryIndex = randomInt(0, 1); } else if (level >= 40 && level < 60) { subCategoryIndex = randomInt(0, 2); } else if (level >= 60 && level < 80) { subCategoryIndex = randomInt(0, 3); } else if (level >= 80 && level < 100) { subCategoryIndex = randomInt(0, 4); } else { subCategoryIndex = randomInt(0, 4); } return (this.returnOneItem(categoryIndex, subCategoryIndex, itemIndex)); } randomFood(level) { let categoryIndex = 0 let subCategoryIndex = 1; let itemIndex = 0 if (level >= 0 && level < 20) { itemIndex = 0; } else if (level >= 20 && level < 40) { itemIndex = 1 } else if (level >= 40 && level < 60) { itemIndex = 3 } else if (level >= 60 && level < 80) { itemIndex = 4 } else if (level >= 80 && level < 100) { itemIndex = 2 } else { itemIndex = 2 } return (this.returnOneItem(categoryIndex, subCategoryIndex, itemIndex)); } addToCategories(name, settings) { this.categories.push(new Category(name, this.totalCategories, settings)) this.totalCategories++; } listCategories() { let count = this.categories.length for (let x = 0; x < count; x++) { console.log(this.categories[x].name); console.log(this.categories[x].id); } } returnCategorySettings(index) { return this.categories[index].settings; } listSubCategories(index) { this.categories[index].listSubCategories(); } returnSubCategories(index) { return(this.categories[index].returnSubCategories()); } returnSubCategorySettings(categoryIndex, index) { return (this.categories[categoryIndex].returnSubCategorySettings(index)); } returnItems(index, subCategoryIndex) { return (this.categories[index].returnItems(subCategoryIndex)); } returnOneItem(index, subCategoryIndex, itemIndex) { return (this.categories[index].returnOneItem(subCategoryIndex, itemIndex)); } returnItemNames(index, subCategoryIndex) { return (this.categories[index].returnItemNames(subCategoryIndex)); } returnItemsByName(category, subcategory) { return (this.categories[category].subcategory[subcategory]); } createCategories() { const consumeableSettings = { buyable : true, craftable : true } const resourceSettings = { buyable: false, craftable : true } const armorSettings = { buyable: true, craftable: true, } const weaponSettings = { buyable: true, craftable: true, } const magicSettings = { buyable: false, craftable: false, } this.addToCategories("Consumeable", consumeableSettings); this.addToCategories("Resources", resourceSettings); this.addToCategories("Armor", armorSettings); this.addToCategories("Weapon", weaponSettings); this.addToCategories("Magic", magicSettings); } createSubCategories() { const foodSettings = { buyable : false, useable : true, craftable : false, } const potionSettings = { buyable : true, useable : true, craftable : true, } const cookFoodSettings = { buyable : false, useable : true, craftable : true, } const resourceSettings = { buyable : false, useable : false, craftable : false, } const barSettings = { buyable : false, useable : false, craftable : true } const weaponSettings = { buyable : true, useable : false, craftable : true } const armorSettings = { buyable : true, useable : false, craftable : true } const magicSettings = { buyable : false, useable : false, craftable : false } let sub_id = 0; this.categories[0].addSubCategory("Potion", sub_id++, potionSettings); this.categories[0].addSubCategory("Food", sub_id++, foodSettings); this.categories[0].addSubCategory("Water", sub_id++, foodSettings); this.categories[0].addSubCategory("Cooked Food", sub_id++, cookFoodSettings); this.categories[0].addSubCategory("Plants", sub_id++, foodSettings); sub_id = 0; this.categories[1].addSubCategory("Ores", sub_id++, resourceSettings); this.categories[1].addSubCategory("WoodCutting", sub_id++, resourceSettings); this.categories[1].addSubCategory("Gathering", sub_id++, resourceSettings); this.categories[1].addSubCategory("Bars", sub_id++, barSettings); sub_id = 0; this.categories[2].addSubCategory("Bronze", sub_id++, armorSettings); this.categories[2].addSubCategory("Iron", sub_id++, armorSettings); this.categories[2].addSubCategory("Gold", sub_id++, armorSettings); this.categories[2].addSubCategory("Platinum", sub_id++, armorSettings); this.categories[2].addSubCategory("Diamond", sub_id++, armorSettings); sub_id = 0; this.categories[3].addSubCategory("Bronze", sub_id++, weaponSettings); this.categories[3].addSubCategory("Iron", sub_id++, weaponSettings); this.categories[3].addSubCategory("Gold", sub_id++, weaponSettings); this.categories[3].addSubCategory("Platinum", sub_id++, weaponSettings); this.categories[3].addSubCategory("Diamond", sub_id++, weaponSettings); this.categories[3].addSubCategory("Bow", sub_id++, weaponSettings); this.categories[3].addSubCategory("Arrows", sub_id++, weaponSettings); sub_id = 0; this.categories[4].addSubCategory("Magic", sub_id++, magicSettings); } addConsumeableItemsToSubcategory() { this.totalItems = this.categories[0].subcategory[0].addItems(potions, this.totalItems); this.totalItems = this.categories[0].subcategory[1].addItems(food, this.totalItems); this.totalItems = this.categories[0].subcategory[2].addItems(drinks, this.totalItems); this.totalItems = this.categories[0].subcategory[3].addItems(cookedFood, this.totalItems); this.totalItems = this.categories[0].subcategory[4].addItems(plants, this.totalItems); } addMagicItemsToSubcategory() { this.totalItems = this.categories[4].subcategory[0].addMagicItems(magicItems, this.totalItems); } addResourceItemsToSubcategory() { this.totalItems = this.categories[1].subcategory[0].addItems(Ore, this.totalItems); this.totalItems = this.categories[1].subcategory[1].addItems(Wood, this.totalItems); this.totalItems = this.categories[1].subcategory[2].addItems(Seeds, this.totalItems); this.totalItems = this.categories[1].subcategory[3].addItems(Bar, this.totalItems); } addArmorItemsToSubcategory() { this.totalItems = this.categories[2].subcategory[0].addWeaponAndArmorItems(BronzeArmor, this.totalItems); this.totalItems = this.categories[2].subcategory[1].addWeaponAndArmorItems(IronArmor, this.totalItems); this.totalItems = this.categories[2].subcategory[2].addWeaponAndArmorItems(GoldArmor, this.totalItems); this.totalItems = this.categories[2].subcategory[3].addWeaponAndArmorItems(PlatinumArmor, this.totalItems); this.totalItems = this.categories[2].subcategory[4].addWeaponAndArmorItems(DiamondArmor, this.totalItems); } addWeaponItemsToSubcategory() { this.totalItems = this.categories[3].subcategory[0].addWeaponAndArmorItems(BronzeWeapons, this.totalItems); this.totalItems = this.categories[3].subcategory[1].addWeaponAndArmorItems(IronWeapons, this.totalItems); this.totalItems = this.categories[3].subcategory[2].addWeaponAndArmorItems(GoldWeapons, this.totalItems); this.totalItems = this.categories[3].subcategory[3].addWeaponAndArmorItems(PlatinumWeapons, this.totalItems); this.totalItems = this.categories[3].subcategory[4].addWeaponAndArmorItems(DiamondWeapons, this.totalItems); this.totalItems = this.categories[3].subcategory[5].addWeaponAndArmorItems(rangeWeapons, this.totalItems); this.totalItems = this.categories[3].subcategory[6].addWeaponAndArmorItems(arrows, this.totalItems); } } <file_sep>const seed = (db) => { return Promise.all([ // db.users.create({ // name: "NEW USER", password: "<PASSWORD>" // }).then((user) => console.log(user)), // db.users.create({ // name: "another one", password: "<PASSWORD>" // }).then((user) => console.log(user)), db.inventoryItems.bulkCreate([ {name: 'INV ITEM1', user_id: 1}, {name: 'INV ITEM2', user_id: 1}, {name: 'INVITEM 3', user_id: 1} ]), db.skills.bulkCreate([ { value: 2, current : 2, name: "Attack", boost : 2, xp : 2, threshold : 2, user_id: 1, }, { value: 2, current : 2, name: "Speed", boost : 2, xp : 2, threshold : 2, user_id: 1, }, ]) ]) .catch(error => console.log(error)); }; module.exports = { seed }<file_sep>import RigidBody from "../../Helpers/rigidBody" import Draw from "./draw" import {userInterface, playerImages, playerHair, playerPants, playerShirts} from "../../Objects/Animations/images" import ClickHandler from "../clickhandler" export default class GameStartScreen { constructor() { this.page = "start"; this.startGame = false; this.open = true; this.background = { img : userInterface.bankBackGround, body : new RigidBody(0,0,480,480), draw : new Draw(), info: "IDLE FOREST", display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 70, this.body.pos.y + 100, 50, ctx) } } this.start = { startButton : { img : userInterface.greenButton, body : new RigidBody(150, 100, 200,100), info : "Start", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 35, this.body.pos.y + 60, 40, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "chooseName"; } return false; } }, optionsButton : { img : userInterface.greenButton, body : new RigidBody(150, 200, 200,100), info : "Options", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 25, this.body.pos.y + 60, 40, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "options"; } return(false) } }, creditsButton : { img : userInterface.aquaButton, body : new RigidBody(150, 300, 200,100), info : "Credits", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 35, this.body.pos.y + 60, 30, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "credits"; } return(false) } } } this.options = { backButton : { img : userInterface.redButton, body : new RigidBody(150, 100, 200,100), info : "Back", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 35, this.body.pos.y + 60, 40, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "start"; } return("options") } }, soundButton : { img : userInterface.aquaButton, body : new RigidBody(150, 200, 200,100), info : "Sound", draw : new Draw(), clickHandler : new ClickHandler(), on: false, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info + " " + (this.on ? "on" : "off") , this.body.pos.x + 35, this.body.pos.y + 60, 30, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { this.on = !this.on; } return(false) } }, difficultyButton : { img : userInterface.aquaButton, body : new RigidBody(150, 300, 200,100), info : "difficulty", draw : new Draw(), clickHandler : new ClickHandler(), difficulties : ["Easy", "Medium", "Hard"], index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.difficulties[this.index] , this.body.pos.x + 35, this.body.pos.y + 60, 30, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { this.index++; if (this.index >= this.difficulties.length) { this.index = 0; } } return(false) } } } this.credits = { backButton : { img : userInterface.redButton, body : new RigidBody(150, 100, 200,100), info : "Back", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 35, this.body.pos.y + 60, 40, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "start"; } return("credits") } }, } this.chooseName = { label : "Name :", letters : this.makeLetterButtons(), draw: new Draw(), display(player, ctx) { this.draw.text(this.label, 120, 330, 35, ctx, "blue"); this.draw.text(player.name, 240, 330, 35, ctx, "blue"); for (let x = 0; x < this.letters.length; x++) { this.letters[x].display(ctx) } }, add : function(player, letter) { player.name = player.name += letter; }, delete : function(player, mouse,canvas) { if (this.deleteButton.onClick(mouse, canvas)) { player.name = player.name.substring(0, player.name.length - 1); return false } return false }, onClick : function(player, mouse,canvas) { for (let x = 0; x < this.letters.length; x++) { let currLetter = this.letters[x].onClick(mouse,canvas); if (currLetter) { this.add(player, currLetter); return true } } return false }, startButton : { img : userInterface.greenButton, body : new RigidBody(240, 400, 100,50), info : "Next", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 30, 20, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "choosePassword"; } return false; }, }, backButton : { img : userInterface.redButton, body : new RigidBody(130, 400, 100,50), info : "Back", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 30, 20, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "start"; } return false; }, }, deleteButton : { img : userInterface.redButton, body : new RigidBody(390, 247, 80,40), info : "Delete", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 25, 15, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true) } return(false); } } } this.choosePassword = { label : "Pass :", letters : this.makeLetterButtons(), password: "", draw: new Draw(), display(player, ctx) { this.draw.text(this.label, 120, 330, 35, ctx, "blue"); this.draw.text(this.password, 240, 330, 35, ctx, "blue"); for (let x = 0; x < this.letters.length; x++) { this.letters[x].display(ctx) } }, add : function(player, letter) { player.password = player.password += letter; this.password += '*'; }, delete : function(player, mouse,canvas) { if (this.deleteButton.onClick(mouse, canvas)) { player.password = player.password.substring(0, player.password.length - 1); this.password = this.password.substring(0, this.password.length - 1); return false } return false }, onClick : function(player, mouse,canvas) { for (let x = 0; x < this.letters.length; x++) { let currLetter = this.letters[x].onClick(mouse,canvas); if (currLetter) { this.add(player, currLetter); return true } } return false }, startButton : { img : userInterface.greenButton, body : new RigidBody(240, 400, 100,50), info : "Next", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 30, 20, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "characterSelect"; } return false; }, }, backButton : { img : userInterface.redButton, body : new RigidBody(130, 400, 100,50), info : "Back", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 30, 20, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "start"; } return false; }, }, deleteButton : { img : userInterface.redButton, body : new RigidBody(390, 247, 80,40), info : "Delete", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 25, 15, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true) } return(false); } } } this.choosePlayer = { startButton : { img : userInterface.greenButton, body : new RigidBody(240, 400, 100,50), info : "Start", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 30, 20, ctx, "purple") }, onClick : function(mouse,canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return true; } return false; }, }, backButton : { img : userInterface.redButton, body : new RigidBody(130, 400, 100,50), info : "Back", draw : new Draw(), clickHandler : new ClickHandler(), display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 20, this.body.pos.y + 30, 20, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return "chooseName"; } return("characterSelect"); } }, skin: { types : [ playerImages.coffee, playerImages.comet, playerImages.copper, playerImages.dove, playerImages.gold, playerImages.gray, playerImages.ivory, playerImages.sienna ], index : 0, info : "skin", draw : new Draw(), display : function (ctx){ this.prevButton.display(ctx); this.nextButton.display(ctx); this.draw.text(this.info, this.prevButton.body.pos.x + 57, this.prevButton.body.pos.y + 30, 20, ctx, "purple") }, change: function(player) { player.armor.animation.changePlayer(this.types[this.index]); }, next: function(player) { this.index++; if (this.index >= this.types.length) { this.index = 0; } this.change(player); }, prev: function(player) { this.index--; if (this.index < 0) { this.index = this.types.length; } this.change(player); }, onClick(player, mouse, canvas) { if (this.prevButton.onClick(mouse,canvas)) { this.prev(player); } if (this.nextButton.onClick(mouse,canvas)) { this.next(player); } }, prevButton : { img : userInterface.greenButton, body : new RigidBody(160, 150, 50,50), info : "<", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } }, nextButton : { img : userInterface.greenButton, body : new RigidBody(260, 150, 50,50), info : ">", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } } }, hair: { types : [ playerHair.black, playerHair.brown, playerHair.gold, playerHair.red, playerHair.darkRed, ], index: 0, info : "hair", draw : new Draw(), display : function (ctx){ this.prevButton.display(ctx); this.nextButton.display(ctx); this.draw.text(this.info, this.prevButton.body.pos.x + 57, this.prevButton.body.pos.y + 30, 20, ctx, "purple") }, next: function(player) { this.index++; if (this.index >= this.types.length) { this.index = 0; } this.change(player) }, prev: function(player) { this.index--; if (this.index < 0) { this.index = this.types.length; } this.change(player) }, change: function(player) { player.armor.animation.addHair(this.types[this.index]); }, onClick(player, mouse, canvas) { if (this.prevButton.onClick(mouse,canvas)) { this.prev(player); } if (this.nextButton.onClick(mouse,canvas)) { this.next(player); } }, prevButton : { img : userInterface.greenButton, body : new RigidBody(160, 200, 50,50), info : "<", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } }, nextButton : { img : userInterface.greenButton, body : new RigidBody(260, 200, 50,50), info : ">", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } } }, shirt: { types : [ playerShirts.black, playerShirts.blue, playerShirts.forest, playerShirts.gray, playerShirts.lavender, playerShirts.sky, playerShirts.teal, ], index: 0, info : "shirt", draw : new Draw(), display : function (ctx){ this.prevButton.display(ctx); this.nextButton.display(ctx); this.draw.text(this.info, this.prevButton.body.pos.x + 52, this.prevButton.body.pos.y + 30, 20, ctx, "purple") }, next: function(player) { this.index++; if (this.index >= this.types.length) { this.index = 0; } this.change(player) }, prev: function(player) { this.index--; if (this.index < 0) { this.index = this.types.length; } this.change(player) }, change: function(player) { player.armor.animation.addShirt(this.types[this.index]); }, onClick(player, mouse, canvas) { if (this.prevButton.onClick(mouse,canvas)) { this.prev(player); } if (this.nextButton.onClick(mouse,canvas)) { this.next(player); } }, prevButton : { img : userInterface.greenButton, body : new RigidBody(160, 250, 50,50), info : "<", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } }, nextButton : { img : userInterface.greenButton, body : new RigidBody(260, 250, 50,50), info : ">", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } } }, pants: { types : [ playerPants.black, playerPants.blue, playerPants.forest, playerPants.gray, playerPants.lavender, playerPants.sky, playerPants.teal, ], index: 0, info : "pants", draw : new Draw(), display : function (ctx){ this.prevButton.display(ctx); this.nextButton.display(ctx); this.draw.text(this.info, this.prevButton.body.pos.x + 49, this.prevButton.body.pos.y + 30, 20, ctx, "purple") }, next: function(player) { this.index++; if (this.index >= this.types.length) { this.index = 0; } this.change(player) }, prev: function(player) { this.index--; if (this.index < 0) { this.index = this.types.length; } this.change(player) }, change: function(player) { player.armor.animation.addPants(this.types[this.index]); }, onClick(player, mouse, canvas) { if (this.prevButton.onClick(mouse,canvas)) { this.prev(player); } if (this.nextButton.onClick(mouse,canvas)) { this.next(player); } }, prevButton : { img : userInterface.greenButton, body : new RigidBody(160, 300, 50,50), info : "<", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } }, nextButton : { img : userInterface.greenButton, body : new RigidBody(260, 300, 50,50), info : ">", draw : new Draw(), clickHandler : new ClickHandler(), index: 0, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info , this.body.pos.x + 20, this.body.pos.y + 30, 30, ctx, "purple") }, onClick(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return (true); } return(false) } } }, } } letter(x,y,w,h, letter) { let button = { clickHandler : new ClickHandler(), img : userInterface.greenButton, draw : new Draw(), body : new RigidBody(x, y, w,h), info : letter, display : function(ctx) { this.draw.img(this.img, this.body.pos.x, this.body.pos.y, this.body.size.x, this.body.size.y, ctx); this.draw.text(this.info, this.body.pos.x + 10, this.body.pos.y + 20, 15, ctx, "purple") }, onClick : function(mouse, canvas) { let click = this.clickHandler.click(mouse, this, canvas); if (click) { return this.info; } return(false) } } return button } makeLetterButtons() { let line1 = ["q","w","e","r","t","y","u","i","o","p"] let line2 = ["a","s","d","f","g","h","j","k","l"] let line3 = ["z","x","c","v","b","n","m"] let letters = [] for (let x = 0; x < line1.length; x++) { letters.push(this.letter((x * 45) + 20, 150 ,40,40, line1[x])); } for (let x = 0; x < line2.length; x++) { letters.push(this.letter((x * 45) + 40, 200 ,40,40, line2[x])); } for ( let x = 0; x < line3.length; x++) { letters.push(this.letter((x * 45) + 70, 250 ,40,40, line3[x])); } return letters } display(player,ctx) { if (this.open === false) { return false; } this.background.display(ctx); if (this.page === "start") { this.start.startButton.display(ctx); this.start.optionsButton.display(ctx); this.start.creditsButton.display(ctx); } else if (this.page === "chooseName") { this.chooseName.display(player, ctx); this.chooseName.deleteButton.display(ctx); this.chooseName.startButton.display(ctx); this.chooseName.backButton.display(ctx); } else if (this.page === "choosePassword") { this.choosePassword.display(player, ctx); this.choosePassword.deleteButton.display(ctx); this.choosePassword.startButton.display(ctx); this.choosePassword.backButton.display(ctx); } else if (this.page === "options") { this.options.backButton.display(ctx); this.options.soundButton.display(ctx); this.options.difficultyButton.display(ctx); } else if (this.page === "credits") { this.credits.backButton.display(ctx); } if (this.page === "characterSelect") { this.choosePlayer.skin.display(ctx); this.choosePlayer.hair.display(ctx); this.choosePlayer.shirt.display(ctx); this.choosePlayer.pants.display(ctx); this.choosePlayer.startButton.display(ctx); this.choosePlayer.backButton.display(ctx); } } characterSelectClick(player, mouse, canvas) { this.choosePlayer.skin.onClick(player,mouse,canvas); this.choosePlayer.hair.onClick(player,mouse,canvas); this.choosePlayer.shirt.onClick(player,mouse,canvas); this.choosePlayer.pants.onClick(player,mouse,canvas); this.page = this.choosePlayer.backButton.onClick(mouse,canvas) this.startGame = this.choosePlayer.startButton.onClick(mouse,canvas) } clickHandler(player, mouse,canvas) { if (this.open === false) { return false; } let click = false; if (this.page === "start") { if (this.page = this.start.startButton.onClick(mouse,canvas)) { return false } if (this.page = this.start.optionsButton.onClick(mouse,canvas)) { return false } if (this.page = this.start.creditsButton.onClick(mouse,canvas)) { return false } } else if (this.page === "chooseName") { click = this.chooseName.onClick(player,mouse,canvas); if (click) { return false; } click = this.chooseName.delete(player,mouse,canvas); if (click) { return false; } click = this.chooseName.backButton.onClick(mouse,canvas); if (click) { this.page = click; return false; } click = this.page = this.chooseName.startButton.onClick(mouse,canvas) if (click) { this.page = click; return false; } this.page = "chooseName" } else if (this.page === "choosePassword") { click = this.choosePassword.onClick(player,mouse,canvas); if (click) { return false; } click = this.choosePassword.delete(player,mouse,canvas); if (click) { return false; } click = this.choosePassword.backButton.onClick(mouse,canvas); if (click) { this.page = click; return false; } click = this.page = this.choosePassword.startButton.onClick(mouse,canvas) if (click) { this.page = click; this.open = false; return false; } this.page = "choosePassword" } if (this.page === "options") { this.page = this.options.backButton.onClick(mouse,canvas) this.options.soundButton.onClick(mouse,canvas) this.options.difficultyButton.onClick(mouse,canvas) } if (this.page === "credits") { this.page = this.credits.backButton.onClick(mouse,canvas) } if (this.page === "characterSelect") { this.characterSelectClick(player, mouse, canvas) } } }<file_sep>import RigidBody from "../rigidBody" function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } function scale(value, x1, y1, x2, y2) { return ((value - x1) * (y2 - x2) / (y1 - x1) + x2) } function button (x, y, width, height) { return ({ body : new RigidBody(x,y,width,height) }) } function timer (time) { let date = new Date(); let expiration = date.getTime() + time; return ({ date : date, time : time, expiration: expiration, reset: function() { let date = new Date(); let newTime = date.getTime() this.expiration = newTime + this.time; }, isDone() { let date = new Date(); let newTime = date.getTime() if (newTime > this.expiration) { return (true) } return false; }, check : function() { let date = new Date(); let newTime = date.getTime() if (newTime > this.expiration) { this.reset(); return (true) } return false }, setExpiration : function(newExpiration) { this.time = newExpiration; this.reset() } }) } export { randomInt, scale, button, timer, }<file_sep>export default class Vector2d { constructor(x, y) { this.x = x; this.y = y } test() { let v = new Vector2d(10,20); v.log(); let one = new Vector2d(20,10); one.log(); } log() { console.log(this.x, this.y); } } <file_sep>import Item from "../../Objects/Item" import Player from "../../Objects/Player" export default class InventoryTest { constructor() { // this.inventory = new Inventory(); this.player = new Player(); this.player.setName("PLAYER!") this.player2 = new Player(); this.player2.setName("PLAYER @@@") console.log("TESTING INVENTORY") this.test(); } fillInventory(items) { for (let i = 0; i < 10; i++) { console.log(this.player.inventory.add(items.smallPotion())); console.log(this.player.inventory.add(items.mediumPotion())); console.log(this.player.inventory.add(items.largePotion())); console.log(this.player.inventory.add(items.megaPotion())); console.log(this.player.inventory.add(items.tinyWater())); console.log(this.player.inventory.add(items.smallWater())); console.log(this.player.inventory.add(items.mediumWater())); console.log(this.player.inventory.add(items.largeWater())); console.log(this.player.inventory.add(items.megaWater())); console.log(this.player.inventory.add(items.tinyFood())); console.log(this.player.inventory.add(items.smallFood())); console.log(this.player.inventory.add(items.mediumFood())); console.log(this.player.inventory.add(items.largeFood())); console.log(this.player.inventory.add(items.megaFood())); console.log(this.player.inventory.add(items.healthLevel())); console.log(this.player.inventory.add(items.attackSpeedLevel())); console.log(this.player.inventory.add(items.attackLevel())); console.log(this.player.inventory.add(items.thirstLevel())); console.log(this.player.inventory.add(items.hungerLevel())); } } useItems() { for (let i = 0; i < 20; i++) { this.player2.inventory.useItem(this.player2.skills, 14); } } transferInventory() { this.player2.inventory.addInventory(this.player.inventory) console.log(this.player2.inventory); } test() { // let skills = new Skills(); let items = new Item(); this.fillInventory(items) this.transferInventory(); this.useItems(); console.log("INVENTORY SPACES") console.log(this.player2.skills) } }<file_sep> module.exports = (app, db) => { app.get('/armor', (req, res) => { db.armorItems.findAll({ where : { user_id: req.session.userId, }, }).then(armor => { if (armor) { console.log(armor) res.json({code: 1, message: "Get Armor Success", armor: armor}) } else { res.json({code : -1, message: "No Session Available"}) } }); }) app.post('/saveArmor', (req, res) => { let armor = req.body.armor let armorKeys = Object.keys(armor) let key = false; let createArmor = []; for (key of armorKeys) { createArmor.push({ user_id : req.session.userId, armor_id : armor[key].id, key : key, name : armor[key].item.name, item_id: armor[key].item.id, item_index: armor[key].item.item_index, subCategory_id: armor[key].item.subCategory_id, category_id :armor[key].item.category_id, quantity : armor[key].item.quantity, }) } db.armorItems.bulkCreate(createArmor).then(function() { res.json({code : 1, message: "Armor save Successful"}) }, function(err){ res.json({code : -1, message: "Armor save Not Successful"}) }) }) app.post('/updateArmor', (req, res) => { let armor = req.body.armor let armorKeys = Object.keys(armor) let key = false; for (key of armorKeys) { db.armorItems.update({ armor_id : armor[key].id, name : armor[key].item.name, item_id: armor[key].item.id, item_index: armor[key].item.item_index, subCategory_id: armor[key].item.subCategory_id, category_id :armor[key].item.category_id, quantity : armor[key].item.quantity, }, { where: {armor_id: armor[key].id, user_id : req.session.userId}, returning: true, // needed for affectedRows to be populated }).then(function() { }, function(err){ res.json({code : -1, message: "Update Not Successful"}) return -1; }) } res.json({code : 1, message: "Skill Update Successful"}) }) }<file_sep>import ItemTemplate from '../ItemTemplate.js' import {playerWeapons, playerTools} from "../../../Animations/images" import {Bar, Wood} from "../ResourceItems/resourceItems" //take in inventory, move item to armor/weapon slot //return a bonus whenever needed let BronzeWeapons = [ { info : new ItemTemplate({ name : "Mace (B)", price : 10000, bonus : 8, speed : 150, animation: false, img : false, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[0].info, quantity: 10}, {item: Wood[0].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "Sword (B)", price : 30000, bonus : 12, speed : 125, animation: false, img : playerWeapons.bronzeSword, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[0].info, quantity: 20}, {item: Wood[0].info, quantity: 700} ] }), }, { info : new ItemTemplate({ name : "Axe (B)", price : 50, bonus : 2, speed : 150, animation: false, img : playerTools.bronzeAxe, use : function(playerArmor) { return playerArmor.addAxe(this); }, recipe: [ {item: Bar[0].info, quantity: 2}, {item: Wood[0].info, quantity: 20} ] }), }, { info : new ItemTemplate({ name : "Pickaxe (B)", price : 50, bonus : 2, speed : 150, animation: false, img : playerTools.bronzePickaxe, use : function(playerArmor) { return playerArmor.addPickAxe(this); }, recipe: [ {item: Bar[0].info, quantity: 2}, {item: Wood[0].info, quantity: 20} ] }), }, ] let IronWeapons = [ { info : new ItemTemplate({ name : "Iron Mace", price : 100000, bonus : 20, speed : 140, animation: false, img : false, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[1].info, quantity: 10}, {item: Wood[1].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "Iron Sword", price : 115000, bonus : 26, speed : 115, animation: false, img : playerWeapons.ironSword, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[1].info, quantity: 20}, {item: Wood[1].info, quantity: 700} ] }), }, { info : new ItemTemplate({ name : "Iron Axe", price : 500, bonus : 10, speed : 140, animation: false, img : playerTools.ironAxe, use : function(playerArmor) { return playerArmor.addAxe(this); }, recipe: [ {item: Bar[1].info, quantity: 2}, {item: Wood[1].info, quantity: 20} ] }), }, { info : new ItemTemplate({ name : "Iron Pic", price : 500, bonus : 10, speed : 140, animation: false, img : playerTools.ironPickaxe, use : function(playerArmor) { return playerArmor.addPickAxe(this); }, recipe: [ {item: Bar[1].info, quantity: 2}, {item: Wood[1].info, quantity: 20} ] }), }, ] let GoldWeapons = [ { info : new ItemTemplate({ name : "Gold Mace", price : 300000, bonus : 40, speed : 130, animation: false, img : false, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[2].info, quantity: 10}, {item: Wood[2].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "Gold Sword", price : 350000, bonus : 50, speed : 105, animation: false, img : playerWeapons.goldSword, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[2].info, quantity: 20}, {item: Wood[2].info, quantity: 700} ] }), }, { info : new ItemTemplate({ name : "Gold Axe", price : 20000, bonus : 20, speed : 130, animation: false, img : playerTools.goldAxe, use : function(playerArmor) { return playerArmor.addAxe(this); }, recipe: [ {item: Bar[2].info, quantity: 2}, {item: Wood[2].info, quantity: 20} ] }), }, { info : new ItemTemplate({ name : "Gold Pic", price : 20000, bonus : 20, speed : 130, animation: false, img : playerTools.goldPickaxe, use : function(playerArmor) { return playerArmor.addPickAxe(this); }, recipe: [ {item: Bar[2].info, quantity: 2}, {item: Wood[2].info, quantity: 20} ] }), }, ] let PlatinumWeapons = [ { info : new ItemTemplate({ name : "Platinum Mace", price : 800000, bonus : 70, speed : 120, animation: false, img : false, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[3].info, quantity: 20}, {item: Wood[3].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "Platinum Sword", price : 900000, bonus : 85, speed : 95, animation: false, img : playerWeapons.platinumSword, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[3].info, quantity: 30}, {item: Wood[3].info, quantity: 700} ] }), }, { info : new ItemTemplate({ name : "Platinum Axe", price : 50000, bonus : 40, speed : 120, animation: false, img : playerTools.platinumAxe, use : function(playerArmor) { return playerArmor.addAxe(this); }, recipe: [ {item: Bar[3].info, quantity: 2}, {item: Wood[3].info, quantity: 20} ] }), }, { info : new ItemTemplate({ name : "Platinum Pic", price : 50000, bonus : 40, speed : 120, animation: false, img : playerTools.platinumPickaxe, use : function(playerArmor) { return playerArmor.addPickAxe(this); }, recipe: [ {item: Bar[3].info, quantity: 2}, {item: Wood[3].info, quantity: 20} ] }), }, ] let DiamondWeapons = [ { info : new ItemTemplate({ name : "<NAME>", price : 2000000, bonus : 115, speed : 110, animation: false, img : false, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[4].info, quantity: 50}, {item: Wood[4].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "<NAME>", price : 2500000, bonus : 140, speed : 85, animation: false, img : playerWeapons.diamondSword, use : function(playerArmor) { return playerArmor.addWeapon(this); }, recipe: [ {item: Bar[4].info, quantity: 75}, {item: Wood[4].info, quantity: 700} ] }), }, { info : new ItemTemplate({ name : "Diamond Axe", price : 100000, bonus : 70, speed : 110, animation: false, img : playerTools.diamondAxe, use : function(playerArmor) { return playerArmor.addAxe(this); }, recipe: [ {item: Bar[4].info, quantity: 2}, {item: Wood[4].info, quantity: 20} ] }), }, { info : new ItemTemplate({ name : "Diamond Pic", price : 100000, bonus : 70, speed : 110, animation: false, img : playerTools.diamondPickaxe, use : function(playerArmor) { return playerArmor.addPickAxe(this); }, recipe: [ {item: Bar[4].info, quantity: 2}, {item: Wood[4].info, quantity: 20} ] }), }, ] let rangeWeapons = [ { info : new ItemTemplate({ name : "Oak Bow", price : 10000, bonus : 20, speed : 120, animation: false, img : playerWeapons.oakBow, use : function(playerArmor) { return playerArmor.addBow(this); }, recipe: [ {item: Wood[0].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "Maple Bow", price : 100000, bonus : 42, speed : 110, animation: false, img : playerWeapons.mapleBow, use : function(playerArmor) { return playerArmor.addBow(this); }, recipe: [ {item: Wood[1].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "<NAME>", price : 500000, bonus : 65, speed : 100, animation: false, img : playerWeapons.mahogonyBow, use : function(playerArmor) { return playerArmor.addBow(this); }, recipe: [ {item: Wood[2].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "Magic Bow", price : 1000000, bonus : 88, speed : 90, animation: false, img : playerWeapons.magicBow, use : function(playerArmor) { return playerArmor.addBow(this); }, recipe: [ {item: Wood[3].info, quantity: 500} ] }), }, { info : new ItemTemplate({ name : "Super Bow", price : 10000000, bonus : 123, speed : 80, animation: false, img : playerWeapons.superBow, use : function(playerArmor) { return playerArmor.addBow(this); }, recipe: [ {item: Wood[4].info, quantity: 500} ] }), }, ] let arrows = [ { info : new ItemTemplate({ name : "Bronze Arrow", price : 200, bonus : 7, img : playerWeapons.arrows.bronze, animation : playerWeapons.firedArrows.bronze, use : function(playerArmor) { return playerArmor.addArrows(this); }, recipe: [ {item: Bar[0].info, quantity: 1}, {item: Wood[0].info, quantity: 1} ] }), }, { info : new ItemTemplate({ name : "Iron Arrow", price : 500, bonus : 17, img : playerWeapons.arrows.iron, animation : playerWeapons.firedArrows.iron, use : function(playerArmor) { return playerArmor.addArrows(this); }, recipe: [ {item: Bar[1].info, quantity: 1}, {item: Wood[1].info, quantity: 1} ] }), }, { info : new ItemTemplate({ name : "Gold Arrow", price : 2000, bonus : 31, img : playerWeapons.arrows.gold, animation : playerWeapons.firedArrows.gold, use : function(playerArmor) { return playerArmor.addArrows(this); }, recipe: [ {item: Bar[2].info, quantity: 1}, {item: Wood[2].info, quantity: 1} ] }), }, { info : new ItemTemplate({ name : "Platinum Arrow", price : 5000, bonus : 43, img : playerWeapons.arrows.platinum, animation : playerWeapons.firedArrows.platinum, use : function(playerArmor) { return playerArmor.addArrows(this); }, recipe: [ {item: Bar[3].info, quantity: 1}, {item: Wood[3].info, quantity: 1} ] }), }, { info : new ItemTemplate({ name : "Diamond Arrow", price : 10000, bonus : 55, img : playerWeapons.arrows.diamond, animation : playerWeapons.firedArrows.diamond, use : function(playerArmor) { return playerArmor.addArrows(this); }, recipe: [ {item: Bar[4].info, quantity: 1}, {item: Wood[4].info, quantity: 1} ] }), }, ] export { BronzeWeapons, IronWeapons, GoldWeapons, PlatinumWeapons, DiamondWeapons, rangeWeapons, arrows } <file_sep>const bcrypt = require('bcrypt'); const saltRounds = 10; module.exports = (app, db) => { // get all users app.get('/user', (req, res) => { if (!req.session.loggedIn) { res.json({code : -1}); return ; } db.users.findOne({ where : { id: req.session.userId, }, attributes: ["name", "id"], }).then(user => { if (user) { res.json({code: 1, user: user}) } else { res.json({code : -1, message: "No Session Available"}) } }); }) app.get('/checkSession', (req, res) => { if (!req.session.loggedIn) { res.json({code : -1}); } else { res.json({code : 1}); } }) app.get('/logout', (req, res) => { if (!req.session.loggedIn) { res.json({code : -1, message: "You aren't logged in Yet!"}); return ; } req.session.regenerate(function(err) { if (err) { console.log(err); res.json({code : 1, message: "Something Went Wrong with Logout"}); } else { res.json({code : 1, message: "Logout Successful"}); } }) }) app.post('/save', (req, res) => { db.users.findOne({ where : { id: req.session.userId, }, }).then(user => { if (user) { user.update({ name: req.body.player.name, info: req.body.player.info, gold: req.body.gold, }) .then(user => { res.json({code : 1, message: "save Successful"}) }) } else { res.json({code : -1, message: "save Unsuccessful"}) } }); }) app.post('/login', (req, res) => { db.users.findOne({ where : { email: req.body.email, }, attributes: ["id", "password"], }).then(user => { if (user) { bcrypt.compare(req.body.password, user.password, function(err, response) { if (response === true) { req.session.loggedIn = true; req.session.userId = user.id res.json({code : 1, message: "Login Successful"}) } else { res.json({code : -1, message: "Login Unsuccessful, Please Try Again or Register"}) } }); } else { res.json({code : -1, message: "Login Unsuccessful, Please Try Again or Register"}) } }); }) app.post('/register', (req, res) => { if (!req.body.name || !req.body.password) { res.json({code : -1, message: "credsNeeded"}); return ; } bcrypt.hash(req.body.password, saltRounds, function(err, hash) { db.users.findOrCreate({ where: { name: req.body.name }, defaults : { password: <PASSWORD>, gold : 100, } }) .then(([user, created]) => { if (created) { req.session.loggedIn = true; req.session.userId = user.id delete user.password res.json({code : 2, message: "Register Successful", user:user}) } else { if (user) { bcrypt.compare(req.body.password, user.password, function(err, response) { if (response === true) { db.users.findOne({ where : {id : user.id}, include: [ { model: db.inventoryItems, }, { model: db.skills, } ] }).then(users => { delete users.password req.session.loggedIn = true; req.session.userId = users.id res.json({code : 1, message: "Login Successful", user:users}) }); } else { res.json({code : -1, message: "Login Unsuccessful, Please Try Again or Register"}) } }); } else { res.json({code : -1, message: "Login Unsuccessful, Please Try Again or Register"}) } } }); }) }) }<file_sep>import ItemTemplate from '../ItemTemplate.js' import {magicImages} from "../../../Animations/images" let magicItems = [ { info : new ItemTemplate({ name: "Teleport\nStone", price: 0, img: magicImages.teleportStone, use: function(player, level) { if (level === 0) { player.currLevel = 0 } else { player.currLevel = player.currLevel + level; } player.teleported = true; return {used:false} } }) }, { info : new ItemTemplate({ name: "Shield\nStone", price: 0, img: magicImages.defenseStone, use: function(player, level) { player.skills.defense.boost = level; return {used:false} } }) }, { info : new ItemTemplate({ name: "Attack\nStone", price: 0, img: magicImages.attackStone, use: function(player, level) { player.skills.attack.boost = level; } }) }, { info : new ItemTemplate({ name: "Archer\nStone", price: 0, img: magicImages.rangeStone, use: function(player, level) { player.skills.range.boost = level; } }) }, { info : new ItemTemplate({ name: "Mining\nStone", price: 0, img: magicImages.miningStone, use: function(player, level) { player.skills.mining.boost = level; } }) }, { info : new ItemTemplate({ name: "Hunting\nStone", price: 0, img: magicImages.huntingStone, use: function(player, level) { player.skills.hunting.boost = level; } }) }, { info : new ItemTemplate({ name: "WoodCutting\nStone", price: 0, img: magicImages.woodcutStone, use: function(player, level) { player.skills.woodcutting.boost = level; } }) }, ] export { magicItems } <file_sep>import {userInterface, magicImages} from "../../Objects/Animations/images" import {button} from "../../Helpers/functions" import Grid from "./grid" export default class MakeMenu { actionButtons(player) { let keys = Object.keys(player.status.actions) let imgs = []; let labels = []; for (var i = 0; i < keys.length; i++) { imgs.push(player.status.actions[keys[i]].button()); labels.push(player.status.actions[keys[i]].label()) } let background = { img: userInterface.actionButtonBackGround, x : 0, y : 430, width : 360, height : 180, } let actionButtons = new Grid({ x: 0, y: 440, width : keys.length, height : 1, cellWidth : 60, cellHeight: 50, labelOffsetX : 5, labelOffsetY : 5, labelSize : 10, imgs : imgs, labels :labels, background : background, }) return (actionButtons) } vendor(items, menuType, name) { let menu = { name : name, categoryGrid : false, subCategoryGrids : {}, currentCategory : items.categories[0].name, currentSubcategory : items.categories[0].subcategory[0].name, }; let background = { img: userInterface.buyBackGround, x : 25, y : 25, width : userInterface.buyBackGround.pos.width, height : userInterface.buyBackGround.pos.height, } let categoryButtonImg = { image : userInterface.aquaButton, repeat : true, } let borderImg = { image : userInterface.itemBorder, repeat : true, } let SubCategoryButtonImg = { image : userInterface.greenButton, repeat : true, } let controls = [ { button : button(295, 39, 16, 16), img : userInterface.closeButton, }, ]; let labels = [] let categoryCount = 0; for (let x = 0; x < items.categories.length; x++) { let categorySettings = items.returnCategorySettings(x) if (categorySettings[menuType]) { labels.push(items.categories[x].name); categoryCount++; } } menu.categoryGrid = new Grid({ x: 50, y: 400, width : categoryCount, height : 1, cellWidth : 70, cellHeight: 50, labelOffsetX : 5, labelOffsetY : 30, labelSize : 10, imgs : categoryButtonImg, labels : labels, background : background, controls : controls }) for (let x = 0; x < items.categories.length; x++) { labels = []; let subCategories = items.returnSubCategories(x); let subCategoryCount = 0; let categoryName = items.categories[x].name; let subCategoryCheck = false; let itemGrids = {}; for (let y = 0; y < subCategories.length; y++) { let subCategorySettings = items.returnSubCategorySettings(x,y); if (subCategorySettings[menuType]) { subCategoryCheck = true labels.push(subCategories[y].name); subCategoryCount++; let subcategoryItems = items.returnItems(x,y); itemGrids[subCategories[y].name] = { grid : new Grid({ x: 40, y: 70, width : 4, height : 3, cellCount : subcategoryItems.length, cellWidth : 70, cellHeight: 50, labelOffsetX : 5, labelOffsetY : 5, labelSize : 10, imgs : borderImg, }), items: subcategoryItems, } } } if (subCategoryCheck) { menu.subCategoryGrids[categoryName] = { first : labels[0], grid: new Grid({ x: 50, y: 300, width : 4, height : 2, cellCount : subCategoryCount, cellWidth : 60, cellHeight: 40, labelOffsetX : 5, labelOffsetY : 30, labelSize : 10, imgs : SubCategoryButtonImg, labels : labels, }), itemGrids : itemGrids, } } } return menu } bank() { let bankButtons = { page : 0, }; let background = { img: userInterface.bankBackGround, x : 10, y : 30, width : 320, height : 430, } let img = { image : userInterface.itemBorder, repeat : true, } let controls = [ { button : button(292, 390, 16, 16), img : userInterface.upArrow, }, { button: button(292, 416, 16, 16), img : userInterface.downArrow, }, { button: button(292, 45, 16, 16), img : userInterface.closeButton, }, { button: button(292, 70, 16, 60), img : userInterface.bankScrollBar, }, ]; bankButtons.grid = new Grid({ x: 40, y: 40, width : 5, height : 10, cellWidth : 45, cellHeight: 40, labelOffsetX : 5, labelOffsetY : 5, labelSize : 10, imgs : img, background : background, controls : controls, }) return bankButtons } inventorySpaces() { let background = { img: userInterface.stats, x : 360, y : 0, width : 120, height : 480, } let img = { image : userInterface.itemBorder, repeat : true, } let inventorySpaces = new Grid({ x: 365, y: 120, width : 3, height : 8, cellWidth : 40, cellHeight: 40, labelOffsetX : 5, labelOffsetY : 5, labelSize : 10, imgs : img, background : background, }) return inventorySpaces; } inventoryButtons() { let menuImages = [ userInterface.inventoryIcon, userInterface.armorIcon, userInterface.statsIcon, userInterface.magicIcon ] let inventoryMenuButtons = new Grid({ x: 365, y: 440, width : 4, height : 1, cellWidth : 30, cellHeight: 40, labelOffsetX : 2, labelOffsetY : 20, labelSize : 9, imgs : menuImages }) return inventoryMenuButtons; } magic() { let magicLabels = [ "Home", "+10", "+50", "+5", "+10", "+30", "+5", "+10", "+30", "+5", "+10", "+30", "+5", "+10", "+30", "+5", "+10", "+30", "+5", "+10", "+30", ]; let magicImgs = [ magicImages.teleportStone, magicImages.teleportStone, magicImages.teleportStone, magicImages.rangeStone, magicImages.rangeStone, magicImages.rangeStone, magicImages.defenseStone, magicImages.defenseStone, magicImages.defenseStone, magicImages.attackStone, magicImages.attackStone, magicImages.attackStone, magicImages.miningStone, magicImages.miningStone, magicImages.miningStone, magicImages.woodcutStone, magicImages.woodcutStone, magicImages.woodcutStone, magicImages.huntingStone, magicImages.huntingStone, magicImages.huntingStone, ]; let magicMenu = new Grid({ x: 365, y: 140, width : 3, height : 7, cellWidth : 40, cellHeight: 40, labelOffsetX : 0, labelOffsetY : 10, labelSize : 9, labels : magicLabels, imgs : magicImgs, ySpace : 2, xSpace : 5, }) return magicMenu; } }<file_sep>import {userInterface} from "../../Animations/images" export default class Status { constructor(settings) { this.type = settings.type || "enemy"; this.dead = settings.dead || false; this.deaths = settings.deaths || 0; this.currLevel = settings.currLevel || 0; this.highestLevel = settings.highestLevel || 0; this.teleported = settings.teleported || false; this.location = settings.location || "home"; this.destination = settings.destination || "home"; this.action = "stop"; this.currentDirection = "north" this.actions = { walk : this.toggleSwitch("Walk", true), home : this.toggleSwitch("Home", true), farm : this.toggleSwitch("Farm", false), mine : this.toggleSwitch("Mine", false), woodCut : this.toggleSwitch("WoodCut", false), hunt : this.toggleSwitch("Hunt", false), } } toggleSwitch(name, state) { return ({ name : name, state : state, start : function() { this.state = true; }, stop : function() { this.state = false; }, label : function() { if (this.state) { return this.name + "\nStop"; } else { return this.name + "\nStart"; } }, button : function() { if (this.state) { return userInterface.redButton } else { return userInterface.greenButton } } }) } log() { console.log(this) } }<file_sep>import Resource from "./index" import {randomInt} from "../../Helpers/functions" import {settings} from "../../Helpers/settings" export default class Resources { constructor(items, level) { this.arr = []; this.items = items; this.count = randomInt(settings.resources.spawnCountRange.start, settings.resources.spawnCountRange.end); this.complete = false; this.target = 0; for (var x = 0; x < this.count; x++) { let x = randomInt(settings.resources.positionRange.start, settings.resources.positionRange.end) * 5; let y = randomInt(settings.resources.positionRange.start, settings.resources.positionRange.end) * 5; let newResource = new Resource(x, y, 32, 32, items); newResource.skills.health.setupLvl(level + 1, settings.resources.health.base, settings.resources.health.exponent); this.arr.push(newResource) } } clear() { this.arr = []; this.count = 0; } createOres(level) { for (var x = 0; x < this.count; x++) { this.arr[x].createOres(level); } } createWood(level) { for (var x = 0; x < this.count; x++) { this.arr[x].createWood(level); } } choose_target() { if (this.target >= this.count - 1) { this.target = 0; this.complete = true; } else { if (this.complete === false) { this.target++; } } } log() { for (var x = 0; x < this.count; x++) { console.log(this.arr[x]); } } }<file_sep>import RigidBody from '../../../Helpers/rigidBody' export default class ItemTemplate { constructor(info) { return ( { name: info.name, body: new RigidBody(0, 0, 20 ,40), id: 0, item_index : -1, category_id : -1, subCategory_id : -1, quantity: 1, maxStack: 99, bonus : info.bonus || 0, speed : info.speed || 0, price: info.price || 0, wearable: false, magic: false, use : info.use, recipe : info.recipe || false, animation : info.animation || false, img: info.img || false, info: info.name, setId(id) { this.id = id; }, addRecipe(recipe) { for (var i = recipe.length - 1; i >= 0; i--) { this.recipe.push(recipe[i]) } }, setPos(x, y) { this.body.pos.x = x this.body.pos.y = y }, setSize(width, height) { this.body.size.x = width; this.body.size.y = height; }, setVelocity(x,y) { this.body.velocity.x = x; this.body.velocity.y = y; }, isWearable : function() { this.wearable = true; }, copy : function(x = 0, y = 0, width = 20, height = 20) { return ({ name: this.name, body: new RigidBody(x, y, width ,height), id: this.id, item_index : this.item_index, category_id : this.category_id, subCategory_id : this.subCategory_id, animation : this.animation, img : this.img, quantity: 1, bonus : this.bonus, speed : this.speed, maxStack: this.maxStack, price: this.price, wearable: this.wearable, magic : this.magic, use : this.use, recipe : this.recipe, setPos : this.setPos, setSize : this.setSize, isWearable : this.isWearable, setVelocity : this.setVelocity, info : this.info, copy : this.copy }) } } ) } } <file_sep> module.exports = (app, db) => { app.get('/inventory', (req, res) => { db.inventoryItems.findAll({ where : { user_id: req.session.userId, }, }).then(inventory => { if (inventory) { console.log(inventory) res.json({code: 1, message: "Get inventory Success", inventory: inventory}) } else { res.json({code : -1, message: "No Session Available"}) } }); }) app.post('/saveInventory', (req, res) => { let inventory = req.body.inventory let items = []; db.inventoryItems.destroy({ where: { user_id : req.session.userId } }).then(function() { for (var i = 0; i < inventory.length; i++) { if (inventory[i].id != -1) { items.push({ user_id : req.session.userId, name : inventory[i].name, item_id: inventory[i].id, item_index: inventory[i].item_index, subCategory_id: inventory[i].subCategory_id, category_id :inventory[i].category_id, quantity : inventory[i].quantity, }) } } db.inventoryItems.bulkCreate(items).then(function() { res.json({code : 1, message: "Inventory save Successful"}) }, function(err){ // console.log(err) res.json({code : -1, message: "save Not Successful"}) }) }) }) }<file_sep>import Entity from "../../Objects/Entity" import Items from "../../Objects/Item" import {randomInt} from "../../Helpers/functions" export default class EntityTest { constructor() { // this.testPlayer(); // this.testRange(); this.player1 = new Entity(this.player()); let arrows = this.player1.items.returnItems(3,6); this.addArmor(this.player1, arrows[1]); this.enemies = []; this.enemies[0] = new Entity(this.enemy()); this.player1.range.shoot(this.player1, this.enemies[0]); this.player1.range.log(); } testPlayer() { let player = new Entity(this.player()); this.displayName(player); this.displaySkills(player); this.displayLocation(player); this.displayArmor(player); this.displayHome(player); this.displayInventory(player); this.displayItems(player); this.displayRange(player); } addArmor(entity, arrows) { for (var i = 0; i < 100; i++) { entity.armor.addArrows(arrows); } } testRange() { let player = new Entity(this.player()); let arrows = player.items.returnItems(3,6); this.addArmor(player, arrows[0]); let enemy = []; enemy[0] = new Entity(this.enemy()); player.range.shoot(player, enemy[0]); player.range.log(); for (var i = 0; i < 300; i++) { player.range.checkCollision(enemy); } } displaySkills(entity) { console.log(entity.skills); } displayLocation(entity) { console.log(entity.body); } displayArmor(entity) { console.log(entity.armor); } displayHome(entity) { console.log(entity.home); } displayInventory(entity) { console.log(entity.inventory); } displayItems(entity) { console.log(entity.items); } displayName(entity) { console.log(entity.name); } displayRange(entity) { console.log(entity.range); } player() { return ({ name : "Emszy", x : 0, y : 0, width : 64, height : 64, startingGold : 100, dead : false, deaths : 0, currLevel : 1, highestLevel : 0, teleported : false, skills : { attack : 1, health : 100, defense : 1, attackSpeed : 1, range : 1, magic : 1, thirst : 1, hunger : 1, mining : 1, woodcutting : 1, hunting : 1, hungerDecay : 1000, thirstDecay : 800, }, items : new Items() }) } enemy() { return ({ name : "Bob", x : randomInt(0, 450), y : randomInt(0, 450), width : 64, height : 64, startingGold : 100, dead : false, deaths : 0, currLevel : 1, highestLevel : 0, teleported : false, skills : { attack : 1, health : 100, defense : 1, attackSpeed : 1, range : 1, magic : 1, thirst : 1, hunger : 1, mining : 1, woodcutting : 1, hunting : 1, hungerDecay : 1000, thirstDecay : 800, }, items : new Items() }) } }<file_sep>import React from "react" import Logic from "../../Objects/Logic" import PlayerUpdater from "../../Objects/playerUpdater" import {timer} from "../../Helpers/functions" import GameStartScreen from "../../Objects/UI/gameStartScreen" import axios from "axios" // import RigidBody from "../../Helpers/rigidBody" // import ClickHandler from "../../Objects/clickhandler" export default class Draw extends React.Component { constructor() { super() this.state = { greeting : "" } this.canvasRef = React.createRef(); this.gameStartScreen = new GameStartScreen(); this.logic = new Logic(); this.gameStart = false; this.loadHandler = { bankLoaded : false, playerLoaded : false, inventoryLoaded : false, skillsLoaded : false, armorLoaded : false, gameStart : function() { if (this.bankLoaded && this.playerLoaded && this.inventoryLoaded && this.skillsLoaded && this.armorLoaded) { return true } else { return false } } } this.playerUpdater = new PlayerUpdater(this.logic.items); this.gameStartTimer = timer(100); this.saveTimer = timer (4000); } componentDidMount() { let frameRate = 60 this.frameRateTimer = timer(1000 / frameRate); document.getElementById("canvas").focus(); document.getElementById("canvas").style.cursor = "initial"; this.updateCanvas(); } componentWillUnmount() { cancelAnimationFrame(this.rAF); } savePlayerInfo() { axios.post(`/save`, { player : { name: this.logic.player.name, info : this.logic.player.name, }, gold : this.logic.player.inventory.gold } ) .then(res => { }) } savePlayerSkills() { axios.post(`/saveSkills`, { skills : this.logic.player.skills } ) .then(res => { }) } updatePlayerSkills() { axios.post(`/updateSkills`, { skills : this.logic.player.skills } ) .then(res => { }) } getPlayerSkills() { axios.get(`/skills`) .then(res => { this.logic.player = this.playerUpdater.updateSkills(this.logic.player, res.data.skills); this.loadHandler.skillsLoaded = true; }) } getPlayerInventory() { axios.get(`/inventory`) .then(res => { this.logic.player = this.playerUpdater.updateInventory(this.logic.player, res.data.inventory) this.loadHandler.inventoryLoaded = true; }) } savePlayerInventory() { axios.post(`/saveInventory`, { inventory : this.logic.player.inventory.spaces } ) .then(res => { }) } getPlayerBank() { axios.get(`/bank`) .then(res => { if (res.data.code === 1) { this.logic.player = this.playerUpdater.updateBank(this.logic.player, res.data.bank) this.loadHandler.bankLoaded = true; } }) } savePlayerBank() { axios.post(`/saveBank`, { bank : this.logic.player.home.bank.inventory.spaces } ) .then(res => { }) } savePlayerArmor() { console.log(this.logic.player.armor.getEquipment()); axios.post(`/saveArmor`, { armor : this.logic.player.armor.getEquipment() } ) .then(res => { }) } updatePlayerArmor() { axios.post(`/updateArmor`, { armor : this.logic.player.armor.getEquipment() } ) .then(res => { }) } getPlayerArmor() { axios.get(`/armor`) .then(res => { this.logic.player = this.playerUpdater.updateArmor(this.logic.player, res.data.armor) this.loadHandler.armorLoaded = true; }) } saveCharacter() { this.savePlayerInfo(); this.updatePlayerSkills(); this.savePlayerInventory(); this.savePlayerBank(); this.updatePlayerArmor(); } login() { axios.post(`/register`, { name: this.logic.player.name, password: <PASSWORD>, } ) .then(res => { if (res.data.code === 1) { this.logic.player.password = <PASSWORD>; //load DATA HERE this.logic.player = this.playerUpdater.update(this.logic.player, res.data.user) this.getPlayerSkills(); this.getPlayerInventory(); this.getPlayerBank(); this.getPlayerArmor(); this.loadHandler.playerLoaded = true; } if (res.data.code === 2) { this.savePlayerSkills(); this.savePlayerArmor(); this.logic.player.password = <PASSWORD>; this.gameStartScreen.page = "characterSelect" this.gameStartScreen.open = true } else { this.gameStartScreen.open = true this.gameStartScreen.page = "choosePassword" } }) } updateLogic() { this.logic = this.logic.play() } updateCanvas = () => { const canvas = this.canvasRef.current; const ctx = canvas.getContext('2d'); let player = this.logic.player; let ui = this.logic.UI; if (!this.gameStart && this.gameStartTimer.check() ) { if (this.loadHandler.gameStart()) { this.gameStartScreen.open = false; this.gameStart = true } this.gameStartScreen.display(player, ctx); ui.drawEntity.handler({ player: player, }, ctx) } if (this.logic && this.gameStart) { if (this.saveTimer.check()) { this.saveCharacter() } if (this.frameRateTimer.check()) { ctx.clearRect(0,0, 480, 480); this.updateLogic(); let enemies = this.logic.enemies; let map = this.logic.map; let merchant = this.logic.merchant; ui.drawMap(map, ctx); ui.drawHomeDesign(player, merchant, ctx) ui.drawInventory(player, ctx); ui.drawMapInventory(map.inventory[player.status.currLevel - 1], ctx); ui.drawFarm(player, ctx); ui.drawEntity.handler({ player: player, enemies: enemies, merchant: merchant, animals: this.logic.animals, trees: this.logic.trees, ore: this.logic.ore, }, ctx) ui.drawHome(player, this.logic.items, ctx); ui.drawMouseSwapItem("inventory", ctx) ui.drawMouseSwapItem("bank", ctx) ui.drawInfoBox(ctx, player.inventory); } } this.rAF = requestAnimationFrame(this.updateCanvas); } handleClick = (e) => { const canvas = this.canvasRef.current; let player = this.logic.player if (!this.gameStart) { this.gameStartScreen.clickHandler(player,e,canvas); this.gameStart = this.gameStartScreen.startGame; if (this.gameStartScreen.open === false) { this.login() } return false; } let merchant = this.logic.merchant let ui = this.logic.UI; // fire arrow with mouse, might implement this as main way to shoot arrows; // let mouse = this.clickHandler.transformedCoordinate(e, canvas) // mouse = {body: new RigidBody(mouse.x, mouse.y, 1,1)}; // player.range.shoot(player, mouse, 20); ui.menuClick(e, canvas); ui.actionClick(e, player, canvas); if (player.status.currLevel > -1) { ui.inventoryClick(e, player, canvas); } ui.armorClick(e, player, canvas); ui.magicClick(e, player, canvas); if (player.status.destination === "home" && player.status.currLevel === 0) { ui.bankButtonClick(e, player, canvas); ui.homeButtonClick(e, player, merchant, canvas); ui.buyButtonClick(e, player, canvas) ui.craftButtonClick(e, player, canvas); } if (player.status.destination === "farm" && player.status.currLevel === -1) { ui.farmButtonClick(e, player, canvas) ui.farmInventoryClick(e, player, canvas) } } handleMouseMove(e) { if (!this.gameStart) { return false; } const canvas = this.canvasRef.current; let player = this.logic.player this.logic.UI.updateMouse(e, canvas); if (player.status.location === "home") { this.logic.UI.setHomeInfoBox( e, canvas, { player: { inventory: player.inventory, grid : this.logic.UI.inventorySpaces, }, bank : { inventory: player.home.bank.inventory, grid: this.logic.UI.bankButtons.grid }, merchant : this.logic.merchant, }, player ); } if (player.status.location === "wild") { this.logic.UI.setWildInfoBox( e, canvas, { enemies : this.logic.enemies, ore : this.logic.ore, trees : this.logic.trees, animals : this.logic.animals, }, ); } let map = this.logic.map; if (player.status.currLevel > 0) { this.logic.UI.mapInventoryClick(e, map.inventory[player.status.currLevel - 1], player ,canvas) } } render() { return ( <div style={{width:480, height: 480}}> {this.state.greeting} <canvas ref={this.canvasRef} width={480} height={480} style={{border: "1px solid black"}} id = "canvas" tabIndex="0" onKeyPress={ (e) => { } } onContextMenu = {(e) => { e.preventDefault() const canvas = this.canvasRef.current; let player = this.logic.player if (player.status.destination === "home" && player.status.currLevel === 0) { this.logic.UI.doubleClickHandler(player, e, canvas); } } } onMouseMove = {(e) => { this.handleMouseMove(e) } } onClick = {(e) => { this.handleClick(e) } } onMouseDown = {(e) => { const canvas = this.canvasRef.current; let player = this.logic.player this.logic.UI.arrangeInventory(player.inventory, e, canvas) this.logic.UI.arrangeBank(player.home.bank.inventory, e, canvas) } } onMouseUp = {(e) => { const canvas = this.canvasRef.current; let player = this.logic.player this.logic.UI.swapInventory(player.inventory, e, canvas) this.logic.UI.swapBank(player.home.bank.inventory, e, canvas) } } /> </div> ); } }<file_sep>export default class HomeAnimation { constructor(resource) { this.resource = resource this.img = resource.img this.resourceTimer = this.makeTimer(10); } makeTimer(animationTime) { return ({ time : 0, index : 0, end : 3, animationTime: animationTime, done : false, clear: function() { this.time = 0 this.index = 0 }, timer : function() { this.time ++; if (this.time > this.animationTime) { this.time = 0; this.index++; if (this.index > this.end) { this.done = true this.index = 0; } } } }) } drawImage(name, obj, ctx) { this.draw(this.img, this.resource[name].x,this.resource[name].y, this.resource[name].width, this.resource[name].height, obj.body.pos.x, obj.body.pos.y, obj.body.size.x, obj.body.size.y, ctx ) } drawFloor(index, obj, ctx) { this.draw(this.img, this.resource.panels[index].x, this.resource.panels[index].y, this.resource.panels[index].width, this.resource.panels[index].height, obj.body.pos.x, obj.body.pos.y, obj.body.size.x, obj.body.size.y, ctx ) } drawWall(ctx) { for (var i = 0; i < 11; i++) { if (i < 5 || i > 6) { this.draw( this.img, this.resource.horizontal.x, this.resource.horizontal.y, this.resource.horizontal.width, this.resource.horizontal.height, i * this.resource.horizontal.width, 0, this.resource.horizontal.width, this.resource.horizontal.height, ctx ) this.draw( this.img, this.resource.horizontal.x, this.resource.horizontal.y, this.resource.horizontal.width, this.resource.horizontal.height, i * this.resource.horizontal.width, 450, this.resource.horizontal.width, this.resource.horizontal.height, ctx ) } } for (i = 0; i < 5; i++) { this.draw( this.img, this.resource.vertical.x, this.resource.vertical.y, this.resource.vertical.width, this.resource.vertical.height, 0, i * this.resource.vertical.height, this.resource.vertical.width, this.resource.vertical.height, ctx ) this.draw( this.img, this.resource.vertical.x, this.resource.vertical.y, this.resource.vertical.width, this.resource.vertical.height, 32 * 10 + 8, i * this.resource.vertical.height, this.resource.vertical.width, this.resource.vertical.height, ctx ) } } drawCraftCorner(obj, ctx) { this.draw( this.img, this.resource.stove.x, this.resource.stove.y, this.resource.stove.width, this.resource.stove.height, obj.body.pos.x + 3, obj.body.pos.y + 40, this.resource.stove.width, this.resource.stove.height, ctx ) this.draw( this.img, this.resource.anvil.x, this.resource.anvil.y, this.resource.anvil.width, this.resource.anvil.height, obj.body.pos.x + 3, obj.body.pos.y, this.resource.anvil.width, this.resource.anvil.height, ctx ) } drawWaterWell(obj, ctx) { this.draw( this.img, this.resource.base.main.x, this.resource.base.main.y, this.resource.base.main.width, this.resource.base.main.height, obj.body.pos.x + 3, obj.body.pos.y + 40, this.resource.base.main.width, this.resource.base.main.height, ctx ) this.draw( this.img, this.resource.bucket.empty.x, this.resource.bucket.empty.y, this.resource.bucket.empty.width, this.resource.bucket.empty.height, obj.body.pos.x + 22, obj.body.pos.y + 10, this.resource.bucket.empty.width, this.resource.bucket.empty.height, ctx ) this.draw( this.img, this.resource.base.frontLayer.x, this.resource.base.frontLayer.y, this.resource.base.frontLayer.width, this.resource.base.frontLayer.height, obj.body.pos.x + 3, obj.body.pos.y + 60, this.resource.base.frontLayer.width, this.resource.base.frontLayer.height, ctx ) this.draw( this.img, this.resource.arms.one.x, this.resource.arms.one.y, this.resource.arms.one.width, this.resource.arms.one.height, obj.body.pos.x - 10, obj.body.pos.y, this.resource.arms.one.width, this.resource.arms.one.height, ctx ) this.draw( this.img, this.resource.handles.one.x, this.resource.handles.one.y, this.resource.handles.one.width, this.resource.handles.one.height, obj.body.pos.x + 67, obj.body.pos.y + 1, this.resource.handles.one.width, this.resource.handles.one.height, ctx ) } draw(img, clipX, clipY, width, height, x, y, drawWidth, drawHeight, ctx) { ctx.drawImage(img, clipX, clipY, width, height, x, y, drawWidth, drawHeight, ); } }<file_sep>export default class Draw { text(str, x, y, size, ctx, color= "white") { ctx.strokeStyle = color ctx.font = size+"px Comic Sans MS"; ctx.strokeText(str, x, y); } img(img, x,y, width, height, ctx) { ctx.drawImage(img.img, img.pos.x, img.pos.y, img.pos.width, img.pos.height, x, y, width, height ); } inventoryItemImg(img, x,y, ctx) { ctx.drawImage(img.img, img.pos.x, img.pos.y, img.pos.width, img.pos.height, x + 4, y + 3, 32, 32 ); } craftRecipeImg(img, x,y, ctx) { ctx.drawImage(img.img, img.pos.x, img.pos.y, img.pos.width, img.pos.height, x + 4, y + 3, 12, 12 ); } rect(obj, ctx) { ctx.beginPath(); ctx.strokeStyle = "white" ctx.rect(obj.x, obj.y, obj.width, obj.height); ctx.stroke(); } gridRect(obj, ctx) { ctx.beginPath(); ctx.strokeStyle = "white" ctx.rect(obj.body.pos.x, obj.body.pos.y, obj.body.size.x, obj.body.size.y); ctx.stroke(); } fillRect(obj, color, ctx) { ctx.fillStyle = color; ctx.fillRect(obj.body.pos.x, obj.body.pos.y, obj.body.size.x, obj.body.size.y); } button(obj, ctx) { ctx.beginPath(); ctx.strokeStyle = "white" ctx.rect(obj.button.body.pos.x, obj.button.body.pos.y, obj.button.body.size.x, obj.button.body.size.y); ctx.stroke(); this.label(obj, ctx); } label(obj, ctx) { ctx.strokeStyle = "white" ctx.font = obj.label.fontSize + "px Comic Sans MS"; let xOffset = 0; if (obj.label.label.length) { let lines = obj.label.label.split('\n'); for (var i = 0; i < lines.length; i++) { if (lines[i].length > 6) { xOffset = -4 } else { xOffset = 0; } ctx.strokeText(lines[i], obj.label.body.pos.x + xOffset, obj.label.body.pos.y + i*15); } } if (obj.label2) { if (obj.label2.label.length) { let lines = obj.label2.label.split('\n'); for (i = 0; i < lines.length; i++) { ctx.strokeText(lines[i], obj.label2.body.pos.x, obj.label2.body.pos.y + i*15); } } } } actionButton(obj, ctx) { ctx.beginPath(); ctx.strokeStyle = "white" // ctx.rect(obj.button.body.pos.x, obj.button.body.pos.y, obj.button.body.size.x, obj.button.body.size.y); // ctx.stroke(); ctx.font = obj.label.fontSize + "px Comic Sans MS"; ctx.strokeText(obj.label.label, obj.label.body.pos.x, obj.label.body.pos.y); ctx.font = obj.label2.fontSize + "px Comic Sans MS"; ctx.strokeText(obj.label2.label, obj.label2.body.pos.x, obj.label2.body.pos.y); } craftButton(obj, items, ctx) { ctx.beginPath(); ctx.strokeStyle = "white" ctx.font = obj.label.fontSize + "px Comic Sans MS"; ctx.font = obj.label2.fontSize + "px Comic Sans MS"; ctx.font = obj.label3.fontSize + "px Comic Sans MS"; ctx.font = obj.label4.fontSize + "px Comic Sans MS"; ctx.strokeText(obj.label.label, obj.label.body.pos.x, obj.label.body.pos.y - 10); if (items.recipe[0].item.img) { this.img(items.recipe[0].item.img, obj.label.body.pos.x + 4, obj.label.body.pos.y + 12, 12,12, ctx ) obj.label2.changeLabel(" x " + items.recipe[0].quantity) ctx.font = "8px Comic Sans MS"; ctx.strokeText(obj.label2.label, obj.label2.body.pos.x + 20, obj.label2.body.pos.y + 10); } else { obj.label2.changeLabel(items.recipe[0].item.name + " x " + items.recipe[0].quantity) ctx.strokeText(obj.label2.label, obj.label2.body.pos.x, obj.label2.body.pos.y); } if (items.recipe[1]) { if (items.recipe[1].item.img) { this.img(items.recipe[1].item.img, obj.label3.body.pos.x + 4, obj.label3.body.pos.y - 9, 12,12, ctx ) obj.label3.changeLabel(" x " + items.recipe[1].quantity) ctx.strokeText(obj.label3.label, obj.label3.body.pos.x + 20, obj.label3.body.pos.y); } else { obj.label3.changeLabel(items.recipe[1].item.name + " x " + items.recipe[1].quantity) ctx.strokeText(obj.label2.label, obj.label2.body.pos.x, obj.label2.body.pos.y); } } else { obj.label3.changeLabel(""); } ctx.strokeText(obj.label4.label, obj.label4.body.pos.x, obj.label4.body.pos.y); } }<file_sep>import React from "react" import Skills from "../../Helpers/Skills" export default class SkillsTest extends React.Component { constructor() { super() this.test(); } levelUpEverything() { this.skills.attack.levelUp(); this.skills.health.levelUp(); this.skills.attackSpeed.levelUp(); this.skills.thirst.levelUp(); this.skills.hunger.levelUp(); } levelDownEverything() { this.skills.attack.take(5); this.skills.health.take(5); this.skills.attackSpeed.take(5); this.skills.thirst.take(5); this.skills.hunger.take(5); } showSkills() { this.skills.attack.log(); this.skills.health.log(); this.skills.attackSpeed.log(); this.skills.thirst.log(); this.skills.hunger.log(); } skillLessThanZero() { this.skills.attack.take(50); this.skills.attack.log(); } death() { this.skills.health.take(50); this.skills.isDead() ? console.warn("DEAD") : console.warn("Alive"); } alive() { this.skills.health.giveLimit(50); this.skills.health.log(); this.skills.isDead() ? console.warn("DEAD") : console.warn("Alive"); } equalizeSkill() { this.skills.health.levelUp(); this.skills.health.levelUp(); this.skills.health.levelUp(); this.skills.health.levelUp(); this.skills.health.levelUp(); this.skills.health.log(); this.skills.health.equalize(); this.skills.health.log(); } test() { this.skills = new Skills(); this.skills.test(); this.levelUpEverything(); this.showSkills(); this.levelDownEverything(); this.showSkills(); this.skillLessThanZero(); this.death(); this.alive(); this.equalizeSkill(); } }<file_sep> import Projectiles from "../Projectiles" export default class Magic { constructor(items) { this.items = items.returnItems(4,0); this.projectiles = new Projectiles(); this.teleport = this.makeTeleport(this.items[0]); this.defense = this.makeSpell(this.items[1]); this.attack = this.makeSpell(this.items[2]); this.archery = this.makeSpell(this.items[3]); this.mining = this.makeSpell(this.items[4]); this.hunting = this.makeSpell(this.items[5]); this.woodcutting = this.makeSpell(this.items[6]); this.thirst = this.makeSpell(this.items[7]); this.hunger = this.makeSpell(this.items[8]); } shoot(player, spell, enemy) { this.projectiles.fire(player, spell, enemy); } checkCollision(enemies) { this.projectiles.checkArrowCollision(enemies); } makeSpell(stone) { return({ stone: stone, pushSpells(spellArr) { spellArr.push(this.five, this.ten, this.thirty, this.fifty) }, spell : function(player, quantity, level) { let find = player.inventory.find(this.stone) if (find.found) { if (player.inventory.spaces[find.index].quantity >= quantity) { this.stone.use(player, level); player.inventory.deleteQuantity(find.index, quantity); } } }, five : function(player) { this.spell(player, 5, 5) }, ten : function(player) { this.spell(player, 20, 10) }, thirty : function(player) { this.spell(player, 50, 30) }, fifty : function(player) { this.spell(player, 100, 50) }, }) } makeTeleport (teleport_stone) { return({ stone : teleport_stone, pushSpells(spellArr) { spellArr.push(this.home, this.ten, this.fifty, this.oneHundred) }, teleport : function(player, quantity, level) { let find = player.inventory.find(this.stone) if (player.highestLevel < player.currLevel + level && level !== 0) { return false } if (find.found) { if (player.inventory.spaces[find.index].quantity >= quantity) { this.stone.use(player, level); player.inventory.deleteQuantity(find.index, quantity); } } }, home : function(player) { this.teleport(player, 5, 0); }, ten : function(player) { this.teleport(player, 10, 10); }, fifty : function(player) { this.teleport(player, 50, 50); }, oneHundred : function(player) { this.teleport(player, 50, 100); }, }) } }<file_sep>const express = require('express'); const bodyParser = require('body-parser'); const pino = require('express-pino-logger')(); const uuidv4 = require('uuid/v4'); var session = require('express-session'); const app = express(); app.use(bodyParser.json({limit: '50mb', extended: true})) app.use(bodyParser.urlencoded({limit: '50mb', extended: true})) const jsonParser = bodyParser.json(); app.use(jsonParser); // use it globally app.use(pino); const userRoute = require("./routes/user"); const skillsRoute = require("./routes/skills"); const inventoryRoute = require("./routes/inventory"); const bankRoute = require("./routes/bank"); const armorRoute = require("./routes/armor"); app.use(session({ genid: function(req) { return uuidv4() // use UUIDs for session IDs }, secret: "OOOOH A SECRET KEY GOES HERE", resave: false, saveUninitialized: true, })) const { db } = require('./sequelize') userRoute(app, db); skillsRoute(app, db); inventoryRoute(app, db); bankRoute(app, db); armorRoute(app, db); app.get('*', (req, res) => { }); app.listen(3001, () => console.log('Express server is running on localhost:3001') );<file_sep>export default class ItemSubCategory { constructor(name, id, settings, category_id) { this.name = name; this.id = id; this.category_id = category_id; this.items = []; this.settings = settings } addItem(item) { this.items.push(item) } addItems(itemArr, id) { let count = itemArr.length; for (let x = 0; x < count; x++) { itemArr[x].info.setId(id); itemArr[x].info.item_index = x; itemArr[x].info.subCategory_id = this.id; itemArr[x].info.category_id = this.category_id; this.items.push(itemArr[x]); id++; } return (id) } addWeaponAndArmorItems(itemArr, id) { let count = itemArr.length; for (let x = 0; x < count; x++) { itemArr[x].info.isWearable() itemArr[x].info.setId(id); itemArr[x].info.item_index = x; itemArr[x].info.subCategory_id = this.id; itemArr[x].info.category_id = this.category_id; this.items.push(itemArr[x]); id++; } return (id) } addMagicItems(itemArr, id) { let count = itemArr.length; for (let x = 0; x < count; x++) { itemArr[x].info.magic = true; itemArr[x].info.setId(id); itemArr[x].info.item_index = x; itemArr[x].info.subCategory_id = this.id; itemArr[x].info.category_id = this.category_id; this.items.push(itemArr[x]); id++; } return (id) } listItems() { let count = this.items.length for (let x = 0; x < count; x++) { console.log(this.items[x].info.name); } } returnItems() { let items = [] let count = this.items.length for (let x = 0; x < count; x++) { items.push(this.items[x].info.copy()) } return(items); } returnOneItem(index) { return(this.items[index].info.copy()) } returnItemNames() { let items = [] let count = this.items.length for (let x = 0; x < count; x++) { items.push({ name: this.items[x].info.name, price : this.items[x].info.price, recipe : this.items[x].info.recipe }); } return(items); } } <file_sep>import RigidBody from "../../Helpers/rigidBody" import Inventory from "../../Objects/Inventory" import {mapAtlas} from "../Animations/images" import MapAnimation from "../Animations/mapAnimation" import {randomInt} from "../../Helpers/functions" export default class MapLogic { constructor(items) { this.end = { name : "end", body: new RigidBody(32 * 5,400, 1,1) } this.start = { name: "beginning", body: new RigidBody(32 * 5, 0, 1, 1) } this.middle = { name: "middle", body: new RigidBody(5 * 32, 7 * 32, 1, 1) } this.drawUpdate = false; this.inventory = []; this.items = items; this.inventory.push(new Inventory(this.items, 250)) this.animation = new MapAnimation(mapAtlas) this.width = 15; this.height = 15; this.tiles = []; this.layer = []; } addInventories(player) { let mapInventories = player.currLevel - player.highestLevel if (mapInventories > 0) { for (var i = 0; i <= mapInventories; i++) { this.addInventory(); } } } addInventory() { this.inventory.push(new Inventory(this.items, 250)) } randomGrassTerrain() { let type = ["light"]; let imgs = ["hole", "specks", "main"]; return ({ terrain : "dirt", type: type[0], img : imgs[randomInt(0, imgs.length - 1)] }) } layerType(terrain) { let type = Object.keys(mapAtlas.terrain[terrain]) return (type[randomInt(0, type.length - 1)]) } terrainBase(terrain, type) { let img = Object.keys(mapAtlas.terrain[terrain][type].base) img = img[randomInt(0,img.length - 1)] return ({ terrain : terrain, type: type, img : img }) } terrainLayer(terrain, type) { let img = Object.keys(mapAtlas.terrain[terrain][type]) img = img[randomInt(0,img.length - 1)] return ({ terrain : terrain, type: type, img : img }) } selectTerrain(level) { let terrain = ["home", 'grass', "dirt", "sand", "lava"]; let index = 1; if (level > 0 && level < 20){ index = 1; } else if (level >= 20 && level < 40){ index = 2; } else if (level >= 40 && level < 60){ index = 3; } else if (level >= 60 && level < 80){ index = 4; } else { index = 4; } return (terrain[index]); } create_base(level) { let tiles = [] let terrain = this.selectTerrain(level); let layerType = this.layerType(terrain); for (let y = 0; y < this.height; y++) { tiles[y] = []; for (let x = 0; x < this.width; x++) { let tile = { body : new RigidBody(x * 32, y * 32, 32 ,32), info : this.terrainBase(terrain, layerType) } tiles[y][x] = tile; } } this.tiles = tiles; this.create_layer(terrain, layerType) } create_layer(terrain, type) { this.drawUpdate = true // console.log(this.drawUpdate) let tiles = [] let layerAmount = randomInt(5, 10); for (let x = 0; x < layerAmount; x++) { let info = this.terrainLayer(terrain, type); if (info.img !== "base") { let tile = { body : new RigidBody(randomInt(0, 15) * 32, randomInt(0, 15) * 32, 32 ,32 ), info : info } tiles.push(tile); } } this.layer = tiles; } }<file_sep>import RigidBody from "../../Helpers/rigidBody" import Draw from "./draw" import DrawEntity from "./DrawEntity" import MakeMenu from "./MakeMenu" import {timer} from "../../Helpers/functions" import ClickHandler from "../clickhandler" import {userInterface} from "../../Objects/Animations/images" export default class UI { constructor(items, player) { this.clickHandler = new ClickHandler(); this.drawEntity = new DrawEntity(); this.draw = new Draw(); let makeMenu = new MakeMenu(); this.currentHomeMenu = "none"; this.inventoryMenu = "inventory"; this.magicMenu = makeMenu.magic(); this.buyMenu = makeMenu.vendor(items, "buyable", "Shop"); this.craftMenu = makeMenu.vendor(items, "craftable", "Craft"); this.inventoryMenuButtons = makeMenu.inventoryButtons() this.inventorySpaces = makeMenu.inventorySpaces(); this.actionButtons = makeMenu.actionButtons(player); this.bankButtons = makeMenu.bank(); this.armorButtons = []; this.infoBox = { body : new RigidBody(150,150,100,100), draw : new Draw(), infoItem: false, recipe : false, price : false, timer : timer(700), titleFontSize: 10, background : { img: userInterface.itemInfoBackGround, body : new RigidBody(150,150,50,50), width : userInterface.itemInfoBackGround.pos.width, height : userInterface.itemInfoBackGround.pos.height, setPos : function(x,y) { this.body.setPos(x,y) }, setSize : function(width, height) { this.body.size.x = width; this.body.size.y = height; } }, display : function(ctx) { if (this.infoItem && this.timer.isDone()) { ctx.globalAlpha = 0.5; this.draw.img(this.background.img, this.background.body.pos.x-50, this.background.body.pos.y-50, this.background.body.size.x, this.background.body.size.y, ctx, ); ctx.globalAlpha = 1 this.draw.text( this.infoItem.info, this.body.pos.x - 50, this.body.pos.y - 40, this.titleFontSize, ctx, "white" ) if (this.price) { this.draw.text( "price: " + this.price, this.body.pos.x - 50, this.body.pos.y - 20, 10, ctx, "white" ) } if (this.recipe) { let x = -50; let imgY = -40; let y = -20 for (var i = this.recipe.length - 1; i >= 0; i--) { this.draw.img(this.recipe[i].item.img, this.body.pos.x + x, this.body.pos.y + imgY, 32, 32, ctx, ); this.draw.text( this.recipe[i].item.name, this.body.pos.x + x + 30, this.body.pos.y + y, 10, ctx, "white" ) this.draw.text( "Cost: " + this.recipe[i].quantity, this.body.pos.x + x + 40, this.body.pos.y + y + 10, 10, ctx, "red" ) y+= 40 imgY += 40 } } } }, setPos : function(x,y) { this.body.setPos(x,y) }, clear() { this.infoItem = false this.recipe = false this.price = false } } this.mouseSwapItem = { inventory : { swap : false, index : false, item : false }, bank : { swap : false, index : false, item : false } }; this.mousePosition = { x: false, y: false, } this.farmButtons = { spaces : [], controls: [], open : true, } this.waterWellButton = { open : false, collect : function(player) { if (this.open === true) { player.home.waterWell.getWater(player.inventory); } } } this.rightClickMenu = { background : this.button(0, 0, 50, 100), index : -1, buttons : [], open : false, menu : "", clear : function() { this.menu = ""; this.open = false this.index = -1 this.buttons = [] } } this.homeMenuButtons = []; this.makeArmorMenu(); this.makeHomeActionButtons(player); this.makeFarmButtons(player); } setHomeInfoBox(mouse, canvas, menus, player) { let bank = player.home.bank; let craft = player.home.buyMenu; let waterWell = player.home.waterWell let inventoryClick = menus.player.grid.click(mouse, canvas); let bankClick = menus.bank.grid.click(mouse, canvas); let buySettings = this.getMenuConfig(this.buyMenu) let buyClick = buySettings.items.grid.click(mouse, canvas); let craftSettings = this.getMenuConfig(this.craftMenu) let craftClick = craftSettings.items.grid.click(mouse, canvas); let merchantClick = this.clickHandler.click(mouse, menus.merchant, canvas); let playerClick = this.clickHandler.click(mouse, player, canvas); let bankOpenClick = this.clickHandler.click(mouse, bank, canvas); let craftOpenClick = this.clickHandler.click(mouse, craft, canvas); let waterWellOpenClick = this.clickHandler.click(mouse, waterWell, canvas); this.infoBox.timer.reset(); if(inventoryClick.click && this.inventoryMenu === "inventory") { if (menus.player.inventory.spaces[inventoryClick.index].id === -1) { this.infoBox.clear(); } else { this.infoBox.background.setSize(50,50) this.infoBox.titleFontSize = 10; this.infoBox.infoItem = menus.player.inventory.spaces[inventoryClick.index]; } } else if (bankClick.click && this.currentHomeMenu === "bank") { if (menus.bank.inventory.spaces[bankClick.index + this.bankButtons.page].id === -1) { this.infoBox.clear(); } else { this.infoBox.background.setSize(50,50) this.infoBox.titleFontSize = 10; this.infoBox.infoItem = menus.bank.inventory.spaces[bankClick.index + this.bankButtons.page]; } } else if (buyClick.click && this.currentHomeMenu === "buy") { this.infoBox.background.setSize(80,50) this.infoBox.titleFontSize = 10; this.infoBox.infoItem = buySettings.items.items[buyClick.index]; this.infoBox.price = buySettings.items.items[buyClick.index].price } else if (craftClick.click && this.currentHomeMenu === "craft") { this.infoBox.infoItem = craftSettings.items.items[craftClick.index]; this.infoBox.titleFontSize = 15; this.infoBox.recipe = craftSettings.items.items[craftClick.index].recipe; let height = this.infoBox.recipe.length * 50; this.infoBox.background.setSize(100,height) } else if(merchantClick && this.currentHomeMenu === "none") { this.infoBox.infoItem = menus.merchant; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 5,50) } else if(playerClick && this.currentHomeMenu === "none") { this.infoBox.infoItem = player; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 6,50) } else if (bankOpenClick && this.currentHomeMenu === "none") { this.infoBox.infoItem = bank; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 6,50) } else if (craftOpenClick && this.currentHomeMenu === "none") { this.infoBox.infoItem = craft; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 6,50) } else if (waterWellOpenClick && this.currentHomeMenu === "none") { this.infoBox.infoItem = waterWell; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 6,50) } else { this.infoBox.clear(); } } setWildInfoBox(mouse, canvas, menus) { let enemyIndex = this.clickHandler.clickArr(mouse, menus.enemies, canvas); let oreIndex = this.clickHandler.clickArr(mouse, menus.ore, canvas); let treeIndex = this.clickHandler.clickArr(mouse, menus.trees, canvas); let animalIndex = this.clickHandler.clickArr(mouse, menus.animals, canvas); this.infoBox.timer.reset(); if(enemyIndex.click) { this.infoBox.infoItem = menus.enemies[enemyIndex.index]; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 5,50) } else if(oreIndex.click) { this.infoBox.infoItem = menus.ore[oreIndex.index]; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 6,50) } else if (treeIndex.click) { this.infoBox.infoItem = menus.trees[treeIndex.index]; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 6,50) } else if (animalIndex.click) { this.infoBox.infoItem = menus.animals[animalIndex.index]; this.infoBox.background.setSize(this.infoBox.infoItem.info.length * 6,50) } else { this.infoBox.clear(); } } drawInfoBox(ctx) { this.infoBox.background.setPos(this.mousePosition.x, this.mousePosition.y) this.infoBox.setPos(this.mousePosition.x, this.mousePosition.y) this.infoBox.display(ctx); } getMenuConfig(menu) { let subCategory = menu.subCategoryGrids[menu.currentCategory]; let items = subCategory.itemGrids[menu.currentSubcategory]; return({ currentCategory : menu.currentCategory, currentSubcategory : menu.currentSubcategory, categories : menu.categoryGrid, subCategory : subCategory, items : items, imgs : items.items }) } //map drawMap(map, ctx) { for (let x = 0; x < map.height; x++) { for (let y = 0; y < map.width; y++) { let tile = map.tiles[y][x] map.animation.drawImageBase(tile.info.terrain, tile.info.type, tile.info.img, tile.body.pos, ctx) } } for (let y = 0; y < map.layer.length; y++) { let tile = map.layer[y] map.animation.drawImageLayer(tile.info.terrain, tile.info.type, tile.info.img, tile.body.pos, ctx) } } drawMapInventory(inventory, ctx) { if (!inventory) { return (false); } for (let i = 0; i < inventory.spaces.length; i++) { if (inventory.spaces[i].id !== -1) { if (inventory.spaces[i].img) { this.draw.inventoryItemImg(inventory.spaces[i].img, inventory.spaces[i].body.pos.x - 12, inventory.spaces[i].body.pos.y - 12, ctx) } else { this.draw.text(inventory.spaces[i].name, inventory.spaces[i].body.pos.x - 12, inventory.spaces[i].body.pos.y - 12, 10, ctx) } } } } mapInventoryClick(mouse, inventory, player, canvas) { let len = inventory.spaces.length for (let x = 0; x < len; x++) { if (this.clickHandler.click(mouse, inventory.spaces[x], canvas)) { if(player.inventory.addQuantity(inventory.spaces[x], inventory.spaces[x].quantity)) { inventory.delete(x); } } } } // stats drawPlayerStats(player, ctx) { let xOffset = 370; let yOffset = 50; let yIncrement = 15 let yXpIncrement = 10 let skills = player.skills let inventory = player.inventory let skillKeys = Object.keys(skills) let key = false; this.draw.img(userInterface.stats, 360, 0, 120,480, ctx) for (key of skillKeys) { this.draw.text(skills[key].show(), xOffset, yOffset += yIncrement, "10", ctx); this.draw.text(skills[key].showXp(), xOffset + 10, yOffset += yXpIncrement, "8", ctx); } yOffset += 40 this.draw.text("Gold: " + inventory.gold, xOffset, yOffset += yIncrement, "10", ctx); this.draw.text("Level: " + player.status.currLevel, xOffset, yOffset += yIncrement, "10", ctx); this.draw.text("Highest Level: " + player.status.highestLevel, xOffset, yOffset += yIncrement, "10", ctx); } // inventory drawSpacesForInventory(player, ctx) { this.inventorySpaces.drawGrid(ctx) this.inventorySpaces.drawInventory(player.inventory, ctx) } drawInventory(player, ctx) { if (this.inventoryMenu === "inventory") { this.drawSpacesForInventory(player, ctx); } else if (this.inventoryMenu === "armor") { this.drawSpacesForArmor(ctx); this.drawPlayerArmor(player,ctx) } else if (this.inventoryMenu === "stats") { this.drawPlayerStats(player, ctx) } else if (this.inventoryMenu === "magic") { this.draw.img(userInterface.stats, 360, 0,120,480, ctx) this.magicMenu.drawGrid(ctx); } this.inventoryMenuButtons.drawGrid(ctx); this.drawActionButtons(ctx); } drawHomeDesign(player, merchant, ctx) { if (player.status.currLevel === 0) { for (var i = 0; i < player.home.floor.length; i++) { player.home.floorAnimation.drawFloor(player.home.floor[i].index, player.home.floor[i], ctx) } player.home.wallAnimation.drawWall(ctx); this.drawHomeActionButtons(player, ctx) } } drawHome(player, items, ctx) { if (player.status.currLevel === 0) { if (this.currentHomeMenu === "bank") { this.drawBankButtons(player, ctx); } if (this.currentHomeMenu === "buy") { this.drawMenu(this.buyMenu, ctx); } if (this.currentHomeMenu === "craft") { this.drawMenu(this.craftMenu, ctx); } if (this.rightClickMenu.open === true) { this.drawDoubleClickButtons(player, ctx); } this.waterWellButton.collect(player); } } drawFarm(player, ctx) { if (player.status.destination === "farm" && player.status.currLevel === -1) { this.drawFarmButtons(player, ctx); } } drawActionButtons(ctx){ this.actionButtons.drawGrid(ctx); } drawHomeActionButtons(player, ctx){ this.draw.img(userInterface.greenButton,this.homeMenuButtons[3].button.body.pos.x - 10,this.homeMenuButtons[3].button.body.pos.y - 13, 85, 30, ctx); this.draw.label(this.homeMenuButtons[3], ctx); player.home.bank.animation.drawImage("open", player.home.bank, ctx) player.home.waterWell.animation.drawWaterWell(player.home.waterWell, ctx); player.home.buyMenu.animation.drawCraftCorner(player.home.buyMenu, ctx) } // armor drawSpacesForArmor(ctx){ this.draw.img(userInterface.armor, 360, 0, 120,480, ctx) } armorDrawCheck(armor, ctx) { if (armor.id === -1) { return false } if (armor.img) { this.draw.inventoryItemImg(armor.img, armor.body.pos.x, armor.body.pos.y, ctx) } else { this.draw.text(armor.name, armor.body.pos.x, armor.body.pos.y + 10, "9", ctx); } } arrowArmorDrawCheck(armor, ctx) { if (armor.id === -1) { return false } if (armor.img) { this.draw.inventoryItemImg(armor.img, armor.body.pos.x, armor.body.pos.y, ctx) } else { this.draw.text(armor.quantity, armor.body.pos.x, armor.body.pos.y + 20, "9", ctx); this.draw.text(armor.name, armor.body.pos.x, armor.body.pos.y + 10, "9", ctx); } } drawPlayerArmor(player, ctx) { this.armorDrawCheck(player.armor.helm, ctx); this.armorDrawCheck(player.armor.chest, ctx); this.armorDrawCheck(player.armor.legs, ctx); this.armorDrawCheck(player.armor.feet, ctx); this.armorDrawCheck(player.armor.weapon, ctx); this.armorDrawCheck(player.armor.shield, ctx); this.armorDrawCheck(player.armor.pickAxe, ctx); this.armorDrawCheck(player.armor.axe, ctx); this.armorDrawCheck(player.armor.bow, ctx); this.arrowArmorDrawCheck(player.armor.arrows, ctx); this.draw.text("Attack Bonus: ", 360, 375, "10", ctx); this.draw.text(player.armor.attackBonus, 450, 375, "10", ctx); this.draw.text("Speed Bonus: ", 360, 385, "10", ctx); this.draw.text(player.armor.attackSpeedBonus, 450, 385, "10", ctx); this.draw.text("Defense Bonus: ", 360, 395, "10", ctx); this.draw.text(player.armor.defenseBonus, 450, 395, "10", ctx); this.draw.text("Mining Bonus: ", 360, 415, "10", ctx); this.draw.text(player.armor.miningBonus, 450, 415, "10", ctx); this.draw.text("Woodcut Bonus: ", 360, 435, "10", ctx); this.draw.text(player.armor.woodCuttingBonus, 450, 435, "10", ctx); } //toggle and settings menuClick(mouse, canvas) { let click = this.inventoryMenuButtons.click(mouse, canvas) if (click.click) { if (click.index === 0) { this.showItemMenu(); } else if (click.index === 1) { this.showArmorMenu(); } else if (click.index === 2) { this.showStatsMenu(); } else if (click.index === 3) { this.showMagicMenu(); } } } magicClick(mouse, player, canvas) { if (this.inventoryMenu !== "magic") { return false; } let click = this.magicMenu.click(mouse, canvas) if (click.click) { switch (click.index) { case 0: player.magic.teleport.home(player); break case 1: player.magic.teleport.ten(player); break case 2: player.magic.teleport.fifty(player); break case 3: player.magic.archery.five(player); break case 4: player.magic.archery.ten(player); break case 5: player.magic.archery.thirty(player); break case 6: player.magic.defense.five(player); break case 7: player.magic.defense.ten(player); break case 8: player.magic.defense.thirty(player); break case 9: player.magic.attack.five(player); break case 10: player.magic.attack.ten(player); break case 11: player.magic.attack.thirty(player); break case 12: player.magic.mining.five(player); break case 13: player.magic.mining.ten(player); break case 14: player.magic.mining.thirty(player); break case 15: player.magic.woodcutting.five(player); break case 16: player.magic.woodcutting.ten(player); break case 17: player.magic.woodcutting.thirty(player); break case 18: player.magic.hunting.five(player); break case 19: player.magic.hunting.ten(player); break case 20: player.magic.hunting.thirty(player); break default : break; } } } teleportHomeLabel(player) { this.actionButtons[3].label.changeLabel("Stop"); } actionToggle(action, index) { if (action.state === false) { action.start() } else { action.stop() } this.actionButtons.changeImg(index, action.button()) this.actionButtons.changeLabel(index, action.label()) } actionClick(mouse, player, canvas) { if (this.currentHomeMenu !== "none") { return false } let click = this.actionButtons.click(mouse, canvas) if (click.click) { let keys = Object.keys(player.status.actions) this.actionToggle(player.status.actions[keys[click.index]], click.index); } } arrangeInventory(inventory, mouse, canvas) { if (this.inventoryMenu !== "inventory") { return false } this.mouseSwapItem.inventory.swap = false; let click = this.inventorySpaces.click(mouse, canvas) if (click.click) { this.mouseSwapItem.inventory.index = click.index this.mouseSwapItem.inventory.item = inventory.spaces[click.index]; } } swapInventory(inventory, mouse, canvas) { if (this.inventoryMenu !== "inventory") { return false } let click = this.inventorySpaces.click(mouse, canvas) if (click.click) { if (click.index !== this.mouseSwapItem.inventory.index && this.mouseSwapItem.inventory.item) { inventory.swap(this.mouseSwapItem.inventory.index, click.index); this.mouseSwapItem.inventory.swap = true; this.infoBox.clear(); } else { this.mouseSwapItem.inventory.swap = false; } } this.mouseSwapItem.inventory.item = false; this.mouseSwapItem.inventory.index = false } arrangeBank(inventory, mouse, canvas) { if (this.currentHomeMenu !== "bank") { return false } this.mouseSwapItem.bank.swap = false; let click = this.bankButtons.grid.click(mouse, canvas) if (click.click) { this.mouseSwapItem.bank.index = click.index + this.bankButtons.page this.mouseSwapItem.bank.item = inventory.spaces[click.index + this.bankButtons.page]; } } swapBank(inventory, mouse, canvas) { if (this.currentHomeMenu !== "bank") { return false } let click = this.bankButtons.grid.click(mouse, canvas) if (click.click) { if (click.index + this.bankButtons.page !== this.mouseSwapItem.bank.index && this.mouseSwapItem.bank.item) { inventory.swap(this.mouseSwapItem.bank.index, click.index + this.bankButtons.page); this.mouseSwapItem.bank.swap = true; this.infoBox.clear(); } else { this.mouseSwapItem.bank.swap = false; } } this.mouseSwapItem.bank.item = false; this.mouseSwapItem.bank.index = false } drawMouseSwapItem(menu, ctx) { if (this.mouseSwapItem[menu].item.img && this.mousePosition.x && this.mousePosition.y && ctx) { this.draw.inventoryItemImg(this.mouseSwapItem[menu].item.img, this.mousePosition.x - 10, this.mousePosition.y - 10, ctx); } else if (this.mouseSwapItem[menu].item.name && this.mouseSwapItem[menu].item.id !== -1){ this.draw.text(this.mouseSwapItem[menu].item.name, this.mousePosition.x - 10, this.mousePosition.y - 10, 10, ctx) } } updateMouse(mouse,canvas) { this.mousePosition = this.clickHandler.transformedCoordinate(mouse, canvas); } inventoryClick(mouse, player, canvas) { if (this.inventoryMenu !== "inventory" || this.mouseSwapItem.inventory.swap === true) { return false } let len = this.rightClickMenu.buttons.length; let bank = player.home.bank; if (this.rightClickMenu.open === true && this.rightClickMenu.menu === "inventory" && (this.currentHomeMenu === "bank" || this.currentHomeMenu === "buy")) { for (var i = 0; i < len; i++) { if (this.clickHandler.click(mouse, this.rightClickMenu.buttons[i].button, canvas)) { let max = player.inventory.spaces[this.rightClickMenu.index].quantity let quantity = this.getDoubleClickQuantity(i, max); if (this.currentHomeMenu === "buy") { if (player.inventory.sell(this.rightClickMenu.index, quantity)) { this.rightClickMenu.clear(); } } else { bank.inventory.addQuantity(player.inventory.spaces[this.rightClickMenu.index], quantity) if (player.inventory.deleteQuantity(this.rightClickMenu.index, quantity)) { this.rightClickMenu.clear(); } } return true } } this.rightClickMenu.clear(); return (true) } let click = this.inventorySpaces.click(mouse, canvas) if (click.click) { if (this.currentHomeMenu === "bank") { player.home.bank.inventory.add(player.inventory.spaces[click.index]) player.inventory.deleteOne(click.index); } else if (this.currentHomeMenu === "buy") { player.inventory.sell(click.index, 1); } else { if (player.inventory.spaces[click.index].wearable) { player.inventory.wearItem(player.armor, click.index) } else if (player.inventory.spaces[click.index].magic) { } else { player.inventory.useItem(player.skills, click.index) } } } } farmInventoryClick(mouse, player, canvas) { let click = this.inventorySpaces.click(mouse, canvas) if (click.click) { if (player.inventory.spaces[click.index].quantity > 5) { if (player.home.farm.add(player.inventory.spaces[click.index])) { player.inventory.deleteQuantity(click.index,5); } } if (player.home.farm.addWater(player.inventory.spaces[click.index])) { player.inventory.deleteOne(click.index); } } } drawBankButtons(player, ctx){ let page = this.bankButtons.page; this.bankButtons.grid.drawGrid(ctx) this.bankButtons.grid.drawInventory(player.home.bank.inventory, ctx, page) this.bankButtons.grid.drawControls(ctx); } drawMenu(menu, ctx){ let settings = this.getMenuConfig(menu); settings.categories.drawGrid(ctx); settings.subCategory.grid.drawGrid(ctx); settings.items.grid.drawGrid(ctx); settings.items.grid.drawItems(settings.imgs, ctx); settings.categories.drawControls(ctx); this.draw.text(menu.name, menu.categoryGrid.backGround.x + 125, menu.categoryGrid.backGround.y + 25, 20, ctx) } getDoubleClickQuantity(index, max) { let quantity = 0; if (index === 0) { quantity = 10; } else if (index === 1) { quantity = 50; } else if (index === 2) { quantity = max } if (quantity > max) { quantity = max } return (quantity) } menuButtonClick(menu, player, purchaseType, mouse, canvas) { let settings = this.getMenuConfig(menu) let click = settings.categories.controlClick(mouse, canvas) if (click.click) { if (click.index === 0) { this.currentHomeMenu = "none" } } click = settings.items.grid.click(mouse, canvas); if (click.click) { let item = settings.items.items[click.index]; if (purchaseType === "buy") { player.inventory.buy(item, 1) } else if (purchaseType === "craft") { player.inventory.craft(item, 1) } } click = settings.categories.click(mouse, canvas); if (click.click) { menu.currentCategory = click.label; menu.currentSubcategory = menu.subCategoryGrids[menu.currentCategory].first } click = settings.subCategory.grid.click(mouse,canvas); if (click.click) { menu.currentSubcategory = click.label; } } buyButtonClick(mouse, player, canvas) { if (this.currentHomeMenu !== "buy") { return false } let len = this.rightClickMenu.buttons.length; if (this.rightClickMenu.open === true && this.rightClickMenu.menu === "buy") { for (var i = 0; i < len; i++) { if (this.clickHandler.click(mouse, this.rightClickMenu.buttons[i].button, canvas)) { let item = this.buyMenu.subCategoryGrids[this.buyMenu.currentCategory].itemGrids[this.buyMenu.currentSubcategory].items[this.rightClickMenu.index]; if (player.inventory.gold <= 0 || item.price > player.inventory.gold) { return (false) } let quantity = this.getDoubleClickQuantity(i, Math.floor(player.inventory.gold / item.price)); player.inventory.buy(item, quantity) return true } } this.rightClickMenu.clear(); return (true) } this.menuButtonClick(this.buyMenu, player, "buy", mouse, canvas) } drawDoubleClickButtons(player, ctx) { if (this.rightClickMenu.open === true) { this.draw.fillRect(this.rightClickMenu.background, "black", ctx) for (var i = this.rightClickMenu.buttons.length - 1; i >= 0; i--) { this.draw.img(userInterface.aquaButton, this.rightClickMenu.buttons[i].button.body.pos.x,this.rightClickMenu.buttons[i].button.body.pos.y, 50, 35, ctx) this.draw.label(this.rightClickMenu.buttons[i], ctx) } } } doubleClickHandler(player, mouse, canvas) { let menuSettings = { player : player, mouse : mouse, canvas : canvas, }; let inventorySettings = { player : player, mouse : mouse, canvas : canvas, }; switch (this.currentHomeMenu) { case "bank" : menuSettings.grid = this.bankButtons.grid; menuSettings.tag = "bank"; menuSettings.page = this.bankButtons.page; inventorySettings.grid = this.inventorySpaces inventorySettings.tag = "inventory" break; case "buy" : menuSettings.grid = this.buyMenu.subCategoryGrids[this.buyMenu.currentCategory].itemGrids[this.buyMenu.currentSubcategory].grid; menuSettings.tag = "buy"; inventorySettings.grid = this.inventorySpaces inventorySettings.tag = "inventory" break; case "craft": menuSettings.grid = this.craftMenu.subCategoryGrids[this.craftMenu.currentCategory].itemGrids[this.craftMenu.currentSubcategory].grid; menuSettings.tag = "craft"; break; default : break; } if (menuSettings.grid) { this.doubleClick(menuSettings) } if (inventorySettings.grid) { this.doubleClick(inventorySettings) } } doubleClick(settings) { let page = settings.page || 0; let click = settings.grid.click(settings.mouse, settings.canvas); if (click.click) { let coordinate = this.clickHandler.transformedCoordinate(settings.mouse, settings.canvas) this.makeRightClickButtons(settings.tag, click.index + page, coordinate.x, coordinate.y); } } bankButtonClick(mouse, player, canvas) { if (this.currentHomeMenu !== "bank" || this.mouseSwapItem.bank.swap === true) { return false } let page = this.bankButtons.page; let len = this.rightClickMenu.buttons.length; let bank = player.home.bank; if (this.rightClickMenu.open === true && this.rightClickMenu.menu === "bank") { let maxAmount = bank.inventory.spaces[this.rightClickMenu.index].quantity for (var i = 0; i < len; i++) { if (this.clickHandler.click(mouse, this.rightClickMenu.buttons[i].button, canvas)) { let quantity = this.getDoubleClickQuantity(i, maxAmount); player.inventory.addQuantity(bank.inventory.spaces[this.rightClickMenu.index], quantity) if (bank.inventory.deleteQuantity(this.rightClickMenu.index, quantity)) { this.rightClickMenu.clear(); } return true } } this.rightClickMenu.clear(); return (true) } let click = this.bankButtons.grid.click(mouse, canvas); if (click.click) { if (player.inventory.add(player.home.bank.inventory.spaces[click.index + page])) { player.home.bank.inventory.deleteOne(click.index + page) } } click = this.bankButtons.grid.controlClick(mouse, canvas); if (click.click) { if (click.index === 0) { this.bankButtons.page -= 20; if (this.bankButtons.page < 0) { this.bankButtons.page = 0 return false } this.bankButtons.grid.controls[3].button.body.pos.y -= 35; } else if (click.index === 1) { this.bankButtons.page += 20; if (this.bankButtons.page > 150) { this.bankButtons.page = 150 return false; } this.bankButtons.grid.controls[3].button.body.pos.y += 35; } else if (click.index === 2) { this.currentHomeMenu = "none"; } } } craftButtonClick(mouse, player, canvas) { if (this.currentHomeMenu !== "craft") { return false } this.showItemMenu() let len = this.rightClickMenu.buttons.length; if (this.rightClickMenu.open === true && this.rightClickMenu.menu === "craft") { for (var i = 0; i < len; i++) { if (this.clickHandler.click(mouse, this.rightClickMenu.buttons[i].button, canvas)) { let item = this.craftMenu.subCategoryGrids[this.craftMenu.currentCategory].itemGrids[this.craftMenu.currentSubcategory].items[this.rightClickMenu.index]; let maxAmount = player.inventory.maxCraft(item); let quantity = this.getDoubleClickQuantity(i, maxAmount) player.inventory.craft(item, quantity) this.rightClickMenu.clear(); return true } } this.rightClickMenu.clear(); return (true) } let currentCategory = this.craftMenu.currentCategory; let currentSubcategory = this.craftMenu.currentSubcategory; let categories = this.craftMenu.categoryGrid let subCategory = this.craftMenu.subCategoryGrids[currentCategory]; let itemGrid = subCategory.itemGrids[currentSubcategory] let click = categories.controlClick(mouse, canvas) if (click.click) { if (click.index === 0) { this.currentHomeMenu = "none" } } click = itemGrid.grid.click(mouse, canvas); if (click.click) { let item = this.craftMenu.subCategoryGrids[this.craftMenu.currentCategory].itemGrids[this.craftMenu.currentSubcategory].items[click.index]; player.inventory.craft(item, 1) } click = categories.click(mouse, canvas); if (click.click) { this.craftMenu.currentCategory = click.label; this.craftMenu.currentSubcategory = this.craftMenu.subCategoryGrids[this.craftMenu.currentCategory].first } click = subCategory.grid.click(mouse,canvas); if (click.click) { this.craftMenu.currentSubcategory = click.label; } } homeButtonClick(mouse, player, merchant, canvas) { if (this.currentHomeMenu !== "none") { return false; } if (this.clickHandler.click(mouse, merchant, canvas)) { this.currentHomeMenu = "buy" } let len = this.homeMenuButtons.length for (let x = 0; x < len; x++) { if (this.clickHandler.click(mouse, this.homeMenuButtons[x].button, canvas)) { if (x === 0) { this.currentHomeMenu = "bank"; this.homeMenuButtons[x].label.changeLabel("Water"); } else if (x === 1) { this.currentHomeMenu = "craft"; this.homeMenuButtons[x].label.changeLabel("Water"); } else if (x === 2) { if (this.waterWellButton.open) { this.waterWellButton.open = false this.homeMenuButtons[x].label.changeLabel("Water"); } else { if (this.currentHomeMenu === "none") { this.waterWellButton.open = true this.homeMenuButtons[x].label.changeLabel("Stop"); } } } else if (x === 3) { if (this.currentHomeMenu === "none") { player.home.waterWell.upgrade(player.inventory); this.homeMenuButtons[x].label.changeLabel(player.home.waterWell.upgradeStr()); } } } } } armorClick(mouse, player, canvas) { if (this.inventoryMenu !== "armor") { return false } let len = this.armorButtons.length for (let x = 0; x < len; x++) { if (this.clickHandler.click(mouse, this.armorButtons[x].button, canvas)) { if (x === 0) { player.armor.removeHelm(player.inventory); } else if (x === 1){ player.armor.removeChest(player.inventory); } else if (x === 2){ player.armor.removeWeapon(player.inventory); } else if (x === 3){ player.armor.removeShield(player.inventory); } else if (x === 4){ player.armor.removeLegs(player.inventory); } else if (x === 5){ player.armor.removeFeet(player.inventory); } else if (x === 6){ player.armor.removePickAxe(player.inventory); } else if (x === 7){ player.armor.removeAxe(player.inventory); } else if (x === 8){ player.armor.removeArrows(player.inventory); } else if (x === 9){ player.armor.removeBow(player.inventory); } } } } showItemMenu() { this.inventoryMenu = "inventory" } showArmorMenu() { this.inventoryMenu = "armor" } showStatsMenu() { this.inventoryMenu = "stats" } showMagicMenu() { this.inventoryMenu = "magic" } armorButton(button, label) { this.armorButtons.push({button: button, label:label}) } homeButton(button, label) { this.homeMenuButtons.push({button: button, label:label}) } button (x, y, width, height) { return ({ body : new RigidBody(x,y,width,height) }) } label(label, x, y, fontSize) { return ({ body : new RigidBody(x,y,32,32), fontSize: fontSize, label: label, changeLabel : function(label) { this.label = label; } }) } makeArmorMenu() { this.armorButton( this.button(400, 135, 40, 40), this.label("Helm", 405, 130, "10") ) this.armorButton( this.button(400, 195, 40, 40), this.label("Chest", 405, 190, "10") ) this.armorButton( this.button(360, 195, 40, 40), this.label("Weapon", 360, 190, "10") ) this.armorButton( this.button(440, 195, 40, 40), this.label("Shield", 440, 190, "10") ) this.armorButton( this.button(400, 255, 40, 40), this.label("Legs", 405, 250, "10") ) this.armorButton( this.button(400, 315, 40, 40), this.label("Boots", 405, 310, "10") ) this.armorButton( this.button(360, 15, 40, 40), this.label("Pic", 365, 10, "10") ) this.armorButton( this.button(360, 70, 40, 40), this.label("Axe", 365, 65, "10") ) this.armorButton( this.button(440, 15, 40, 40), this.label("Arrows", 440, 10, "10") ) this.armorButton( this.button(440, 70, 40, 40), this.label("Bow", 440, 65, "10") ) } makeHomeActionButtons(player) { let bank = player.home.bank; let buy = player.home.buyMenu; let waterWell = player.home.waterWell this.homeButton( this.button(bank.body.pos.x, bank.body.pos.y, bank.body.size.x, bank.body.size.y), this.label("Bank", bank.body.pos.x + 30, bank.body.pos.y + 25, "15") ) this.homeButton( this.button(buy.body.pos.x, buy.body.pos.y, buy.body.size.x, buy.body.size.y), this.label("craft", buy.body.pos.x + 10, buy.body.pos.y + 50, "15") ) this.homeButton( this.button(waterWell.body.pos.x, waterWell.body.pos.y, waterWell.body.size.x, waterWell.body.size.y), this.label("Water", waterWell.body.pos.x + 15, waterWell.body.pos.y + 50, "15") ) this.homeButton( this.button(waterWell.body.pos.x, waterWell.body.pos.y + 100, 70, 25), this.label(waterWell.upgradeStr(), waterWell.body.pos.x + 5, waterWell.body.pos.y + 110, "9") ) } makeRightClickButtons(menu, index, x, y) { let yOffset = 10; let xNameOffset = 10; let yNameOffset = 20; x = x - 30; y = y - 20; this.rightClickMenu.clear(); this.rightClickMenu.open = true; this.rightClickMenu.index = index this.rightClickMenu.menu = menu; this.rightClickMenu.background = this.button(x,y, 50,120) this.rightClickMenu.buttons.push({ button: this.button(x, y, 50, 40), label: this.label("10", x + xNameOffset, y + yNameOffset, "10") }) yOffset += 30; yNameOffset += 40; this.rightClickMenu.buttons.push({ button: this.button(x, y + yOffset, 50, 40), label: this.label("50", x + xNameOffset, y + yNameOffset, "10") }) yOffset += 40; yNameOffset += 40 this.rightClickMenu.buttons.push({ button: this.button(x, y + yOffset, 50, 40), label: this.label("All", x + xNameOffset, y + yNameOffset, "10") }) } makeFarmButton(button, label) { this.farmButtons.spaces.push({button: button, label:label}) } farmControlButton(button, label) { this.farmButtons.controls.push({button: button, label:label}) } makeFarmButtons(player) { let farm = player.home.farm; for (let i = 0; i < farm.spaces.length; i++) { this.makeFarmButton(this.button(farm.spaces[i].body.pos.x, farm.spaces[i].body.pos.y, 32, 32), this.label("", 0, 0, "0") ) } this.farmControlButton(this.button(50,250,100,50), this.label(farm.waterLevel, 75, 275, "20") ) } drawFarmButtons(player, ctx) { player.home.farm.plot.drawFarmPlot(player.home.farm, ctx) for (let i = 0; i < this.farmButtons.spaces.length; i++) { if (player.home.farm.spaces[i].seed) { player.home.farm.spaces[i].seed.animation.drawPlants(player.home.farm.spaces[i], player.home.farm.spaces[i].level, ctx) } } this.draw.button({button: this.button(50,125,0,0), label: this.label("Water:", 55, 100, "15") }, ctx ); this.draw.button({button: this.button(50,75,100,50), label: this.label(player.home.farm.waterLevelStr(), 55, 120, "15") }, ctx ); } farmButtonClick(mouse, player, canvas) { let len = this.farmButtons.spaces.length for (let x = 0; x < len; x++) { if (this.clickHandler.click(mouse, this.farmButtons.spaces[x].button, canvas)) { player.home.farm.harvest(x, player.inventory) } } } }<file_sep>const Sequelize = require('sequelize') const uuidv4 = require('uuid/v4'); const {seed} = require("./seed"); const sequelize = new Sequelize('idle_forest', 'postgres', 'postgres', { host: 'localhost', dialect: 'postgres', pool: { max: 10, min: 0, acquire: 30000, idle: 10000 } }) const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.users = require('./models/user.js')(sequelize, Sequelize); db.inventoryItems = require('./models/inventory.js')(sequelize, Sequelize); db.skills = require('./models/skills.js')(sequelize, Sequelize); db.bankItems = require('./models/bank.js')(sequelize, Sequelize); db.armorItems = require('./models/armor.js')(sequelize, Sequelize); db.inventoryItems.belongsTo(db.users); db.skills.belongsTo(db.users); db.bankItems.belongsTo(db.users); db.armorItems.belongsTo(db.users); db.users.hasMany(db.inventoryItems); db.users.hasMany(db.skills); db.users.hasMany(db.bankItems); db.users.hasMany(db.armorItems); sequelize.sync({ // force: true }) .then(() => { // seed(db) // .then(() => { // db.users.findOne({ // where : {id:1}, // include: [ // { // model: db.inventoryItems, // }, // { // model: db.skills, // } // ] // }).then(users => { // console.log(users) // }); console.log(`Database & tables created!`) // }) }) module.exports = { db }<file_sep>import Draw from "./draw" import {scale} from "../../Helpers/functions" import {userInterface} from "../../Objects/Animations/images" export default class DrawEntity { constructor() { this.draw = new Draw(); } handler (objList, ctx) { if (objList.enemies) { this.enemies(objList.enemies, ctx); } if (objList.animals) { this.animals(objList.animals, ctx); } if (objList.trees) { this.resources(objList.trees, ctx); } if (objList.ore) { this.resources(objList.ore, ctx); } if (objList.player) { this.player(objList.player, ctx) } if (objList.merchant && objList.player.status.currLevel === 0) { this.character(objList.merchant, ctx) } } animationAction(player, direction, ctx) { if (player.body.action === "fight") { player.armor.animation.fight(direction, player, ctx) } else if (player.body.action === "archery") { player.armor.animation.range(direction, player, ctx) } else if (player.body.action === "mine") { player.armor.animation.mine(direction, player, ctx) } else if (player.body.action === "woodcut") { player.armor.animation.woodcut(direction, player, ctx) } else if (player.body.action === "stop") { player.armor.animation.stop(direction, player, ctx) } else { if (player.target && player.armor.animation.walk(direction, player, ctx)) { player.body.move_to(player.target.body.pos.x, player.target.body.pos.y) } } } playerAnimationMovement(player, ctx) { if (player.status.dead === true) { player.armor.animation.death(player,ctx) return false } if (player.body.currentDirection === "north") { this.animationAction(player, "up", ctx) } else if (player.body.currentDirection === "east") { this.animationAction(player, "right", ctx) } else if (player.body.currentDirection === "south") { this.animationAction(player, "down", ctx) } else if (player.body.currentDirection === "west") { this.animationAction(player, "left", ctx) } } enemies(enemies, ctx) { for (let i = 0; i < enemies.length; i++) { this.playerAnimationMovement(enemies[i], ctx); this.drawHealthBar(enemies[i], ctx); } } player(player, ctx) { for (var i = 0; i < player.range.projectiles.active.length; i++) { if (player.range.projectiles.active[i]) { if(player.range.projectiles.active[i].img) { this.draw.img( player.range.projectiles.active[i].img, player.range.projectiles.active[i].projectile.body.pos.x, player.range.projectiles.active[i].projectile.body.pos.y, 64, 64, ctx ) } else { this.draw.fillRect(player.range.projectiles.active[i].projectile, "blue", ctx); } } } this.playerAnimationMovement(player, ctx) this.drawPlayerStatsInCorner(player, ctx); } animals(animals, ctx) { for (let i = 0; i < animals.length; i++) { let move = false; if (animals[i].body.currentDirection === "north") { move = animals[i].armor.animation.walk("up", animals[i], ctx) } else if (animals[i].body.currentDirection === "east") { move = animals[i].armor.animation.walk("right", animals[i], ctx) } else if (animals[i].body.currentDirection === "south") { move = animals[i].armor.animation.walk("down", animals[i], ctx) } else if (animals[i].body.currentDirection === "west") { move = animals[i].armor.animation.walk("left", animals[i], ctx) } if (move) { animals[i].body.followPath(); } this.drawHealthBar(animals[i], ctx); } } resources(resource, ctx) { for (let i = 0; i < resource.length; i++) { resource[i].armor.animation.drawResource(resource[i], ctx) this.drawHealthBar(resource[i], ctx); } } character(character, ctx) { this.playerAnimationMovement(character, ctx) } drawHealthBar (obj, ctx) { this.draw.img(userInterface.emptyBar, obj.body.pos.x, obj.body.pos.y, obj.body.size.x, 5, ctx); let scaledHealth = scale(obj.skills.health.getCurrent(), 0, obj.skills.health.get(), 0 , obj.body.size.x) this.draw.img(userInterface.healthBar, obj.body.pos.x, obj.body.pos.y, scaledHealth, 5, ctx); } drawPlayerStatsInCorner(player, ctx) { const xOffset = 35; this.draw.img(userInterface.emptyBar, xOffset, 0, 50, 15, ctx); this.draw.img(userInterface.emptyBar, xOffset, 15, 50, 15, ctx); this.draw.img(userInterface.emptyBar, xOffset, 30, 50, 15, ctx); let scaledHealth = scale(player.skills.health.getCurrent(), 0, player.skills.health.get(), 0 , 50) this.draw.img(userInterface.healthBar, xOffset, 0, scaledHealth, 15, ctx); let scaledThirst = scale(player.skills.thirst.getCurrent(), 0, player.skills.thirst.get(), 0 , 50) this.draw.img(userInterface.thirstBar, xOffset, 15, scaledThirst, 15, ctx); let scaledHunger = scale(player.skills.hunger.getCurrent(), 0, player.skills.hunger.get(), 0 , 50) this.draw.img(userInterface.hungerBar, xOffset, 30, scaledHunger, 15, ctx); this.draw.text("HP:", 0, 8, "8", ctx, "purple") this.draw.text("Thirst:", 0, 24, "8", ctx, "purple") this.draw.text("Hunger:", 0, 40, "8", ctx, "purple") this.draw.text("Level: " + player.status.currLevel, 0, 54, "7", ctx, "purple"); } }<file_sep> import Entity from '../Entity' import AnimalAnimation from "../Animations/animalAnimation" import {randomInt} from "../../Helpers/functions" import { npc } from "../Animations/images" import {settings} from "../../Helpers/settings" export default class Npc { constructor(items) { this.items = items } animals(level) { let arr = []; for (var i = 0; i < randomInt(1,4); i++) { let animalSettings = this.chooseAnimal(level) let animal = new Entity({ name : animalSettings.name, x : randomInt(0, 300), y : randomInt(0, 300), width : animalSettings.size, height : animalSettings.size, startingGold : 0, info: animalSettings.name, status : { dead : false, deaths : 0, currLevel : 1, highestLevel : 0, teleported : false, type : "animal", }, skills : { attack : 1, health : 10, defense : 1, attackSpeed : 1, range : 1, magic : 1, thirst : 1, hunger : 1, mining : 1, woodcutting : 1, hunting : animalSettings.huntingLvl, hungerDecay : 1000, thirstDecay : 800, }, animation : { singleImg : animalSettings.animation }, items : this.items }) for (i = 0; i < animalSettings.amount; i++) { animal.inventory.add(this.items.randomFood(level)) } animal.body.createPath(animal.body.pos.x, animal.body.pos.y); animal.body.setVelocity(settings.animals.walkVelocity.x, settings.animals.walkVelocity.y) arr.push(animal) } return (arr); } chooseAnimal(level) { let animal = npc.chicken; let name = "chicken"; let huntingLvl = 1; let animation = new AnimalAnimation(npc.chicken); let size = 64 if (level >= 0 && level < 20) { animal = npc.chicken name = "Chicken" size = 32 } else if (level >= 20 && level < 40) { animal = npc.cow name = "Cow" } else if (level >= 40 && level < 60) { animal = npc.pig name = "Pig" } else if (level >= 60 && level < 80) { animal = npc.turkey name = "Turkey" } else if (level >= 80 && level < 100) { animal = npc.llama name = "Llama" } else { animal = npc.llama name = "Llama" } let amount = randomInt(settings.animals.itemDropCountRange.start, settings.animals.itemDropCountRange.end); animation = new AnimalAnimation(animal); return ({ name : name, amount : amount, miningLvl : 1, woodCutLvl : 1, huntingLvl : huntingLvl, health : 100, animation : animation, size : size, }) } }<file_sep> module.exports = (app, db) => { app.get('/bank', (req, res) => { db.bankItems.findAll({ where : { user_id: req.session.userId, }, }).then(bank => { if (bank) { console.log(bank) res.json({code: 1, message: "Get BANK Success", bank: bank}) } else { res.json({code : -1, message: "No Session Available"}) } }); }) app.post('/saveBank', (req, res) => { let inventory = req.body.bank let items = []; db.bankItems.destroy({ where: { user_id : req.session.userId } }).then(function() { for (var i = 0; i < inventory.length; i++) { if (inventory[i].id != -1) { items.push({ user_id : req.session.userId, name : inventory[i].name, item_id: inventory[i].id, item_index: inventory[i].item_index, subCategory_id: inventory[i].subCategory_id, category_id :inventory[i].category_id, quantity : inventory[i].quantity, }) } } db.bankItems.bulkCreate(items).then(function() { res.json({code : 1, message: "bank save Successful"}) }, function(err){ // console.log(err) res.json({code : -1, message: "Bank Save Not Successful"}) }) }) }) }<file_sep>import React from "react" import Player from "../../Objects/Player" import SkillsTest from "../../Test/Skills" import Item from "../../Objects/Item" export default class PlayerTest extends React.Component { constructor() { super() this.test(); } checkNoCollision() { // moves player2 far away from player 1 and checks collision while (this.player2.body.move_to(0,230) === false) { console.log(this.player2.getName()) this.player.body.log(); } console.warn("COLLISION:", this.player.body.collide(this.player2.body)); } checkYesCollision() { // moves both players to same coordinate and check collision while (this.player.body.move_to(50,50) === false) { console.log(this.player.getName()) this.player.body.log(); } while (this.player2.body.move_to(50,50) === false) { console.log(this.player2.getName()) this.player.body.log(); } console.warn("COLLISION:", this.player.body.collide(this.player2.body)); } testSkills() { console.log(this.player.getName()); this.player.skills = new SkillsTest(); console.log(this.player2.getName()); this.player2.skills = new SkillsTest(); } testCollision() { this.checkNoCollision(); this.checkYesCollision(); } testItems(items) { this.player2 = new Player(0,0,32,32); this.player2.inventory.add(items.healthLevel()); this.player2.inventory.useItem(this.player2.skills, 0) this.player2.inventory.add(items.healthLevel()); this.player2.inventory.useItem(this.player2.skills, 0) this.player2.inventory.add(items.healthLevel()); this.player2.inventory.useItem(this.player2.skills, 0) this.player2.inventory.add(items.healthLevel()); this.player2.inventory.useItem(this.player2.skills, 0) this.player2.setName("player two"); console.log(this.player2.inventory) console.log(this.player2.skills) if (this.player2.skills.health.get() === 14) { console.log("SKILL VALUE MATCHED") } else { console.warn("SKILL VALUE DOWSNT MATCH"); } } testGold() { this.player.inventory.addGold(200); if (this.player.inventory.gold === 200) { console.log("gold Check GOOD"); } else { console.warn("GOLD CHECK BAD"); } if (this.player.inventory.useGold(300) === false) { console.log("Pass gold use test") } this.player.inventory.useGold(100) if (this.player.inventory.gold === 100) { console.log("gold Check GOOD"); } else { console.warn("GOLD CHECK BAD"); } console.log("GOLD" + this.player.inventory.gold) } testAddWholeInventory() { let items = new Item(); let testPlayer = new Player(0,0,32,32) let testPlayer2= new Player(0,0,32,32) testPlayer.setName("TESTPLAYER 1"); testPlayer.inventory.add(items.smallPotion()); testPlayer.inventory.add(items.smallPotion()); testPlayer.inventory.add(items.smallPotion()); testPlayer.inventory.add(items.smallPotion()); testPlayer.inventory.add(items.smallPotion()); testPlayer2.inventory.addGold(1000); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.smallWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer2.inventory.add(items.megaWater()); testPlayer.inventory.addInventory(testPlayer2.inventory); console.log(testPlayer) } test() { let items = new Item(); this.player = new Player(0,0,32,32); // this.player.setName("player one"); // this.player.inventory.add(items.smallPotion()); // console.log(this.player.inventory) // this.testItems(items); // this.testGold(); // this.testCollision(); // this.testSkills() this.testAddWholeInventory(); } log() { this.player.log(); } }<file_sep>export default class Collision { box(obj1, obj2) { if (obj1.pos.x < obj2.pos.x + obj2.size.x && obj1.pos.x + obj1.size.x > obj2.pos.x && obj1.pos.y < obj2.pos.y + obj2.size.y && obj1.pos.y + obj1.size.y > obj2.pos.y) { return (true); } return (false); } test() { } log() { } }<file_sep>import {timer} from "../../Helpers/functions" export default class AnimalAnimation { constructor(animal) { this.animal = animal; this.walkTimer = this.makeTimer(this.animal.images.walk.directions.up.end, 150); this.eatTimer = this.makeTimer(this.animal.images.eat.directions.up.end, 150); this.deathTimer = this.makeTimer(this.animal.images.eat.directions.up.end, 150); } makeTimer(end, animationTime) { return ({ index : 0, end : end, done : false, delayTimer : timer(animationTime), clear: function() { this.time = 0 this.index = 0 }, timer : function() { if (this.delayTimer.check()) { this.index++; if (this.index > this.end) { this.done = true this.index = 0; } return true } } }) } animate(animal, ctx, animation, direction, timer) { let size = this.animal.size let clipY = this.animal.images[animation].directions[direction].index * size let animalX = animal.body.pos.x let animalY = animal.body.pos.y this.draw(this.animal.images[animation].img, size * timer.index, clipY, size, animalX, animalY, ctx, size) } walk(direction, player, ctx) { this.animate(player, ctx, "walk", direction, this.walkTimer) return(this.walkTimer.timer()); } eat(direction, player, ctx) { this.animate(player, ctx, "eat", direction, this.eatTimer) return(this.eatTimer.timer()); } draw(img, clipX, clipY, size, resourceX, resourceY, ctx, drawSize = 64) { ctx.drawImage(img, clipX, clipY, size, size, resourceX, resourceY, drawSize, drawSize ); } }<file_sep>import Items from "../../Objects/Item/" export default class ItemTest { constructor() { this.items = new Items(); // this.items.listCategories(); // this.listSubCategories(); this.test(); } listSubCategories() { this.items.listSubCategories(0); this.items.listSubCategories(1); this.items.listSubCategories(2); this.items.listSubCategories(3); } test() { let item = this.items.getItemFromClick(0) let none = this.items.none(); console.log(none); console.log(none.use()); let randomItem = this.items.randomItemDrop(0); // let randomItemCopy = randomItem.copy(); console.log(randomItem) for (var x = 1; x < 20; x++) { let randomItem = this.items.randomItemDrop(5); console.log(randomItem) } } log() { } }<file_sep>import Projectiles from "../Projectiles" export default class Range { constructor(items) { this.projectiles = new Projectiles(); this.items = items } shoot(player, enemy, damage) { if (player.armor.arrows.id === -1) { return false } else { this.projectiles.fire(player, player.armor.arrows, enemy, damage); } } checkCollision(enemies) { return (this.projectiles.checkArrowCollision(enemies)); } log() { console.log(this.projectiles); } }<file_sep>import Vector2d from '../vector2d' import Collision from '../collision' import {randomInt} from "../functions" export default class RigidBody { constructor(x, y, width, height) { this.pos = new Vector2d(x,y); this.size = new Vector2d(width, height); this.collision = new Collision(); this.setVelocity(5,5); this.stop = false; this.stopMining = true; this.stopWoodCutting = true; this.goHome = false; this.stopHunting = true this.goFarm = false this.currentDirection = "north"; this.action = "stop" } setVelocity(x,y) { this.velocity = new Vector2d(x,y); } setPos(x,y) { this.pos.x = x; this.pos.y = y; } createPath(x, y) { let arr = [] for (let i = 0; i < 4; i++) { let x1 = randomInt(0,5) * 5; let y1 = randomInt(0,5) * 5; let size = 32; arr.push(new RigidBody(x + x1,y + y1,size,size)); } this.path = { index: 0, len: 4, arr: arr, newPath() { let arr = [] for (let i = 0; i < 4; i++) { let x = randomInt(0,50) * 5; let y = randomInt(0,50) * 5; let size = 2; arr.push(new RigidBody(x,y,size,size)); } this.arr = arr; }, next : function() { if (this.index === this.len - 1) { this.index = 0; this.newPath(); } else { this.index++; } }, }; } followPath() { if (this.move_to(this.path.arr[this.path.index].pos.x, this.path.arr[this.path.index].pos.y) ) { this.path.next(); } } move_right() { if (this.pos.x > 480) { return false } this.pos.x += this.velocity.x; } move_left() { if (this.pos.x <= 0) { return false } this.pos.x -= this.velocity.x; } move_down() { this.pos.y += this.velocity.y } move_up() { this.pos.y -= this.velocity.y } move_to(x,y) { if (this.at_destination(x,y)) { return (true); } if(this.pos.x <= x) { this.move_right() this.currentDirection = "east" } if (this.pos.y <= y) { this.move_down() this.currentDirection = "south" } if(this.pos.x > x) { this.move_left() this.currentDirection = "west" } if (this.pos.y > y) { this.move_up(); this.currentDirection = "north" } return(false) } at_destination(x,y) { let point = new RigidBody(x,y,32,32); if (this.pos.x < x) { this.currentDirection = "east" } if (this.pos.x > x) { this.currentDirection = "west" } if (this.pos.y < y) { this.currentDirection = "south" } if (this.pos.y > y) { this.currentDirection = "north" } if (this.collide(point)) { return true; } return (false); } collide(obj) { return(this.collision.box(this, obj)); } test() { this.log(); } log() { this.pos.log(); this.size.log(); } }<file_sep>import ItemTemplate from '../ItemTemplate.js' import {itemImages} from "../../../Animations/images" let food = [ { info : new ItemTemplate({ name: "Chicken", price : 100, img: itemImages.rawMeat.chicken, use : function(skill) { return ({skill: skill, description: "Used In Cooking", used: false}); } }) }, { info : new ItemTemplate({ name: "Cow", price : 500, img: itemImages.rawMeat.cow, use : function(skill) { return ({skill: skill, description: "Used In Cooking", used: false}); } }) }, { info : new ItemTemplate({ name: "Llama", price : 1500, img: itemImages.rawMeat.llama, use : function(skill) { return ({skill: skill, description: "Used In Cooking", used: false}); } }) }, { info : new ItemTemplate({ name: "Pig", price : 3000, img: itemImages.rawMeat.pig, use : function(skill) { return ({skill: skill, description: "Used In Cooking", used: false}); } }) }, { info : new ItemTemplate({ name: "Turkey", price : 6000, img: itemImages.rawMeat.turkey, use : function(skill) { return ({skill: skill, description: "Used In Cooking", used: false}); } }) }, ] let plants = [ { info : new ItemTemplate({ name: "Carrot", price : 1000, img: itemImages.plants.carrot, use : function() { return ({description: "Used For Farming carrots", used: false}); } }) }, { info : new ItemTemplate({ name: "Potatoes", price : 1500, img: itemImages.plants.potatoes, use : function() { return ({description: "Used For Farming Potatoes", used: false}); } }) }, { info : new ItemTemplate({ name: "Corn", price : 1300, img: itemImages.plants.corn, use : function() { return ({description: "Used For Farming Corn", used: false}); } }) }, { info : new ItemTemplate({ name: "cucumber", price : 800, img: itemImages.plants.cucumber, use : function() { return ({description: "Used For Farming Cucumber", used: false}); } }) }, { info : new ItemTemplate({ name: "Tomatoes", price : 800, img: itemImages.plants.tomatoes, use : function() { return ({description: "Used For Farming Tomatoes", used: false}); } }) }, { info : new ItemTemplate({ name: "Artichoke", price : 800, img: itemImages.plants.artichoke, use : function() { return ({description: "Used For Farming Artichoke", used: false}); } }) }] let cookedFood = [ { info : new ItemTemplate({ name: "Chicken (C)", price : 100, img: itemImages.cookedMeat.chicken, use : function(skill) { skill.hunger.giveLimit(100) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: food[0].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Cow (C)", price : 500, img: itemImages.cookedMeat.cow, use : function(skill) { skill.hunger.giveLimit(500) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: food[1].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Llama (C)", price : 1500, img: itemImages.cookedMeat.llama, use : function(skill) { skill.hunger.giveLimit(1000) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: food[2].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Pig (C)", price : 3000, img: itemImages.cookedMeat.pig, use : function(skill) { skill.hunger.giveLimit(2000) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: food[3].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Turkey (C)", price : 6000, img: itemImages.cookedMeat.turkey, use : function(skill) { skill.hunger.giveLimit(4000) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: food[4].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Carrots (C)", price : 100, img: itemImages.cookedPlants.carrot, use : function(skill) { skill.hunger.giveLimit(200) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: plants[0].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Potatoes (C)", price : 100, img: itemImages.cookedPlants.potatoes, use : function(skill) { skill.hunger.giveLimit(200) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: plants[1].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Corn (C)", price : 100, img: itemImages.cookedPlants.corn, use : function(skill) { skill.hunger.giveLimit(200) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: plants[2].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Cucumber (C)", price : 100, img: itemImages.cookedPlants.cucumber, use : function(skill) { skill.hunger.giveLimit(200) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: plants[3].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Tomatoes (C)", price : 100, img: itemImages.cookedPlants.tomatoes, use : function(skill) { skill.hunger.giveLimit(200) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: plants[4].info, quantity: 1}] }) }, { info : new ItemTemplate({ name: "Artichoke (C)", price : 100, img: itemImages.cookedPlants.artichoke, use : function(skill) { skill.hunger.giveLimit(200) return ({skill: skill, description: "Eat Up", used: true}); }, recipe: [{item: plants[5].info, quantity: 1}] }) }, ] export { food, cookedFood, plants } <file_sep>import RigidBody from '../../Helpers/rigidBody' import Skills from "./Skills" import Inventory from "../../Objects/Inventory" import Armor from './Armor' import Home from './Home' import Range from './Range' import Magic from './Magic' import Status from './Status' export default class Entity { constructor(settings) { this.target = false; this.name = settings.name; this.password = ""; this.info = settings.info || settings.name || "FRED"; this.items = settings.items; this.body = new RigidBody(settings.x, settings.y, settings.width, settings.height); this.skills = new Skills(settings.skills); this.armor = new Armor(settings.items, settings.animation); this.home = new Home(settings.items); this.inventory = new Inventory(settings.items); this.inventory.addGold(settings.startingGold); this.magic = new Magic(settings.items); this.status = new Status(settings.status); this.range = new Range(settings.items); this.redrawHome = true; } homeDrawUpdate() { if (this.status.currLevel === 0) { this.redrawHome = true; } } setLocation() { if (this.status.currLevel === 0) { this.status.location = "home"; } else if (this.status.currLevel === -1) { this.status.location = "farm"; } else if (this.status.currLevel > 0) { this.status.location = "wild"; } else { this.status.location = "lost"; } } setDestination() { if (this.status.actions.walk.state === true && this.status.actions.home.state === true && this.status.actions.farm.state === true) { this.status.destination = "farm"; } else if (this.status.actions.walk.state === true && this.status.actions.home.state === false && this.status.actions.farm.state === true) { this.status.destination = "farm"; } else if (this.status.actions.walk.state === true && this.status.actions.home.state === true && this.status.actions.farm.state === false) { this.status.destination = "home"; } else if (this.status.actions.walk.state === false && this.status.actions.home.state === true && this.status.actions.farm.state === false) { this.status.destination = "home"; } else if (this.status.actions.walk.state === false && this.status.actions.home.state === false && this.status.actions.farm.state === true) { this.status.destination = "farm"; } else if (this.status.actions.walk.state === false && this.status.actions.home.state === false && this.status.actions.farm.state === false) { this.status.destination = "none"; } else if (this.status.actions.walk.state === false && this.status.actions.home.state === true && this.status.actions.farm.state === true) { this.status.destination = "home"; } else { this.status.destination = "wild" } } setAction(enemies, ores, trees, animals) { if (enemies.length) { this.status.action = "fighting"; } else if (this.status.actions.mine.state === true && ores.length) { this.status.action = "mining"; } else if (this.status.actions.woodCut.state === true && trees.length) { this.status.action = "woodCutting"; } else if (this.status.actions.hunt.state === true && animals.length) { this.status.action = "hunting"; } else { this.status.action = "walk"; } } setAnimationAction() { if (this.status.action === "fighting") { if (this.armor.arrows.id !== -1 && this.armor.bow.id !== -1) { this.body.action = "archery" } else { this.body.action = "fight"; } } else if (this.status.action === "mining") { this.body.action = "mine"; } else if (this.status.action === "woodCutting") { this.body.action = "woodcut"; } else if (this.status.action === "hunting") { this.body.action = "fight"; } else { this.body.action = "walk"; } } newLevel(x, y, map) { this.body.setPos(x,y) this.status.currLevel++; if (this.status.highestLevel < this.status.currLevel) { this.status.highestLevel = this.status.currLevel; map.addInventory(); } this.homeDrawUpdate(); } teleLevel(x, y, map) { if (this.status.highestLevel < this.status.currLevel) { this.status.highestLevel = this.status.currLevel; } } prevLevel(x, y) { this.body.setPos(x,y) this.status.currLevel--; this.homeDrawUpdate(); } nextLevel(x, y) { this.body.setPos(x,y) this.status.currLevel++; this.homeDrawUpdate(); } display() { console.log("location", this.status.location) console.log("destination", this.status.destination) console.log("action", this.status.action) console.log("bodyAction", this.body.action) } }<file_sep>export default class Armor { constructor(items, animation) { this.items = items; this.helm = this.items.none() this.chest = this.items.none() this.legs = this.items.none() this.feet = this.items.none() this.weapon = this.items.none() this.shield = this.items.none() this.bow = this.items.none() this.arrows = this.items.none() this.pickAxe = this.items.none(); this.axe = this.items.none(); this.attackBonus = 0; this.defenseBonus = 0; this.attackSpeedBonus = 0; this.rangeBonus = 0; this.miningBonus = 0; this.woodCuttingBonus = 0; if (animation.singleImg) { this.animation = animation.singleImg; } if (animation.body) { this.animation = animation.body this.animation.addShirt(animation.shirt) this.animation.addPants(animation.pants) this.animation.addHair(animation.hair) } } getEquipment() { let id = 0; return ({ helm : { item : this.helm, id : id++, }, chest : { item : this.chest, id : id++, }, legs: { item : this.legs, id : id++, }, feet: { item : this.feet, id : id++, }, weapon: { item : this.weapon, id : id++, }, shield : { item : this.shield, id : id++, }, bow : { item : this.bow, id : id++, }, arrows: { item : this.arrows, id : id++, }, pickaxe: { item : this.pickAxe, id : id++, }, axe: { item : this.axe, id : id++, }, }) } logBonus() { console.log(this.helm.bonus, this.chest.bonus, this.legs.bonus, this.feet.bonus, this.shield.bonus) } getAttack() { return (this.attackBonus) } getDefense() { return (this.defenseBonus) } addBonus() { let defense = 0; let attack = 0; let attackSpeed = 200; defense += this.helm.bonus defense += this.chest.bonus defense += this.legs.bonus defense += this.feet.bonus defense += this.shield.bonus attack += this.weapon.bonus if (this.weapon.id === -1) { this.animation.swingTimer.defaultExpiration(); } else { attackSpeed = this.weapon.speed; this.animation.swingTimer.setExpiration(attackSpeed); } this.attackBonus = attack; this.defenseBonus = defense; this.attackSpeedBonus = attackSpeed; this.rangeBonus = this.bow.bonus; this.miningBonus = this.pickAxe.bonus; this.woodCuttingBonus = this.axe.bonus; } removeHelm(inventory) { if (inventory.add(this.helm)) { this.helm = this.items.none(); this.animation.remove("helm") } this.addBonus(); } removeChest(inventory) { if (inventory.add(this.chest)) { this.chest = this.items.none(); this.animation.remove("chest") } this.addBonus(); } removeLegs(inventory) { if (inventory.add(this.legs)) { this.legs = this.items.none(); this.animation.remove("legs") } this.addBonus(); } removeFeet(inventory) { if (inventory.add(this.feet)) { this.feet = this.items.none(); this.animation.remove("feet") } this.addBonus(); } removeWeapon(inventory) { if (inventory.add(this.weapon)) { this.weapon = this.items.none(); this.animation.remove("weapon") } this.addBonus(); } removeShield(inventory) { if (inventory.add(this.shield)) { this.shield = this.items.none(); this.animation.remove("shield") } this.addBonus(); } removePickAxe(inventory) { if (inventory.add(this.pickAxe)) { this.pickAxe = this.items.none(); this.animation.remove("pickaxe") } this.addBonus(); } removeAxe(inventory) { if (inventory.add(this.axe)) { this.axe = this.items.none(); this.animation.remove("axe") } this.addBonus(); } removeBow(inventory) { if (inventory.add(this.bow)) { this.bow = this.items.none(); this.animation.remove("bow") } this.addBonus(); } removeArrows(inventory) { if (inventory.addQuantity(this.arrows, this.arrows.quantity)) { this.arrows = this.items.none(); this.animation.remove("arrows") } this.addBonus(); } addHelm(helm) { let tmp = this.helm.copy() this.animation.add("helm", helm.img) helm.setPos(400, 140); this.helm = helm; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addChest(chest) { let tmp = this.chest.copy() this.animation.add("chest", chest.img) chest.setPos(400, 200); this.chest = chest; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addLegs(legs) { let tmp = this.legs.copy() legs.setPos(400, 260); this.legs = legs; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addFeet(feet) { let tmp = this.feet.copy() feet.setPos(400, 320); this.feet = feet; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addWeapon(weapon) { let tmp = this.weapon.copy() this.animation.add("weapon", weapon.img) weapon.setPos(360, 200); this.weapon = weapon; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addShield(shield) { let tmp = this.shield.copy() this.animation.add("shield", shield.img) shield.setPos(440, 200) this.shield = shield; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addArrows(arrows) { let tmp = this.arrows.copy() let addQuantity = false if (arrows.id === this.arrows.id) { this.arrows.quantity ++; addQuantity = true } else { let newArrow = arrows.copy() newArrow.setPos(440, 15); this.arrows = newArrow; } this.addBonus(); if (tmp.id !== -1 && !addQuantity) { return (tmp); } else { return false } } addBow(bow) { let tmp = this.bow.copy() this.animation.add("bow", bow.img) bow.setPos(440, 70) this.bow = bow; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addPickAxe(pickAxe) { let tmp = this.pickAxe.copy() this.animation.add("pickaxe", pickAxe.img) pickAxe.setPos(360, 15) this.pickAxe = pickAxe; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } addAxe(axe) { let tmp = this.axe.copy() this.animation.add("axe", axe.img) axe.setPos(360, 70) this.axe = axe; this.addBonus(); if (tmp.id !== -1 ) { return (tmp); } else { return false } } }<file_sep>import ItemSubCategory from "./itemSubCategory" export default class ItemCategory { constructor(name, id, settings) { this.name = name; this.id = id; this.subcategory = []; this.settings = settings } addSubCategory(name, id, settings) { this.subcategory.push(new ItemSubCategory(name, id, settings, this.id)); } listSubCategories() { let count = this.subcategory.length for (let x = 0; x < count; x++) { console.log(this.subcategory[x].name); console.log(this.subcategory[x].id); } } returnSubCategories() { let subcategories = []; let count = this.subcategory.length for (let x = 0; x < count; x++) { subcategories.push({ name: this.subcategory[x].name, id : this.subcategory[x].id }) } return (subcategories); } returnSubCategorySettings(index) { return (this.subcategory[index].settings); } returnItems(subCategoryIndex, itemIndex) { return(this.subcategory[subCategoryIndex].returnItems()) } returnOneItem(subCategoryIndex, itemIndex) { return(this.subcategory[subCategoryIndex].returnOneItem(itemIndex)); } returnItemNames(subCategoryIndex) { return(this.subcategory[subCategoryIndex].returnItemNames()) } } <file_sep>import {randomInt} from "../../../Helpers/functions" // skills have a value which is there level, and a current which is what // it is before and after boosts. export default class Skills { constructor(settings) { let skill_id = 0; this.health = this.createSkill(settings.health, "Health", skill_id++); this.attack = this.createSkill(settings.attack, "Attack", skill_id++); this.defense = this.createSkill(settings.defense,"Defense", skill_id++) this.attackSpeed = this.createSkill(settings.attackSpeed, "Attack Speed", skill_id++); this.range = this.createSkill(settings.range, "Range", skill_id++); this.magic = this.createSkill(settings.magic, "Magic", skill_id++); this.thirst = this.createSkill(settings.thirst, "Thirst", skill_id++); this.hunger = this.createSkill(settings.hunger, "Hunger", skill_id++); this.mining = this.createSkill(settings.mining, "Mining", skill_id++); this.woodcutting = this.createSkill(settings.woodcutting, "Woodcutting", skill_id++); this.hunting = this.createSkill(settings.hunting, "Hunting", skill_id++); this.thirst.setDecayValue(settings.thirstDecay || 100); this.hunger.setDecayValue(settings.hungerDecay || 100); } boostDecay() { this.health.boostTimer(); this.attack.boostTimer(); this.defense.boostTimer(); this.attackSpeed.boostTimer(); this.range.boostTimer(); this.thirst.boostTimer(); this.hunger.boostTimer(); this.mining.boostTimer(); this.woodcutting.boostTimer(); this.hunting.boostTimer(); } createSkill(value, name, id) { return ({ skill_id : id, value: value, time: 0, boostTime: 0, current : value, name: name, boost : 0, decayValue: 300, xp : 0, threshold : Math.round(1.1 * (Math.pow(value, 3.4))), boostTimer : function() { if (this.boost <= 0) { return false } this.boostTime++; if (this.boostTime > 200) { this.boostTime = 0 this.boost -= 1; if (this.boost <= 0) { this.boost = 0; } } }, enemyTimer: function(boost) { this.time++; if (this.time > 50 - boost) { this.time = 0; return(randomInt(0, this.get())); } return (0); }, timer: function(boost) { this.time++; let accuracy = 5; if (this.time > 50 - boost) { this.time = 0; return(randomInt(this.get(), this.get() + accuracy + this.boost)); } return (0); }, hitDamage: function() { let accuracy = 5; return(randomInt(this.get(), this.get() + accuracy + this.boost)); }, decayTimer: function(boost) { this.time++; if (this.time > this.decayValue + (boost * 10) + this.boost) { this.time = 0; this.take(1); return(true) } return (0); }, setDecayValue: function(value) { this.decayValue = value; }, addXp(xp) { this.xp += xp; let threshold = Math.round(1.1 * (Math.pow(this.value, 3.4))) while (this.xp > threshold) { this.levelUp(); this.equalize(); threshold = Math.round(1.1 * (Math.pow(this.value, 3.4))) } this.threshold = threshold }, set: function(lvl) { this.value = lvl; this.equalize(); }, setupLvl(mapLvl, exponent, base) { let lvl = Math.round(base * (Math.pow(mapLvl, exponent))) this.value = lvl + this.value this.equalize(); }, get: function() { return this.value; }, getCurrent : function() { return this.current + this.boost; }, getName: function() { return this.name; }, take: function(damage) { this.current = this.current - damage; if (this.isZero()) { this.current = 0; } }, give: function(boost) { this.current += boost; }, giveLimit: function(boost) { this.current += boost; if (this.isGreater()) { this.equalize(); } }, giveBoost : function(boost) { this.boost = boost }, levelUp: function() { this.value++; }, levelUpBy: function (level) { this.value += level }, levelDown: function() { if (this.isZero()) { return (false); } this.current--; }, equalize() { this.current = this.value; }, isZero: function () { if (this.current <= 0) { return (true); } return (false); }, isGreater : function() { if (this.current > this.value) { return (true); } return (false); }, log : function() { console.log(this.getName(), ":", this.getCurrent(), "/" ,this.get()); }, show() { return(this.getName() + " : " + this.getCurrent() + "/" + this.get()); }, showXp() { return("xp: " + this.xp + " / " + this.threshold); } }) } isDead() { if (this.health.isZero()) { this.dead = true; return (true); } this.dead= false; return (false); } test() { this.log(); } log() { console.log('|----------|'); console.log( this ); console.log('|----------|'); } } <file_sep> import Inventory from "../Inventory" import {settings} from "../../Helpers/settings" export default class ActionHandler { takeDamage(player, damage) { if (damage === 0) { return 0 } let bonus = player.armor.defenseBonus; if (damage - bonus <= 0) { damage = 1; } else { damage = damage - bonus; } player.skills.health.take(damage); if (this.isDead(player)){ return (player.inventory); } } isDead(player) { if (player.skills.health.isZero() === true) { player.armor.animation.deathTimer.done = false; player.status.dead = true; player.status.deaths++; return (true) } } xp(player, target) { switch (target.status.type) { case "enemy" : player.skills.attack.addXp(target.skills.health.get() * 4) player.skills.attackSpeed.addXp(target.skills.health.get() * 2) player.skills.health.addXp(target.skills.health.get() * 40) break; case "ore" : player.skills.mining.addXp(target.skills.health.get() * 15) break; case "tree" : player.skills.woodcutting.addXp(target.skills.health.get() * 15) break; case "animal" : player.skills.hunting.addXp(target.skills.health.get() * 15) break; default : break } } revive(player) { player.status.dead = false; player.body.setPos(32 * 5, -32) player.skills.health.equalize(); player.skills.thirst.equalize(); player.skills.hunger.equalize(); player.armor.addBonus() let gold = player.inventory.gold player.inventory = new Inventory(player.items); player.inventory.addGold(gold); player.status.currLevel = 1; } fightRange(player, target) { let skill = false; let attackBonus = false; let damage = 0; let shot = {fired: false, damage : 0} if (!target.status) { return false; } switch (target.status.type) { case "enemy" : skill = player.skills.range; attackBonus = player.armor.rangeBonus; break; default : break } if (player.armor.animation.shootTimer.done && skill) { player.armor.animation.shootTimer.done = false; damage = skill.hitDamage() damage = damage + attackBonus shot.fired = true; shot.damage = damage + attackBonus; } return(shot); } fight(player, target) { let skill = false; // let speedBonus = false; // speedBonus = player.armor.attackSpeedBonus; let attackBonus = false; let damage = 0; switch (target.status.type) { case "enemy" : skill = player.skills.attack; attackBonus = player.armor.attackBonus; break; case "ore" : skill = player.skills.mining; attackBonus = player.armor.miningBonus; break; case "tree" : skill = player.skills.woodcutting; attackBonus = player.armor.woodCuttingBonus; break; case "animal" : skill = player.skills.hunting; attackBonus = player.armor.attackBonus; break; default : break } if (player.armor.animation.swingTimer.done && skill) { player.armor.animation.swingTimer.done = false; damage = skill.hitDamage() damage = damage + attackBonus } return(this.takeDamage(target, damage)); } mine(player) { let damage = player.skills.mining.timer(player.armor.attackSpeedBonus) if (damage > 0) { damage = damage + player.armor.miningBonus } return(damage) } woodCut(player) { let damage = player.skills.woodcutting.timer(player.armor.attackSpeedBonus) if (damage > 0) { damage = damage + player.armor.woodCuttingBonus } return(damage) } hunt(player) { let damage = player.skills.hunting.timer(player.armor.attackSpeedBonus) if (damage > 0) { damage = damage + player.armor.attackBonus } return(damage) } skillDecay(player) { if (player.status.currLevel > 0) { this.decayLogic(player, player.skills.thirst, settings.player.thirstHealthDecay); this.decayLogic(player, player.skills.hunger, settings.player.hungerHealthDecay); } } decayLogic(player, skill, healthDecayRate) { let isTime = skill.decayTimer(skill.get()); if (isTime) { if (skill.isZero()) { this.takeDamage(player, healthDecayRate); } } } }<file_sep>import React from "react" import RigidBody from "../../Helpers/rigidBody" export default class RigidBodyTest extends React.Component { constructor() { super() this.test(); } test() { let v = new RigidBody(0,0,32,32); let v2 = new RigidBody(10,20,32,32); console.log("collision: ", v.collide(v2)); let v3 = new RigidBody(222,2039,32,32); let v4 = new RigidBody(10,20,32,32); console.log("collision: ", v3.collide(v4)); v.log(); if (v.stop) v.stop = false while (v.move_to(50,50) === false) { v.log(); console.log("moving"); } v.log() console.log("MOVED TO TARGET"); console.log("Move Test COmplete") } log() { this.pos.log(); this.size.log(); } }<file_sep># IdleRpg Idle Rpg Game to make a twist to your natural idle and Rpgs <h3> BUILD </h3> Built with Yarn package manager, so you will need yarn installed cd into repository, yarn install You will need postgres installed createdb idle_forest, probably dont want to change that. yarn start - to start the project to run the project locally on port 3000 express proxy port 3001 Still needs a little bit of fixes, was a big project and havent gotten around to absolutely everything. A list of future updates will be listed at the bottom. Going to go live at some Point just needs a major overhaul, but if you can get it to work on your machine.. its a good couple of days of fun. ;) <h3>Basic Structure -</h3> The game has 3 main classes, logic, a draw component, and a UI class. Most interaction and instantiation happens in the logic class. Logic class is instatiated and updated in the draw Component. the objects instantiated in logic are passed to the UI class via the draw component. Players, enemies, NPC's, and Resources are all instances of the entity class. Yes, it is a little overkill for the resources and npcs, but i wanted to keep the possibilities open in case i wanted the npcs/animals to fight back, have enemies use range, or make resources explode and give damage. It also make drawing and instantiating a new entity very easy because they are all the same. <h3>Basic GamePlay-</h3> You are a character that fights automatically as you progress through levels you can toggle buttons to make him mine, woodcut, and hunt in which every resource and kill drops items and you get gold from every kill. hover over items with mouse to add them into your inventory. You can toggle to walk to your farm and walk home no matter how high a level you are at. You can buy things from the merchant, or craft things with your items at the crafting table. You can bank your items so you dont drop them when you die. you can collect water by clicking on the waterwell When farming: click seeds from your inventory to plant them click water from your inventory to add to the plot when the seeds grow into plants, click the plant to harvest when at home, you can hover over pretty much anything to get information about it. It is a big project, and may take a second to load. It is mostly on the front end, which was a bad idea. Should have made the logic on the server side and drawing on the client side, in a future update I may change how that works. until then I wont deploy live because of the possibility to cheat if you figure out how to access the variables from the console, and save it on the server. It has user login and registration built into the game. saves and loads all data except for the farm so be sure to harvest before you close or refresh. <h3>Future updates - </h3> Refactor Some of the bigger classes, some got pretty big. Refactor the file structure, some things aren't as organized as I would like. Refactor the Animations/Images file because it got huge, also create a standard (I used two-three different object-structures because of different spritesheet structures) add armor legs and boots and weapon mace, as of now it is just text because i dont have the sprites. Make difficulty level actually count from the main screen Add a logout button so that you dont refresh to logout, lol Fix the stop button to open the settings, make it so you dont walk in place, and open the settings screen. add sounds to all of the actions add music to the game. There is a bug that the info pane stays if you hold it over something while moving from home to farm or next level make more visual cues when at home, ex: walk to water when you are collecting, walk around more instead of remain in middle of screen. There are probably a few more, send a pull request if you would like to work on something, would love collaborators. as I knock them off the list I will update this read-me. <h4> Add credits into the GameScreen, If you pull, please check that folder, I couldnt have done it without the people at openGameArt, the LPC Project helped me tremendously. Please check out the credits in the credits folder. They are the reasons that everything isn't just text with non animated squares and circles. directory for credits is <a href="src/assets/images/spriteSheets/credit">HERE</a> </h4> <h2> Big thanks to them! </h2> <h1> Game Images </h1> <p align="center"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%205.23.30%20PM.png" width="400" height="400"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%205.23.43%20PM.png" width="400" height="400"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%205.23.53%20PM.png" width="400" height="400"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%205.24.05%20PM.png" width="400" height="400"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%205.24.15%20PM.png" width="400" height="400"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%205.24.24%20PM.png" width="400" height="400"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%205.24.35%20PM.png" width="400" height="400"> <img src="https://github.com/Emszy/IdleRpg/blob/master/src/assets/images/DemoImages/Screen%20Shot%202019-12-03%20at%209.58.47%20PM.png?raw=true" width="400" height="400"> </p>
91a3cc7695b508142bdc01cb25c7f5a3b073a1eb
[ "JavaScript", "Markdown" ]
46
JavaScript
Emszy/IdleRpg
2fdbafa69714aa7086a44651c5b06e108afca26d
36e981d0f318e9008e7177fe83a6a5b2bce11c61
refs/heads/master
<repo_name>cyanesgarcia/Deporte<file_sep>/app/src/main/java/com/example/sport/Fondo.java package com.example.sport; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.media.AudioAttributes; import android.media.SoundPool; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.PowerManager; import android.support.annotation.RequiresApi; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.util.HashSet; import java.util.Random; import java.util.Set; /** * Claudia and <NAME> **/ public class Fondo extends Activity implements View.OnClickListener { private MiCountDownTimer countDownTimer, countDownTimer1, countDownTimer2; private CountUpTimer tiempomas; int[] dcolor = {R.drawable.uno, R.drawable.dos, R.drawable.tres, R.drawable.cuatro, R.drawable.cinco, R.drawable.seis, R.drawable.siete, R.drawable.ocho, R.drawable.nueve, R.drawable.diez }; private UpdateTask updateTask; ImageView im; ImageButton empezar, pausa; public int s= MainActivity.numero3; int boton=0; int cual; int start_antes_error=0; int secondbreak, tipo; TextView textView, textView1, textView2, textView3; private long total=1000*(MainActivity.numero3 *(MainActivity.numero1 * MainActivity.numero2) + (MainActivity.numero3 -1) *MainActivity.numero4); private long tejercicio=1000*(MainActivity.numero1 * MainActivity.numero2); private long tdescanso=1000*(MainActivity.numero4); private SoundPool soundPool; private Set<Integer> soundLoaded; int[]sounds={0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int go, stop, fin, finserie; int tiempoanadir =0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity); im= (ImageView) findViewById(R.id.iblue); im.setImageResource(R.drawable.fondo); im.setKeepScreenOn(true); textView = (TextView) findViewById(R.id.text_view); textView.setText(" " + (total/1000) + " "); textView1 = (TextView) findViewById(R.id.text_view1); textView1.setText(" " + (tejercicio/1000) +" "); textView2 = (TextView) findViewById(R.id.text_view2); textView2.setText(" " + MainActivity.numero4 + " " ); textView3 = (TextView) findViewById(R.id.text_view3); textView3.setText(" " + MainActivity.numero3 + " " ); countDownTimer = new MiCountDownTimer(total, 1000, 0); countDownTimer1 = new MiCountDownTimer(tejercicio, 1000, 1); countDownTimer2 = new MiCountDownTimer(tdescanso, 1000, 2); tiempomas = new CountUpTimer(30000) { @Override public void onTick(int second) { tiempoanadir = second; } }; soundLoaded = new HashSet<Integer>(); if (updateTask != null && updateTask.getStatus() == AsyncTask.Status.FINISHED) { updateTask = null; } else if (updateTask == null ) { updateTask = new UpdateTask(); updateTask.execute(); } boton=0; empezar=(ImageButton)findViewById(R.id.imageButton); empezar.setOnClickListener(this); pausa=(ImageButton)findViewById(R.id.imageButton2); pausa.setOnClickListener(this); } @Override public void onClick(View view) { if(view.getId() == R.id.imageButton){ if(start_antes_error ==222) { Log.i("Loooooogdespues", " value "+ secondbreak); Log.i("sss", "ss" + total); countDownTimer = new MiCountDownTimer(total, 1000, 0); countDownTimer.start(); if (cual == 10000) { Log.i("sss", "ss" + tdescanso); countDownTimer2 = new MiCountDownTimer(tdescanso, 1000, 2); countDownTimer2.start(); } else { Log.i("sss", "ss" + tejercicio); countDownTimer1 = new MiCountDownTimer(tejercicio, 1000, 1); countDownTimer1.start(); } start_antes_error=0; boton=1; } }else if(view.getId() == R.id.imageButton2){ start_antes_error = 222; Log.i("Loooooogantes", " value "+ secondbreak); countDownTimer2.cancel(); countDownTimer1.cancel(); countDownTimer.cancel(); String ejercicio= textView1.getText().toString().trim(); Log.i("Tiempo ejercicio", "este "+ejercicio); Log.i("Tiempo ejercicio", " largo "+ MainActivity.numero1 * MainActivity.numero2); String general = String.valueOf(MainActivity.numero1 * MainActivity.numero2).trim(); if(!ejercicio.equals(general)){ Log.i("Tiempo ejercicio", " entro"); tiempomas.start(); } boton=2; } } private boolean isPause() { if (boton == 2) { return true; } else { return false; } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onResume() { super.onResume(); AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder(); attrBuilder.setUsage(AudioAttributes.USAGE_GAME); SoundPool.Builder spBuilder = new SoundPool.Builder(); spBuilder.setAudioAttributes(attrBuilder.build()); spBuilder.setMaxStreams(2); soundPool = spBuilder.build(); soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { if(status==0){ soundLoaded.add(sampleId); Log.i("SOUND", "Sound loaded"+ sampleId); }else { Log.i("SOUND", "Error cannot load sound status"+ status); } } }); int num1 = soundPool.load(this, R.raw.num1, 1); int num2 = soundPool.load(this, R.raw.num2, 1); int num3 = soundPool.load(this, R.raw.num3, 1); int num4 = soundPool.load(this, R.raw.num4, 1); int num5 = soundPool.load(this, R.raw.num5, 1); int num6 = soundPool.load(this, R.raw.num6, 1); int num7 = soundPool.load(this, R.raw.num7, 1); int num8 = soundPool.load(this, R.raw.num8, 1); int num9 = soundPool.load(this, R.raw.num9, 1); int num10 = soundPool.load(this, R.raw.num10, 1); go=soundPool.load(this, R.raw.go, 1); stop=soundPool.load(this, R.raw.stop, 1); fin=soundPool.load(this, R.raw.aplauso, 1); finserie=soundPool.load(this, R.raw.finserie, 1); sounds = new int[]{num1,num2, num3, num4, num5, num6, num7, num8, num9, num10}; } class UpdateTask extends AsyncTask<Void, Integer, Void> { int i = 0; Random rnd = new Random(); @Override protected Void doInBackground(Void... voids) { while(isPause()==true){ } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } for (int set=0; set<MainActivity.numero3; set++){ if(isCancelled()) break; while(isPause()==true){} if(set!=0) { publishProgress(0,0,5,9); if(MainActivity.numero4>2){ while(isPause()==true) {} try { Log.i("ERRRRRRORNO", "ERRRRRRoR"); Thread.sleep((MainActivity.numero4 - 2) * 1000); } catch (InterruptedException e) { Log.i("ERRRRRROR", "ERRRRRRoR"); e.printStackTrace(); } } } while(isPause()==true){} addtime(); playSound(go); if(MainActivity.numero4==0){ while(isPause()==true){ } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } else if(MainActivity.numero4>=2){ while(isPause()==true){ } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }else{ while(isPause()==true){ } try { Thread.sleep(MainActivity.numero4 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 0; j < MainActivity.numero1; j++) { if(isCancelled()) break; while(isPause()==true){ } i = rnd.nextInt(MainActivity.numero0); publishProgress(i,1,set,j); try { Thread.sleep(MainActivity.numero2 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } tiempomas.cancel(); addtime2 (); }} return null; } @Override protected void onProgressUpdate(Integer... values) { while(isPause()==true){ } if(values[2]==0 && values[3]==0) { countDownTimer.start(); } if(values[3]==0){ tejercicio = 1000*(MainActivity.numero1 * MainActivity.numero2); countDownTimer1 = new MiCountDownTimer(tejercicio, 1000,1); countDownTimer1.start(); cual=0; textView1.setBackgroundColor(Color.GREEN); textView2.setBackgroundColor(Color.BLACK); } String ejercicio= textView1.getText().toString().trim(); if(values[1]==0) { tdescanso = 1000*(MainActivity.numero4); countDownTimer2 = new MiCountDownTimer(tdescanso, 1000,2); countDownTimer2.start(); cual=10000; im.setImageResource(R.drawable.fondo); textView1.setBackgroundColor(Color.BLACK); textView2.setBackgroundColor(Color.GREEN); textView1.setText(" "+ MainActivity.numero1 * MainActivity.numero2 +" "); while(isPause()==true){ } if(MainActivity.numero4>2){ playSound(stop); } playSound(finserie); }else{ while(isPause()==true){ } im.setImageResource(dcolor[values[0]]); playSound(sounds[values[0]]); } } } private void playSound(int soundId){ /* if(boton == 1) { addtime(secondbreak); boton=3; }*/ if (soundLoaded.contains(soundId)) { soundPool.play(soundId, 500.0f, 500.0f, 0, 0, 0f); } } @Override public void onBackPressed() { updateTask.cancel(true); boton=0; Fondo.this.finish(); super.onBackPressed(); } public class MiCountDownTimer extends CountDownTimer { public int n; public MiCountDownTimer(long starTime, long interval, int numero) { super(starTime, interval); // TODO Auto-generated constructor stub n=numero; } public void onTick(long l) { if(n==0) { textView.setText(" "+ (int) (l / 1000)+ " "); total = l; } else if(n==1){ textView1.setText( " "+ (int) (l / 1000)+ " "); tejercicio = l; }else{ textView2.setText(" "+ (int) (l/ 1000)+ " "); tdescanso = l; } } @Override public void onFinish() { if(n==1) { s= s - 1; textView3.setText(" "+ s+ " " ); textView1.setBackgroundColor(Color.BLACK); } if((n==0) && (s==1)){ while(isPause()==true){ } im.setImageResource(R.drawable.done); playSound(fin); textView.setText(" 0 "); textView1.setText(" 0 "); textView2.setText(" 0 "); } if (n==2){ if(s == 1 ){ textView2.setText(" 0 "); }else { textView2.setText(" " + MainActivity.numero4 + " "); } } } } public abstract class CountUpTimer extends CountDownTimer { private static final long INTERVAL_MS = 1000; private final long duration; protected CountUpTimer(long durationMs) { super(durationMs, INTERVAL_MS); this.duration = durationMs; } public abstract void onTick(int second); @Override public void onTick(long msUntilFinished) { int second = (int) ((duration - msUntilFinished) / 1000); onTick(second); } @Override public void onFinish() { onTick(duration / 1000); } } public void addtime2 (){ while(isPause()==true){ } Log.i("Aaaaaaaaaaa", "tiempo " + tiempoanadir); try { Thread.sleep(tiempoanadir * 1000); } catch (InterruptedException e) { e.printStackTrace(); } tiempoanadir = 0; } public void addtime() { /*int entero = MainActivity.numero4; String enteroString = Integer.toString(entero); int entero1 = (MainActivity.numero1 * MainActivity.numero2); String enteroString1 = Integer.toString(entero1); String descanso= textView2.getText().toString().trim(); String ejercicio= textView1.getText().toString().trim(); Log.i("Eeeeeeeeeeeeeeeeeeeeeee", " descanso " + descanso); Log.i("Eeeeeeeeeeeeeeeeeeeeeee", " enteroString " + enteroString); Log.i("Eeeeeeeeeeeeeeeeeeeeeee", " ejercicio " + ejercicio); Log.i("Eeeeeeeeeeeeeeeeeeeeeee", " enteroString1 " + enteroString1); if ( !(descanso.equals(enteroString)) && ejercicio.equals(enteroString1)) {*/ while(isPause()==true){ } Log.i("Eeeeeeeeeeeeeeeeeeeeeee", " s " + tdescanso); if(tdescanso>2500) { try { Thread.sleep(tdescanso - 2500); } catch (InterruptedException e) { e.printStackTrace(); } } } }
f3776955e8fec574db896e2ef3d0cfaf241f3bde
[ "Java" ]
1
Java
cyanesgarcia/Deporte
ed199a039a2ee3e33af709d6074919b77b81da37
b0b28f3a0dc7a79c263a0b75b2c43532adc950c3
refs/heads/master
<file_sep>require 'csv' @students = [] # an empty array accessible to all methods def interactive_menu loop do print_menu process(STDIN.gets.chomp) end end def print_menu puts "1. Input the students" puts "2. Show the students" puts "3. Save the list to specific file" puts "4. Load the list from specific file" puts "9. Exit" end def show_students if @students.count > 0 print_header print_students_list print_footer else puts "We have zero students at the moment" end end def process(selection) case selection when "1" input_students when "2" show_students when "3" puts "Enter filename or leave blank for students.csv" savename = STDIN.gets.chomp if savename.empty? save_students else save_students(savename) end when "4" puts "Enter filename or leave blank for students.csv" loadname = STDIN.gets.chomp if loadname.empty? load_students else load_students(loadname) end when "9" exit else puts "I don't know what you mean, try again" end end # let's put all the students into an array def input_students puts "Please enter the names of the students" puts "To finish, just hit return twice" # get the first name name = STDIN.gets.chomp # while name is not empty, repeat this code while !name.empty? do puts "Enter cohort" cohort = STDIN.gets.chomp # add the student hash to the array if cohort.empty? @students << {name: name, cohort: :november} else push_to_students(name, cohort) end if @students.count > 1 puts "Now we have #{@students.count} students" else puts "Now we have 1 student" end # get another name from the user puts "Enter name" name = STDIN.gets.chomp end end def print_header puts "The students of Villains Academy".center(50) puts "-".center(50,"-") end def print_students_list @students.each_with_index do |student, index| puts "#{index + 1}. #{student[:name]} (#{student[:cohort]} cohort)" end end def print_footer if @students.count > 1 puts "Overall, we have #{@students.count} great students" else @students.count == 1 puts "Overall, we have only 1 great student" end end def save_students(filename = "students.csv") # open file for writing CSV.open(filename, "w") do |line| # iterate over the array of students @students.each do |student| line << [student[:name], student[:cohort]] end end puts "Student list saved to #{filename}" end def load_students(filename = "students.csv") CSV.foreach(filename) do |line| push_to_students(line[0], line[1]) end puts "Loaded list from #{filename}" end def try_load_students filename = ARGV.first # first argument from the command csv_line if filename.nil? load_students elsif File.exists?(filename) load_students(filename) puts "Loaded #{@students.count} from #{filename}" else # if file doesn't exist puts "Sorry #{filename} doesn't exist" exit end end def push_to_students(name, cohort) @students << {name: name, cohort: cohort.to_sym} end # Commented out section below relates to other print options # Exercise answers no longer required =begin # print students whose names starts with specific letter def print_first_letter(students, letter) students.each do |student| if student[:name].start_with?(letter) puts "#{student[:name]} (#{student[:cohort]} cohort)" end end end # print only students whose name is longer than 12 characters def print_length(students, max_length) students.each do |student| if student[:name].length < max_length puts "#{student[:name]} (#{student[:cohort]} cohort)" end end end # print all students def print_while i = 0 until i == @students.length puts "#{i + 1}. #{students[i][:name]} (#{students[i][:cohort]} cohort)" i += 1 end end def print_by_category # print the students grouped by cohort cohort_array = [] @students.each do |hash| cohort_array.push(hash[:cohort]).uniq! end cohort_array.each do |cohort| puts cohort @students.each_with_index do |student, index| if student[:cohort] == cohort puts "#{index + 1}. #{student[:name]} (#{student[:cohort]} cohort)".center(50) end end end end =end try_load_students interactive_menu
7695901b3412a8a6e94a2f632635bc69ccaab06e
[ "Ruby" ]
1
Ruby
Whatapalaver/student-directory
76b851d658dcc2fa34dc2a54701d38030dea2e72
846c1bfb3ada17ed4c0ce27211e8f126d0d83532
refs/heads/master
<file_sep>class ChessError < StandardError end class Array def deep_dup map { |el| Array(el) == el ? el.deep_dup : el } end end <file_sep>require 'colorize' require './cursorable.rb' require './board.rb' require './piece.rb' require './display.rb' require './player.rb' require './chess_helper' class ChessGame def initialize(chessboard) @chessboard = chessboard @players = [ Player.new(:white, chessboard), Player.new(:black, chessboard) ] end def toggle_players @players.rotate! @chessboard.color = @players.first end def run until checkmate? @players[0].take_turn toggle_players end victory_conditions end def checkmate? @chessboard.checkmate?(@players[0].color) end def victory_conditions puts "CHECKMATE" puts "#{@players[0].color.to_s.capitalize} topples their King" puts "#{@players[1].color.to_s.capitalize} Wins!" play_again? end def play_again? puts "Play again?" puts "Y/N" answer = gets.chomp case answer.downcase when "y" restart when "yes" restart when "n" puts "GoodBye!" when "no" puts "GoodBye!" else puts "Huh?" play_again? end end def restart board = Board.new game = ChessGame.new(board) game.run end end board = Board.new game = ChessGame.new(board) game.run <file_sep> class Player attr_reader :color def initialize(color, board) @color = color @display = Display.new(board) @board = board end def move result = nil until result @display.render notifications result = @display.get_input end result end def notifications puts @color == :white ? "⚪ " : "⚫ " if @board.in_check?(@color) puts "#{@color} in check" end end def take_turn movefrom = make_selection moveto = move valid_move = false until valid_move unless @board.break_check?(@board[movefrom], moveto, @color) puts "You can't move into check" movefrom = make_selection moveto = move puts @board.break_check?(@board[movefrom], moveto, @color) else valid_move = true end end @board.move(movefrom, moveto) @display.render rescue ChessError => e puts e.message puts "Move cancelled. Select again." retry end def make_selection piece = parse_selection(move) rescue ChessError => e puts e.message retry end def parse_selection(coords) if !@board[coords].is_a? Piece raise ChessError.new("There is no piece at this position") elsif @board[coords].color != @color raise ChessError.new("Not a #{@color} piece.") else coords end end end <file_sep># Chess Command-line chess game made @ App Academy for two players written in Ruby. A possible moves array is generated for each player and invalid moves are rejected from play. King is prohibited from moving into check by iterating through possible moves of all opponent's pieces. ##How to run You can run the game by navigating to the 'chess' directory and typing 'game.rb'. ##Object Oriented Implementation * Sliding pieces and stepping piece modules mixed-in to DRY up shared methods * Individual pieces classes (e.g. Queen) inherit from Piece superclass ##To-Do * Use colorize gem to add color to rendered string output <file_sep>require "byebug" class Piece attr_reader :pos, :color, :name attr_accessor :moves, :moved def initialize(board, pos, color) @board = board @pos = pos @color = color @name = self.class.to_s @moves = [] @moved = false end DisplayPiece = { "King" => " ♚ ", "Queen" => " ♛ ", "Bishop" => " ♝ ", "Knight" => " ♞ ", "Rook" => " ♜ ", "Pawn" => " ♟ ", "Piece" => "bad" } def pos=(coords) @pos = coords end def inspect "#{@color} #{@name}: #{@pos}" end def to_s DisplayPiece[@name].colorize(@color) end def self.add_coords(coords1, coords2) [coords1[0] + coords2[0], coords1[1] + coords2[1]] end def get_moves raise ChessError.new("This is not a real Piece") end def redefine(board) @board = board end end module SlidingPiece CROSSWAYS = [ [0, 1], [1, 0], [0, -1], [-1, 0] ] DIAGONALS = [ [1, 1], [-1, -1], [1, -1], [-1, 1] ] def movement @moves = [] get_local_movement.each do |move| tile = Piece.add_coords(@pos, move) while @board.in_bounds?(tile) if @board.empty?(tile) @moves << tile elsif @board[tile].color == @color break else @moves << tile break end tile = Piece.add_coords(tile, move) end end @moves end end module SteppingPiece def movement @moves = [] get_local_movement.each do |move| tile = Piece.add_coords(@pos, move) next unless @board.in_bounds?(tile) if @board.empty?(tile) || @board[tile].color != @color @moves << tile end end @moves end end class King < Piece include SteppingPiece def get_local_movement [[0, 1],[1, 0],[0, -1],[-1, 0],[1, 1],[1, -1],[-1, 1],[-1, -1]] end end class Queen < Piece include SlidingPiece def get_local_movement SlidingPiece::CROSSWAYS + SlidingPiece::DIAGONALS end end class Bishop < Piece include SlidingPiece def get_local_movement SlidingPiece::DIAGONALS end end class Knight < Piece include SteppingPiece def get_local_movement [[1, 2],[2, 1],[-1, 2],[2, -1],[-2, 1],[1, -2],[-1, -2],[-2, -1]] end end class Rook < Piece include SlidingPiece def get_local_movement SlidingPiece::CROSSWAYS end end class Pawn < Piece def movement @moves = [] @moves.concat(pawn_movement) @moves.concat(pawn_attack) @moves end def get_local_movement if @moved @color == :black ? [[1,0]] : [[-1,0]] else @color == :black ? [[1,0],[2,0]] : [[-1,0],[-2,0]] end end def pawn_movement moves = get_local_movement moves.map! { |move| Piece.add_coords(@pos, move) } moves.reject! do |coords| !@board.empty?(coords) || !@board.in_bounds?(coords) end moves end def pawn_attack attack_pos = @color == :black ? [[1,-1], [1,1]] : [[-1,-1], [-1,1]] attack_pos.map! { |move| Piece.add_coords(@pos, move) } attack_pos.reject! do |coords| if !@board.empty?(coords) && !@board[coords].nil? @board[coords].color == @color else @board.empty?(coords) || !@board.in_bounds?(coords) end end attack_pos end end <file_sep>require "byebug" class Board attr_accessor :rows, :piece, :color BLANK_SPACE = " " def initialize(rows = nil) @rows = rows ? rows : generate_board @piece = false @color = nil end def inspect @rows.each do |row| p row.map{|el| el == BLANK_SPACE ? " " : el} end end def previous(moved, taken) end def check_all_moves @rows.flatten.each do |tile| tile.get_moves if tile.is_a?(Piece) end end def [](pos) row, col = pos @rows[row][col] end def []=(pos, mark) row, col = pos @rows[row][col] = mark end # |||||| # pick up piece logic def pick(coords) if empty?(coords) || !same_color?(coords) return else @piece = self[coords] end end # ||||| # same color checks def same_color(coords) self[coords].color == @color end # |||||| def move(movefrom, moveto) piece = self[movefrom] piece.movement if piece.moves.include?(moveto) direct_move(piece, moveto) else raise ChessError.new("That is not a valid move for this piece") end end def direct_move(piece, moveto) self[piece.pos] = BLANK_SPACE piece.pos = moveto self[moveto] = piece piece.moved = true end def in_bounds?(coords) coords.all? do |coord| (0..7).cover? coord end end def empty?(coords) self[coords] == BLANK_SPACE end def in_check?(color) opp_color = color == :white ? :black : :white throne = find_king(color) throne = throne.pos if check_knights(opp_color, throne) return true elsif check_bishops_and_royal(opp_color, throne) return true elsif check_rooks_and_royal(opp_color, throne) return true elsif check_pawns(opp_color, throne) return true else return false end end def check_knights(opp_color, throne) spots = [[1,2], [-1,2], [1,-2],[-1,-2],[2,1],[2,-1],[-2,1],[-2,-1]] spots.each do |spot| pos = throne.zip(spot).map {|a| a.inject(:+)} next if pos[0] > 7 || pos[0] < 0 next if pos[1] > 7 || pos[1] < 0 curr_spot = self[pos] if curr_spot.is_a?(Knight) if curr_spot.color == opp_color return true end end end return false end def check_bishops_and_royal(opp_color, throne) dirs = [[1,1],[1,-1],[-1,1],[-1,-1]] dirs.each do |dir| blocked = false pos = throne.zip(dir).map {|a| a.inject(:+)} next if pos[0] > 7 || pos[0] < 0 next if pos[1] > 7 || pos[1] < 0 curr_spot = self[throne.zip(dir).map {|a| a.inject(:+)}] while !blocked if curr_spot.is_a?(Piece) if curr_spot.is_a?(Bishop) || curr_spot.is_a?(Queen) if curr_spot.color == opp_color return true end else blocked = true end end pos = pos.zip(dir).map {|a| a.inject(:+)} break if pos[0] > 7 || pos[0] < 0 break if pos[1] > 7 || pos[1] < 0 curr_spot = self[pos] end end return false end def check_rooks_and_royal(opp_color, throne) dirs = [[1,0],[0,1],[-1,0],[0,-1]] dirs.each do |dir| blocked = false pos = throne.zip(dir).map {|a| a.inject(:+)} next if pos[0] > 7 || pos[0] < 0 next if pos[1] > 7 || pos[1] < 0 curr_spot = self[pos] return true if curr_spot.is_a?(King) while !blocked if curr_spot.is_a?(Piece) if curr_spot.is_a?(Rook) || curr_spot.is_a?(Queen) if curr_spot.color == opp_color return true end else blocked = true end end pos = pos.zip(dir).map {|a| a.inject(:+)} break if pos[0] > 7 || pos[0] < 0 break if pos[1] > 7 || pos[1] < 0 curr_spot = self[pos] end end return false end def check_pawns(opp_color, throne) color = opp_color == :white ? :black : :white if color == :white danger = [[-1,-1],[-1,1]] else danger = [[1,-1],[1,1]] end i = 0 while i < 2 curr_spot = self[throne.zip(danger[i]).map {|a| a.inject(:+)}] if curr_spot.is_a?(Pawn) if curr_spot.color == opp_color return true end end i += 1 end return false end def checkmate?(color) return false unless in_check?(color) select_pieces(color).each do |piece| piece.movement.each do |move| return false if break_check?(piece, move, color) end end true # false end def break_check?(piece, moveto, color) dupped = dup_board og_spot = piece.pos dupped.direct_move(piece, moveto) good_move = !dupped.in_check?(color) dupped.direct_move(piece, og_spot) good_move end def dup_board dupped = Board.new(@rows.deep_dup) dupped.select_pieces(:white).each{ |piece| piece.redefine(dupped) } dupped.select_pieces(:black).each{ |piece| piece.redefine(dupped) } dupped end def select_pieces(color) @rows.flatten.select do |tile| tile.is_a?(Piece) && tile.color == color end end def find_king(color) king = @rows.flatten.select do |tile| tile.is_a?(King) && tile.color == color end king.first end private def generate_board Array.new(8) do |row| Array.new(8) do |col| if row == 0 || row == 7 command_row([row,col]) elsif row == 1 || row == 6 pawn_row([row,col]) else BLANK_SPACE end end end end def pawn_row(coords) color = coords[0] == 1 ? :black : :white Pawn.new(self, coords, color) end def command_row(coords) color = coords[0] == 0 ? :black : :white case coords.last when 0 ; Rook.new(self, coords, color) when 1 ; Knight.new(self, coords, color) when 2 ; Bishop.new(self, coords, color) when 3 ; King.new(self, coords, color) when 4 ; Queen.new(self, coords, color) when 5 ; Bishop.new(self, coords, color) when 6 ; Knight.new(self, coords, color) when 7 ; Rook.new(self, coords, color) else raise "error" end end end
102f76cd12200ddb0f799377999faf7a9f4f4c69
[ "Markdown", "Ruby" ]
6
Ruby
jmtsharpe/Chess
315a31666c02285cb31fd29701367abc8cd0306c
ef8ccd946c5d58d56223d83cdadf96f14e864c31
refs/heads/master
<file_sep>require 'rails_helper' RSpec.describe User, type: :model do it "should validate presence of first_name" do user = User.create(:first_name => '') user.valid? expect(user.errors).to have_key(:first_name) end it "should validate presence of last_name" do user = User.create(:last_name => '') user.valid? expect(user.errors).to have_key(:last_name) end it "should validate presence of email" do user = User.create(:email => nil) user.valid? expect(user.errors).to have_key(:email) end # it "should validate presence of role" do # user = FactoryGirl.build(:regular_user, :role_id => '') # user.valid? # expect(user.errors).to have_key(:role_id) # end # it "should validate uniqueness of email" do # regular_user = FactoryGirl.create(:regular_user) # admin_user = FactoryGirl.build(:admin_user, :email => regular_user.email) # admin_user.valid? # expect(admin_user.errors).to have_key(:email) # end # it "should validate formatting of email" do # user = FactoryGirl.build(:regular_user, :email => 'blabla') # user.valid? # expect(user.errors).to have_key(:email) # end # it "should validate formatting of email" do # user = FactoryGirl.build(:regular_user, :email => '<EMAIL>') # user.valid? # expect(user.errors.present?).to be false # end # it "should validate presence of password" do # user = FactoryGirl.build(:regular_user, :password => '') # user.valid? # expect(user.errors).to have_key(:password) # end # it "should validate confirmation of password" do # user = FactoryGirl.build(:regular_user, :password => '<PASSWORD>', :password_confirmation => '<PASSWORD>') # user.valid? # expect(user.errors).to have_key(:password_confirmation) # end # it "should validate length of password" do # user = FactoryGirl.build(:regular_user, :password => '123') # user.valid? # expect(user.errors).to have_key(:password) # end # it "should validate length of password" do # user = FactoryGirl.build(:regular_user, :password => '<PASSWORD>') # user.valid? # expect(user.errors).to have_key(:password) # end # it "user should belong to role" do # role = FactoryGirl.create(:regular_role) # user = FactoryGirl.create(:regular_user, :role_id => role.id) # expect(user).to respond_to(:role) # expect(user.role.name).to eq "regular" # end # it "user should have one associated expense" do # role = FactoryGirl.create(:regular_role) # user = FactoryGirl.create(:regular_user, :role_id => role.id) # expense = FactoryGirl.create(:expense, :user_id => user.id) # expect(user).to respond_to(:expenses) # expect(user.expenses.first.description).to eq "some description" # end end<file_sep>class FilesController < ApplicationController def upload end def import_data puts "import_data" p params #Sample.import_data(params[:attachment]) TestWorker.perform_in(10.seconds, 'http://samplecsvs.s3.amazonaws.com/SalesJan2009.csv') redirect_to samples_path() end end <file_sep>class Api::V1::UsersController < Api::V1::ApplicationController skip_before_action :authenticate_user, :only => :create #before_action :set_cors, :only => [:create, :loggedin_user] def create @user = User.new(user_params) if @user.save render 'create.json.jbuilder', :status => 201 else render :json => { :message => @user.errors.full_messages.to_sentence }, :status => 409 end end def update @user = User.find(params[:id]) authorize @user if @user.update_attributes(user_params) render 'update.json.jbuilder', :status => 200 else render :json => { :message => @user.errors.full_messages.to_sentence }, :status => 409 end end def destroy @user = User.find(params[:id]) authorize @user if @user.destroy render :json => { :message => "User deleted"}, :status => 200 else render :json => { :message => @user.errors.full_messages.to_sentence }, :status => 409 end end def show @user = User.find(params[:id]) authorize @user render 'show.json.jbuilder', :status => 200 end def index @users = User.all authorize @users render 'index.json.jbuilder', :status => 200 end def report @user = User.find(params[:id]) authorize @user data = ReportService.generate_report_data(params, @user) if data.nil? render :json => { :message => "Wrong params"}, :status => 400 else if request.headers['Accept'] && (request.headers['Accept'] == 'application/pdf' || request.headers['Accept'] == 'application/octet-stream') send_data ReportService.generate_pdf(data), filename: APP_CONFIG['report_file_name'], type: 'application/pdf', :status => 200 else send_data data, filename: APP_CONFIG['report_file_name'], type: 'json', :status => 200 end end end def loggedin_user @user = User.find_by_api_token(request.headers["api-token"]) authorize @user render 'loggedin_user.json.jbuilder', :status => 200 end private # def set_cors # response.headers["Access-Control-Allow-Origin"] = "*" # # response.headers["Access-Control-Request-Method"] = "*" # end def user_params params.permit(*policy(User).user_attributes) end end <file_sep> app.factory("LoginService", ["$http", function($http){ return { login: function(user){ console.log("user", user); var req = { method: "POST", url: "http://localhost:8080/api/sessions", data: user, headers : { "Content-Type" : "application/x-www-form-urlencoded" }, transformRequest: function(user){ var str = []; for (var attr in user){ str.push(encodeURIComponent(attr) + "=" + encodeURIComponent(user[attr])); } return str.join("&"); } }; return $http(req); } }; }]);<file_sep> var signup_directives_module = angular.module("signup.directives", []); signup_directives_module.directive("passwordMatch", function passwordMatch(){ return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { // console.log("scope", scope); // console.log("elem", elem); // console.log("attrs", attrs); // console.log("ngModel", ngModel); scope.$watch(attrs.ngModel, function(){ if (scope.signupForm.password_confirmation.$viewValue === scope.signupForm.password.$viewValue){ scope.signupForm.password_confirmation.$setValidity("passwordMatch", true); }else { scope.signupForm.password_confirmation.$setValidity("passwordMatch", false); } }); } }; });<file_sep> var home_module = angular.module("home", ["ui.router", "ui.bootstrap"]); home_module.config(["$stateProvider", function homeConfig($stateProvider) { $stateProvider.state("home", { url: "/home", templateUrl: "home/home.tpl.html", controller: "HomeController" }); }]); home_module.controller("HomeController", ["$scope", "HomeService", function HomeController($scope, HomeService) { console.log("HomeController"); $scope.current_user = JSON.parse(sessionStorage.getItem("current_user")); $scope.adminRole = $scope.current_user.role == 'admin'; console.log("$scope.current_user.api_token", $scope.current_user); var data =[ {id: 1, name :"All"}, {id: 2, name : "Last Week"}, {id: 3, name : "Last Month"}, {id: 4, name : "Amount > 100"}, {id: 5, name : "Amount < 100"}, {id: 6, name : "Today"}]; $scope.expenseFilters = data; $scope.selectedFilter = $scope.expenseFilters[0]; // var getFiltersResult = HomeService.getAllFilters($scope.current_user.api_token, $scope.current_user.email) // .success(function(response_data, status, response_headers, request){ // $scope.expenseFilters = response_data.filters; // }).error(function(response_data, status, response_headers, request){ // console.log("error: ", response_data); // }); console.log("expenseFilters", $scope.expenseFilters); }]);<file_sep>class Expense < ActiveRecord::Base #attributes: description, amount, date, time, comment, user_id #associations belongs_to :user #validations validates :description, :amount, :date, :time, :comment, :user_id, :presence => true validates :amount, :numericality => true end <file_sep> var login_module = angular.module("login", ["ui.router"]); login_module.config(["$stateProvider", function loginConfig($stateProvider){ $stateProvider.state("login", { url: "/login", controller: "LoginController", templateUrl: "login/login.tpl.html", data: { pageTitle: " - login"} }); $stateProvider.state("main", { url: "/", controller: "ApplicationController" }); }]); login_module.controller("LoginController", ["$scope", "$state", "LoginService", function LoginController($scope, $state, LoginService){ console.log("LoginController"); $scope.login = function(user){ if (!$scope.loginForm.$valid){ alert("Please check your credentials."); return; } var loginResult = LoginService.login(user); loginResult.success(function(response_data, status, response_headers, request){ $scope.$emit("flashMessage", params = { message : "You've successfully logged in.", data : ""} ); sessionStorage.setItem("loggedIn", true); sessionStorage.setItem("current_user", JSON.stringify(response_data.user)); $state.go("main"); }).error(function(response_data, status, response_headers, request){ alert("Error: " + response_data.message); }); }; }]);<file_sep>class FilterPolicy < ApplicationPolicy class Scope < Scope def resolve scope end end def index? user.present? end end <file_sep> app.factory("UserService", ["$http", function($http){ return { getLoggedInUser: function(apiToken, email){ var req = { method: "GET", url: "http://localhost:8080/api/users/loggedin_user", headers: { "api-token" : apiToken, "email" : email } }; return $http(req); } }; }]);<file_sep>class SessionsController < ApplicationController def new @user = User.new end def create if !SessionService.login_params_valid?(params) flash.now[:alert] = "Error: check your credentials." render :new and return end user = User.find_by_email(params[:email].downcase) if user.present? if user.authenticate(params[:password]) cookies[:auth_token] = user.auth_token flash.now[:notice] = "You have successfully logged in." redirect_to user_path(user.id) and return else flash.now[:error] = 'Error: check your password.' render :new and return end else flash.now[:error] = 'Error: check your email.' render :new and return end end def destroy cookies.delete(:auth_token) reset_session redirect_to root_path, :notice => 'You have been logged out.' end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). #roles roles = Role.create([ {:name => 'admin'}, {:name => 'regular'} ]) #filters filters = Filter.create([ {:name => 'All'}, {:name => 'Last Week'}, {:name => 'Last Month'}, {:name => 'Amount < 100'}, {:name => 'Amount >= 100'}, {:name => 'Today'} ])<file_sep>json.user do json.id @user.id json.name @user.first_name json.last_name @user.last_name json.email @user.email json.role @user.role.name json.api_token @user.api_token end json.success "true"<file_sep>class Image < ActiveRecord::Base has_attached_file :image, styles: { small: "64x64", medium: "300x300>", large: "500x500>" }, default_url: "/images/:style/missing.png" # validates :image, :attachment_presence => true # validates_attachment :image, :size => { :in => 0..10000.kilobytes } # validates_attachment :image, :content_type => { :content_type => "image/jpg" } validates_attachment :image, :presence => true, :content_type => { :content_type => /\Aimage\/.*\Z/ }, :size => { :in => 0..10000.kilobytes } end <file_sep>class Api::V1::ExpensesController < Api::V1::ApplicationController before_action :find_parent before_action :find_record, :except => [:create, :index, :filter] def create @expense = Expense.new(expense_params) authorize @expense if @expense.save render 'create.json.jbuilder', :status => 201 else render :json => { :message => @expense.errors.full_messages.to_sentence }, :status => 409 end end def update if @expense.update_attributes(expense_params) render 'update.json.jbuilder', :status => 200 else render :json => { :message => @expense.errors.full_messages.to_sentence }, :status => 409 end end def destroy if @expense.destroy render :json => { :message => "Expense deleted." }, :status => 200 else render :json => { :message => @expense.errors.full_messages.to_sentence }, :status => 409 end end def show render 'show.json.jbuilder', :status => 200 end def index @expenses = @user.expenses render 'index.json.jbuilder', :status => 200 end def filter @filter_result = ExpensesFilterService.get_filter_results(params[:type], @user) if !@filter_result.nil? render 'filter.json.jbuilder', :status => 200 else render :status => 204 end end private def find_record @expense = Expense.find(params[:id]) authorize @expense end def find_parent @user = User.find(params[:user_id]) authorize @user, :can_manage_expenses? end def expense_params params.permit(*policy(Expense).expense_attributes) end end <file_sep> app.factory("SignupService", ["$http", function($http){ return { register: function(newUser){ var req = { method: "POST", url: "http://localhost:8080/api/users", data: newUser, headers : { "Content-Type" : "application/x-www-form-urlencoded" }, transformRequest: function(newUser){ var str = []; for (var attr in newUser){ str.push(encodeURIComponent(attr) + "=" + encodeURIComponent(newUser[attr])); } return str.join("&"); } }; return $http(req); } }; }]);<file_sep>== README Setting-up the app: ----------------------------- Dependencies: Ruby ver. 2.1.4 PostgreSQL 1. Install RVM, Ruby (2.1.4), Bundler and PostgreSQL servers 2. Run "bundle install" 3. Run "rake db:migrate" #to create DB and schema 4. Run "rake db:seed" #to seed data 5. Run "rake users:admin_init" #to initialize admin account 6. Boot the app by typing "unicorn" (or if you prefer rails' built-in WebBrick server, then run the app by typing "rails s") 7. Open you browser and type "http://localhost:8080", if you're using Unicorn web server, or "http://localhost:3000" if you prefer WebBrick 8. To login to app use credentials: email: <EMAIL> pass: <PASSWORD> FrontEnd: --------- 1. sudo npm -g install grunt-cli karma bower 2. npm install 3. bower install 4. grunt watch Testing: ------------ To run the tests do the following: - run "rake db:test:prepare" #to create test db for RestAPI testing: - run tests for each controller by typing: "bundle exec rspec spec/api/expenses_controller_spec.rb" #for expenses controller "bundle exec rspec spec/api/users_controller_spec.rb" #for users controller "bundle exec rspec spec/api/sessions_controller_spec.rb" #for sessions controller for model testing: - run tests for each model by typing: "bundle exec rspec spec/models/user_spec.rb" #for user model "bundle exec rspec spec/models/expense_spec.rb" #for expense model and so on... for service testing: -run tests for each service by typing: "bundle exec rspec spec/services/expenses_filter_service_spec.rb" and so on... for policy testing: - run tests for each policy by typing: "bundle exec rspec spec/policies/expense_policy_spec.rb" and so on... You can find deployed version of the app on: http://tt-project.herokuapp.com<file_sep> var app = angular.module("ExpenseTrackerApp", ["templates-app", "templates-common", "ui.router", "about", "home", "contact", "guest", "login", "signup", "signup.directives", "forbidden" ]); app.constant("DEV_CONFIG", { "BASE_URL" : "http://localhost:8080/" }); app.constant("PROD_CONFIG", { "BASE_URL" : "http://expense-tracker-app.herokuapp.com/" }); // app.value("loggedIn", {val : false, current_user : false }); app.config(["$stateProvider", "$urlRouterProvider", function myAppConfig ($stateProvider, $urlRouterProvider) { $urlRouterProvider.when("main", "index.html"); $urlRouterProvider.otherwise("/"); }]); app.run(function run () { console.log("Starting app"); }); app.controller("ApplicationController", ["$scope", "$state", function ApplicationController($scope, $state) { console.log("ApplicationController"); $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ $scope.pageTitle = (toState.data && toState.data.pageTitle) ? ("Expense Tracker App" + toState.data.pageTitle) : "Expense Tracker App"; $scope.loggedIn = sessionStorage.getItem("loggedIn"); if (toState.name == "home"){ if (!$scope.loggedIn){ $state.go("forbidden"); } } }); $scope.$on("flashMessage", function(event, params){ $scope.showFlashMessage = true; $scope.flashMessage = params.message; }); $scope.closeFlashMessages = function(){ $scope.showFlashMessage = false; $scope.flashMessage = ""; }; $scope.loggedIn = sessionStorage.getItem("loggedIn"); $scope.current_user = JSON.parse(sessionStorage.getItem("current_user")); if ($scope.loggedIn) { $state.go("home"); } else { $state.go("guest"); } }]);<file_sep>class Api::V1::SessionsController < Api::V1::ApplicationController skip_before_action :authenticate_user, :only => :create before_action :set_cors, :only => :create def create @user = User.find_by_email(params[:email].downcase) if params[:email].present? if @user && @user.authenticate(params[:password]) render 'create.json.jbuilder', :status => 201 else render :json => { :message => 'Please check your credentials.'}, :status => 401 end end def destroy user = User.find(params[:id]) if user authorize user, :logout? user.reset_api_token user.save render :json => { :message => 'Session deleted.'}, :success => true, :status => 200 else render :json => { :message => 'Not found'}, :status => 404 end end private def set_cors response.headers["Access-Control-Allow-Origin"] = "*" # response.headers["Access-Control-Allow-Methods"] = "OPTIONS, POST, DELETE, PUT" # response.headers["Access-Control-Allow-Headers"] = "*" # response.headers["Access-Control-Request-Method"] = "*" end end <file_sep>class CreateExpenses < ActiveRecord::Migration def change create_table :expenses do |t| t.string :description t.float :amount t.date :date t.time :time t.string :comment t.integer :user_id, :references => :user t.timestamps null: false end end end <file_sep>class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :email t.string :first_name t.string :last_name t.string :password_digest t.integer :role_id, :references => :role, :default => 2 t.string :auth_token t.string :api_token t.timestamps null: false end end end <file_sep>class ReportService def self.generate_report_data(params, user) data = [] if check_date(params) week_start = params[:week].to_date.beginning_of_week week_end = week_start + 6.days expenses = user.expenses.where("date >= ? AND date <= ?", week_start, week_end) if expenses.any? data << "Expenses for period #{week_start} to #{week_end}: " data << "---------------------------------------------------------------" data << "\n" total_amount = 0 average = 0 expenses.each do |ex| data << "Expense description: #{ex.description}" data << "Expense amount: #{ex.amount}" data << "\n" total_amount += ex.amount end average = (total_amount / expenses.size).to_f data << "---------------------------------------------------------------" data << "Average: #{average}" data << "Total: #{total_amount}" else data << "There is no expenses for selected period #{week_start} to #{week_end}." end else data = nil end data end def self.generate_pdf(data) Prawn::Document.new do data.each do |el| text el.to_s end end.render end def self.check_date(params) if params[:week].present? begin Date.parse(params[:week]) true rescue ArgumentError => e false end else false end end end<file_sep>class Api::V1::ApplicationController < ApplicationController #force_ssl protect_from_forgery with: :null_session before_action :authenticate_user, :destroy_session def current_user if @current_user @current_user elsif request.headers["api-token"] @current_user = User.find_by_api_token(request.headers["api-token"]) end end def authenticate_user if request.headers["api-token"] && request.headers["email"] user = User.find_by_email(request.headers["email"].downcase) if user && ActiveSupport::SecurityUtils.secure_compare(user.api_token, request.headers["api-token"]) @current_user = user else return unauthenticated! end else return unauthenticated! end end #disabling CSRF token and cookies => API's are stateless, and session is opposite of that def destroy_session request.session_options[:skip] = true end def unauthenticated! response.headers['WWW-Authenticate'] = "Token realm=Application" render :json => { :error => 'Bad credentials' }, status: 401 end def user_not_authorized render :json => { :error => "Access denied" }, :status => 403 end def record_not_found render :json => { :error => "Not found" }, :status => 404 end end<file_sep>class SamplesController < ApplicationController def index @samples = Sample.all.order('name') end end<file_sep>class UsersController < ApplicationController before_filter :find_record, :except => :create def create @user = User.new(user_params) authorize @user @user.save respond_to do |format| format.js end end def show @user = User.find(params[:id]) authorize @user @expenses = @user.expenses if current_user.role.name == "admin" @users = User.all end end def user_details respond_to do |format| format.js end end def edit respond_to do |format| format.js end end def update @user.update_attributes(user_params) respond_to do |format| format.js end end def destroy @user.destroy respond_to do |format| format.js end end def report data = ReportService.generate_report_data(params, @user) if data.nil? data << "Wrong date params." end send_data ReportService.generate_pdf(data), filename: APP_CONFIG['report_file_name'], type: 'application/pdf', :disposition => "attachment" end private def user_params params.permit(*policy(User).user_attributes) end def find_record @user = User.find(params[:id]) authorize @user end end <file_sep>class ApplicationController < ActionController::Base include Pundit # Prevent CSRF attacks by raising an exception. protect_from_forgery with: :exception rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found helper_method :current_user, :user_logged_in? def current_user @current_user ||= User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token] end def user_logged_in? !current_user.nil? end def record_not_found flash[:error] = "Error: record not found!" redirect_to user_path(current_user) end def user_not_authorized(exception) Rails.logger.info build_authorization_log(exception) flash[:error] = 'Access denied' redirect_to root_path end def build_authorization_log(exception) policy_name = exception.policy.class.to_s.underscore message = "Authorization Error! pundit.#{policy_name}.#{exception.query} from ip address #{request.remote_ip}" message += " by user #{current_user}" if current_user message end end <file_sep>class SessionService def self.login_params_valid?(params) if !params[:email].present? && !params[:password].present? return false end email = params[:email].downcase password = params[:password] if password.size < 4 || password.size > 15 return false else email_regex = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i result = email_regex.match(email) return !result.nil? end end end<file_sep>json.expenses @filter_result do |ex| json.expense do json.id ex.id json.description ex.description json.amount ex.amount json.date ex.date json.time ex.time.strftime("%H:%M") json.comment ex.comment end end<file_sep>class Role < ActiveRecord::Base #attributes: name #associations has_many :users #validations validates :name, :presence => true end <file_sep>class Api::V1::FiltersController < Api::V1::ApplicationController def index @filters = Filter.all authorize @filters.first render 'index.json.jbuilder', :status => 200 end end <file_sep>class User < ActiveRecord::Base #attributes: email, first_name, last_name, :password_digest, role_id, auth_token, api_token has_secure_password #associations belongs_to :role has_many :expenses, :dependent => :destroy #validations validates :first_name, :last_name, :email, :role_id, :presence => true validates :email, :uniqueness => true validates_formatting_of :email, :using => :email validates :password, :presence => true, :length => { :within => 4..15 }, :if => :validate_password? #callbacks before_create :init_user before_validation :do_before_save def reset_api_token self.api_token = SecureRandom.urlsafe_base64 true end private def init_user self.auth_token = SecureRandom.urlsafe_base64 self.api_token = SecureRandom.urlsafe_base64 true end def do_before_save if self.email_changed? self.email.strip! self.email.downcase! end end def validate_password? @force_password_verification || new_record? || !password.blank? end end <file_sep>json.user do json.id @user.id json.first_name @user.first_name json.last_name @user.last_name json.email @user.email json.role @user.role.name if @user.role json.api_token @user.api_token end<file_sep>require 'rails_helper' RSpec.describe Role, type: :model do it "should validate presence of name" do role = Role.create(:name => '') role.valid? expect(role.errors).to have_key(:name) another_role = Role.create(:name => 'regular') another_role.valid? expect(another_role.errors.present?).to be false end it "should have one associated user record" do role = Role.create(:name => 'regular') user = User.create(:first_name => 'test', :last_name => 'test', :password => '<PASSWORD>', :password_confirmation => '<PASSWORD>', :role_id => role.id, :email => '<EMAIL>') expect(role).to respond_to(:users) expect(role.users.first.email).to eq "<EMAIL>" end end<file_sep> var forbidden_module = angular.module("forbidden", []); forbidden_module.config(["$stateProvider", function($stateProvider){ $stateProvider.state("forbidden", { url: "/forbidden", templateUrl: "errors/forbidden.tpl.html", controller: "ForbiddenController" }); }]); forbidden_module.controller("ForbiddenController", ["$scope", function($scope){ console.log("ForbiddenController"); }]);<file_sep>class ExpensePolicy < ApplicationPolicy class Scope < Scope def resolve scope end end def create? can_manage_expense? end def show? can_manage_expense? end def edit? can_manage_expense? end def update? can_manage_expense? end def destroy? can_manage_expense? end def expense_attributes [:description, :amount, :date, :time, :comment, :user_id] end def can_manage_expense? is_admin? || (user.present? && record.user_id == user.id) end end <file_sep>class Sample < ActiveRecord::Base require 'csv' require 'open-uri' self.inheritance_column = :foo def self.import_data(file) csv_path = 'http://samplecsvs.s3.amazonaws.com/SalesJan2009.csv' csv_file = open(csv_path, 'r') csv_options = { chunk_size: 100 } CSV.foreach(csv_file, headers: true) do |row| print "row" p row # sample = find_by_name(row["name"]) || new # sample.attributes = row.to_hash # #Sample.create! row.to_hash # sample.save! sample = find_by_name(row["Name"]) || new sample.update_attributes( :transaction_date => row["Transaction_date"], :product => row["Product"], :price => row["Price"], :payment_type => row["Payment_Type"], :name => row["Name"], :city => row["City"], :state => row["State"], :country => row["Country"], :account_created => row["Account_Created"], :last_login => row["Last_Login"], :latitude => row["Latitude"], :longitude => row["Longitude"] ) sample.save! end end end # # how to read and process a CSV that has to be accessed over HTTP using smarter_csv # # I didn't have to specify this in my Rails setup, but you might # require 'open-uri' # # URL that points to where the CSV is hosted # csv_path = 'http://example.com/path/to/csv/file.csv' # # open the CSV file using open-uri # # you may have to specify encoding # csv_file = open(csv_path,'r') # # whatever options (optional) # csv_options = { # chunk_size: 100 # } # # SmarterCSV can actually handle any object that responds to readline # # I didn't see that in the docs and I had to look at the source, which is why I'm writing this gist # SmarterCSV.process(csv_file, csv_options) do |chunk| # chunk.each do |row| # # do some stuff with row # end # end <file_sep>require 'sidekiq/web' require 'api_constraints' Rails.application.routes.draw do mount Sidekiq::Web => '/sidekiq' root 'home#index' get 'logout' => 'sessions#destroy', :as => 'logout' get 'upload' => 'files#upload' post 'import_data' => 'files#import_data' resources :samples, :only => :index resources :signup, :only => [:new, :create] resources :sessions, :only => [:new, :create] resources :images, :only => [:index, :new, :create] resources :users, :except => [:index, :new] do resources :expenses, :except => [:index, :new] do collection do get :filter end end member do get :report get :user_details end end #API namespace :api, :defaults => { :format => 'json'} do scope module: :v1, :constraints => ApiConstraints.new(version: 1, default: true) do resources :sessions, :only => [:create, :destroy] resources :users, :except => [:new, :edit] do collection do get :loggedin_user end resources :expenses, :except => [:new, :edit] do collection do get :filter end end member do get :report end end resources :filters, :only => [:index] end end end <file_sep>class CreateSamples < ActiveRecord::Migration def change create_table :samples do |t| t.datetime :transaction_date t.string :product t.decimal :price t.string :payment_type t.string :name t.string :city t.string :state t.string :country t.datetime :account_created t.datetime :last_login t.string :latitude t.string :longitude t.timestamps null: false end end end <file_sep>class TestWorker include Sidekiq::Worker require 'csv' require 'open-uri' def perform(file_url) csv_path = file_url csv_file = open(csv_path, 'r') csv_options = { chunk_size: 100 } CSV.foreach(csv_file, headers: true) do |row| print "row" p row # sample = find_by_name(row["name"]) || new # sample.attributes = row.to_hash # #Sample.create! row.to_hash # sample.save! sample = Sample.find_by_name(row["Name"]) || Sample.new sample.update_attributes( :transaction_date => row["Transaction_date"], :product => row["Product"], :price => row["Price"], :payment_type => row["Payment_Type"], :name => row["Name"], :city => row["City"], :state => row["State"], :country => row["Country"], :account_created => row["Account_Created"], :last_login => row["Last_Login"], :latitude => row["Latitude"], :longitude => row["Longitude"] ) sample.save! end end end<file_sep>class ExpensesController < ApplicationController before_filter :find_parent before_filter :find_record, :except => [:create, :filter] def show respond_to do |format| format.js end end def create @expense = Expense.new(expense_params) @expense.user_id = @user.id authorize @expense @expense.save respond_to do |format| format.js end end def edit respond_to do |format| format.js end end def update @expense.update_attributes(expense_params) respond_to do |format| format.js end end def destroy @expense.destroy respond_to do |format| format.js end end def filter @filter_result = ExpensesFilterService.get_filter_results(params[:filter_id], @user) respond_to do |format| format.js end end private def find_parent @user = User.find(params[:user_id]) authorize @user, :can_manage_expenses? end def find_record @expense = Expense.find(params[:id]) authorize @expense end def expense_params params.permit(*policy(Expense).expense_attributes) end end <file_sep> namespace :users do desc "Initialization of the admin account." task :admin_init => :environment do role = Role.find_by_name("admin") user = User.new() user.first_name = "Big" user.last_name = "Boss" user.email = "<EMAIL>" user.auth_token = SecureRandom.urlsafe_base64 user.api_token = SecureRandom.urlsafe_base64 user.role_id = role.id user.password = "<PASSWORD>" user.password_confirmation = "<PASSWORD>" if user.save puts "Admin successfully initialized!" else puts "Error: #{user.errors.full_messages.to_sentence}" end end end<file_sep>class SignupController < ApplicationController def new @user = User.new end def create @user = User.new(signup_params) if @user.save flash[:notice] = "Congratulations, you've created your account successfully!" redirect_to new_session_path else flash.now[:error] = "Error: #{@user.errors.full_messages.to_sentence}" render "new" end end private def signup_params params.permit(*policy(User).user_attributes) end end <file_sep>class UserPolicy < ApplicationPolicy class Scope < Scope def resolve scope end end def index? is_admin? end def show? is_admin? || is_profile_owner? end def user_details? is_admin? end def create? is_admin? end def update? is_admin? || is_profile_owner? end def destroy? is_admin? end def filter_expenses? is_admin? || is_profile_owner? end def report? is_admin? || is_profile_owner? end def logout? user && user.id == record.id end def loggedin_user? user && user.id == record.id end def can_manage_expenses? is_admin? || is_profile_owner? end def user_attributes if user.present? && user.role.name == "admin" [:first_name, :last_name, :password, :password_confirmation, :email, :role_id] else [:first_name, :last_name, :password, :password_confirmation, :email] end end private def is_profile_owner? user.present? && user.id == record.id end end <file_sep>class Filter < ActiveRecord::Base #attributes: name #validations validates :name, :presence => true end <file_sep>json.filters @filters do |f| json.id f.id json.name f.name end<file_sep>json.users @users do |u| json.user do json.id = u.id json.first_name = u.first_name json.last_name = u.last_name json.email = u.email json.role = u.role.name end end<file_sep>FactoryGirl.define do factory :sample do Transaction_date "2016-02-27 14:20:46" Product "MyString" Price "9.99" Payment_type "MyString" Name "MyString" city "MyString" state "MyString" country "MyString" account_created "2016-02-27 14:20:46" last_login "2016-02-27 14:20:46" latitude "MyString" longitude "MyString" end end <file_sep>json.expense do json.id @expense.id json.description @expense.description json.amount @expense.amount json.date @expense.date json.time @expense.time.strftime("%H:%M") json.comment @expense.comment end json.message "Expense successfully updated." json.success "true"<file_sep>class ImagesController < ApplicationController def index @images = Image.all end def new end def create image = Image.new image.image = params[:attachment] image.save! redirect_to images_path end end<file_sep> var guest_module = angular.module("guest", ["ui.router", "ui.bootstrap"]); guest_module.config(["$stateProvider", function guestConfig($stateProvider) { $stateProvider.state("guest", { url: "/guest", controller: "GuestController", templateUrl: "guest/guest.tpl.html" }); }]); guest_module.controller("GuestController", ["$scope", function GuestController($scope) { console.log("GuestController"); }]);<file_sep>class ExpensesFilterService def self.get_filter_results(filter_id, user) case filter_id when "1" result = user.expenses.order('date DESC') when "2" result = user.expenses.where("date >= ? AND date < ?", Time.now.to_date() - 7.days, Time.now.to_date() ).order(:date) when "3" result = user.expenses.where("date >= ? AND date < ?", Time.now.to_date() - 1.month, Time.now.to_date() ).order(:date) when "4" result = user.expenses.where("amount < ?", 100).order(:amount) when "5" result = user.expenses.where("amount >= ?", 100).order(:amount) when "6" result = user.expenses.where("date = ?", Date.today()).order(:created_at) else result = nil end result end end<file_sep> app.factory("HomeService", ["$http", function($http){ return { getAllFilters: function(apiToken, email){ var req = { method: "GET", url: "http://localhost:8080/api/filters", headers : { "api-token" : apiToken, "email" : email } }; return $http(req); } }; }]);
c5ceb60e18a91e01d8d4e6619dc0c1ffed227c29
[ "JavaScript", "RDoc", "Ruby" ]
52
Ruby
matejtest/testing
0051f4f834aea5a7aabe248fd5f902ab3f96cfe9
283836269059a5c62bbd2595d803f787a154ed2a
refs/heads/main
<file_sep>// author: <First name, last name; YOUR SFU USER ID HERE> // date: // input: // output: // description: #include <stdio.h> #include "t2mirror.h" int main(void) { int a1[3] = {10, 15, 20}; int a2[3] = {20, 15, 10}; if (mirror(a1, a2, 3) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } int a1[1] = {100}; int a2[1] = {100}; if (mirror(a1, a2, 1) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } int a1[7] = {5,2,2,3,4,5,5}; int a2[7] = {5,5,4,3,2,2,5}; if (mirror(a1, a2, 7) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } if (mirror(a1, a2, 0) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } int a1[2] = {1,1}; int a2[2] = {1,2}; if (mirror(a1, a2, 2) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } int a1[3] = {10,15,20}; int a2[3] = {10,15,20}; if (mirror(a1, a2, 3) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } int a1[5] = {1,2,3,4,5}; int a2[5] = {5,3,4,1,2}; if (mirror(a1, a2, 7) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } int a1[5] = {1,2,3,4,5}; int a2[5] = {5,3,4,2,2}; if (mirror(a1, a2, 7) == 1) { printf("a1 and a2 are mirrored\n"); } else { printf("a1 and a2 are NOT mirrored\n"); } return 0; } ```<file_sep>int identical(int arr1[], int arr2[], unsigned int len) { if (len == 0) { return 1; } for (int i=0; i<len; i++) { if (arr1[i] != arr2[i]) { return 0; } } return 1; } int scrambled(int arr1[], int arr2[], unsigned int len) { // FILL IN BODY return 0; }
264209b304578e94f048ef96072d6a9139f95b28
[ "C" ]
2
C
XusongHe-R/202105_sfu_cmpt_127
abc532adf956b36e01bf7d2f27dac36a7a615b92
710c32588219cdd3d3f731b27a30e55d1a76930c
refs/heads/master
<file_sep>package tk.hugo4715.golema.santabox.gui; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import net.golema.database.support.builder.items.ItemBuilder; import tk.hugo4715.golema.santabox.BoxPlugin; import tk.hugo4715.golema.santabox.database.DatabaseManager.Prize; import tk.hugo4715.golema.santabox.util.AbstractGui; public class LootListGui extends AbstractGui { private List<ItemStack> prizes = new ArrayList<>(); public LootListGui(Player player) { super(BoxPlugin.get(), player, "Liste des lots", 4*9, 10); try { List<Prize> p = BoxPlugin.get() .getDatabaseManager() .getPrizes(); for(Prize prize : p){ ItemStack is = new ItemBuilder() .type(prize.getRarity().getMaterial()) .name(prize.getRarity().getColor() + prize.getRarity().getFrench() + ChatColor.WHITE + " │ " + ChatColor.YELLOW + prize.getName()) .lore(ChatColor.GRAY + "Marque: " + ChatColor.GOLD + prize.getMarque()) .build(); prizes.add(is); } } catch (SQLException e) { e.printStackTrace(); player.sendMessage(ChatColor.RED + "Une erreur est survenue."); stop(); return; } } @Override public void update() { if(prizes != null) { for (int i = 0; i < prizes.size(); i++) { inv.setItem(i, prizes.get(i)); } } } } <file_sep>package tk.hugo4715.golema.santabox.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; import net.minecraft.server.v1_8_R3.EntityArmorStand; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; import tk.hugo4715.golema.santabox.BoxPlugin; public class HologramBuilder { private String message; private int stay; private Location location; private EntityArmorStand stand; private List<Player> playersList; private Player player_; public String getMessage() { return message; } public int getStay() { return stay; } public Location getLocation() { return location; } /** * * Editer le message * */ public HologramBuilder editMessage(String message) { this.message = message; return this; } /** * * Editer la location * */ public HologramBuilder editLocation(Location location) { this.location = location; return this; } /** * * Editer le stay * */ public HologramBuilder editStay(int stay) { this.stay = stay; return this; } /** * CONSTRUCTEUR POUR UN HOLOGRAMME AVEC PLAYERS DE COLLECTIONS * */ public HologramBuilder() { } /** * Mettez le message ? afficher sur l'hologramme * * @param message * > String * * @return HologramBuilder * */ public HologramBuilder withMessage(String message) { this.message = message; return this; } /** * Mettez le @param ? 0 si vous voulez que l'hologramme reste ind?finiment * * @param stay * > Integer (Le temps que va rester l'hologramme) * * @return HologramBuilder * */ public HologramBuilder withStay(int stay) { this.stay = stay; return this; } /** * Permet de set la location ? laquelle va apparaitre l'hologramme * * @param location * > Location * * @return HologramBuilder * */ public HologramBuilder withLocation(Location location) { this.location = location; return this; } /** * Permet d'envoyer l'hologramme ? un joueur * * @param player * > Player (Le joueur en question) * */ public void sendToPlayer(Player player) { stand = getArmorStand(); this.player_ = player; PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(stand); ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); /* SI LE TEMPS EST PAS INDETERMINE */ if (stay != 0) { Bukkit.getServer().getScheduler().runTaskLater(BoxPlugin.get(), () -> { PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(stand.getId()); ((CraftPlayer) player).getHandle().playerConnection.sendPacket(destroy); }, stay); } } /** * Permet d'envoyer l'hologramme ? une collection de joueurs * * @param players * > Collection type Player (Ex: Bukkit.getOnlinePlayers()) * */ public void sendToPlayers(Collection<? extends Player> players) { stand = getArmorStand(); this.playersList = new ArrayList<Player>(); PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(stand); for (Player playerCollection : players) { this.playersList.add(playerCollection); ((CraftPlayer) playerCollection).getHandle().playerConnection.sendPacket(packet); } /* SI LE TEMPS EST PAS INDETERMINE */ if (stay != 0) { Bukkit.getServer().getScheduler().runTaskLater(BoxPlugin.get(), () -> { PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(stand.getId()); for (Player playerCollection : players) ((CraftPlayer) playerCollection).getHandle().playerConnection.sendPacket(destroy); }, stay); } } private EntityArmorStand getArmorStand() { EntityArmorStand stand = new EntityArmorStand(((CraftWorld) location.getWorld()).getHandle()); stand.setLocation(location.getX(), location.getY(), location.getZ(), 0, 0); stand.setCustomName(message); stand.setCustomNameVisible(true); stand.setGravity(false); stand.setInvisible(true); EntityRegistry.add(stand.getBukkitEntity()); return stand; } /** * * Delete le stand. * */ public void destroy() { if (this.player_ != null) { PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(stand.getId()); ((CraftPlayer) player_).getHandle().playerConnection.sendPacket(destroy); } } public void destroyAllPlayers() { PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(stand.getId()); for (Player playerCollection : playersList) { if (playerCollection != null) { ((CraftPlayer) playerCollection).getHandle().playerConnection.sendPacket(destroy); } } } }<file_sep>package tk.hugo4715.golema.santabox.util; import java.util.Arrays; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.PotionEffect; public class ItemFactory { private ItemStack item; public ItemFactory(ItemStack item){ this.item = item; } public ItemFactory(Material mat) { item = new ItemStack(mat); } public ItemFactory(Material mat, int amount) { item = new ItemStack(mat,amount); } public ItemFactory withName(String name){ ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); return this; } public ItemFactory withLore(String... lore){ ItemMeta meta = item.getItemMeta(); meta.setLore(Arrays.asList(lore)); item.setItemMeta(meta); return this; } public ItemFactory withColor(DyeColor color){ item.setDurability(color.getData()); return this; } public ItemFactory withOwner(String owner){ if(item.getType().equals(Material.SKULL_ITEM)){ item.setDurability((short) 3); SkullMeta m = (SkullMeta) item.getItemMeta(); m.setOwner(owner); item.setItemMeta(m); } return this; } public ItemFactory withAmount(int amount){ item.setAmount(amount); return this; } public ItemFactory withEnchant(Enchantment e, int lvl){ ItemMeta m = item.getItemMeta(); m.addEnchant(e, lvl, true); item.setItemMeta(m); return this; } public ItemFactory withEffect(PotionEffect e){ if(!(item.getType().equals(Material.POTION)))return this; PotionMeta pm = (PotionMeta) item.getItemMeta(); pm.addCustomEffect(e, true); item.setItemMeta(pm); return this; } public ItemFactory addFlag(ItemFlag... f){ item.getItemMeta().removeItemFlags(f); return this; } public ItemStack done(){ return item; } public ItemFactory withGlowEffect(){ Glow.registerGlow(); withEnchant(new Glow(70), 1); return this; } }<file_sep>package tk.hugo4715.golema.santabox.box; import java.sql.SQLException; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.lang3.Validate; import org.bukkit.Location; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Player; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import net.md_5.bungee.api.ChatColor; import tk.hugo4715.golema.santabox.BoxPlugin; import tk.hugo4715.golema.santabox.anim.BoxOpenAnimation; public class Box implements ConfigurationSerializable { public static Set<UUID> opening = Sets.newHashSet(); private Location boxLocation; //used to indicate if the box is used by a player private AtomicBoolean used = new AtomicBoolean(false); public Box(Location center) { boxLocation = center; } public Box(Map<?,?> s){ Validate.isTrue(s.containsKey("center")); boxLocation = Location.deserialize((Map<String, Object>) s.get("center")); } public Location getBoxLocation() { return boxLocation; } public void open(Player p){ try { if(BoxPlugin.get().getDatabaseManager().getPlayerKeys(p) < 1){ p.sendMessage(BoxPlugin.PREFIX + ChatColor.YELLOW + "Vous n'avez pas de clé pour ouvrir une SantaBox, achetez en sur " + ChatColor.AQUA + "store.golemamc.net"); return; } if(opening.contains(p.getUniqueId())){ p.sendMessage(BoxPlugin.PREFIX + ChatColor.RED + "Vous etes déja en train d'ouvrir une box."); return; } if(!isUsed().compareAndSet(false, true)){ p.sendMessage(BoxPlugin.PREFIX + ChatColor.RED + "Cette box est en cours d'utilisation."); return; } opening.add(p.getUniqueId()); p.sendMessage(BoxPlugin.PREFIX + "Vous ouvrez maintenant une box."); BoxOpenAnimation.openBox(p, this); } catch (SQLException e) { e.printStackTrace(); p.sendMessage(BoxPlugin.PREFIX + ChatColor.RED + "Une erreur s'est produite. Merci de contacter un administrateur pour régler le probleme."); } } public Map<String, Object> serialize() { Map<String,Object> map = Maps.newHashMap(); map.put("center", boxLocation.serialize()); return map; } public AtomicBoolean isUsed() { return used; } } <file_sep>package tk.hugo4715.golema.santabox.util; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.Inventory; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import com.google.common.collect.Maps; public abstract class AbstractGui implements Listener{ private String name; private int taskId; private boolean stopped = false; protected Map<Integer, ButtonClickListener> buttons; protected Player player; protected Inventory inv; public AbstractGui(JavaPlugin plugin, Player player,String invName, int size ,int refreshTicks){ this.player = player; this.name = invName; this.buttons = Maps.newHashMap(); Bukkit.getPluginManager().registerEvents(this, plugin); player.openInventory(getInventory(size)); if(refreshTicks > 0){ taskId = new BukkitRunnable(){ public void run() { update(); } }.runTaskTimer(plugin, 0, refreshTicks).getTaskId(); } } private Inventory getInventory(int size) { inv = Bukkit.createInventory(null, size,name); update(); return inv; } protected void stop(){ if(stopped)return; stopped = true; player.closeInventory(); HandlerList.unregisterAll(this); Bukkit.getScheduler().cancelTask(taskId); } public void update(){} @EventHandler public void onInvClose(InventoryCloseEvent e){ if(!(e.getPlayer() instanceof Player && ((Player)e.getPlayer()).equals(player) && e.getInventory().getName().equals(name)))return; stop(); } @EventHandler public void onClick(InventoryClickEvent e){ if(!(e.getWhoClicked() instanceof Player && ((Player)e.getWhoClicked()).equals(player) && e.getInventory().getName().equals(name)))return; e.setCancelled(true); if(!buttons.containsKey(e.getSlot()))return; buttons.get(e.getSlot()).onClick(e.getSlot()); } public interface ButtonClickListener{ public abstract void onClick(int slot); } }<file_sep>package tk.hugo4715.golema.santabox.box; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.bukkit.Material; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import com.google.common.collect.Sets; import tk.hugo4715.golema.santabox.BoxPlugin; public class BoxManager { private Set<Box> boxes = Sets.newHashSet(); public BoxManager() { if(BoxPlugin.get().getConfig().contains("boxes")){ BoxPlugin.get().getConfig().getMapList("boxes").forEach(map -> boxes.add(new Box(map))); } BoxPlugin.get().getLogger().info("Loaded " + boxes.size() + " boxes"); } public void saveBoxes(){ BoxPlugin.get().getConfig().set("boxes", boxes.stream().map(Box::serialize).collect(Collectors.toList())); BoxPlugin.get().saveConfig(); BoxPlugin.get().getLogger().info("Saved boxes"); } public void addBox(Box box){ boxes.add(box); saveBoxes(); } public void removeBox(Box box){ boxes.remove(box); saveBoxes(); } public Set<Box> getBoxes(){ return Collections.unmodifiableSet(boxes); } public Optional<Box> getclickedBox(PlayerInteractEvent e){ if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK) && e.getClickedBlock() != null && e.getClickedBlock().getType().equals(Material.ENDER_CHEST)){ for(Box box : getBoxes()){ if(box.getBoxLocation().equals(e.getClickedBlock().getLocation())){ return Optional.of(box); } } } return Optional.empty(); } } <file_sep>package tk.hugo4715.golema.santabox.anim; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.text.WordUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import com.google.common.collect.Lists; import net.golema.database.GolemaBukkitDatabase; import net.golema.database.golemaplayer.GolemaPlayer; import net.golema.database.golemaplayer.UUIDFetcher; import net.golema.database.golemaplayer.rank.Rank; import net.golema.database.support.particle.ParticleEffect; import net.md_5.bungee.api.ChatColor; import net.minecraft.server.v1_8_R3.BlockPosition; import net.minecraft.server.v1_8_R3.TileEntityEnderChest; import net.minecraft.server.v1_8_R3.World; import tk.hugo4715.golema.santabox.BoxPlugin; import tk.hugo4715.golema.santabox.box.Box; import tk.hugo4715.golema.santabox.database.DatabaseManager.Prize; import tk.hugo4715.golema.santabox.util.EntityRegistry; import tk.hugo4715.golema.santabox.util.HologramBuilder; import tk.hugo4715.golema.santabox.util.Skull; public class BoxOpenAnimation { public static void openBox(Player p, Box box) throws SQLException { Prize reward = null; GolemaPlayer gp = GolemaPlayer.getGolemaPlayer(p); try { BoxPlugin.get().getDatabaseManager().addPlayerKeys(UUIDFetcher.getUUID(GolemaPlayer.getGolemaPlayer(p).getPlayerRealName()), -1); reward = BoxPlugin.get().getDatabaseManager().choosePrize(); BoxPlugin.get().getDatabaseManager().usePrize(reward); BoxPlugin.get().getDatabaseManager().winPrize(p, reward); reward.give(gp); } catch (SQLException e) { e.printStackTrace(); p.sendMessage(BoxPlugin.PREFIX + ChatColor.RED + "Une erreur s'est produite. Merci de contacter un administrateur pour régler le probleme."); } final Prize r = reward; new BukkitRunnable() { int ticks = 0; HologramBuilder holo; HologramBuilder holo2; //orb: //http://textures.minecraft.net/texture/e6799bfaa3a2c63ad85dd378e66d57d9a97a3f86d0d9f683c498632f4f5c //present: //http://textures.minecraft.net/texture/b5651a18f54714b0b8f7f011c018373b33fd1541ca6f1cfe7a6c97b65241f5 ItemStack head = Skull.getCustomSkull("http://textures.minecraft.net/texture/b5651a18f54714b0b8f7f011c018373b33fd1541ca6f1cfe7a6c97b65241f5"); ArmorStand stand; float pitch = 0; @Override public void run() { ticks++; if(!p.isOnline()){ playChestAction(box.getBoxLocation(), false); box.opening.remove(p.getUniqueId()); box.isUsed().set(false); cancel(); return; } if(stand != null){ stand.setHeadPose(stand.getHeadPose().add(0, 0.25, 0)); ParticleEffect.FIREWORKS_SPARK.display(0, 0,0, 0.1f, 1, stand.getEyeLocation(), box.getBoxLocation().getWorld().getPlayers()); } if(ticks < 60 && ticks % 5 == 0){ p.playSound(p.getLocation(), Sound.NOTE_PLING, 1, pitch); pitch += 0.1; } for (int i = 0; i < 10; i++) { int a = i * 2; double dx = Math.cos((ticks+a)/5.0)*2; double dy = (Math.min((ticks+a),90)/20.0)-1; double dz = Math.sin((ticks+a)/5.0)*2; ParticleEffect.CLOUD.display(new Vector(0,0,0), 0, box.getBoxLocation().clone().add(dx + 0.5, dy, dz + 0.5),Lists.newArrayList(Bukkit.getOnlinePlayers())); } //one time events if(ticks == 1){ //spawn all armorstands stand = box.getBoxLocation().getWorld().spawn(box.getBoxLocation().clone().add(0.5, 0, 0.5), ArmorStand.class); stand.setGravity(false); stand.setVisible(false); stand.setHelmet(head); stand.setMetadata("stop-taking-my-items", new FixedMetadataValue(BoxPlugin.get(), true)); EntityRegistry.add(stand); }else if(ticks == 60){ //show reward here Rank rank = getRealRank(gp); p.sendMessage(BoxPlugin.PREFIX + "Vous venez d'obtenir " + r.getRarity().getTag() + WordUtils.capitalizeFully(r.getName()) + ChatColor.GREEN + "."); switch(r.getRarity()){ case COMMON: break; case EPIC: Bukkit.getOnlinePlayers().forEach(player -> player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 1, 1)); GolemaBukkitDatabase.INSTANCE.redisPubSubSpigot.broadcastMessage(BoxPlugin.PREFIX + rank.getPrefix() + " " + gp.getPlayerRealName() + ChatColor.YELLOW + " viens d'obtenir " + r.getRarity().getTag() + " " + r.getName()); break; case LEGENDARY: box.getBoxLocation().getWorld().strikeLightningEffect(box.getBoxLocation()); Bukkit.getOnlinePlayers().forEach(player -> player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 1, 1)); GolemaBukkitDatabase.INSTANCE.redisPubSubSpigot.broadcastMessage(" "); GolemaBukkitDatabase.INSTANCE.redisPubSubSpigot.broadcastMessage(BoxPlugin.PREFIX + rank.getPrefix() + " " + gp.getPlayerRealName() + ChatColor.YELLOW + " viens d'obtenir " + r.getRarity().getTag() + " " + r.getName()); GolemaBukkitDatabase.INSTANCE.redisPubSubSpigot.broadcastMessage(" "); break; } if(!r.isAutomatic()){ p.sendMessage(BoxPlugin.PREFIX + "Vous pouvez des a present nous contacter en message privé sur twitter " + ChatColor.AQUA + " @GolemaMC" + ChatColor.YELLOW + " pour reclamer votre prix!"); } //open chest playChestAction(box.getBoxLocation(), true); holo2 = new HologramBuilder(); holo2.editLocation(box.getBoxLocation().clone().add(0.5, -0.5, 0.5)); holo2.editMessage(r.getRarity().getColor() + r.getName()); holo2.sendToPlayers(box.getBoxLocation().getWorld().getPlayers()); holo = new HologramBuilder(); holo.editLocation(box.getBoxLocation().clone().add(0.5, -1, 0.5)); holo.editMessage(r.getRarity().getColor() + r.getRarity().getFrench()); holo.sendToPlayers(box.getBoxLocation().getWorld().getPlayers()); stand.remove(); }else if(ticks > 150){ holo.destroyAllPlayers(); holo2.destroyAllPlayers(); playChestAction(box.getBoxLocation(), false); box.opening.remove(p.getUniqueId()); box.isUsed().set(false); cancel(); } } }.runTaskTimer(BoxPlugin.get(), 1, 1); } private static void playChestAction(Location location, boolean open) { World world = ((CraftWorld) location.getWorld()).getHandle(); BlockPosition position = new BlockPosition(location.getX(), location.getY(), location.getZ()); TileEntityEnderChest tileChest = (TileEntityEnderChest) world.getTileEntity(position); world.playBlockAction(position, tileChest.w(), 1, open ? 1 : 0); } private static Rank getRealRank(GolemaPlayer gp){ for(Rank r : Rank.values()){ if(r.getPower() == gp.getRankPower())return r; } return Rank.PLAYER; } }
c9584b599256ea93a3560ddee9758fd4d229272c
[ "Java" ]
7
Java
hugo4715/SantaBox
453538308b133d31c3b7966fee30dec704545ff1
643692605578655ccfb6ee1e55ae8c4f954850e4
refs/heads/main
<repo_name>vasiliy509/ogu-web-project<file_sep>/shop.ru/basket.php <?php session_start(); require_once "include/db.php"; require_once "include/function.php"; ?> <!DOCTYPE html> <html> <head> <title>Сайт</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <h2>Ваши товары:</h2> <?php $user = get_user_last_name($auth_session['last_name']); $basket_posts = get_basket_user($user['id']); ?> <?php foreach ($basket_posts as $basket_post): ?> <?php if ($basket_post['количество товара']!=0): ?> <?php $post = get_post_by_id($basket_post['id_товара']); ?> <table > <tr> <td colspan="4"> <h3 class="item"><a href="/post.php?post_id=<?=$post['id']?>"><?=$post['Наименование'] ?></a></h3><div>Кол-во: <?= $basket_post['количество товара']?></div><div>Цена всего: <?= $post['Цена']*$basket_post['количество товара'] ?></div> </td> </tr> <tr> <td> <div class="img"><img src="<?=$post['Картинка'] ?>"></div> </td> <td colspan="3"> <p class="item"><?=mb_substr($post['Описание'], 0, 128, 'UTF-8').' ...'?></p> <p class="item"><a href="/post.php?post_id=<?=$post['id']?>">Читать полностью</a></p> </td> </tr> </table> <br><br> <?php endif; $summa += $post['Цена']*$basket_post['количество товара']; ?> <?php endforeach ?> Итоговая сумма: <?= $summa ?> </section> </main> </body> </html><file_sep>/shop.ru/include/register_user_db.php <?php $link = new mysqli('localhost', 'root', 'root', 'register_bd'); $link->query('INSERT INTO 'users') ?><file_sep>/shop.ru/leftblock.php <div class = "leftblock"> <?php $categories = get_categories(); ?> <?php if ($user_role['role'] == 1): ?> <div class="action"><a href="add_category.php"> Добавить </a></div><br><br> <?php endif; ?> <table class="edit"> <?php foreach($categories as $category): ?> <tr> <td> <a href="/category.php?id=<?=$category['id']?>"><?=$category["title"]?></a> </td> <td> <?php if ($user_role['role'] == 1): ?> <a href="/edit.php?edit_category=<?=$category['id']?>"><img class="edit" src="images/edit.png"></a> <?php endif; ?> </td> </tr> <?php endforeach; ?> </table> </div><file_sep>/shop.ru/orders.php <?php session_start(); require_once "include/db.php"; require_once "include/function.php"; ?> <!DOCTYPE html> <html> <head> <title>Сайт</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <h2>Заказы пользователей:</h2> <?php $users=get_users()?> <ul> <?php foreach ($users as $user): ?> <li> <label class="description"><?=$user['last_name']?> <?=$user['first_name']?> <?=$user['patronymic']?></label> <?php $basket_posts = get_basket_user($user['id']); ?> <?php if (empty($basket_posts)): ?> <p>Заказов нет.</p> <?php else: ?> <table > <?php foreach ($basket_posts as $basket_post): ?> <?php if ($basket_post['количество товара']!=0): ?> <?php $post = get_post_by_id($basket_post['id_товара']); $category = get_category_name($post['category_id']); ?> <tr> <td> <a href="/post.php?post_id=<?=$post['id']?>"><?=$post['Наименование'] ?> (Кол-во: <?= $basket_post['количество товара']?>; Цена всего: <?= $post['Цена']*$basket_post['количество товара'] ?>)</a> <?php endif ?> <?php endforeach ?> <?php endif ?> </table> <br><br> </li> <?php endforeach ?> </ul> </section> </main> </body> </html><file_sep>/shop.ru/auth.php <?php session_start(); require_once "include/db.php"; require_once "include/function.php"; //Объявляем ячейку для добавления ошибок, которые могут возникнуть при обработке формы. $auth_session =& $_SESSION['auth_subsystem']; $last_name = filter_var(trim($_POST['last_name']), FILTER_SANITIZE_STRING); $password = filter_var(trim($_POST['password']), FILTER_SANITIZE_STRING); global $link; $password = md5($password."<PASSWORD>"); $result = $link->query("SELECT * FROM `users` WHERE `last_name` = '$last_name' AND `password` = '$<PASSWORD>'"); $user = $result->fetch_assoc(); if (count($user)>0) { $auth_session['last_name'] = $last_name; $auth_session['password'] = $<PASSWORD>; $auth_session['is_authorized'] = true; header('Location: index.php'); # перенаправление на главную страницу $link->close(); exit(); } else { $auth_session['is_authorized'] = false; header('Location: authorization.php?$auth_session["last_name"]'); # перенаправление на форму авторизации print_r("<p>Такой пользователь не найден!</p>"); $link->close(); exit(); } ?><file_sep>/shop.ru/forms/basket_new_post.php <?php require_once "../include/db.php"; require_once "../include/function.php"; // ищем товар по id в корзине, если такого товара нет, то записываем новую строчку товара // если такой товар есть, то изменяем количество товара в корзине if(isset($_GET['post_id']) and isset($_GET['user_id'])) { $id = $_GET['post_id']; $user_id = $_GET['user_id']; $post = set_basket($user_id, $id); header("Location: ".$_SERVER['HTTP_REFERER']); # перенаправление на предыдущую страницу $link->close(); exit(); } if(isset($_GET['del_id']) and isset($_GET['user_id'])) { $id = $_GET['del_id']; $user_id = $_GET['user_id']; del_basket_post($user_id, $id); header("Location: ".$_SERVER['HTTP_REFERER']); # перенаправление на предыдущую страницу $link->close(); exit(); } $link->close(); exit(); ?> <file_sep>/shop.ru/include/db.php <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", "<PASSWORD>" ); define("DB_NAME", "shop"); $link = @new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (mysqli_connect_errno()) { echo 'Ошибка подключения к БД ('.mysqli_connect_errno().'): '.mysqli_connect_eror(); exit(); } $auth_session['last_name'] = 'Викулов'; $auth_session['is_authorized'] = trye; ?><file_sep>/shop.ru/test.php <?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>Ошибка авторизации</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <h2>Ошибка авторизации</h2> <?php $auth_session['is_authorized'] = false; print_r("<p>Такой пользователь не найден!</p>"); exit("<a href="authorization.php">Авторизоваться</a>"); ?> </section> </main> </body> </html><file_sep>/shop.ru/add_category.php <?php require_once "include/db.php" ?><!-- --> <?php require_once "include/function.php"; ?> <!DOCTYPE html> <html> <head> <title>Сайт</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <h2>Добавление категории</h2> <form action="/forms/check_category.php" method="post"> <input type="text" class="form-control" name="category_name" id="category_name" placeholder="Введите название"><br><br> <button class="form" type="submit">Добавить категорию</button> </form > </section> </main> </body> </html><file_sep>/shop.ru/registration.php <?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>Регистрация</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <h2>Регистрация</h2> <form action="check.php" method="post"> <input type="text" class="form" name="last_name" id="last_name" placeholder="Введите фамилию"><br> <input type="text" class="form" name="first_name" id="first_name" placeholder="Введите имя"><br> <input type="text" class="form" name="patronymic" id="patronymic" placeholder="Введите отчество"><br> <input type="<PASSWORD>" class="form" name="password" id="password" placeholder="<PASSWORD> <PASSWORD>"><br> <button class="form">Зарегистрироваться</button> </form > </section> </main> </body> </html><file_sep>/shop.ru/brand.php <?php session_start(); require_once "include/db.php"; require_once "include/function.php"; ?> <!DOCTYPE html> <html> <head> <title>Сайт</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <h2>Список производителей</h2> <ul> <?php $brands=get_brands(); ?> <?php foreach ($brands as $brand): ?> <li> <table class="edit"> <tr> <td><label class="description"><?= $brand['Наименование'] ?></label></td> <td><a href="/edit.php?edit_brand=<?=$brand['id']?>"><img class="edit" src="images/edit.png"></a></td> </tr> </table> </li> <?php endforeach; ?> <li> <h2>Добавление</h2> </li> <form action="/forms/check_category.php" method="post"> <li> <input type="text" class="form-control" name="brand_name" id="brand_name" placeholder="Введите название"> </li> <li> <button class="form" type="submit">Добавить</button> </li> </form ><br> <form action="/forms/delete.php" method="post"> <li> <h2>Удаление</h2> </li> <?php $brands=get_brands(); ?> <li> <select class="form" name="brand"> <?php foreach ($brands as $brand): ?> <option value="<?= $brand['Наименование'] ?>" ><?= $brand['Наименование'] ?></option> <?php endforeach; ?> </select> </li> <li><br><button class="form" type="submit">Удалить</button> </form> </section> </main> </body> </html><file_sep>/shop.ru/check.php <?php session_start(); require_once "include/db.php"; $last_name = filter_var(trim($_POST['last_name']), FILTER_SANITIZE_STRING); $first_name = filter_var(trim($_POST['first_name']), FILTER_SANITIZE_STRING); $patronymic = filter_var(trim($_POST['patronymic']), FILTER_SANITIZE_STRING); $password = filter_var(trim($_POST['password']), FILTER_SANITIZE_STRING); if (mb_strlen($last_name) < 2 || mb_strlen($last_name) > 250) { echo "Недопустимая длина фамилии"; exit(); } else if (mb_strlen($first_name) < 2 || mb_strlen($first_name8) > 250) { echo "Недопустимая длина имени"; exit(); } else if (mb_strlen($patronymic) < 2 || mb_strlen($patronymic) > 50) { echo "Недопустимая длина отчества"; exit(); } else if (mb_strlen($password) < 6 || mb_strlen($password) > 180) { echo "Недопустимая длина пароля (от 6 до 8 символов)"; exit(); } global $link; $password = md5($password."<PASSWORD>"); $link->query("INSERT INTO `users` (`last_name`, `first_name`, `patronymic`, `password`) VALUES ('$last_name', '$first_name', '$patronymic', '$password')"); $link->close(); header('Location: index.php'); # перенаправление на главную страницу exit(); ?> <file_sep>/shop.ru/new_post.php <?php session_start(); require_once "include/db.php"; require_once "include/function.php"; ?> <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title>Добавление товара</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <h2>Добавление товара</h2> <form action="forms/check_post.php" method="post"> <ul> <li> <label class="description">Наименование </label> <input type="text" class="form" name="title" placeholder="Введите название"><br> </li> <li > <label class="description">Описание </label> <textarea class="form" name="description" id="textarea"> </textarea> </li><br> <li> <label class="description">Ссылка на фото товара </label> <input name="image" class="form" type="text" placeholder="Введите ссылку"> <br> </li> <li> <label class="description">В наличии </label> <input name="available" class="form" type="text" placeholder="Введите количество"> <br> </li> <li> <label class="description">Цена </label> <input name="price" class="form" type="text" placeholder="В рублях"><br> </li> <?php $brands=get_brands(); ?> <label class="description">Производитель</label><br> <?php foreach ($brands as $brand): ?> <li id="radio"> <input name="brand" class="radio" type="radio" id="brand_name" value="<?= $brand['id'] ?>"> <label ><?= $brand['Наименование'] ?></label> </li><?php endforeach; ?> <br> <?php $countries=get_countries() ?> <li> <label class="description">Страна производства</label> <div> <select class="form" name="country"> <option value="" selected="selected"></option> <?php foreach ($countries as $country): ?> <option value="<?= $country['id'] ?>" ><?= $country['Наименование'] ?></option> <?php endforeach; ?> </select> </div> <br> </li> <li> <label class="description" >Категория</label> <?php $categories=get_categories(); ?> <select class="form" name="category"> <option value="" selected="selected"></option> <?php foreach ($categories as $category): ?> <option value="<?= $category['id'] ?>" ><?= $category['title'] ?></option><?php endforeach; ?> </select> </li><br> <button class="form" type="submit">Добавить</button> </ul> </form> </section> </main> </body> </html><file_sep>/shop.ru/forms/del_category.php <?php require_once "../include/db.php"; require_once "../include/function.php"; if(isset($_GET['del'])) { $id = $_GET['del']; $delete = del_category($id); header('Location: ../index.php'); # перенаправление на главную страницу $link->close(); exit(); } $link->close(); exit(); ?> <file_sep>/shop.ru/forms/basket_plus.php <?php require_once "../include/db.php"; require_once "../include/function.php"; // ищем товар по id в корзине, если такого товара нет, то записываем новую строчку товара // если такой товар есть, то изменяем количество товара в корзине if(isset($_GET['post_id']) and isset($_GET['user_id'])) { $id = $_GET['post_id']; $user_id = $_GET['user_id']; set_basket_plus($user_id, $id); header("Location: ".$_SERVER['HTTP_REFERER']); # перенаправление на предыдущую страницу $link->close(); exit(); } $link->close(); exit(); ?> <file_sep>/shop.ru/post.php <?php session_start(); require_once "include/db.php"; require_once "include/function.php"; $post_id =$_GET['post_id']; ?> <!DOCTYPE html> <html> <head> <title>Сайт</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php"; $user_id = get_user_last_name($auth_session['last_name']); $post = get_post_by_id($post_id); $basket_post = get_basket($post_id, $user_id['id']); $post_basket = get_basket_post($post_id); ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <section class="item"> <div class="post"> <h2><?=$post['Наименование'] ?></h2> <div> <?php if ($user_role['role'] == 1): ?> <?php if($post_basket==NULL): ?> <a href="/forms/del_post.php?del=<?= $_GET['post_id'] ?>"> Удалить товар</a> <?php endif; ?> <?php endif; ?> </div> </div> <table> <tr> <td> <div class="img"><img src="<?=$post['Картинка'] ?>"></div> <div class="price"><h3>Цена: <?=$post['Цена'] ?> руб.</h3> </div> <div class="basket"> <?php if($auth_session['is_authorized'] == true and $user_role['role'] == 0): ?> <h4>В корзине:</h4> <?php if($basket_post==NULL): ?> <a href="/forms/basket_new_post.php?post_id=<?=$_GET['post_id'] ?>&user_id=<?= $user_id['id'] ?>"><img src="images/плюс.png"></a> <?php elseif ($basket_post['количество товара']==0): ?> <?= $basket_post['количество товара'] ?><br> <a href="/forms/basket_plus.php?post_id=<?= $_GET['post_id'] ?>&user_id=<?= $user_id['id'] ?>"><img src="images/плюс.png"></a> <?php elseif ($basket_post['количество товара']>1): ?> <?= $basket_post['количество товара'] ?><br> <a href="/forms/basket_minus.php?post_id=<?=$_GET['post_id'] ?>&user_id=<?= $user_id['id'] ?>"><img src="images/минус.png"></a> <a href="/forms/basket_plus.php?post_id=<?=$_GET['post_id']?>&user_id=<?= $user_id['id'] ?>"><img src="images/плюс.png"></a> <?php else: ?> <?= $basket_post['количество товара'] ?><br> <a href="/forms/basket_new_post.php?del_id=<?=$_GET['post_id'] ?>&user_id=<?= $user_id['id'] ?>"><img src="images/минус.png"></a> <a href="/forms/basket_plus.php?post_id=<?=$_GET['post_id'] ?>&user_id=<?= $user_id['id'] ?>"><img src="images/плюс.png"></a> <?php endif; ?> <?php endif; ?> </div> </td> <td colspan="3"> <p class="item"><?=$post['Описание'] ?></p> </td> </tr> <tr class="detalies"> <?php $brand = get_brand_name($post['Код производителя']); $country = get_country_name($post['Код страны']); $category = get_category_name($post['category_id']); ?> <td>Страна: <?= $country['Наименование'] ?></td> <td>Бренд: <?= $brand['Наименование'] ?></td> <td>Категория: <?= $category['title'] ?></td> <td>В начилии: <?= $post['В наличии'] ?></td> </tr> </table> </section> </main> </body> </html> <file_sep>/shop.ru/forms/check_post.php <?php require_once "../include/db.php"; require_once "../include/function.php"; $title = filter_var(trim($_POST['title']), FILTER_SANITIZE_STRING); $description = filter_var(trim($_POST['description']), FILTER_SANITIZE_STRING); $image = filter_var(trim($_POST['image']), FILTER_SANITIZE_STRING); $available = filter_var(trim($_POST['available']), FILTER_SANITIZE_STRING); $price = filter_var(trim($_POST['price']), FILTER_SANITIZE_STRING); $brand = $_POST['brand']; $country = $_POST['country']; $category = $_POST['category']; set_post($title,$description,$image,$available,$price,$brand,$country,$category); header('Location: ../index.php'); # перенаправление на другую страницу $link->close(); exit(); ?><file_sep>/shop.ru/forms/delete.php <?php require_once "../include/db.php"; require_once "../include/function.php"; if (isset($_POST['category_name'])) { $category_name = filter_var(trim($_POST['category_name']), FILTER_SANITIZE_STRING); $category = set_category($category_name); } if (isset($_POST['brand'])) { $brand = filter_var(trim($_POST['brand']), FILTER_SANITIZE_STRING); $brand = del_brand($brand); } if (isset($_POST['country'])) { $country = filter_var(trim($_POST['country']), FILTER_SANITIZE_STRING); $country = del_country($country); } header("Location: ".$_SERVER['HTTP_REFERER']); # перенаправление на предыдущую страницу exit(); ?><file_sep>/shop.ru/include/function.php <?php // запрос всех покупателей function get_users() { global $link; $sql = "SELECT * FROM `users` WHERE role=0"; $result = mysqli_query($link, $sql); $users = mysqli_fetch_all($result, MYSQLI_ASSOC); return $users; } // запрос всех категорий товара function get_categories() { global $link; $sql = "SELECT * FROM `группа инструмента`"; $result = mysqli_query($link, $sql); $categories = mysqli_fetch_all($result, MYSQLI_ASSOC); return $categories; } // запрос всех производителей function get_brands() { global $link; $sql = "SELECT * FROM `производитель`"; $result = mysqli_query($link, $sql); $brands = mysqli_fetch_all($result, MYSQLI_ASSOC); return $brands; } // запрос всех стран производства function get_countries() { global $link; $sql = "SELECT * FROM `страна производства`"; $result = mysqli_query($link, $sql); $countries = mysqli_fetch_all($result, MYSQLI_ASSOC); #var_dump($countries); return $countries; } // запрос последних 5 товаров для гравной страницы function get_posts() { global $link; $sql = "SELECT * FROM `товар` WHERE `В наличии`>0 ORDER BY id DESC LIMIT 5"; $result = mysqli_query($link, $sql); $posts = mysqli_fetch_all($result, MYSQLI_ASSOC); return $posts; } // запрос конкретного товара по id function get_post_by_id($post_id) { global $link; $post_id = mysqli_real_escape_string($link, $post_id); $sql = "SELECT * FROM товар WHERE id =".$post_id; $result = mysqli_query($link, $sql); $post = mysqli_fetch_assoc($result) ; return $post; } // запрос товаров в категории по id категории function get_posts_by_category_id($category_id) { global $link; $category_id = mysqli_real_escape_string($link, $category_id); $sql = "SELECT * FROM товар WHERE `В наличии`>0 AND category_id=".$category_id; $result = mysqli_query($link, $sql); $posts = mysqli_fetch_all($result, MYSQLI_ASSOC) ; return $posts; } // запрос страны производства по id function get_country_name($country_id) { global $link; $country_id = mysqli_real_escape_string($link, $country_id); $sql = "SELECT Наименование FROM `страна производства` WHERE id=" .$country_id; $result = mysqli_query($link, $sql); $country = mysqli_fetch_assoc($result);; return $country ; } // запрос производителя по id function get_brand_name($brand_id) { global $link; $brand_id = mysqli_real_escape_string($link, $brand_id); $sql = "SELECT Наименование FROM производитель WHERE id =" .$brand_id; $result = mysqli_query($link, $sql); $brand = mysqli_fetch_assoc($result); return $brand; } // запрос наименования категории товара по id категории function get_category_name($category_id) { global $link; $category_id = mysqli_real_escape_string($link, $category_id); $sql = "SELECT title FROM `группа инструмента` WHERE `id`=" .$category_id; $result = mysqli_query($link, $sql); $category = mysqli_fetch_assoc($result); return $category; } // запрос id пользователя по фамилии function get_user_last_name($user_last_name) { global $link; $sql = "SELECT `id` FROM `users` WHERE `last_name`='$user_last_name'"; $result = mysqli_query($link, $sql); $user = mysqli_fetch_assoc($result); return $user; } // запрос данных пользователя по id function get_user($user_id) { global $link; $sql = "SELECT * FROM `users` WHERE id=".$user_id; $result = mysqli_query($link, $sql); $user = mysqli_fetch_assoc($result); return $user; } // запрос роли пользователя по id function get_user_role($user_id) { global $link; $sql = "SELECT `role` FROM `users` WHERE id=".$user_id; $result = mysqli_query($link, $sql); $role = mysqli_fetch_assoc($result); return $role; } // запрос содержимого корзины покупателя function get_basket_user($user_id) { global $link; $sql = "SELECT * FROM `корзина` WHERE `user_id`=".$user_id; $result = mysqli_query($link, $sql); $posts = mysqli_fetch_all($result, MYSQLI_ASSOC); return $posts; } // добавление категории товара function set_category($category_set) { global $link; $category_set = mysqli_real_escape_string($link, $category_set); $sql = "INSERT INTO `группа инструмента` (`title`) VALUES ('$category_set')"; $result = mysqli_query($link, $sql); } // добавление производителя товара function set_brand($brand_set) { global $link; $brand_set = mysqli_real_escape_string($link, $brand_set); $sql = "INSERT INTO `производитель` (`наименование`) VALUES ('$brand_set')"; $result = mysqli_query($link, $sql); } // добавление страны производства function set_country($country_set) { global $link; #$country_set = mysqli_real_escape_string($link, $country_set); $sql = "INSERT INTO `страна производства` (`наименование`) VALUES ('$country_set')"; $result = mysqli_query($link, $sql); } // добавление товара function set_post($title,$description,$image,$available,$price,$brand,$country,$category) { global $link; $sql = "INSERT INTO `товар`(`Наименование`, `Описание`, `Картинка`, `В наличии`, `Цена`, `Код производителя`, `Код страны`, `category_id`) VALUES ('$title','$description','$image','$available','$price','$brand','$country','$category')"; $result = mysqli_query($link, $sql); } // добавление товара в корзину function set_basket($user_id, $id_post) { global $link; $sql = "INSERT INTO `корзина`(`user_id`, `id_товара`, `количество товара`) VALUES ('$user_id','$id_post', '1')"; mysqli_query($link, $sql); } // редактирование категории товара function edit_category($category_name, $id_category) { global $link; $category_name = mysqli_real_escape_string($link, $category_name); $sql = "UPDATE `группа инструмента` SET `title`='$category_name' WHERE id='$id_category'"; $result = mysqli_query($link, $sql); } // редактирование производителя товара function edit_brand($brand_name, $id_brand) { global $link; $brand_name = mysqli_real_escape_string($link, $brand_name); $sql = "UPDATE `производитель` SET `Наименование`='$brand_name' WHERE id='$id_brand'"; $result = mysqli_query($link, $sql); } // редактирование страны производства function edit_country($country_name, $id_country) { global $link; $country_name = mysqli_real_escape_string($link, $country_name); $sql = "UPDATE `страна производства` SET `Наименование`='$country_name' WHERE id='$id_country'"; $result = mysqli_query($link, $sql); } // редактирование товара function edit_post($title,$description,$image,$available,$price,$brand,$country,$category) { global $link; $sql = "INSERT INTO `товар`(`Наименование`, `Описание`, `Картинка`, `В наличии`, `Цена`, `Код производителя`, `Код страны`, `category_id`) VALUES ('$title','$description','$image','$available','$price','$brand','$country','$category')"; $result = mysqli_query($link, $sql); } // удаление категории товара function del_category($id) { global $link; $id = mysqli_real_escape_string($link, $id); $sql = "DELETE FROM `группа инструмента` WHERE id='$id'"; $result = mysqli_query($link, $sql); return $result; } // удаление товара по id function del_post($post_id) { global $link; $post_id = mysqli_real_escape_string($link, $post_id); $sql = "DELETE FROM `товар` WHERE id='$post_id'"; $result = mysqli_query($link, $sql); return $result; } // удаление производителя товара function del_brand($brand) { global $link; $brand = mysqli_real_escape_string($link, $brand); $sql = "DELETE FROM `производитель` WHERE Наименование='$brand'"; $result = mysqli_query($link, $sql); return $result; } // удаление страны производителя function del_country($country) { global $link; $country = mysqli_real_escape_string($link, $country); $sql = "DELETE FROM `страна производства` WHERE Наименование='$country'"; $result = mysqli_query($link, $sql); return $result; } // удаление товара из корзины function del_basket_post($user_id, $id_post) { global $link; $sql = "DELETE FROM `корзина` WHERE `корзина`.`id_товара`='$id_post' and `user_id`='$user_id'"; $result = mysqli_query($link, $sql); } // увеличение на единицу количества товара в корзине function set_basket_plus($user_id, $id_post) { global $link; $sql = "UPDATE`корзина` SET `количество товара`=`количество товара`+1 WHERE `id_товара`='$id_post' and `user_id`='$user_id'"; $result = mysqli_query($link, $sql); } // уменьшение на единицу количества товара в корзине function set_basket_minus($user_id, $id_post) { global $link; $sql = "UPDATE`корзина` SET `количество товара`=`количество товара`-1 WHERE `id_товара`='$id_post' and `user_id`='$user_id'"; $result = mysqli_query($link, $sql); } // проверка корзины на наличие товара по id товара и id покупателя function get_basket($post_id, $user_id) { global $link; $sql = "SELECT `количество товара` FROM `корзина` WHERE `id_товара`='$post_id' and `user_id`='$user_id'"; $result = mysqli_query($link, $sql); $post = mysqli_fetch_assoc($result); return $post; } // проверка корзины на наличие товара по id товара function get_basket_post($post_id) { global $link; $sql = "SELECT `количество товара` FROM `корзина` WHERE `id_товара`='$post_id'"; $result = mysqli_query($link, $sql); $post = mysqli_fetch_assoc($result); return $post; } ?><file_sep>/shop.ru/connection.php <?php try{ $pdo = new PDO('mysql:host=localhost; dbname=shop', 'root', 'root'); } catch (PDOException $e) { echo "Невозможно установить соединение с базой данных"; } ?><file_sep>/shop.ru/forms/check_category.php <?php require_once "../include/db.php"; require_once "../include/function.php"; if (isset($_POST['category_name'])) { $category_name = filter_var(trim($_POST['category_name']), FILTER_SANITIZE_STRING); $category = set_category($category_name); } if (isset($_POST['edit_category'])) { $edit_category = filter_var(trim($_POST['edit_category']), FILTER_SANITIZE_STRING); $id_category = $_POST['id_category']; $category = edit_category($edit_category, $id_category); } if (isset($_POST['brand_name'])) { $brand_name = filter_var(trim($_POST['brand_name']), FILTER_SANITIZE_STRING); $brand = set_brand($brand_name); } if (isset($_POST['edit_brand'])) { $edit_name = filter_var(trim($_POST['edit_brand']), FILTER_SANITIZE_STRING); $id_brand = $_POST['id_brand']; $brand = edit_brand($edit_name, $id_brand); header('Location: ../brand.php'); # перенаправление на главную страницу $link->close(); exit(); } if (isset($_POST['country_name'])) { $country_name = filter_var(trim($_POST['country_name']), FILTER_SANITIZE_STRING); $country = set_country($country_name); } if (isset($_POST['edit_country'])) { $edit_name = filter_var(trim($_POST['edit_country']), FILTER_SANITIZE_STRING); $id_country = $_POST['id_country']; $country = edit_country($edit_name, $id_country); header('Location: ../country.php'); # перенаправление на главную страницу $link->close(); exit(); } header("Location: ".$_SERVER['HTTP_REFERER']); # перенаправление на предыдущую страницу $link->close(); exit(); ?> <file_sep>/shop.ru/edit.php <?php require_once "include/db.php"; require_once "include/function.php"; $id_category = $_GET['edit_category']; $id_brand = $_GET['edit_brand']; $id_country = $_GET['edit_country']; ?> <!DOCTYPE html> <html> <head> <title>Сайт</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header class="container"> <?php include "header.php" ?> </header> <main class="container"> <nav class="item"> <?php include "leftblock.php" ?> </nav> <?php if (isset($_GET['edit_category'])): ?> <section class="item"> <h2>Редактирование категории <?php print_r(get_category_name($id_category)['title']) ?></h2> <form action="/forms/check_category.php" method="post"> <input type="hidden" name="id_category" value="<?php echo $id_category ?>"> <input type="text" class="form-control" name="edit_category" id="edit_category" placeholder="Введите название"><br><br> <button class="form" type="submit">Отправить</button> </form > </section> <?php endif ?> <?php if (isset($_GET['edit_brand'])): ?> <section class="item"> <h2>Редактирование производителя <?php print_r(get_brand_name($id_brand)['Наименование']) ?></h2> <form action="/forms/check_category.php" method="post"> <input type="hidden" name="id_brand" value="<?php echo $id_brand ?>"> <input type="text" class="form-control" name="edit_brand" id="edit_brand" placeholder="Введите название"><br><br> <button class="form" type="submit">Отправить</button> </form > </section> <?php endif ?> <?php if (isset($_GET['edit_country'])): ?> <section class="item"> <h2>Редактирование страны производства <?php print_r(get_country_name($id_country)['Наименование']) ?></h2> <form action="/forms/check_category.php" method="post"> <input type="hidden" name="id_country" value="<?php echo $id_country ?>"> <input type="text" class="form-control" name="edit_country" id="edit_country" placeholder="Введите название"><br><br> <button class="form" type="submit">Отправить</button> </form > </section> <?php endif ?> </main> </body> </html><file_sep>/shop.ru/header.php <?php require_once "include/db.php"; require_once "include/function.php"; if($auth_session['is_authorized'] == true){ $user = get_user_last_name($auth_session['last_name']); $user_role = get_user_role($user['id']); } ?> <div class = "item"> <a href="index.php"><img class="logo" src="images/logo.png"></a> </div> <nav class = "item"> <?php if ($user_role['role'] == 0): ?> <ul> <!--<li class="button"><a href="index.php">Главная</a></li>--> <?php if($auth_session['is_authorized'] == true): ?> <li class="button"><a href="basket.php">Корзина</a></li> <?php endif ?> </ul> <?php elseif ($user_role['role'] == 1): ?> <ul> <li class="button"><a href="orders.php">Просмотр заказов</a></li> <li class="button"><a href="brand.php">Производители</a></li> <li class="button"><a href="country.php">Страны производства</a></li> </ul> <?php endif ?> </nav> <div class="user"> <?php if($auth_session['is_authorized'] == true): ?> <div> <?php if($user_role['role'] == 1) echo "Администратор <br>"; else echo "Покупатель <br>"; echo $auth_session['last_name']; ?> </div> <br> <div> <a href="exit.php" >Выйти</a> </div> <?php else: ?> <div> <img src="images/user-profile-icons.png"> <a href="authorization.php" >Войти</a> </div> <div> <a href="registration.php">Регистрация</a> </div> <?php endif ?> </div>
d4fec7ef954da16c64739dc0be436fe1ff36d92a
[ "PHP" ]
23
PHP
vasiliy509/ogu-web-project
a8f6b2f8352d6fb6c864f2acb065fe76c7baa5ea
cf6039678232c174c0168f2d0bf0b7de64dc0093
refs/heads/master
<repo_name>sdgit14/run_analysis<file_sep>/README.md ## run_analysis This project is part of "Getting and Cleaning Data Course". This repository has code to download and transform the data collected from the accelerometers from the Samsung Galaxy S smartphone. The data can be obtained from from [here](https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip ). Documentation is available [here](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones). The code run_analysis.R downloads the data and creates an output of tidy.txt. The details of the extract and transformation are available in CodeBook.md <file_sep>/CodeBook.md ## CodeBook.md ### Data Processing 1. The data set is available [here](https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip ). 2. Documentation is available [here](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones). 3. Download the zip file using download.file function and unzip the file. 4. The data files are whitespace delimited files. They are read using read.table function. 5. The data set has the following files: - activity_labels.txt: This file contains the labels for various activities. - features.txt: This file contains the labels for the various features. - subject_train.txt: Identifies the subjects for Training data set. - y_train.txt: Acitivity identifier for training data set. - X_train.txt: Feature vector for training data set. - subject_test.txt: Identifies the subjects for test data set. - y_test.txt: Acitivity identifier for test data set. - X_test.txt: Feature vector for test data set. 6. Training and test data sets are first merged: - X_train and X_test are merged using rbind. - y_train and y_test are merged using rbind. - subject_train and subject_test are merged using rbind. 7. Assign colnames to merged X using features 8. Assign colnames to merged y using activity labels. 9. Extract required columns from X using grep into data. Grep for mean|std to get the required columns. 10. Merge data, y, and subject. 11. Summarise the data using summarise_each function and grouping by Activity label and Subject id. Apply the function mean to each column in the data frame. 12. Write the output to tidy.txt using write.table. ### Variables **Information from the documentation [site](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones)** #### Description of Data The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data. The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window). The sensor acceleration signal, which has gravitational and body motion components, was separated using a Butterworth low-pass filter into body acceleration and gravity. The gravitational force is assumed to have only low frequency components, therefore a filter with 0.3 Hz cutoff frequency was used. From each window, a vector of features was obtained by calculating variables from the time and frequency domain. #### Attributes in the dataset: For each record in the dataset it is provided: - Triaxial acceleration from the accelerometer (total acceleration) and the estimated body acceleration. - Triaxial Angular velocity from the gyroscope. - A 561-feature vector with time and frequency domain variables. - Its activity label. - An identifier of the subject who carried out the experiment.<file_sep>/run_analysis.R library(dplyr) # Set working directory setwd("C:/coursera/Getting and Cleaning Data/Project") # Download the file from the Url fileUrl = "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" dFile = "getdata-projectfiles-UCI HAR Dataset.zip" download.file(fileUrl, dFile) # Unzip the file unzip(dFile) # Set Working drectory to UCI HAR Dataset setwd("C:/coursera/Getting and Cleaning Data/Project/UCI HAR Dataset") # Read Activity labels activity <- read.table("activity_labels.txt", col.names = c("ActivityId", "ActivityNm")) # Read Feature labels features <- read.table("features.txt", col.names = c("FeatureId", "FeatureNm")) # Read subjects test_subject <- read.table("test/subject_test.txt", col.names = c("SubjectId") ) train_subject <- read.table("train/subject_train.txt", col.names = c("SubjectId") ) # Merge subjects - train and then test subject <- rbind(train_subject, test_subject) # Read y test_y <- read.table("test/y_test.txt", col.names = c("ActivityId") ) train_y <- read.table("train/y_train.txt", col.names = c("ActivityId") ) # Merge y all_y <- rbind(train_y, test_y) y <- inner_join(activity, all_y, by = "ActivityId") # Read X test_x <- read.table("test/X_test.txt") train_x <- read.table("train/X_train.txt") x <- rbind(train_x, test_x) colnames(x) <- features[, 2] # Extract only the required columns - mean and std data <- x[, grep("mean|std", colnames(x))] # Column Bind Data, subject and Activity data <- cbind(data, subject, y) # Compute average for all measures for each group of Activity and subject avg_data <- summarise_each( group_by(data, ActivityNm, SubjectId), funs(mean) ) # Write the data to a file with col headers and a white space as sep write.table(avg_data, "../tidy.txt", row.names = FALSE)
537dc982093af8e524f3df47dd031bb50d7ab980
[ "Markdown", "R" ]
3
Markdown
sdgit14/run_analysis
7401c009e8dbfb9a9b1bc182e9bc2aa6f9e9d39f
30e9a95158452ceb92006e1dea3c45444168e201
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity; using DaVenti.Models; namespace DaVenti.Controllers { [Authorize] public class PromoController : Controller { // GET: Promo public ActionResult Index() { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Promoes.ToList()); } } // GET: Promo/Details/5 public ActionResult Details(string id) { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Promoes.Where(x => x.id_promo == id).FirstOrDefault()); } } // GET: Promo/Create public ActionResult Create() { return View(); } // POST: Promo/Create [HttpPost] public ActionResult Create(Promo promo) { try { // TODO: Add insert logic here using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { dBEntities.Promoes.Add(promo); dBEntities.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } // GET: Promo/Edit/5 public ActionResult Edit(string id) { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Promoes.Where(x => x.id_promo == id).FirstOrDefault()); } } // POST: Promo/Edit/5 [HttpPost] public ActionResult Edit(string id, Promo promo) { try { // TODO: Add update logic here using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { dBEntities.Entry(promo).State = EntityState.Modified; dBEntities.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } // GET: Promo/Delete/5 public ActionResult Delete(string id) { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Promoes.Where(x => x.id_promo == id).FirstOrDefault()); } } // POST: Promo/Delete/5 [HttpPost] public ActionResult Delete(string id, FormCollection collection) { try { // TODO: Add delete logic here using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { Promo promo = dBEntities.Promoes.Where(x => x.id_promo == id).FirstOrDefault(); dBEntities.Promoes.Remove(promo); dBEntities.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace DaVenti.Models { public class Login { [Display(Name = "Email")] [DataType(DataType.EmailAddress)] [Required(AllowEmptyStrings = false, ErrorMessage = "Email required")] public string email_emp { get; set; } [Display(Name = "Password")] [DataType(DataType.Password)] [Required(AllowEmptyStrings = false, ErrorMessage = "Password required")] public string password_emp { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using DaVenti.Models; using System.Data.Entity; namespace DaVenti.Controllers { public class CategoryController : Controller { // GET: Category public ActionResult Index() { using (DaVentiDBEntities en = new DaVentiDBEntities()) { return View(en.Categories.ToList()); } } // GET: Category/Create public ActionResult Create() { return View(); } // POST: Category/Create [HttpPost] public ActionResult Create(Category category) { try { using (DaVentiDBEntities en = new DaVentiDBEntities()) { en.Categories.Add(category); en.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } // GET: Category/Edit/5 public ActionResult Edit(string id) { using (DaVentiDBEntities en = new DaVentiDBEntities()) { return View(en.Categories.Where(x => x.id_category == id).FirstOrDefault()); } } // POST: Category/Edit/5 [HttpPost] public ActionResult Edit(string id, Category category) { try { using (DaVentiDBEntities en = new DaVentiDBEntities()) { en.Entry(category).State = EntityState.Modified; en.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } // GET: Default/Delete/5 public ActionResult Delete(string id) { using (DaVentiDBEntities en = new DaVentiDBEntities()) { return View(en.Categories.Where(x => x.id_category == id).FirstOrDefault()); } } // POST: Default/Delete/5 [HttpPost] public ActionResult Delete(string id, FormCollection collection) { try { using (DaVentiDBEntities en = new DaVentiDBEntities()) { Category category = en.Categories.Where(x => x.id_category == id).FirstOrDefault(); en.Categories.Remove(category); en.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace DaVenti.Models { [MetadataType(typeof(EmployeeMetaData))] public partial class Employee { public string confirm_password_emp { get; set; } } public class EmployeeMetaData { [Display(Name = "Email")] [DataType(DataType.EmailAddress)] [Required(AllowEmptyStrings = false, ErrorMessage = "Email required")] public string email_emp { get; set; } [Display(Name = "Password")] [DataType(DataType.Password)] [Required(AllowEmptyStrings = false, ErrorMessage = "Password required")] public string password_emp { get; set; } [Display(Name = "Confirm Password")] [DataType(DataType.Password)] [Compare("password_emp", ErrorMessage = "Password do not match")] public string confirm_password_emp { get; set; } [Display(Name = "Name")] [Required(AllowEmptyStrings = false, ErrorMessage = "Name required")] public string name_emp { get; set; } [Display(Name = "Gender")] [Required(AllowEmptyStrings = false, ErrorMessage = "Gender required")] public string gender { get; set; } [Display(Name = "Phone Number")] [DataType(DataType.PhoneNumber)] [Required(AllowEmptyStrings = false, ErrorMessage = "Phone number required")] public string phone_num_emp { get; set; } [Display(Name = "Role")] [Required(AllowEmptyStrings = false, ErrorMessage = "Role required")] public string role { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity; using DaVenti.Models; namespace DaVenti.Controllers { [Authorize] public class BookController : Controller { // GET: Book public ActionResult Index() { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Books.ToList()); } } // GET: Book/Details/5 public ActionResult Details(string id) { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Books.Where(x => x.id_book == id).FirstOrDefault()); } } // GET: Book/Create public ActionResult Create() { return View(); } // POST: Book/Create [HttpPost] public ActionResult Create(Book book) { try { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { dBEntities.Books.Add(book); dBEntities.SaveChanges(); } // TODO: Add insert logic here ViewBag.Message = "Book added"; return RedirectToAction("Index"); } catch { return View(); } } // GET: Book/Edit/5 public ActionResult Edit(string id) { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Books.Where(x => x.id_book == id).FirstOrDefault()); } } // POST: Book/Edit/5 [HttpPost] public ActionResult Edit(string id, Book book) { try { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { dBEntities.Entry(book).State = EntityState.Modified; dBEntities.SaveChanges(); } // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Book/Delete/5 public ActionResult Delete(string id) { using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { return View(dBEntities.Books.Where(x => x.id_book == id).FirstOrDefault()); } } // POST: Book/Delete/5 [HttpPost] public ActionResult Delete(string id, FormCollection collection) { try { // TODO: Add delete logic here using (DaVentiDBEntities dBEntities = new DaVentiDBEntities()) { Book book = dBEntities.Books.Where(x => x.id_book == id).FirstOrDefault(); dBEntities.Books.Remove(book); dBEntities.SaveChanges(); } return RedirectToAction("Index"); } catch { return View(); } } } } <file_sep>using DaVenti.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace DaVenti.Controllers { public class AuthController : Controller { // GET registration [HttpGet] public ActionResult Registration() { return View(); } // POST registration [HttpPost] [ValidateAntiForgeryToken] public ActionResult Registration(Employee employee) { bool Status = false; string message = ""; // model validation if (ModelState.IsValid) { #region email already exist var isExist = IsEmailExist(employee.email_emp); if (isExist) { ModelState.AddModelError("EmailExist", "Email already exist"); return View(employee); } #endregion #region saving to database using(DaVentiDBEntities en = new DaVentiDBEntities()) { en.Employees.Add(employee); en.SaveChanges(); message = "Registration successful. Welcome abroad!"; Status = true; } #endregion } else { message = "Invalid request"; } ViewBag.Message = message; ViewBag.Status = Status; return View(employee); } [HttpGet] public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(Login login) { string message = ""; using (DaVentiDBEntities en = new DaVentiDBEntities()) { var check = en.Employees.Where(a => a.email_emp == login.email_emp).FirstOrDefault(); if(check != null) { if(string.Compare(login.password_emp, check.password_emp) == 0) { FormsAuthentication.SetAuthCookie(login.email_emp, false); return RedirectToAction("Index", "Home"); } else { message = "Wrong email or password!"; } } else { message = "Invalid credentials!"; } } ViewBag.Message = message; return View(); } [Authorize] public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToAction("Login", "Auth"); } [NonAction] public bool IsEmailExist(string email) { using (DaVentiDBEntities en = new DaVentiDBEntities()) { var check = en.Employees.Where(a => a.email_emp == email).FirstOrDefault(); return check != null; } } } }
ade51ccb743e9532281736c6401bde1fad2eff19
[ "C#" ]
6
C#
codestellations/WEBPRO_quiz2
4cfd39ba636519e999db6acfd693d777afdcf297
f24af7bc29f9dd95b0431755c0abd50eab979301
refs/heads/master
<repo_name>huangtaosdt/Visualizing-The-Gender-Gap-In-College-Degrees<file_sep>/visualize.py # coding: utf-8 # In[10]: #------------------------Reading file----------------------- import pandas as pd data=pd.read_csv('./data/percent-bachelors-degrees-women-usa.csv') #------------------------Plotting line charts----------------------- def decorateAxes(axes): for key,spine in axes.spines.items(): spine.set_visible(False) axes.set_ylim(0, 100) axes.set_yticks([0,100]) axes.axhline(y=50,c=(171/255, 171/255, 171/255),alpha=0.3) axes.tick_params(left='off',right='off',top='off',bottom='off',labelbottom='off') def plotCharts(axes,sub_cats,index): axes.plot(data['Year'],data[sub_cats[index]],c=cb_dark_blue,label='Women',linewidth=3) axes.plot(data['Year'],100-data[sub_cats[index]],c=cb_orange,label='Men',linewidth=3) for key,spine in axes.spines.items(): spine.set_visible(False) axes.set_title(sub_cats[index]) decorateAxes(axes) if index==(len(sub_cats)-1): axes.tick_params(labelbottom='on') import matplotlib.pyplot as plt get_ipython().magic('matplotlib inline') #Group degrees into three category. sc_cats = ['Psychology', 'Biology', 'Math and Statistics', 'Physical Sciences', 'Computer Science', 'Engineering'] lib_arts_cats = ['Foreign Languages', 'English', 'Communications and Journalism', 'Art and Performance', 'Social Sciences and History'] other_cats = ['Health Professions', 'Public Administration', 'Education', 'Agriculture','Business', 'Architecture'] fig=plt.figure(figsize=(16,16)) cb_dark_blue = (0/255,107/255,164/255) cb_orange = (255/255, 128/255, 14/255) for i in range(1,17,3): #Generate first column in line charts.Science degrees. sc_cats_index=int(i/3) ax=fig.add_subplot(6,3,i) plotCharts(ax,sc_cats,sc_cats_index) if i==1: ax.text(2003, 85, 'Women') ax.text(2005, 10, 'Men') if i==16: ax.text(2005, 87, 'Men') ax.text(2003, 7, 'Women') #Generate second column in line charts.Liberal arts degrees. t=i+1 if t<15: lib_arts_cats_index=int(t/3) ax2=fig.add_subplot(6,3,t) plotCharts(ax2,lib_arts_cats,lib_arts_cats_index) if t==2: ax2.text(2003, 85, 'Women') ax2.text(2005, 10, 'Men') #Generate third column in line charts.Other degrees. r=i+2 other_cats_index=int((r-1)/3) ax3=fig.add_subplot(6,3,r) plotCharts(ax3,other_cats,other_cats_index) if r==3: ax3.text(2003, 90, 'Women') ax3.text(2005, 5, 'Men') if r==18: ax3.text(2005, 62, 'Men') ax3.text(2003, 30, 'Women')
890316a08d32a29503faa486e022df8dcaca9fc6
[ "Python" ]
1
Python
huangtaosdt/Visualizing-The-Gender-Gap-In-College-Degrees
b6a33d442650a0dad2de7886a66e3b3a49cd75b2
cf5101c95e356da5152077cbae345edb2868fa67
refs/heads/master
<repo_name>davelet/graphql<file_sep>/src/main/java/com/example/graphql/graphql/BookSearchController.java package com.example.graphql.graphql; import java.io.File; import java.io.IOException; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import graphql.schema.idl.RuntimeWiring; import graphql.schema.idl.SchemaGenerator; import graphql.schema.idl.SchemaParser; import graphql.schema.idl.TypeDefinitionRegistry; @RestController @RequestMapping("/bookstore") public class BookSearchController { @Autowired private BookService service; // load graphqls file @Value("classpath:book.schema") private Resource schemaResource; @Autowired private AllBookDataFetcher allBookDataFetcher; @Autowired private BookDataFetcher bookDataFetcher; private GraphQL graphQL; // load schema at application start up @PostConstruct public void loadSchema() throws IOException { // get the schema File schemaFile = schemaResource.getFile(); // parse schema TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(schemaFile); RuntimeWiring wiring = buildRuntimeWiring(); GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring); graphQL = GraphQL.newGraphQL(schema).build(); } private RuntimeWiring buildRuntimeWiring() { return RuntimeWiring.newRuntimeWiring() .type("Query", typeWiring -> typeWiring.dataFetcher("allBooks", allBookDataFetcher).dataFetcher("book", bookDataFetcher)) .build(); } @GetMapping("/booksList") public List<Book> getBooksList() { return service.findAllBooks(); } /* * In PostMan use Post URL: localhost:8080/bookstore/getAllBooks and Body: * query{ allBooks{ bookId, bookName } } */ @PostMapping("/getAllBooks") public ResponseEntity<Object> getAllBooks(@RequestBody String query) { ExecutionResult result = graphQL.execute(query); return new ResponseEntity<Object>(result, HttpStatus.OK); } @GetMapping("/search/{bookId}") public Book getBookInfo(@PathVariable String movieId) { return service.findBookById(movieId); } @PostMapping("/getBookById") public ResponseEntity<Object> getBookById(@RequestBody String query) { ExecutionResult result = graphQL.execute(query); return new ResponseEntity<Object>(result, HttpStatus.OK); } }<file_sep>/README.md # graphql GraphQL是Facebook开发的一套微服务API,用于代替REST方案。 在REST中,通过不同的http行为区分用户动作,及时相同的uri搭配不同的行为,内部逻辑也差别迥异。GraphQL(Graph + Query Language)中,由客户端决定自己需要的数据:这就是客户端发送请求服务端响应数据的原因。《[RPC vs REST vs GraphQL](https://segmentfault.com/a/1190000013961872)》中介绍了REST和GraphQL的差别。[官方首页](http://graphql.cn/)的动态展示会让你更了解GraphQL。 这是一个例子,一个使用spring boot搭建的简易网上书店。 <file_sep>/src/main/java/com/example/graphql/graphql/AllBookDataFetcher.java package com.example.graphql.graphql; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; @Component public class AllBookDataFetcher implements DataFetcher<List<Book>> { @Autowired private BookRepository repository; @Override public List<Book> get(DataFetchingEnvironment environment) { return repository.findAll(); } }<file_sep>/src/main/java/com/example/graphql/graphql/BookDataFetcher.java package com.example.graphql.graphql; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; @Component public class BookDataFetcher implements DataFetcher<Book> { @Autowired private BookRepository repository; @Override public Book get(DataFetchingEnvironment environment) { String movieId = environment.getArgument("id"); return repository.findOne(movieId); } }
a3bd27d62f1bf6a64009129458397dd32d14eef5
[ "Markdown", "Java" ]
4
Java
davelet/graphql
a24d36962685a3bafed384c74e858ee367076d5a
2111aa272b32d229ec2bfeeb0d933ffd4a93f9f9
refs/heads/master
<repo_name>mcrider/thingy<file_sep>/models/properties/partOfSeries.js var mongoose = require('mongoose') var Schema = mongoose.Schema; var schema = new Schema({ value: { type: Schema.Types.ObjectId, ref: "Series" } }); module.exports = mongoose.model('partOfSeries', schema);<file_sep>/models/things/DietarySupplement.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ activeIngredient: { type: Schema.Types.ObjectId, ref: 'activeIngredient' }, background: { type: Schema.Types.ObjectId, ref: 'background' }, dosageForm: { type: Schema.Types.ObjectId, ref: 'dosageForm' }, isProprietary: { type: Schema.Types.ObjectId, ref: 'isProprietary' }, legalStatus: { type: Schema.Types.ObjectId, ref: 'legalStatus' }, manufacturer: { type: Schema.Types.ObjectId, ref: 'manufacturer' }, maximumIntake: { type: Schema.Types.ObjectId, ref: 'maximumIntake' }, mechanismOfAction: { type: Schema.Types.ObjectId, ref: 'mechanismOfAction' }, nonProprietaryName: { type: Schema.Types.ObjectId, ref: 'nonProprietaryName' }, recommendedIntake: { type: Schema.Types.ObjectId, ref: 'recommendedIntake' }, safetyConsideration: { type: Schema.Types.ObjectId, ref: 'safetyConsideration' }, targetPopulation: { type: Schema.Types.ObjectId, ref: 'targetPopulation' }, adverseOutcome: { type: Schema.Types.ObjectId, ref: 'adverseOutcome' }, contraindication: { type: Schema.Types.ObjectId, ref: 'contraindication' }, duplicateTherapy: { type: Schema.Types.ObjectId, ref: 'duplicateTherapy' }, indication: { type: Schema.Types.ObjectId, ref: 'indication' }, seriousAdverseOutcome: { type: Schema.Types.ObjectId, ref: 'seriousAdverseOutcome' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, code: { type: Schema.Types.ObjectId, ref: 'code' }, guideline: { type: Schema.Types.ObjectId, ref: 'guideline' }, medicineSystem: { type: Schema.Types.ObjectId, ref: 'medicineSystem' }, recognizingAuthority: { type: Schema.Types.ObjectId, ref: 'recognizingAuthority' }, relevantSpecialty: { type: Schema.Types.ObjectId, ref: 'relevantSpecialty' }, study: { type: Schema.Types.ObjectId, ref: 'study' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('DietarySupplement', schema);<file_sep>/models/index.js // Loop over all files in this folder and require each model var fs = require("fs"), path = require("path"); var properties = {}; var startTime = new Date().getTime(); fs.readdir(__dirname, function (err, files) { if (err) { throw err; } files.map(function (file) { return path.join(__dirname, file); }).filter(function (file) { return fs.statSync(file).isFile(); }).forEach(function (file) { var modelName = file.substr(0, file.lastIndexOf('.')).replace(/^.*[\\\/]/, ''); if (modelName !== 'index') { properties[modelName] = require(file); } }); var endTime = new Date().getTime(); console.log('Property models loaded (' + (endTime - startTime) + 'ms)'); }); module.exports = properties;<file_sep>/routes.js // Define the routes for lucien var express = require('express'); module.exports = (function() { 'use strict'; var api = express.Router(); // Include all our models var models = {}; models.properties = require('./models/properties'); models.things = require('./models/things'); //** Things are objects made up of properties (which can be values or other things) // Get a thing by its ID api.get('/thing/:id.:format?', function(req, res) { if (req.params.format == 'json') { res.send('json - by id'); } else if (req.params.format == 'rdf') { // Todo: Use library to convert JSON-LD to RDFa res.send('rdfa - by id'); } else { // Todo: Strip attributes from RDF? res.send('html - by id'); } }); // Get all things of a given type api.get('/things/:type.:format?', function(req, res) { // Extract the suffix manually (FIXME: Is there a way to do this with the router regex?) // var regex = /(?:\.([^.]+))?$/; // var suffix = regex.exec(req.params[0]); // if (!suffix) { // res.send('html - by type'); // } else if (suffix == 'json') { // res.send('json - by type'); // } else if (suffix == 'rdfa') { // res.send('rdfa - by type'); // } console.log(models.things[req.params.type]); // Todo: .find() things with the requested type and return in various formats // Assuming no hierarchy for types in the URL: if (req.params.format == 'json') { res.send('json - by type. Type = ' + req.params.type); } else if (req.params.format == 'rdf') { // Todo: Use library to convert JSON-LD to RDFa res.send('rdfa - by type. Type = ' + req.params.type); } else { res.send('html - by type. Type = ' + req.params.type); } }); //** Properties are values that have a many to many relationship with things // Get a property by its ID api.get('/property/:id.:format?', function(req, res) { if (req.params.format == 'json') { res.send('property json - by id'); } else if (req.params.format == 'rdf') { // Todo: Use library to convert JSON-LD to RDFa res.send('property property rdfa - by id'); } else { res.send('property html - by id'); } }); // Get all properties of a given type api.get('/properties/:type.:format?', function(req, res) { // Assuming no hierarchy for types in the URL: if (req.params.format == 'json') { res.send('property json - by type. Type = ' + req.params.type); } else if (req.params.format == 'rdfa') { res.send('property rdfa - by type. Type = ' + req.params.type); } else { res.send('property html - by type. Type = ' + req.params.type); } }); api.get('/', function(req, res) { res.send('root!'); }); return api; })(); // Note: The cleaner routing format technique is based on request type: // res.format({ // text: function(){ // res.send('hey'); // }, // html: function(){ // res.send('<p>hey</p>'); // }, // json: function(){ // res.send({ message: 'hey' }); // } // });<file_sep>/models/things/EntryPoint.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ httpMethod: { type: Schema.Types.ObjectId, ref: 'httpMethod' }, encodingType: { type: Schema.Types.ObjectId, ref: 'encodingType' }, contentType: { type: Schema.Types.ObjectId, ref: 'contentType' }, application: { type: Schema.Types.ObjectId, ref: 'application' }, urlTemplate: { type: Schema.Types.ObjectId, ref: 'urlTemplate' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('EntryPoint', schema);<file_sep>/models/things/Offer.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ acceptedPaymentMethod: { type: Schema.Types.ObjectId, ref: 'acceptedPaymentMethod' }, addOn: { type: Schema.Types.ObjectId, ref: 'addOn' }, advanceBookingRequirement: { type: Schema.Types.ObjectId, ref: 'advanceBookingRequirement' }, aggregateRating: { type: Schema.Types.ObjectId, ref: 'aggregateRating' }, availability: { type: Schema.Types.ObjectId, ref: 'availability' }, availabilityEnds: { type: Schema.Types.ObjectId, ref: 'availabilityEnds' }, availabilityStarts: { type: Schema.Types.ObjectId, ref: 'availabilityStarts' }, availableAtOrFrom: { type: Schema.Types.ObjectId, ref: 'availableAtOrFrom' }, availableDeliveryMethod: { type: Schema.Types.ObjectId, ref: 'availableDeliveryMethod' }, businessFunction: { type: Schema.Types.ObjectId, ref: 'businessFunction' }, category: { type: Schema.Types.ObjectId, ref: 'category' }, deliveryLeadTime: { type: Schema.Types.ObjectId, ref: 'deliveryLeadTime' }, eligibleCustomerType: { type: Schema.Types.ObjectId, ref: 'eligibleCustomerType' }, eligibleDuration: { type: Schema.Types.ObjectId, ref: 'eligibleDuration' }, eligibleQuantity: { type: Schema.Types.ObjectId, ref: 'eligibleQuantity' }, eligibleRegion: { type: Schema.Types.ObjectId, ref: 'eligibleRegion' }, eligibleTransactionVolume: { type: Schema.Types.ObjectId, ref: 'eligibleTransactionVolume' }, gtin13: { type: Schema.Types.ObjectId, ref: 'gtin13' }, gtin14: { type: Schema.Types.ObjectId, ref: 'gtin14' }, gtin8: { type: Schema.Types.ObjectId, ref: 'gtin8' }, includesObject: { type: Schema.Types.ObjectId, ref: 'includesObject' }, inventoryLevel: { type: Schema.Types.ObjectId, ref: 'inventoryLevel' }, itemCondition: { type: Schema.Types.ObjectId, ref: 'itemCondition' }, itemOffered: { type: Schema.Types.ObjectId, ref: 'itemOffered' }, mpn: { type: Schema.Types.ObjectId, ref: 'mpn' }, price: { type: Schema.Types.ObjectId, ref: 'price' }, priceSpecification: { type: Schema.Types.ObjectId, ref: 'priceSpecification' }, priceValidUntil: { type: Schema.Types.ObjectId, ref: 'priceValidUntil' }, review: { type: Schema.Types.ObjectId, ref: 'review' }, seller: { type: Schema.Types.ObjectId, ref: 'seller' }, serialNumber: { type: Schema.Types.ObjectId, ref: 'serialNumber' }, sku: { type: Schema.Types.ObjectId, ref: 'sku' }, validFrom: { type: Schema.Types.ObjectId, ref: 'validFrom' }, validThrough: { type: Schema.Types.ObjectId, ref: 'validThrough' }, warranty: { type: Schema.Types.ObjectId, ref: 'warranty' }, priceCurrency: { type: Schema.Types.ObjectId, ref: 'priceCurrency' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('Offer', schema);<file_sep>/models/things/Ticket.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ underName: { type: Schema.Types.ObjectId, ref: 'underName' }, totalPrice: { type: Schema.Types.ObjectId, ref: 'totalPrice' }, priceCurrency: { type: Schema.Types.ObjectId, ref: 'priceCurrency' }, issuedBy: { type: Schema.Types.ObjectId, ref: 'issuedBy' }, dateIssued: { type: Schema.Types.ObjectId, ref: 'dateIssued' }, ticketedSeat: { type: Schema.Types.ObjectId, ref: 'ticketedSeat' }, ticketNumber: { type: Schema.Types.ObjectId, ref: 'ticketNumber' }, ticketToken: { type: Schema.Types.ObjectId, ref: 'ticketToken' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('Ticket', schema);<file_sep>/models/things/MedicalDevice.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ adverseOutcome: { type: Schema.Types.ObjectId, ref: 'adverseOutcome' }, contraindication: { type: Schema.Types.ObjectId, ref: 'contraindication' }, indication: { type: Schema.Types.ObjectId, ref: 'indication' }, postOp: { type: Schema.Types.ObjectId, ref: 'postOp' }, preOp: { type: Schema.Types.ObjectId, ref: 'preOp' }, procedure: { type: Schema.Types.ObjectId, ref: 'procedure' }, purpose: { type: Schema.Types.ObjectId, ref: 'purpose' }, seriousAdverseOutcome: { type: Schema.Types.ObjectId, ref: 'seriousAdverseOutcome' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, code: { type: Schema.Types.ObjectId, ref: 'code' }, guideline: { type: Schema.Types.ObjectId, ref: 'guideline' }, medicineSystem: { type: Schema.Types.ObjectId, ref: 'medicineSystem' }, recognizingAuthority: { type: Schema.Types.ObjectId, ref: 'recognizingAuthority' }, relevantSpecialty: { type: Schema.Types.ObjectId, ref: 'relevantSpecialty' }, study: { type: Schema.Types.ObjectId, ref: 'study' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('MedicalDevice', schema);<file_sep>/models/things/NutritionInformation.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ calories: { type: Schema.Types.ObjectId, ref: 'calories' }, carbohydrateContent: { type: Schema.Types.ObjectId, ref: 'carbohydrateContent' }, cholesterolContent: { type: Schema.Types.ObjectId, ref: 'cholesterolContent' }, fatContent: { type: Schema.Types.ObjectId, ref: 'fatContent' }, fiberContent: { type: Schema.Types.ObjectId, ref: 'fiberContent' }, proteinContent: { type: Schema.Types.ObjectId, ref: 'proteinContent' }, saturatedFatContent: { type: Schema.Types.ObjectId, ref: 'saturatedFatContent' }, servingSize: { type: Schema.Types.ObjectId, ref: 'servingSize' }, sodiumContent: { type: Schema.Types.ObjectId, ref: 'sodiumContent' }, sugarContent: { type: Schema.Types.ObjectId, ref: 'sugarContent' }, transFatContent: { type: Schema.Types.ObjectId, ref: 'transFatContent' }, unsaturatedFatContent: { type: Schema.Types.ObjectId, ref: 'unsaturatedFatContent' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('NutritionInformation', schema);<file_sep>/models/things/EventReservation.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ reservationId: { type: Schema.Types.ObjectId, ref: 'reservationId' }, reservationStatus: { type: Schema.Types.ObjectId, ref: 'reservationStatus' }, reservationFor: { type: Schema.Types.ObjectId, ref: 'reservationFor' }, underName: { type: Schema.Types.ObjectId, ref: 'underName' }, provider: { type: Schema.Types.ObjectId, ref: 'provider' }, bookingAgent: { type: Schema.Types.ObjectId, ref: 'bookingAgent' }, bookingTime: { type: Schema.Types.ObjectId, ref: 'bookingTime' }, modifiedTime: { type: Schema.Types.ObjectId, ref: 'modifiedTime' }, programMembershipUsed: { type: Schema.Types.ObjectId, ref: 'programMembershipUsed' }, reservedTicket: { type: Schema.Types.ObjectId, ref: 'reservedTicket' }, totalPrice: { type: Schema.Types.ObjectId, ref: 'totalPrice' }, priceCurrency: { type: Schema.Types.ObjectId, ref: 'priceCurrency' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('EventReservation', schema);<file_sep>/util/processSchema.js // Load all properties from the schema.org.json file and create models for them var fs = require('fs'), request = require('request'), cheerio = require('cheerio'), mustache = require('mustache'); var schemaUrl = 'http://schema.org/docs/schema_org_rdfa.html'; var $; // Download the canonical RDFa for schema.org and parse it fs.readFile('./schema.org.rdfa.html', 'utf8', function (error, text) { if (!error){ $ = cheerio.load(text); // Process properties $('div[typeof="rdf:Property"]').each(function (i, elem) { var label = $(this).find('span[property="rdfs:label"]').text(), comment = $(this).find('span[property="rdfs:comment"]').text(), domain = [], range = []; $(this).find('a[property="http://schema.org/domainIncludes"]').each(function() { domain.push($(this).text()); }); $(this).find('a[property="http://schema.org/rangeIncludes"]').each(function() { range.push($(this).text()); }); if (range.length > 1) { dataType = 'Schema.Types.Mixed'; } else { dataType = parseDataType(range[0]); } generatePropertyModel(label.trim(), dataType); generatePropertyAdminPartial(label.trim(), comment, dataType); }); // Process things $('div[typeof="rdfs:Class"]').each(function (i, elem) { var label = $(this).find('span[property="rdfs:label"]').text(), comment = $(this).find('span[property="rdfs:comment"]').text(); var properties = getPropertiesForThing(label, $(this).html()) || []; var propertiesMap = properties.map(function(property) { return property + ': { type: Schema.Types.ObjectId, ref: \''+property+'\' }'; }) var schema = propertiesMap.join(",\n "); generateThingModel(label.trim(), schema); generateThingAdminPartial(label.trim(), comment, properties); }); } }); // // Helper Functions // // Render a template and pass it into a callback. Path is relative to util/templates/ var renderTemplate = function (templatePath, templateData, callback) { fs.readFile(__dirname + '/templates/' + templatePath, 'utf8', function (err,text) { console.log('reading....'); if (err) { console.log('error?'); return console.log(err); } var renderedTemplate = mustache.render(text, templateData); callback(renderedTemplate); }); } var getPropertiesForThing = function(label, thingHtml) { var properties = []; // If has ancestors, get parent properties recursively and push onto properties stack // Get properties specific to this thing $('body').find('a[property="http://schema.org/domainIncludes"][href="http://schema.org/'+label+'"]').parent().parent().find('[property="rdfs:label"]').each(function() { properties.push($(this).text()); }) // If this thing inherits properties from other things, push their properties onto the stack (recursively) var parents = []; $(thingHtml).find('a[property="rdfs:subClassOf"]').each(function() { parents.push($(this).text()); }); // if parents.lenth > 0, get parent properties and append if (parents.length > 0) { parents.forEach(function(element, index) { properties = properties.concat(getPropertiesForThing(element, $('div[typeof="rdfs:Class"][resource="http://schema.org/'+element+'"]'))); }) } return properties; } var parseDataType = function(type) { switch (type) { case 'Boolean': return 'Boolean'; case 'Date': case 'DateTime': case 'Time': return 'Date'; case 'Number': case 'Float': case 'Integer': return 'Number'; case 'URL': case 'Text': return 'String'; default: return '{ type: Schema.Types.ObjectId, ref: "'+type+'" }'; } } var generatePropertyModel = function(label, dataType) { renderTemplate('propertyModel.txt', { dataType: dataType, propertyName: label }, function(renderedTemplate) { fs.writeFile('../models/properties/' + label + '.js', renderedTemplate, function(err) { if(err) { console.log(err); } else { console.log('Created ../models/properties/' + label + '.js'); } }); }); } var generateThingModel = function(label, schema) { renderTemplate('thingModel.txt', { schema: schema, thingName: label }, function(renderedTemplate) { fs.writeFile('../models/things/' + label + '.js', renderedTemplate, function(err) { if(err) { console.log(err); } else { console.log('Created ../models/things/' + label + '.js'); } }); }); } var generatePropertyAdminPartial = function(label, description, dataType) { // FIXME: We need different form templates depending on the data type renderTemplate('forms/text.txt', { label: label, description: description }, function(renderedTemplate) { fs.writeFile('../views/admin/properties/' + label + '.jade', renderedTemplate, function(err) { if(err) { console.log(err); } else { console.log('Created ../views/admin/properties/' + label + '.jade'); } }); }); } var generateThingAdminPartial = function(label, description, properties) { var propertyIncludes = properties.map(function(property) { if (property == properties[0]) { return 'include ../properties/' + property + '.jade'; } else { return ' include ../properties/' + property + '.jade'; } }).join("\n"); renderTemplate('forms/thing.txt', { label: label, description: description, propertyIncludes: propertyIncludes }, function(renderedTemplate) { console.log('asdf'); fs.writeFile('../views/admin/things/' + label + '.jade', renderedTemplate, function(err) { if(err) { console.log('error writing file: ' + err); } else { console.log('Created ../views/admin/things/' + label + '.jade'); } }); }); } <file_sep>/models/things/HomeAndConstructionBusiness.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ branchOf: { type: Schema.Types.ObjectId, ref: 'branchOf' }, currenciesAccepted: { type: Schema.Types.ObjectId, ref: 'currenciesAccepted' }, openingHours: { type: Schema.Types.ObjectId, ref: 'openingHours' }, paymentAccepted: { type: Schema.Types.ObjectId, ref: 'paymentAccepted' }, priceRange: { type: Schema.Types.ObjectId, ref: 'priceRange' }, address: { type: Schema.Types.ObjectId, ref: 'address' }, aggregateRating: { type: Schema.Types.ObjectId, ref: 'aggregateRating' }, brand: { type: Schema.Types.ObjectId, ref: 'brand' }, contactPoint: { type: Schema.Types.ObjectId, ref: 'contactPoint' }, department: { type: Schema.Types.ObjectId, ref: 'department' }, duns: { type: Schema.Types.ObjectId, ref: 'duns' }, email: { type: Schema.Types.ObjectId, ref: 'email' }, employee: { type: Schema.Types.ObjectId, ref: 'employee' }, event: { type: Schema.Types.ObjectId, ref: 'event' }, faxNumber: { type: Schema.Types.ObjectId, ref: 'faxNumber' }, founder: { type: Schema.Types.ObjectId, ref: 'founder' }, dissolutionDate: { type: Schema.Types.ObjectId, ref: 'dissolutionDate' }, foundingDate: { type: Schema.Types.ObjectId, ref: 'foundingDate' }, globalLocationNumber: { type: Schema.Types.ObjectId, ref: 'globalLocationNumber' }, hasPOS: { type: Schema.Types.ObjectId, ref: 'hasPOS' }, interactionCount: { type: Schema.Types.ObjectId, ref: 'interactionCount' }, isicV4: { type: Schema.Types.ObjectId, ref: 'isicV4' }, legalName: { type: Schema.Types.ObjectId, ref: 'legalName' }, location: { type: Schema.Types.ObjectId, ref: 'location' }, logo: { type: Schema.Types.ObjectId, ref: 'logo' }, makesOffer: { type: Schema.Types.ObjectId, ref: 'makesOffer' }, member: { type: Schema.Types.ObjectId, ref: 'member' }, memberOf: { type: Schema.Types.ObjectId, ref: 'memberOf' }, naics: { type: Schema.Types.ObjectId, ref: 'naics' }, owns: { type: Schema.Types.ObjectId, ref: 'owns' }, review: { type: Schema.Types.ObjectId, ref: 'review' }, seeks: { type: Schema.Types.ObjectId, ref: 'seeks' }, subOrganization: { type: Schema.Types.ObjectId, ref: 'subOrganization' }, taxID: { type: Schema.Types.ObjectId, ref: 'taxID' }, telephone: { type: Schema.Types.ObjectId, ref: 'telephone' }, vatID: { type: Schema.Types.ObjectId, ref: 'vatID' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' }, address: { type: Schema.Types.ObjectId, ref: 'address' }, aggregateRating: { type: Schema.Types.ObjectId, ref: 'aggregateRating' }, containedIn: { type: Schema.Types.ObjectId, ref: 'containedIn' }, event: { type: Schema.Types.ObjectId, ref: 'event' }, faxNumber: { type: Schema.Types.ObjectId, ref: 'faxNumber' }, geo: { type: Schema.Types.ObjectId, ref: 'geo' }, globalLocationNumber: { type: Schema.Types.ObjectId, ref: 'globalLocationNumber' }, interactionCount: { type: Schema.Types.ObjectId, ref: 'interactionCount' }, isicV4: { type: Schema.Types.ObjectId, ref: 'isicV4' }, logo: { type: Schema.Types.ObjectId, ref: 'logo' }, hasMap: { type: Schema.Types.ObjectId, ref: 'hasMap' }, openingHoursSpecification: { type: Schema.Types.ObjectId, ref: 'openingHoursSpecification' }, photo: { type: Schema.Types.ObjectId, ref: 'photo' }, review: { type: Schema.Types.ObjectId, ref: 'review' }, telephone: { type: Schema.Types.ObjectId, ref: 'telephone' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('HomeAndConstructionBusiness', schema);<file_sep>/models/things/JobPosting.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ baseSalary: { type: Schema.Types.ObjectId, ref: 'baseSalary' }, benefits: { type: Schema.Types.ObjectId, ref: 'benefits' }, datePosted: { type: Schema.Types.ObjectId, ref: 'datePosted' }, educationRequirements: { type: Schema.Types.ObjectId, ref: 'educationRequirements' }, employmentType: { type: Schema.Types.ObjectId, ref: 'employmentType' }, experienceRequirements: { type: Schema.Types.ObjectId, ref: 'experienceRequirements' }, hiringOrganization: { type: Schema.Types.ObjectId, ref: 'hiringOrganization' }, incentives: { type: Schema.Types.ObjectId, ref: 'incentives' }, industry: { type: Schema.Types.ObjectId, ref: 'industry' }, jobLocation: { type: Schema.Types.ObjectId, ref: 'jobLocation' }, occupationalCategory: { type: Schema.Types.ObjectId, ref: 'occupationalCategory' }, qualifications: { type: Schema.Types.ObjectId, ref: 'qualifications' }, responsibilities: { type: Schema.Types.ObjectId, ref: 'responsibilities' }, salaryCurrency: { type: Schema.Types.ObjectId, ref: 'salaryCurrency' }, skills: { type: Schema.Types.ObjectId, ref: 'skills' }, specialCommitments: { type: Schema.Types.ObjectId, ref: 'specialCommitments' }, title: { type: Schema.Types.ObjectId, ref: 'title' }, workHours: { type: Schema.Types.ObjectId, ref: 'workHours' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('JobPosting', schema);<file_sep>/models/things/ParcelDelivery.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ carrier: { type: Schema.Types.ObjectId, ref: 'carrier' }, deliveryAddress: { type: Schema.Types.ObjectId, ref: 'deliveryAddress' }, deliveryStatus: { type: Schema.Types.ObjectId, ref: 'deliveryStatus' }, expectedArrivalFrom: { type: Schema.Types.ObjectId, ref: 'expectedArrivalFrom' }, expectedArrivalUntil: { type: Schema.Types.ObjectId, ref: 'expectedArrivalUntil' }, hasDeliveryMethod: { type: Schema.Types.ObjectId, ref: 'hasDeliveryMethod' }, itemShipped: { type: Schema.Types.ObjectId, ref: 'itemShipped' }, originAddress: { type: Schema.Types.ObjectId, ref: 'originAddress' }, partOfOrder: { type: Schema.Types.ObjectId, ref: 'partOfOrder' }, trackingNumber: { type: Schema.Types.ObjectId, ref: 'trackingNumber' }, trackingUrl: { type: Schema.Types.ObjectId, ref: 'trackingUrl' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('ParcelDelivery', schema);<file_sep>/models/things/LiteraryEvent.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ organizer: { type: Schema.Types.ObjectId, ref: 'organizer' }, attendee: { type: Schema.Types.ObjectId, ref: 'attendee' }, doorTime: { type: Schema.Types.ObjectId, ref: 'doorTime' }, duration: { type: Schema.Types.ObjectId, ref: 'duration' }, endDate: { type: Schema.Types.ObjectId, ref: 'endDate' }, eventStatus: { type: Schema.Types.ObjectId, ref: 'eventStatus' }, location: { type: Schema.Types.ObjectId, ref: 'location' }, offers: { type: Schema.Types.ObjectId, ref: 'offers' }, performer: { type: Schema.Types.ObjectId, ref: 'performer' }, previousStartDate: { type: Schema.Types.ObjectId, ref: 'previousStartDate' }, startDate: { type: Schema.Types.ObjectId, ref: 'startDate' }, subEvent: { type: Schema.Types.ObjectId, ref: 'subEvent' }, superEvent: { type: Schema.Types.ObjectId, ref: 'superEvent' }, typicalAgeRange: { type: Schema.Types.ObjectId, ref: 'typicalAgeRange' }, workPerformed: { type: Schema.Types.ObjectId, ref: 'workPerformed' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('LiteraryEvent', schema);<file_sep>/models/things/SomeProducts.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ inventoryLevel: { type: Schema.Types.ObjectId, ref: 'inventoryLevel' }, aggregateRating: { type: Schema.Types.ObjectId, ref: 'aggregateRating' }, audience: { type: Schema.Types.ObjectId, ref: 'audience' }, brand: { type: Schema.Types.ObjectId, ref: 'brand' }, color: { type: Schema.Types.ObjectId, ref: 'color' }, depth: { type: Schema.Types.ObjectId, ref: 'depth' }, gtin13: { type: Schema.Types.ObjectId, ref: 'gtin13' }, gtin14: { type: Schema.Types.ObjectId, ref: 'gtin14' }, gtin8: { type: Schema.Types.ObjectId, ref: 'gtin8' }, height: { type: Schema.Types.ObjectId, ref: 'height' }, isAccessoryOrSparePartFor: { type: Schema.Types.ObjectId, ref: 'isAccessoryOrSparePartFor' }, isConsumableFor: { type: Schema.Types.ObjectId, ref: 'isConsumableFor' }, isRelatedTo: { type: Schema.Types.ObjectId, ref: 'isRelatedTo' }, isSimilarTo: { type: Schema.Types.ObjectId, ref: 'isSimilarTo' }, itemCondition: { type: Schema.Types.ObjectId, ref: 'itemCondition' }, logo: { type: Schema.Types.ObjectId, ref: 'logo' }, manufacturer: { type: Schema.Types.ObjectId, ref: 'manufacturer' }, model: { type: Schema.Types.ObjectId, ref: 'model' }, mpn: { type: Schema.Types.ObjectId, ref: 'mpn' }, offers: { type: Schema.Types.ObjectId, ref: 'offers' }, productID: { type: Schema.Types.ObjectId, ref: 'productID' }, releaseDate: { type: Schema.Types.ObjectId, ref: 'releaseDate' }, review: { type: Schema.Types.ObjectId, ref: 'review' }, sku: { type: Schema.Types.ObjectId, ref: 'sku' }, weight: { type: Schema.Types.ObjectId, ref: 'weight' }, width: { type: Schema.Types.ObjectId, ref: 'width' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('SomeProducts', schema);<file_sep>/models/things/Person.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ additionalName: { type: Schema.Types.ObjectId, ref: 'additionalName' }, address: { type: Schema.Types.ObjectId, ref: 'address' }, affiliation: { type: Schema.Types.ObjectId, ref: 'affiliation' }, alumniOf: { type: Schema.Types.ObjectId, ref: 'alumniOf' }, award: { type: Schema.Types.ObjectId, ref: 'award' }, birthDate: { type: Schema.Types.ObjectId, ref: 'birthDate' }, brand: { type: Schema.Types.ObjectId, ref: 'brand' }, children: { type: Schema.Types.ObjectId, ref: 'children' }, colleague: { type: Schema.Types.ObjectId, ref: 'colleague' }, contactPoint: { type: Schema.Types.ObjectId, ref: 'contactPoint' }, deathDate: { type: Schema.Types.ObjectId, ref: 'deathDate' }, duns: { type: Schema.Types.ObjectId, ref: 'duns' }, email: { type: Schema.Types.ObjectId, ref: 'email' }, familyName: { type: Schema.Types.ObjectId, ref: 'familyName' }, faxNumber: { type: Schema.Types.ObjectId, ref: 'faxNumber' }, follows: { type: Schema.Types.ObjectId, ref: 'follows' }, gender: { type: Schema.Types.ObjectId, ref: 'gender' }, givenName: { type: Schema.Types.ObjectId, ref: 'givenName' }, globalLocationNumber: { type: Schema.Types.ObjectId, ref: 'globalLocationNumber' }, hasPOS: { type: Schema.Types.ObjectId, ref: 'hasPOS' }, homeLocation: { type: Schema.Types.ObjectId, ref: 'homeLocation' }, honorificPrefix: { type: Schema.Types.ObjectId, ref: 'honorificPrefix' }, honorificSuffix: { type: Schema.Types.ObjectId, ref: 'honorificSuffix' }, interactionCount: { type: Schema.Types.ObjectId, ref: 'interactionCount' }, isicV4: { type: Schema.Types.ObjectId, ref: 'isicV4' }, jobTitle: { type: Schema.Types.ObjectId, ref: 'jobTitle' }, knows: { type: Schema.Types.ObjectId, ref: 'knows' }, makesOffer: { type: Schema.Types.ObjectId, ref: 'makesOffer' }, memberOf: { type: Schema.Types.ObjectId, ref: 'memberOf' }, naics: { type: Schema.Types.ObjectId, ref: 'naics' }, nationality: { type: Schema.Types.ObjectId, ref: 'nationality' }, owns: { type: Schema.Types.ObjectId, ref: 'owns' }, parent: { type: Schema.Types.ObjectId, ref: 'parent' }, performerIn: { type: Schema.Types.ObjectId, ref: 'performerIn' }, relatedTo: { type: Schema.Types.ObjectId, ref: 'relatedTo' }, seeks: { type: Schema.Types.ObjectId, ref: 'seeks' }, sibling: { type: Schema.Types.ObjectId, ref: 'sibling' }, spouse: { type: Schema.Types.ObjectId, ref: 'spouse' }, taxID: { type: Schema.Types.ObjectId, ref: 'taxID' }, telephone: { type: Schema.Types.ObjectId, ref: 'telephone' }, vatID: { type: Schema.Types.ObjectId, ref: 'vatID' }, workLocation: { type: Schema.Types.ObjectId, ref: 'workLocation' }, worksFor: { type: Schema.Types.ObjectId, ref: 'worksFor' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('Person', schema);<file_sep>/models/things/Drug.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ activeIngredient: { type: Schema.Types.ObjectId, ref: 'activeIngredient' }, administrationRoute: { type: Schema.Types.ObjectId, ref: 'administrationRoute' }, alcoholWarning: { type: Schema.Types.ObjectId, ref: 'alcoholWarning' }, availableStrength: { type: Schema.Types.ObjectId, ref: 'availableStrength' }, breastfeedingWarning: { type: Schema.Types.ObjectId, ref: 'breastfeedingWarning' }, clincalPharmacology: { type: Schema.Types.ObjectId, ref: 'clincalPharmacology' }, cost: { type: Schema.Types.ObjectId, ref: 'cost' }, dosageForm: { type: Schema.Types.ObjectId, ref: 'dosageForm' }, doseSchedule: { type: Schema.Types.ObjectId, ref: 'doseSchedule' }, drugClass: { type: Schema.Types.ObjectId, ref: 'drugClass' }, foodWarning: { type: Schema.Types.ObjectId, ref: 'foodWarning' }, interactingDrug: { type: Schema.Types.ObjectId, ref: 'interactingDrug' }, isAvailableGenerically: { type: Schema.Types.ObjectId, ref: 'isAvailableGenerically' }, isProprietary: { type: Schema.Types.ObjectId, ref: 'isProprietary' }, labelDetails: { type: Schema.Types.ObjectId, ref: 'labelDetails' }, legalStatus: { type: Schema.Types.ObjectId, ref: 'legalStatus' }, manufacturer: { type: Schema.Types.ObjectId, ref: 'manufacturer' }, mechanismOfAction: { type: Schema.Types.ObjectId, ref: 'mechanismOfAction' }, nonProprietaryName: { type: Schema.Types.ObjectId, ref: 'nonProprietaryName' }, overdosage: { type: Schema.Types.ObjectId, ref: 'overdosage' }, pregnancyCategory: { type: Schema.Types.ObjectId, ref: 'pregnancyCategory' }, pregnancyWarning: { type: Schema.Types.ObjectId, ref: 'pregnancyWarning' }, prescribingInfo: { type: Schema.Types.ObjectId, ref: 'prescribingInfo' }, prescriptionStatus: { type: Schema.Types.ObjectId, ref: 'prescriptionStatus' }, relatedDrug: { type: Schema.Types.ObjectId, ref: 'relatedDrug' }, warning: { type: Schema.Types.ObjectId, ref: 'warning' }, adverseOutcome: { type: Schema.Types.ObjectId, ref: 'adverseOutcome' }, contraindication: { type: Schema.Types.ObjectId, ref: 'contraindication' }, duplicateTherapy: { type: Schema.Types.ObjectId, ref: 'duplicateTherapy' }, indication: { type: Schema.Types.ObjectId, ref: 'indication' }, seriousAdverseOutcome: { type: Schema.Types.ObjectId, ref: 'seriousAdverseOutcome' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, code: { type: Schema.Types.ObjectId, ref: 'code' }, guideline: { type: Schema.Types.ObjectId, ref: 'guideline' }, medicineSystem: { type: Schema.Types.ObjectId, ref: 'medicineSystem' }, recognizingAuthority: { type: Schema.Types.ObjectId, ref: 'recognizingAuthority' }, relevantSpecialty: { type: Schema.Types.ObjectId, ref: 'relevantSpecialty' }, study: { type: Schema.Types.ObjectId, ref: 'study' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('Drug', schema);<file_sep>/models/things/Flight.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ carrier: { type: Schema.Types.ObjectId, ref: 'carrier' }, provider: { type: Schema.Types.ObjectId, ref: 'provider' }, flightNumber: { type: Schema.Types.ObjectId, ref: 'flightNumber' }, departureTime: { type: Schema.Types.ObjectId, ref: 'departureTime' }, arrivalTime: { type: Schema.Types.ObjectId, ref: 'arrivalTime' }, departureAirport: { type: Schema.Types.ObjectId, ref: 'departureAirport' }, departureAirport: { type: Schema.Types.ObjectId, ref: 'departureAirport' }, departureGate: { type: Schema.Types.ObjectId, ref: 'departureGate' }, arrivalGate: { type: Schema.Types.ObjectId, ref: 'arrivalGate' }, departureTerminal: { type: Schema.Types.ObjectId, ref: 'departureTerminal' }, arrivalTerminal: { type: Schema.Types.ObjectId, ref: 'arrivalTerminal' }, aircraft: { type: Schema.Types.ObjectId, ref: 'aircraft' }, mealService: { type: Schema.Types.ObjectId, ref: 'mealService' }, estimatedFlightDuration: { type: Schema.Types.ObjectId, ref: 'estimatedFlightDuration' }, flightDistance: { type: Schema.Types.ObjectId, ref: 'flightDistance' }, webCheckinTime: { type: Schema.Types.ObjectId, ref: 'webCheckinTime' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('Flight', schema);<file_sep>/models/things/Waterfall.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ address: { type: Schema.Types.ObjectId, ref: 'address' }, aggregateRating: { type: Schema.Types.ObjectId, ref: 'aggregateRating' }, containedIn: { type: Schema.Types.ObjectId, ref: 'containedIn' }, event: { type: Schema.Types.ObjectId, ref: 'event' }, faxNumber: { type: Schema.Types.ObjectId, ref: 'faxNumber' }, geo: { type: Schema.Types.ObjectId, ref: 'geo' }, globalLocationNumber: { type: Schema.Types.ObjectId, ref: 'globalLocationNumber' }, interactionCount: { type: Schema.Types.ObjectId, ref: 'interactionCount' }, isicV4: { type: Schema.Types.ObjectId, ref: 'isicV4' }, logo: { type: Schema.Types.ObjectId, ref: 'logo' }, hasMap: { type: Schema.Types.ObjectId, ref: 'hasMap' }, openingHoursSpecification: { type: Schema.Types.ObjectId, ref: 'openingHoursSpecification' }, photo: { type: Schema.Types.ObjectId, ref: 'photo' }, review: { type: Schema.Types.ObjectId, ref: 'review' }, telephone: { type: Schema.Types.ObjectId, ref: 'telephone' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('Waterfall', schema);<file_sep>/models/things/ExerciseAction.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ course: { type: Schema.Types.ObjectId, ref: 'course' }, diet: { type: Schema.Types.ObjectId, ref: 'diet' }, distance: { type: Schema.Types.ObjectId, ref: 'distance' }, exercisePlan: { type: Schema.Types.ObjectId, ref: 'exercisePlan' }, exerciseType: { type: Schema.Types.ObjectId, ref: 'exerciseType' }, fromLocation: { type: Schema.Types.ObjectId, ref: 'fromLocation' }, opponent: { type: Schema.Types.ObjectId, ref: 'opponent' }, sportsActivityLocation: { type: Schema.Types.ObjectId, ref: 'sportsActivityLocation' }, sportsEvent: { type: Schema.Types.ObjectId, ref: 'sportsEvent' }, sportsTeam: { type: Schema.Types.ObjectId, ref: 'sportsTeam' }, toLocation: { type: Schema.Types.ObjectId, ref: 'toLocation' }, audience: { type: Schema.Types.ObjectId, ref: 'audience' }, event: { type: Schema.Types.ObjectId, ref: 'event' }, agent: { type: Schema.Types.ObjectId, ref: 'agent' }, endTime: { type: Schema.Types.ObjectId, ref: 'endTime' }, instrument: { type: Schema.Types.ObjectId, ref: 'instrument' }, location: { type: Schema.Types.ObjectId, ref: 'location' }, object: { type: Schema.Types.ObjectId, ref: 'object' }, participant: { type: Schema.Types.ObjectId, ref: 'participant' }, result: { type: Schema.Types.ObjectId, ref: 'result' }, startTime: { type: Schema.Types.ObjectId, ref: 'startTime' }, actionStatus: { type: Schema.Types.ObjectId, ref: 'actionStatus' }, target: { type: Schema.Types.ObjectId, ref: 'target' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('ExerciseAction', schema);<file_sep>/models/things/PostalAddress.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ addressCountry: { type: Schema.Types.ObjectId, ref: 'addressCountry' }, addressLocality: { type: Schema.Types.ObjectId, ref: 'addressLocality' }, addressRegion: { type: Schema.Types.ObjectId, ref: 'addressRegion' }, postalCode: { type: Schema.Types.ObjectId, ref: 'postalCode' }, postOfficeBoxNumber: { type: Schema.Types.ObjectId, ref: 'postOfficeBoxNumber' }, streetAddress: { type: Schema.Types.ObjectId, ref: 'streetAddress' }, areaServed: { type: Schema.Types.ObjectId, ref: 'areaServed' }, availableLanguage: { type: Schema.Types.ObjectId, ref: 'availableLanguage' }, contactOption: { type: Schema.Types.ObjectId, ref: 'contactOption' }, contactType: { type: Schema.Types.ObjectId, ref: 'contactType' }, email: { type: Schema.Types.ObjectId, ref: 'email' }, faxNumber: { type: Schema.Types.ObjectId, ref: 'faxNumber' }, hoursAvailable: { type: Schema.Types.ObjectId, ref: 'hoursAvailable' }, productSupported: { type: Schema.Types.ObjectId, ref: 'productSupported' }, telephone: { type: Schema.Types.ObjectId, ref: 'telephone' }, additionalType: { type: Schema.Types.ObjectId, ref: 'additionalType' }, alternateName: { type: Schema.Types.ObjectId, ref: 'alternateName' }, description: { type: Schema.Types.ObjectId, ref: 'description' }, image: { type: Schema.Types.ObjectId, ref: 'image' }, name: { type: Schema.Types.ObjectId, ref: 'name' }, sameAs: { type: Schema.Types.ObjectId, ref: 'sameAs' }, url: { type: Schema.Types.ObjectId, ref: 'url' }, potentialAction: { type: Schema.Types.ObjectId, ref: 'potentialAction' } }); module.exports = mongoose.model('PostalAddress', schema);
6424953769e0b6c17da2f9910a7240c7c02b4b16
[ "JavaScript" ]
22
JavaScript
mcrider/thingy
63c1a2ea85e1b864d26f8f136f5e521ef5e4f857
461a631bc9551d4d963066edd433bd2132207c02
refs/heads/main
<repo_name>C-CCM-TC1028-102-2113/tarea-2-Jeronimo-Uribe<file_sep>/assignments/06BMI/src/exercise.py def main(): #escribe tu código abajo de esta línea p=float(input('Peso en kg: ')) if p>0: a=float(input('Altura en m: ')) if a>0: i=p/(a)**2 if i<20: print('PESO BAJO') elif 20<=i<25: print('NORMAL') elif 25<=i<30: print('SOBREPESO') elif 30<=i<40: print('OBESIDAD') elif i>=40: print('OBESIDAD MORBIDA') elif a<=0: print('Revisa tus datos, alguno de ellos es erróneo') elif p<=0: print('Revisa tu dato, es erróneo') pass if __name__=='__main__': main() <file_sep>/assignments/04Maximo/src/exercise.py def main(): #escribe tu código abajo de esta línea x=int(input('Ingresa el primer número: ')) y=int(input('Ingresa el segundo número: ')) z=int(input('Ingresa el tercer número: ')) if x>y and x>z: print(x) elif y>x and y>z: print(y) elif z>x and z>y: print(z) pass if __name__=='__main__': main() <file_sep>/assignments/02Licencia/src/exercise.py def main(): #Escribe tu código debajo de esta línea e=int(input('Ingresa tu edad: ')) if e>=18: io=str(input('¿Tienes identificación oficial? (s/n): ')) if io==('s'): print('Trámite de licencia concedido') elif io==('n'): print('No cumples con los requisitos') elif io!=('s') or ('n'): print('Respuesta incorrecta') elif e<0: print('Respuesta incorrecta') elif e<18: print('No cumples requisitos') pass if __name__ == '__main__': main()
459591152590b8b4d53da120425be3912ea45f1b
[ "Python" ]
3
Python
C-CCM-TC1028-102-2113/tarea-2-Jeronimo-Uribe
7953b2fd2b6631570561374015eef8b1f8216e25
29c4723e66cb1c2362c835955d0f67861aea340e
refs/heads/main
<file_sep> // Our List of Boys var boys = [ '<NAME>', '<NAME>', 'Jasper', '<NAME>', '<NAME>', '<NAME>' ]; // List of boy images var imgBoy = new Array(); imgBoy[0] = new Image(); imgBoy[0].src = 'images/barry allen.png'; imgBoy[1] = new Image(); imgBoy[1].src = 'images/carter jenkins.png'; imgBoy[2] = new Image(); imgBoy[2].src = 'images/jasper.png'; imgBoy[3] = new Image(); imgBoy[3].src = 'images/Ji chang wook.png'; imgBoy[4] = new Image(); imgBoy[4].src = 'images/Niklaus Mikaelson.png'; imgBoy[5] = new Image(); imgBoy[5].src = 'images/xiao nai.png'; /*------------------------------------*/ // Our List of countries var country = [ 'Paris', 'Turkey', 'South Korea', 'Dubai', 'China', 'Austrailia' ]; // List of country images var imgcountry = new Array(); imgcountry[0] = new Image(); imgcountry[0].src = 'images/paris.png'; imgcountry[1] = new Image(); imgcountry[1].src = 'images/turkey.png'; imgcountry[2] = new Image(); imgcountry[2].src = 'images/korea.png'; imgcountry[3] = new Image(); imgcountry[3].src = 'images/dubai.png'; imgcountry[4] = new Image(); imgcountry[4].src = 'images/china.png'; imgcountry[5] = new Image(); imgcountry[5].src = 'images/austrailia.png'; /*------------------------------------*/ var randomboy = Math.floor(Math.random()*boys.length); var randomcountry = Math.floor(Math.random()*country.length); var boyname = boys[randomboy]; var countryname = country[randomcountry]; var bname = document.getElementById('boyname'); var cname = document.getElementById('countryname'); // Javascript Function document.addEventListener("click", function(){ // display h1 and images document.getElementById('suggestion').style.display = 'block'; document.getElementById('images').style.display = 'flex'; var randomboy = Math.floor(Math.random()*boys.length); var randomcountry = Math.floor(Math.random()*country.length); var boyname = boys[randomboy]; var countryname = country[randomcountry]; bname.innerText = `${boyname}` ; cname.innerText = `${countryname}` ; document.images.namedItem("boyimage").src = imgBoy[randomboy].src; document.images.namedItem("countryimage").src = imgcountry[randomcountry].src; });<file_sep><!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="description" content="Randomizer App - How about a date!?"> <meta name="keywords" content="Dating, random, beers"> <title>randomizer app</title> <!-- external CSS link --> <link rel="stylesheet" href="css/style.css"> </head> <body> <!-- PAGE CONTENT WILL BE PRINTED HERE --> <h1>Hey Beautiful!!</h1> <p>You wanna start your randomizer app to find out with whom you go for a date and where? Oki, then click anywhere on your screen..</p> <h4 id="suggestion" style="display: none;">How about you go on a date with <b id="boyname">boyname</b> in <b id="countryname">countryname</b>.</h4> <div id="images" style="display: none;"> <img id="boyimage" alt="" width="400" height="600"> <img id="countryimage" alt="" width="600" height="400"> </div> <script src="randomizer.js"></script> </body> </html>
054ad484066db547fe8b650ce8b0db7348c51187
[ "JavaScript", "HTML" ]
2
JavaScript
toubaijaz19/Randomizer-Dating-App-using-JS-basics
5b53a4dcfd5df99bfccd6a68684e4de7e465c96d
5afef712b1c50a0d3f63547c0e1a6e33c10c42f4
refs/heads/master
<file_sep>drop database IF EXISTS chemical_name CASCADE; create database chemical_name; use chemical_name; create table drug(chemical string,dates string,age1 float ,age2 float,age3 float,age4 float,age5 float,age6 float,age7 float,age8 float,age9 float) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile; describe drug; load data local inpath '/home/ratul/drug/result_chemical' into table drug; insert overwrite directory '/user/result11' row format delimited fields terminated by ' , ' select * from drug limit 30 ; <file_sep>drop database IF EXISTS month CASCADE ; create database month; use month; create table drug(chemical string,dates string,age1 float ,age2 float,age3 float,age4 float,age5 float,age6 float,age7 float,age8 float,age9 float) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile; describe drug; load data local inpath '/home/ratul/drug/full' into table drug; select chemical,dates,age3 from drug where month(dates)="09" ; <file_sep>package drug; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.fs.Path; //get list of input path for mapreduce job import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; //inputformat>>validate the input specification job,split up the file into logical instances import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.conf.Configuration; import java.io.IOException; import java.util.Iterator; public class Drug { public static class chemical extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable arg0,Text Value, Context context) throws IOException,InterruptedException { String line = Value.toString(); if (!(line.length() == 0)) { String name = line.substring(0,16).trim(); String year = line.substring(18,28); String ageleft = line.substring(32,100); if(name.equals("Inhalants")) { context.write(new Text("chemical:- " +name + " year: " +year) ,new Text( "" +ageleft ) ); } } } } public static class greater_age extends Reducer<Text, Text, Text, Text> { public void reduce(Text key, Iterator<Text> Values, Context context) throws IOException, InterruptedException { String view = Values.next().toString(); context.write(key,new Text(view)); } } //main method public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job( conf ,"drug"); job.setJarByClass(Drug.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setMapperClass(chemical.class); job.setReducerClass(greater_age.class); job.setInputFormatClass(TextInputFormat.class); //inputformat>>validate the input specification job,split up the file into logical instances job.setOutputFormatClass(TextOutputFormat.class); Path OutputPath = new Path(args[1]); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); OutputPath.getFileSystem(conf).delete(OutputPath); System.exit(job.waitForCompletion(true) ? 0 :1); } }
f640f39f06141e3623eb63622f5df847bd018be8
[ "Java", "SQL" ]
3
SQL
ratularora/drug-project-with-hadoop-an-hive
dd1bbaa9e590128c9387a5c6891df033f192c6dc
eaf7a045b84aa9498ca8b01b97ac24e97f9cd485
refs/heads/master
<repo_name>s1415495/Practice-github-assignment-s1415495<file_sep>/Practice-github-assignment-s1415495/Program.cs <NAME> May 15, 1997 54th Street
4ec4201c8aa15688833a06d3e1cdaec7bb460365
[ "C#" ]
1
C#
s1415495/Practice-github-assignment-s1415495
3a016b9f64fa305bd7bcfb037b250a23bf8e3757
5094f1becd6577de5962ba62c2c13c0d715ff9d2
refs/heads/master
<repo_name>Ahmed-Saber-25/GAADProject<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/viewmodel/SkillIQLeadersViewModel.kt package com.alyndroid.tabbedviews.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.alyndroid.tabbedviews.model.SkillIQLeadersRespDao import com.alyndroid.tabbedviews.repository.Repository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class SkillIQLeadersViewModel(application: Application) : AndroidViewModel(application) { private var appContext: Application = application fun getSkillIQLeaders(): LiveData<List<SkillIQLeadersRespDao>> { var response = MutableLiveData<List<SkillIQLeadersRespDao>>() viewModelScope.launch { withContext(Dispatchers.IO) { val list: List<SkillIQLeadersRespDao> = Repository().getSkillIQLeaders() response.postValue(list) } } return response } }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/model/RetrofitApi.kt package com.alyndroid.tabbedviews.model import retrofit2.Call import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.POST interface RetrofitApi { @GET("hours") suspend fun getLearningLeaders(): List<LearningLeadersRespDao> @GET("skilliq") suspend fun getSkillIQLeaders(): List<SkillIQLeadersRespDao> @POST("<KEY>") @FormUrlEncoded fun submitProject( @Field("entry.1824927963") emailAddress: String, @Field("entry.1877115667") name: String, @Field("entry.2006916086") lastName: String, @Field("entry.284483984") linkToProject: String ): Call<Void> }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/model/RetrofitClient.kt package com.alyndroid.tabbedviews.model import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitClient { private const val BASE_URL = "https://gadsapi.herokuapp.com/api/" private const val SUBMIT_BASE_URL = "https://docs.google.com/forms/d/e/" fun doRetrofitService(): RetrofitApi { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(RetrofitApi::class.java) } fun doSubmissionService(): RetrofitApi { return Retrofit.Builder() .baseUrl(SUBMIT_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(RetrofitApi::class.java) } }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/view/SkillIQLeadersFragment.kt package com.alyndroid.tabbedviews.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.alyndroid.tabbedviews.R import com.alyndroid.tabbedviews.model.SkillIQLeadersRespDao import com.alyndroid.tabbedviews.view.adapters.SkillIQLeadersAdapter import com.alyndroid.tabbedviews.viewmodel.SkillIQLeadersViewModel import kotlinx.android.synthetic.main.fragment_skill_iq_leaders.* class SkillIQLeadersFragment : Fragment() { private lateinit var skillIQLeadersViewModel: SkillIQLeadersViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) skillIQLeadersViewModel = ViewModelProviders.of(this)[SkillIQLeadersViewModel::class.java] skillIQLeadersViewModel.getSkillIQLeaders().observe( this, Observer { setupView(it) }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_skill_iq_leaders, container, false) } private fun setupView(list: List<SkillIQLeadersRespDao>) { val layout = LinearLayoutManager(context) iqLeadersRecyclerView.layoutManager = layout iqLeadersRecyclerView.adapter = SkillIQLeadersAdapter(list) } }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/view/LearningLeadersFragment.kt package com.alyndroid.tabbedviews.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.alyndroid.tabbedviews.R import com.alyndroid.tabbedviews.model.LearningLeadersRespDao import com.alyndroid.tabbedviews.view.adapters.LearningLeadersAdapter import com.alyndroid.tabbedviews.viewmodel.LearningLeadersViewModel import kotlinx.android.synthetic.main.fragment_learning_leaders.* class LearningLeadersFragment : Fragment() { private lateinit var learningLeadersViewModel: LearningLeadersViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) learningLeadersViewModel = ViewModelProviders.of(this)[LearningLeadersViewModel::class.java] learningLeadersViewModel.getLearningLeaders().observe( this, Observer { setupView(it) }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_learning_leaders, container, false) } private fun setupView(list: List<LearningLeadersRespDao>) { val layout = LinearLayoutManager(context) learningLeadersRecyclerView.layoutManager = layout learningLeadersRecyclerView.adapter = LearningLeadersAdapter(list) } }<file_sep>/README.md # GAADProject # 1- Splash Screen ![Alt text](https://github.com/Ahmed-Saber-25/GAADProject/blob/master/app/src/main/res/ScreenShots/1%20.png?raw=true "") # 2- Leader Board : Learning Leaders ![Alt text](https://github.com/Ahmed-Saber-25/GAADProject/blob/master/app/src/main/res/ScreenShots/2.png?raw=true "") # 3- Leader Board : Skill-IQ Leaders ![Alt text](https://github.com/Ahmed-Saber-25/GAADProject/blob/master/app/src/main/res/ScreenShots/3.png?raw=true "") # 4- Project Submission ![Alt text](https://github.com/Ahmed-Saber-25/GAADProject/blob/master/app/src/main/res/ScreenShots/4.png?raw=true "") # 5- Confirmation Alert ![Alt text](https://github.com/Ahmed-Saber-25/GAADProject/blob/master/app/src/main/res/ScreenShots/6.png?raw=true "") # 6- Project Submission success ![Alt text](https://github.com/Ahmed-Saber-25/GAADProject/blob/master/app/src/main/res/ScreenShots/7.png?raw=true "") <file_sep>/app/src/main/java/com/alyndroid/tabbedviews/viewmodel/SubmitProjectViewModel.kt package com.alyndroid.tabbedviews.viewmodel import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.alyndroid.tabbedviews.repository.Repository import com.alyndroid.tabbedviews.view.SubmitProjectActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class SubmitProjectViewModel(application: Application) : AndroidViewModel(application) { var context: SubmitProjectActivity? = null fun submitProject( emailAddress: String, firstName: String, lastName: String, linkToProject: String ) { viewModelScope.launch { withContext(Dispatchers.IO) { if (Repository().submitProject( emailAddress, firstName, lastName, linkToProject ).execute().isSuccessful ) { launch { withContext(Dispatchers.Main) { context?.submissionSuccessful() } } } else { launch { withContext(Dispatchers.Main) { context?.submissionNotSuccessful() } } } } } } }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/model/SkillIQLeadersRespDao.kt package com.alyndroid.tabbedviews.model data class SkillIQLeadersRespDao( val name: String, val score: Int, val country: String, val badgeUrl: String ) <file_sep>/app/src/main/java/com/alyndroid/tabbedviews/view/adapters/SkillIQLeadersAdapter.kt package com.alyndroid.tabbedviews.view.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.alyndroid.tabbedviews.R import com.alyndroid.tabbedviews.model.SkillIQLeadersRespDao import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.skill_iq_leader_card.view.* class SkillIQLeadersAdapter(private val list: List<SkillIQLeadersRespDao>) : RecyclerView.Adapter<SkillIQLeadersAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflate = LayoutInflater.from(parent.context) .inflate(R.layout.skill_iq_leader_card, parent, false) return ViewHolder(inflate) } override fun getItemCount() = list.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.itemView.iq_leader_name.text = list[position].name holder.itemView.iq_score_and_country_name.text = list[position].score.toString() + " Skill IQ Score , " + list[position].country Glide.with(holder.itemView.context) .load(list[position].badgeUrl) .placeholder(R.drawable.skill_iq) .thumbnail(0.5f) .into(holder.itemView.iq_badge_img) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/view/SubmitProjectActivity.kt package com.alyndroid.tabbedviews.view import android.graphics.Color import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import cn.pedant.SweetAlert.SweetAlertDialog import com.alyndroid.tabbedviews.R import com.alyndroid.tabbedviews.viewmodel.SubmitProjectViewModel import kotlinx.android.synthetic.main.activity_submit_project.* class SubmitProjectActivity : AppCompatActivity() { private lateinit var submitProjectViewModel: SubmitProjectViewModel var isValidFirstName = false var isValidLastName = false var isValidEmail = false var isValidGithubUrl = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_submit_project) submitProjectViewModel = ViewModelProviders.of(this)[SubmitProjectViewModel::class.java] submitProjectViewModel.context = this validateInputOnUI() submit_BTN.setOnClickListener { if (isValidFirstName && isValidLastName && isValidEmail && isValidGithubUrl) { showAlertDialog(resources.getString(R.string.message)) } else { Toast.makeText(this, "please,check your inputs and try later", Toast.LENGTH_LONG) .show() } } close.setOnClickListener { finish() } } private fun validateInputOnUI() { first_name.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) { if (first_name.text.toString().trim().isEmpty()) { first_name.error = getString(R.string.enter_name) isValidFirstName = false } else { first_name.error = null isValidFirstName = true } } } last_name.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) { if (last_name.text.toString().trim().isEmpty()) { last_name.error = getString(R.string.enter_name) isValidLastName = false } else { last_name.error = null isValidLastName = true } } } email_address.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) { val adminMail = email_address.text.toString() if (!android.util.Patterns.EMAIL_ADDRESS.matcher(adminMail) .matches() ) { email_address.error = getString(R.string.invalid_email) isValidEmail = false } else { email_address.error = null isValidEmail = true } } } project_link_on_github.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) { val projectLink = project_link_on_github.text.toString() if (!android.util.Patterns.WEB_URL.matcher(projectLink) .matches() || !projectLink.contains("github", true) ) { project_link_on_github.error = getString(R.string.invalid_github_url) isValidGithubUrl = false } else { project_link_on_github.error = null isValidGithubUrl = true } } } } private fun showAlertDialog(message: String) { SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE) .setTitleText("Are you sure?") .setConfirmText("Yes") .setConfirmButtonBackgroundColor(Color.parseColor("#EC8706")) .setConfirmClickListener { submitProjectViewModel.submitProject( email_address.text.toString(), first_name.text.toString(), last_name.text.toString(), project_link_on_github.text.toString() ) } .show() } fun submissionSuccessful() { SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE) .setTitleText("Submission Successful") .setConfirmText("OK") .setCustomImage(R.drawable.check_circle) .show() } fun submissionNotSuccessful() { SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE) .setTitleText("Submission Not Successful") .setConfirmText("OK") .setCustomImage(R.drawable.report_problem) .show() } }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/repository/Repository.kt package com.alyndroid.tabbedviews.repository import com.alyndroid.tabbedviews.model.RetrofitClient class Repository { private val webService = RetrofitClient.doRetrofitService() private val webServiceSubmission = RetrofitClient.doSubmissionService() suspend fun getLearningLeaders() = webService.getLearningLeaders() suspend fun getSkillIQLeaders() = webService.getSkillIQLeaders() fun submitProject( emailAddress: String, name: String, lastName: String, linkToProject: String ) = webServiceSubmission.submitProject(emailAddress, name, lastName, linkToProject) }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/viewmodel/LearningLeadersViewModel.kt package com.alyndroid.tabbedviews.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.alyndroid.tabbedviews.model.LearningLeadersRespDao import com.alyndroid.tabbedviews.repository.Repository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class LearningLeadersViewModel(application: Application) : AndroidViewModel(application) { private var appContext: Application = application fun getLearningLeaders(): LiveData<List<LearningLeadersRespDao>> { var response = MutableLiveData<List<LearningLeadersRespDao>>() viewModelScope.launch { withContext(Dispatchers.IO) { val list: List<LearningLeadersRespDao> = Repository().getLearningLeaders() response.postValue(list) } } return response } }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/view/SplashScreen.kt package com.alyndroid.tabbedviews.view import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import com.alyndroid.tabbedviews.R class SplashScreen : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) goToHome() } fun goToHome() { Handler().postDelayed({ startActivity( Intent( this@SplashScreen, MainActivity::class.java ) ) finish() }, 2000) } }<file_sep>/app/src/main/java/com/alyndroid/tabbedviews/view/adapters/LearningLeadersAdapter.kt package com.alyndroid.tabbedviews.view.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.alyndroid.tabbedviews.R import com.alyndroid.tabbedviews.model.LearningLeadersRespDao import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.learning_leader_card.view.* class LearningLeadersAdapter(private val list: List<LearningLeadersRespDao>) : RecyclerView.Adapter<LearningLeadersAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflate = LayoutInflater.from(parent.context) .inflate(R.layout.learning_leader_card, parent, false) return ViewHolder(inflate) } override fun getItemCount() = list.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.itemView.leader_name.text = list[position].name holder.itemView.learning_hours_and_country_name.text = list[position].hours.toString() + " Learning Hours , " + list[position].country Glide.with(holder.itemView.context) .load(list[position].badgeUrl) .placeholder(R.drawable.top_learner) .thumbnail(0.5f) .into(holder.itemView.badge_img) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) }
945f88894f8bb3bc717612679d4cae1396d8816a
[ "Markdown", "Kotlin" ]
14
Kotlin
Ahmed-Saber-25/GAADProject
6cef294a873b941ad9d4e7bde730cf26c3ad05fe
91f47831fe110334491daaabc71f5813f8e5abda
refs/heads/master
<file_sep>using Assets.Scripts.GameManager; using Assets.Scripts.DecisionMaking.GOB; using UnityEngine; using Action = Assets.Scripts.DecisionMaking.GOB.Action; using Assets.Scripts.Movement.Arbitration.SteeringPipeline; namespace Assets.Scripts.DecisionMakingActions { public abstract class StandStillAction : CharacterAction { protected string Actuator { get { return "StandStillActuator"; } } protected StandStillAction(string actionName, AutonomousCharacter character) : base(actionName, character) { this.Character = character; } public override void Execute() { this.Character.CharActuator.SwitchActuator(this.Actuator); this.Character.Targeter.UpdateGoal(this.Character.transform.position); } } } <file_sep>using Assets.Scripts.GameManager; using Assets.Scripts.DecisionMaking.GOB; using UnityEngine; using Action = Assets.Scripts.DecisionMaking.GOB.Action; namespace Assets.Scripts.DecisionMakingActions { public abstract class WalkToPositionAndExecuteAction : CharacterAction { public bool PositionSet { get; protected set; } private Vector3 position; public Vector3 Position { get { return this.position; } set { this.position = value; this.PositionSet = true; } } public string TargetName { get; set; } protected string Actuator { get { return "FollowPathActuator"; } } protected WalkToPositionAndExecuteAction(string actionName, AutonomousCharacter character) : base(actionName, character) { this.Position = Vector3.zero; this.PositionSet = false; } public override float GetDuration() { //assume a velocity of 20.0f/s to get to the target return (this.Position - this.Character.Character.KinematicData.position).magnitude / 20.0f; } public override float GetDuration(WorldModel worldModel) { //assume a velocity of 20.0f/s to get to the target var position = (Vector3)worldModel.GetProperty(Properties.POSITION); return (this.Position - position).magnitude / 20.0f; } public override float GetGoalChange(Goal goal) { if (goal.Name == AutonomousCharacter.REST_GOAL) { var distance = (Position - this.Character.Character.KinematicData.position).magnitude; //+0.01 * distance because of the walk return distance * 0.01f; } if (goal.Name == AutonomousCharacter.EAT_GOAL) { var distance = (Position - this.Character.Character.KinematicData.position).magnitude; //+0.01 * distance because of the walk return distance * 0.1f; } else return 0; } public override bool CanExecute(WorldModel worldModel) { if (!base.CanExecute(worldModel)) return false; if (!this.PositionSet) return false; //Secret level 1 /* var node = this.Character.navMesh.QuantizeToNode(this.Position, 1.0f); float redInfluence = this.Character.RedInfluenceMap.GetInfluence(node); float greenInfluence = this.Character.GreenInfluenceMap.GetInfluence(node); float Security = redInfluence - greenInfluence; if (Security <= 0) return false;*/ var targetEnabled = (bool)worldModel.GetProperty(TargetName); var distance = (this.Position - this.Character.Character.KinematicData.position).magnitude; if (((float)worldModel.GetProperty(Properties.ENERGY) - 0.5f <= (distance *0.01f)) && ((float)worldModel.GetProperty(Properties.HUNGER) - 0.1f <= (distance * 0.1f))) { return false; } return targetEnabled; } public override void Execute() { this.Character.CharActuator.SwitchActuator(this.Actuator); this.Character.Targeter.UpdateGoal(this.Position); } public override void ApplyActionEffects(WorldModel worldModel) { var duration = this.GetDuration(worldModel); var energyChange = duration * 0.01f; var hungerChange = duration * 0.1f; var restValue = worldModel.GetGoalValue(AutonomousCharacter.REST_GOAL); worldModel.SetGoalValue(AutonomousCharacter.REST_GOAL, restValue + energyChange); var energy = (float)worldModel.GetProperty(Properties.ENERGY); worldModel.SetProperty(Properties.ENERGY, energy - energyChange); var eatGoalValue = worldModel.GetGoalValue(AutonomousCharacter.EAT_GOAL); worldModel.SetGoalValue(AutonomousCharacter.EAT_GOAL, eatGoalValue + hungerChange); var hunger = (float)worldModel.GetProperty(Properties.HUNGER); worldModel.SetProperty(Properties.HUNGER, hunger + hungerChange); worldModel.SetProperty(Properties.POSITION, this.Position); } } } <file_sep>using Assets.Scripts.GameManager; using Assets.Scripts.DecisionMaking.GOB; using UnityEngine; using Action = Assets.Scripts.DecisionMaking.GOB.Action; namespace Assets.Scripts.DecisionMakingActions { public abstract class WalkToTargetAndExecuteAction : CharacterAction { protected GameObject Target { get; set; } protected string Actuator { get { return "FollowPathActuator"; } } protected WalkToTargetAndExecuteAction(string actionName, AutonomousCharacter character, GameObject target) : base(actionName + "(" + target.name + ")", character) { this.Target = target; } public override float GetDuration() { //assume a velocity of 20.0f/s to get to the target return (this.Target.transform.position - this.Character.Character.KinematicData.position).magnitude / 20.0f; } public override float GetDuration(WorldModel worldModel) { //assume a velocity of 20.0f/s to get to the target var position = (Vector3)worldModel.GetProperty(Properties.POSITION); return (this.Target.transform.position - position).magnitude / 20.0f; } public override float GetGoalChange(Goal goal) { if (goal.Name == AutonomousCharacter.REST_GOAL) { var distance = (this.Target.transform.position - this.Character.Character.KinematicData.position).magnitude; //+0.01 * distance because of the walk return distance * 0.01f; } if (goal.Name == AutonomousCharacter.EAT_GOAL) { var distance = (this.Target.transform.position - this.Character.Character.KinematicData.position).magnitude; //+0.01 * distance because of the walk return distance * 0.1f; } else return 0; } public override bool CanExecute(WorldModel worldModel) { if (!base.CanExecute(worldModel)) return false; if (this.Target == null) return false; //Secret level 1 var node = this.Character.navMesh.QuantizeToNode(this.Target.transform.position, 1.0f); float redInfluence = this.Character.RedInfluenceMap.GetInfluence(node); float greenInfluence = this.Character.GreenInfluenceMap.GetInfluence(node); float Security = redInfluence - greenInfluence; if (Security <= 0) return false; var targetEnabled = (bool)worldModel.GetProperty(this.Target.name); var distance = (this.Target.transform.position - this.Character.Character.KinematicData.position).magnitude; if (((float)worldModel.GetProperty(Properties.ENERGY) - 0.5f <= (distance *0.01f)) && ((float)worldModel.GetProperty(Properties.HUNGER) - 0.1f <= (distance * 0.1f))) { return false; } return targetEnabled; } public override void Execute() { this.Character.CharActuator.SwitchActuator(this.Actuator); this.Character.Targeter.UpdateGoal(this.Target.transform.position); } public override void ApplyActionEffects(WorldModel worldModel) { var duration = this.GetDuration(worldModel); var energyChange = duration * 0.01f; var hungerChange = duration * 0.1f; var restValue = worldModel.GetGoalValue(AutonomousCharacter.REST_GOAL); worldModel.SetGoalValue(AutonomousCharacter.REST_GOAL, restValue + energyChange); var energy = (float)worldModel.GetProperty(Properties.ENERGY); worldModel.SetProperty(Properties.ENERGY, energy - energyChange); var eatGoalValue = worldModel.GetGoalValue(AutonomousCharacter.EAT_GOAL); worldModel.SetGoalValue(AutonomousCharacter.EAT_GOAL, eatGoalValue + hungerChange); var hunger = (float)worldModel.GetProperty(Properties.HUNGER); worldModel.SetProperty(Properties.HUNGER, hunger + hungerChange); worldModel.SetProperty(Properties.POSITION, Target.transform.position); } } } <file_sep>using System; using Assets.Scripts.GameManager; using Assets.Scripts.DecisionMaking.GOB; using Action = Assets.Scripts.DecisionMaking.GOB.Action; using UnityEngine; namespace Assets.Scripts.DecisionMakingActions { public class Rest : StandStillAction { public Rest(AutonomousCharacter character) : base("Rest", character) { this.Duration = 0.5f; } public override float GetGoalChange(Goal goal) { var change = base.GetGoalChange(goal); if (goal.Name == AutonomousCharacter.REST_GOAL) change -= 0.1f; if (goal.Name == AutonomousCharacter.EAT_GOAL) change += 0.1f; return change; } public override bool CanExecute(WorldModel worldModel) { //if (!base.CanExecute(worldModel)) return false; var energy = (float)worldModel.GetProperty(Properties.ENERGY); var hn = (float)worldModel.GetProperty(Properties.HUNGER); return (energy < 2.0f && hn < 9.5); } public override void ApplyActionEffects(WorldModel worldModel) { base.ApplyActionEffects(worldModel); var restValue = worldModel.GetGoalValue(AutonomousCharacter.REST_GOAL); worldModel.SetGoalValue(AutonomousCharacter.REST_GOAL, restValue - 0.1f); var energy = (float)worldModel.GetProperty(Properties.ENERGY); worldModel.SetProperty(Properties.ENERGY, energy + 0.1f); var eatValue = worldModel.GetGoalValue(AutonomousCharacter.EAT_GOAL); worldModel.SetGoalValue(AutonomousCharacter.EAT_GOAL, restValue + 0.1f); var hunger = (float)worldModel.GetProperty(Properties.HUNGER); worldModel.SetProperty(Properties.ENERGY, hunger + 0.1f); } public override void Execute() { base.Execute(); this.Character.GameManager.Rest(); } } } <file_sep>using UnityEngine; namespace Assets.Scripts.Movement.DynamicMovement { public class DynamicStop : DynamicMovement { public override string Name { get { return "Stop"; } } public float TimeToStop { get; set; } public float Delta { get; set; } public override KinematicData Target { get; set; } public DynamicStop(KinematicData character) { this.Target = character; this.Character = character; this.Delta = 0.05f; } public override MovementOutput GetMovement() { MovementOutput output = new MovementOutput(); if (this.Character.velocity.magnitude < Delta) return output; output.linear = -this.Character.velocity; output.linear *= TimeToStop; return output; } } } <file_sep>using System.Collections.Generic; using Assets.Scripts.Pathfinding.DataStructures; using Assets.Scripts.Pathfinding.Heuristics; using Assets.Scripts.Pathfinding.Path; using RAIN.Navigation.Graph; using RAIN.Navigation.NavMesh; using UnityEngine; using Assets.Scripts.TacticalAnalysis; using Assets.Scripts.TacticalAnalysis.DataStructures; namespace Assets.Scripts.Pathfinding { public class InfluenceMapAStarPathfinding : NodeArrayAStarPathFinding { private InfluenceMap RedMap { get; set; } private InfluenceMap GreenMap { get; set; } public InfluenceMapAStarPathfinding(NavMeshPathGraph graph, IHeuristic heuristic, InfluenceMap redMap, InfluenceMap greenMap) : base(graph,heuristic) { this.RedMap = redMap; this.GreenMap = greenMap; } protected new void ProcessChildNode(NodeRecord bestNode, NavigationGraphEdge connectionEdge) { float f; float g; float h; var childNode = connectionEdge.ToNode; var childNodeRecord = this.NodeRecordArray.GetNodeRecord(childNode); if (childNodeRecord == null) { //this piece of code is used just because of the special start nodes and goal nodes added to the RAIN Navigation graph when a new search is performed. //Since these special goals were not in the original navigation graph, they will not be stored in the NodeRecordArray and we will have to add them //to a special structure //it's ok if you don't understand this, this is a hack and not part of the NodeArrayA* algorithm childNodeRecord = new NodeRecord { node = childNode, parent = bestNode, status = NodeStatus.Unvisited }; this.NodeRecordArray.AddSpecialCaseNode(childNodeRecord); } // implement the rest of your code here if (childNodeRecord.status == NodeStatus.Closed) return; float influenceCost = CalculateInfluenceCost(bestNode.node, childNode); if (influenceCost < 0.0f) return; g = bestNode.gValue + connectionEdge.Cost - influenceCost; h = this.Heuristic.H(childNode, this.GoalNode); f = F(g,h); if (childNodeRecord.status == NodeStatus.Open) { if (f <= childNodeRecord.fValue) { childNodeRecord.gValue = g; childNodeRecord.hValue = h; childNodeRecord.fValue = f; childNodeRecord.parent = bestNode; this.NodeRecordArray.Replace(childNodeRecord,childNodeRecord); } } else { childNodeRecord.gValue = g; childNodeRecord.hValue = h; childNodeRecord.fValue = f; childNodeRecord.status = NodeStatus.Open; childNodeRecord.parent = bestNode; this.NodeRecordArray.AddToOpen(childNodeRecord); } } protected float CalculateInfluenceCost(NavigationGraphNode node, NavigationGraphNode child) { float nodeRedInfluence = this.RedMap.GetInfluence(this.Quantize(node.Position)); float nodeGreenInfluence = this.GreenMap.GetInfluence(this.Quantize(node.Position)); float childRedInfluence = this.RedMap.GetInfluence(this.Quantize(child.Position)); float childGreenInfluence = this.GreenMap.GetInfluence(this.Quantize(child.Position)); float securityNodetoChild = nodeRedInfluence - nodeGreenInfluence; float securityChildtoNode = childRedInfluence - childGreenInfluence; return (securityChildtoNode + securityNodetoChild) / 2; } } } <file_sep>using Assets.Scripts.Movement.DynamicMovement; using Assets.Scripts.Pathfinding.Path; using System.Collections.Generic; using UnityEngine; namespace Assets.Scripts.Movement.Arbitration.SteeringPipeline.Components.Actuators { public class ActuatorSwitch : ActuatorComponent { public override string Name { get { return "ActuatorSwitch"; } } public string ActiveActuator { get; set; } public Dictionary<string, ActuatorComponent> Actuators { get; private set; } public ActuatorSwitch(SteeringPipeline pipeline) : base(pipeline) { this.ActiveActuator = this.Name; this.Actuators = new Dictionary<string, ActuatorComponent>(); } public void SwitchActuator(string actuator) { if ((this.ActiveActuator != actuator) && (Actuators.ContainsKey(actuator))) { this.ActiveActuator = actuator; } } public override Path GetPath(SteeringGoal goal) { return new LineSegmentPath(this.Pipeline.Character.position,goal.Position); } public override Path GetPath(GlobalPath path) { return path; } public override MovementOutput GetSteering(Path path) { if (Actuators.ContainsKey(ActiveActuator)) { return Actuators[ActiveActuator].GetSteering(path); } return new MovementOutput(); } } } <file_sep>using Assets.Scripts.Pathfinding.Path; namespace Assets.Scripts.Movement.Arbitration.SteeringPipeline.Components.Decomposers { //A decomposer takes a goal and decomposes it into a a sub-goal public abstract class DecomposerComponent : SteeringPipelineComponent { public DecomposerComponent(SteeringPipeline pipeline) : base(pipeline) { } public abstract SteeringGoal DecomposeGoal(SteeringGoal goal); public abstract GlobalPath DecomposeGoalIntoPath(SteeringGoal goal); } } <file_sep>using System; using UnityEngine; namespace Assets.Scripts.TacticalAnalysis { public class LinearInfluenceFunction : IInfluenceFunction { public float DetermineInfluence(IInfluenceUnit unit, Vector3 location) { return unit.DirectInfluence / (1 + (location - unit.Location.Position).magnitude); } } } <file_sep>using System; using Assets.Scripts.DecisionMaking.GOB; using UnityEngine; using Assets.Scripts.GameManager; namespace Assets.Scripts.DecisionMakingActions { public class PlaceFlag : WalkToPositionAndExecuteAction { public PlaceFlag(AutonomousCharacter character) : base("PlaceFlag", character) { } public override float GetGoalChange(Goal goal) { var change = base.GetGoalChange(goal); if (goal.Name == AutonomousCharacter.CONQUER_GOAL) change -= 2.0f; return change; } public override bool CanExecute(WorldModel worldModel) { if (!base.CanExecute(worldModel)) return false; return true; // (worldModel.GetGoalValue(AutonomousCharacter.CONQUER_GOAL) > 5.5f && worldModel.GetGoalValue(AutonomousCharacter.EAT_GOAL) < 8.5f); } public override void Execute() { base.Execute(); this.Character.GameManager.PlaceFlag(this.Position); if (this.Character.RedFlags.Contains(new Flag(this.Character.navMesh.QuantizeToNode(this.Position, 1.0f), FlagColor.Red))) this.PositionSet = false; } public override void ApplyActionEffects(WorldModel worldModel) { base.ApplyActionEffects(worldModel); var conqValue = worldModel.GetGoalValue(AutonomousCharacter.CONQUER_GOAL); worldModel.SetGoalValue(AutonomousCharacter.CONQUER_GOAL, conqValue - 2.0f); } } } <file_sep>using System.Collections.Generic; using Assets.Scripts.Pathfinding.DataStructures; using Assets.Scripts.Pathfinding.Heuristics; using Assets.Scripts.Pathfinding.Path; using RAIN.Navigation.Graph; using RAIN.Navigation.NavMesh; using UnityEngine; namespace Assets.Scripts.Pathfinding { public class NodeArrayAStarPathFinding : AStarPathfinding { protected NodeRecordArray NodeRecordArray { get; set; } public NodeArrayAStarPathFinding(NavMeshPathGraph graph, IHeuristic heuristic) : base(graph,null,null,heuristic) { //do not change this var nodes = this.GetNodesHack(graph); this.NodeRecordArray = new NodeRecordArray(nodes); this.Open = this.NodeRecordArray; this.Closed = this.NodeRecordArray; } protected void ProcessChildNode(NodeRecord bestNode, NavigationGraphEdge connectionEdge) { float f; float g; float h; var childNode = connectionEdge.ToNode; var childNodeRecord = this.NodeRecordArray.GetNodeRecord(childNode); if (childNodeRecord == null) { //this piece of code is used just because of the special start nodes and goal nodes added to the RAIN Navigation graph when a new search is performed. //Since these special goals were not in the original navigation graph, they will not be stored in the NodeRecordArray and we will have to add them //to a special structure //it's ok if you don't understand this, this is a hack and not part of the NodeArrayA* algorithm childNodeRecord = new NodeRecord { node = childNode, parent = bestNode, status = NodeStatus.Unvisited }; this.NodeRecordArray.AddSpecialCaseNode(childNodeRecord); } // implement the rest of your code here if (childNodeRecord.status == NodeStatus.Closed) return; g = bestNode.gValue + connectionEdge.Cost; h = this.Heuristic.H(childNode, this.GoalNode); f = F(g,h); if (childNodeRecord.status == NodeStatus.Open) { if (f <= childNodeRecord.fValue) { childNodeRecord.gValue = g; childNodeRecord.hValue = h; childNodeRecord.fValue = f; childNodeRecord.parent = bestNode; this.NodeRecordArray.Replace(childNodeRecord,childNodeRecord); } } else { childNodeRecord.gValue = g; childNodeRecord.hValue = h; childNodeRecord.fValue = f; childNodeRecord.status = NodeStatus.Open; childNodeRecord.parent = bestNode; this.NodeRecordArray.AddToOpen(childNodeRecord); } } public override bool Search(out GlobalPath solution, bool returnPartialSolution = false) { var startTime = Time.realtimeSinceStartup; var processedNodes = 0; int count; while (processedNodes < this.NodesPerSearch) { count = this.Open.CountOpen(); if (count == 0) { solution = null; this.InProgress = false; this.CleanUp(); this.TotalProcessingTime += Time.realtimeSinceStartup - startTime; return true; } if (count > this.MaxOpenNodes) { this.MaxOpenNodes = count; } var bestNode = this.NodeRecordArray.GetBestAndRemove(); //goal node found, return the shortest Path if (bestNode.node == this.GoalNode) { solution = this.CalculateSolution(bestNode, false); this.InProgress = false; this.CleanUp(); this.TotalProcessingTime += Time.realtimeSinceStartup - startTime; return true; } this.NodeRecordArray.AddToClosed(bestNode); processedNodes++; this.TotalProcessedNodes++; //put your code here //or if you would like, you can change just these lines of code this in the original A* Pathfinding Class, //create a ProcessChildNode method in the base class with the code from the previous A* algorithm. //if you do this, then you don't need to implement this search method method. Don't forget to override the ProcessChildMethod if you do this var outConnections = bestNode.node.OutEdgeCount; for (int i = 0; i < outConnections; i++) { this.ProcessChildNode(bestNode,bestNode.node.EdgeOut(i)); } } this.TotalProcessingTime += Time.realtimeSinceStartup - startTime; //this is very unlikely but it might happen that we process all nodes alowed in this cycle but there are no more nodes to process if (this.Open.CountOpen() == 0) { solution = null; this.InProgress = false; this.CleanUp(); return true; } //if the caller wants create a partial Path to reach the current best node so far if (returnPartialSolution) { var bestNodeSoFar = this.Open.PeekBest(); solution = this.CalculateSolution(bestNodeSoFar, true); } else { solution = null; } return false; } private List<NavigationGraphNode> GetNodesHack(NavMeshPathGraph graph) { //this hack is needed because in order to implement NodeArrayA* you need to have full acess to all the nodes in the navigation graph in the beginning of the search //unfortunately in RAINNavigationGraph class the field which contains the full List of Nodes is private //I cannot change the field to public, however there is a trick in C#. If you know the name of the field, you can access it using reflection (even if it is private) //using reflection is not very efficient, but it is ok because this is only called once in the creation of the class //by the way, NavMeshPathGraph is a derived class from RAINNavigationGraph class and the _pathNodes field is defined in the base class, //that's why we're using the type of the base class in the reflection call return (List<NavigationGraphNode>) Utils.Reflection.GetInstanceField(typeof(RAINNavigationGraph), graph, "_pathNodes"); } } } <file_sep>using Assets.Scripts.Movement.DynamicMovement; using Assets.Scripts.Pathfinding.Path; namespace Assets.Scripts.Movement.Arbitration.SteeringPipeline.Components.Actuators { public class BasicActuator : ActuatorComponent { public override string Name { get { return "BasicActuator"; } } public BasicActuator(SteeringPipeline pipeline) : base(pipeline) { } public DynamicSeek Seek { get; set; } public override Path GetPath(SteeringGoal goal) { return new LineSegmentPath(this.Pipeline.Character.position, goal.Position); } public override Path GetPath(GlobalPath path) { return path.LocalPaths[0]; } public override MovementOutput GetSteering(Path path) { var target = path.GetPosition(1.0f); this.Seek.Character = this.Pipeline.Character; this.Seek.Target = new KinematicData(new StaticData(target)); this.Seek.MaxAcceleration = this.Pipeline.MaxAcceleration; return this.Seek.GetMovement(); } } } <file_sep>using System; using UnityEngine; namespace Assets.Scripts.Movement.Arbitration.SteeringPipeline.Components.Targeters { public class FixedTargeter : TargeterComponent { public SteeringGoal Target { get; set; } public FixedTargeter(SteeringPipeline pipeline) : base(pipeline) { this.Target = new SteeringGoal(); } public override SteeringGoal GetGoal() { return this.Target; } public void UpdateGoal(SteeringGoal goal) { this.Target = goal; } public void UpdateGoal(Vector3 position) { this.Target.Position = position; } } } <file_sep>using RAIN.Navigation.Graph; namespace Assets.Scripts.Pathfinding.Heuristics { public interface IHeuristic { float H(NavigationGraphNode node, NavigationGraphNode goalNode); } } <file_sep>using Assets.Scripts.Movement.DynamicMovement; using Assets.Scripts.Pathfinding.Path; namespace Assets.Scripts.Movement.Arbitration.SteeringPipeline.Components.Actuators { public class StandStillActuator : ActuatorComponent { public override string Name { get { return "StandStillActuator"; } } private DynamicStop StopMovement { get; set; } public StandStillActuator(SteeringPipeline pipeline) : base(pipeline) { this.StopMovement = new DynamicStop(this.Pipeline.Character) { MaxAcceleration = 40.0f, TimeToStop = 2.0f }; } public override Path GetPath(SteeringGoal goal) { return new LineSegmentPath(this.Pipeline.Character.position,goal.Position); } public override Path GetPath(GlobalPath path) { return path; } public override MovementOutput GetSteering(Path path) { return this.StopMovement.GetMovement(); } } } <file_sep>using System.Collections.Generic; using Assets.Scripts.Utils; using RAIN.Navigation.Graph; using UnityEngine; namespace Assets.Scripts.Pathfinding.Path { public class GlobalPath : Path { public List<NavigationGraphNode> PathNodes { get; protected set; } public List<Vector3> PathPositions { get; protected set; } public bool IsPartial { get; set; } public List<LocalPath> LocalPaths { get; protected set; } public GlobalPath() { this.PathNodes = new List<NavigationGraphNode>(); this.PathPositions = new List<Vector3>(); this.LocalPaths = new List<LocalPath>(); } public void CalculateLocalPathsFromPathPositions(Vector3 initialPosition) { Vector3 previousPosition = initialPosition; for (int i = 0; i < this.PathPositions.Count; i++) { var sqrDistance = (this.PathPositions[i] - previousPosition).sqrMagnitude; if(sqrDistance >= 2.0f) { this.LocalPaths.Add(new LineSegmentPath(previousPosition,this.PathPositions[i])); previousPosition = this.PathPositions[i]; } } } public override float GetParam(Vector3 position, float previousParam) { var localPathIndex = (int)previousParam; if (localPathIndex >= this.LocalPaths.Count) { return this.LocalPaths.Count; } var localPath = this.LocalPaths[localPathIndex]; var localParam1 = localPath.GetParam(position, previousParam - localPathIndex); //if we are at the end of the current local path, try the next one if (localPath.PathEnd(localParam1)) { if (localPathIndex < this.LocalPaths.Count-1) { localPathIndex++; localPath = this.LocalPaths[localPathIndex]; localParam1 = localPath.GetParam(position, 0.0f); } } return localPathIndex + localParam1; } public override Vector3 GetPosition(float param) { var localPathIndex = (int)param; if (localPathIndex >= this.LocalPaths.Count) { return this.LocalPaths[this.LocalPaths.Count-1].GetPosition(1.0f); } var localPath = this.LocalPaths[localPathIndex]; return localPath.GetPosition(param - localPathIndex); } public override bool PathEnd(float param) { return param > this.LocalPaths.Count - MathConstants.EPSILON; } } } <file_sep>using Assets.Scripts.GameManager; using Assets.Scripts.DecisionMaking.GOB; using UnityEngine; using Action = Assets.Scripts.DecisionMaking.GOB.Action; using System; namespace Assets.Scripts.DecisionMakingActions { public abstract class CharacterAction : Action { protected AutonomousCharacter Character { get; set; } protected CharacterAction(string actionName, AutonomousCharacter character) : base(actionName) { this.Character = character; } public override bool CanExecute(WorldModel worldModel) { var en = (float)worldModel.GetProperty(Properties.ENERGY); return en > 0.2; } } }
d3c17148b3b69a21042f9f310fe7b9b458458008
[ "C#" ]
17
C#
IAJ-g04/Lab9
37ce7cb2205b348dafcdc8d6550b7b0aedf1074b
0d4f856c597e0b8a795c91b1fa7d6297a061b4ca
refs/heads/master
<file_sep>CREATE TABLE shop_user( id SERIAL PRIMARY KEY, name varchar(30), hash_password varchar(200), mail varchar (40) ); CREATE TABLE basket( id bigint UNIQUE, user_id bigint, FOREIGN KEY (user_id) REFERENCES shop_user(id) ); CREATE TABLE product( id serial primary key , title varchar(30), price integer ); CREATE TABLE basket_product( basket_id bigint, product_id bigint, FOREIGN KEY(basket_id) REFERENCES basket(id), FOREIGN KEY(product_id) REFERENCES product(id) ); CREATE TABLE auth( id serial primary key, user_id bigint, cookie_value varchar(50), FOREIGN KEY (user_id) REFERENCES shop_user(id) );<file_sep>package repositories; import models.User; public interface UsersRepository extends CrudRepository<User> { User findByMail(String name); } <file_sep>package servlets; import forms.SignUpForm; import org.springframework.jdbc.datasource.DriverManagerDataSource; import repositories.AuthRepository; import repositories.AuthRepositoryImpl; import repositories.UsersRepository; import repositories.UsersRepositoryImpl; import services.UsersService; import services.UsersServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; @WebServlet("/signup") public class SignUp extends HttpServlet { private UsersService usersService; @Override public void init() throws ServletException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setUrl("jdbc:postgresql://localhost:5432/newshop"); UsersRepositoryImpl usersRepository = null; try { usersRepository = new UsersRepositoryImpl(dataSource); } catch (SQLException e) { e.printStackTrace(); } AuthRepositoryImpl authRepository = null; try { authRepository = new AuthRepositoryImpl(dataSource); } catch (SQLException e) { e.printStackTrace(); } usersService = new UsersServiceImpl(usersRepository, authRepository); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("jsp/signUp.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { SignUpForm form = SignUpForm.builder() .name(req.getParameter("name")) .password(req.getParameter("password")) .confirmedpassword(req.getParameter("confirmedpassword")) .mail(req.getParameter("mail")) .build(); if(form.getPassword().equals(form.getConfirmedpassword())){ if(!usersService.isContainMail(form.getMail())){ usersService.registrateUser(form); resp.sendRedirect("/signin"); } else{ System.out.println("Такая почта уже зарегестрирована"); //TODO: джаваскрипт } } else { System.out.println("Неправильный пароль"); //TODO: активировать выполнение джаваскриптового файла } } } <file_sep>package servlets; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; @WebServlet("/basket") public class Basket extends HttpServlet { Connection connection = null; Statement statement = null; private static final String URL = "jdbc:postgresql://localhost:5432/shop"; private static final String USER = "postgres"; private static final String PASSWORD = "<PASSWORD>"; private String select = "SELECT * FROM orders;"; public void init(){ try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection(URL, USER, PASSWORD); statement = connection.createStatement(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); resp.setHeader("Content-Type", "text/html"); try { ResultSet resultSet = statement.executeQuery(select); while(resultSet.next()) { writer.write(resultSet.getString(2)+ " "); } } catch (SQLException e) { e.printStackTrace(); }; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } } <file_sep>package servlets; import com.fasterxml.jackson.databind.ObjectMapper; import models.Auth; import models.Basket; import models.Product; import models.User; import org.springframework.jdbc.datasource.DriverManagerDataSource; import repositories.AuthRepositoryImpl; import repositories.BasketRepositoryImpl; import repositories.ProductsRepositoryJdbcImpl; import repositories.UsersRepositoryImpl; import services.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @WebServlet("/shop") public class MainPageServlet extends HttpServlet { private UsersService usersService; private ProductService productService; private BasketServiceImpl basketService; private List<Long> ids = new ArrayList<>(); private BasketRepositoryImpl basketRepository; private ObjectMapper objectMapper = new ObjectMapper(); private AuthRepositoryImpl authRepository; @Override public void init() throws ServletException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setUrl("jdbc:postgresql://localhost:5432/newshop"); try { authRepository = new AuthRepositoryImpl(dataSource); } catch (SQLException e) { e.printStackTrace(); } UsersRepositoryImpl usersRepository = null; try { usersRepository = new UsersRepositoryImpl(dataSource); } catch (SQLException e) { e.printStackTrace(); } AuthRepositoryImpl authRepository = null; try { authRepository = new AuthRepositoryImpl(dataSource); } catch (SQLException e) { e.printStackTrace(); } usersService = new UsersServiceImpl(usersRepository, authRepository); try { productService = new ProductServiceImpl(new ProductsRepositoryJdbcImpl()); } catch (SQLException e) { e.printStackTrace(); } try { basketRepository = new BasketRepositoryImpl(); basketService = new BasketServiceImpl(basketRepository); } catch (SQLException e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("jsp/shop.jsp").forward(req, resp); // List listWithPriceAndTitle = new ArrayList(); // List<Product> productList = basketService.getAllProductsFromBasket(); // Iterator<Product> iter = productList.iterator(); // while (iter.hasNext()){ // listWithPriceAndTitle.add(iter.next().getPrice()); // listWithPriceAndTitle.add(iter.next().getTitle()); // } // String json = objectMapper.writeValueAsString(listWithPriceAndTitle); // resp.getWriter().write(json); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookies[] = req.getCookies(); Auth auth = null; for (Cookie cookie : cookies) { if (cookie.getName().equals("auth")) { try { auth = Auth.builder().cookieValue(cookie.getValue()).build(); basketRepository.findUserByAuth(auth); } catch (SQLException e) { e.printStackTrace(); } } } Long product_id = Long.valueOf(req.getParameter("productId")); Product product = productService.getProductById(product_id); Basket basket = null; try { User user = authRepository.findUserByAuth(auth); basket = Basket.builder().id(user.getId()).build(); } catch (SQLException e) { e.printStackTrace(); } basketService.addProductByPrimitiveMethod(product, basket); resp.setContentType("application/json"); List<Product> productList = basketService.getAllProductsFromBasket(auth); List newList = new ArrayList(); Iterator<Product> iter = productList.iterator(); while (iter.hasNext()) { product = iter.next(); newList.add(product.getPrice()); newList.add(product.getTitle()); } newList.add(String.valueOf(product.getPrice())); newList.add(product.getTitle()); String json = objectMapper.writeValueAsString(newList); resp.getWriter().write(json); } } <file_sep>package repositories; import lombok.SneakyThrows; import models.User; import javax.swing.tree.RowMapper; import java.sql.*; import java.util.ArrayList; import java.util.List; public class UsersRepositoryJdbcTemplateImpl implements UserRepository { private static final String SQL_SELECT_USER_BY_ID = "SELECT * FROM shop_user WHERE id = ?;"; private static final String SQL_SELECT_ALL_USERS = "SELECT * FROM shop_user;"; private static final String SQL_SAVE_USER = "INSERT INTO shop_user(name) VALUES (?);"; private static final String SQL_DELETE_USER_BY_ID = "DELETE FROM shop_user WHERE id = ?"; private Connection connection; public UsersRepositoryJdbcTemplateImpl(Connection connection) { this.connection = connection; } public List<User> findAll() throws SQLException { PreparedStatement statement = connection.prepareStatement(SQL_SELECT_ALL_USERS); ResultSet resultSet = statement.executeQuery(); List<User> users = new ArrayList<User>(); while (resultSet.next()){ User user = User.builder() .id(resultSet.getLong(1)) .name(resultSet.getString(2)) .build(); users.add(user); } return users; } public User find(Long id) throws SQLException { PreparedStatement statement = connection.prepareStatement(SQL_SELECT_USER_BY_ID); ResultSet resultSet = statement.executeQuery(); return User.builder() .id(resultSet.getLong(1)) .name(resultSet.getString(2)) .build(); } @SneakyThrows public void save(User model) throws SQLException { PreparedStatement statement = connection.prepareStatement(SQL_SAVE_USER); statement.setString(1,model.getName()); statement.execute(); } public void delete(Long id) throws SQLException { PreparedStatement statement = connection.prepareStatement(SQL_DELETE_USER_BY_ID); statement.setLong(1,id); statement.execute(); } public void update(User model) { } } <file_sep>CREATE TABLE orders( id serial primary key, name varchar(40), basket_id bigint ); CREATE TABLE cookie( id serial primary key, name varchar(40) ); CREATE TABLE order_id_cookie_id( cookie_id bigint, order_id bigint, FOREIGN KEY (cookie_id) REFERENCES cookie(id), FOREIGN KEY (order_id) REFERENCES orders(id) ); DELETE FROM orders;<file_sep>package services; import forms.SignInForm; import forms.SignUpForm; public interface UsersService { void registrateUser(SignUpForm form); String signIn(SignInForm form); boolean isContainMail(String mail); boolean isExistByCookie(String value); } <file_sep>package servlets; import Repository.Jdbc; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; @WebServlet("/shop") public class Servlet extends HttpServlet { Connection connection = null; Statement statement = null; private static final String URL = "jdbc:postgresql://localhost:5432/shop"; private static final String USER = "postgres"; private static final String PASSWORD = "<PASSWORD>"; @Override public void init(){ try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection(URL, USER, PASSWORD); statement = connection.createStatement(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("jsp/shop.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List list = new ArrayList(); Cookie[] cookies = req.getCookies(); Cookie c = null; for(Cookie cookie : cookies){ if(cookie.getName().equals("basket")){ c = cookie; break; } } if (c == null){ Cookie cookie = new Cookie("basket","" + 1); cookie.setMaxAge(60*60*24); resp.addCookie(cookie);// todo: дубликация } System.out.println(req.getParameter("product")); if (req.getParameter("product")!= null){ try { System.out.println("insert into " + "orders(basket_id,name)" + " values ("+c.getValue() + ", "+ req.getParameter("product") + ");"); statement.executeUpdate("insert into " + "orders(basket_id, pname)" + " values ("+c.getValue() + ", '"+ req.getParameter("product") + "');"); } catch (SQLException e) { e.printStackTrace(); } } // if (req.getParameter("bubblegum") != null){ // // Cookie cookie = new Cookie("Product","" +1); // cookie.setMaxAge(60*60*24); // resp.addCookie(cookie); // } req.getRequestDispatcher("jsp/shop.jsp").forward(req, resp); resp.sendRedirect("/shop"); } } <file_sep>package servlets; import com.fasterxml.jackson.databind.ObjectMapper; import models.Card; import models.User; import org.springframework.jdbc.datasource.DriverManagerDataSource; import repositories.AuthRepository; import repositories.AuthRepositoryImpl; import repositories.UsersRepositoryImpl; import services.ManagerService; import services.ManagerServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @WebServlet("/addclient") public class ManagerServlet extends HttpServlet { private ManagerServiceImpl managerService; private AuthRepositoryImpl authRepository; private ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("jsp/addclient.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); Long id = Long.parseLong(req.getParameter("id")); User user = User.builder().card(Card.builder().id(id).build()).build(); managerService.openOrder(user); resp.sendRedirect("/main"); } @Override public void init() throws ServletException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setUrl("jdbc:postgresql://localhost:5432/time_cafe"); authRepository = new AuthRepositoryImpl(dataSource); managerService = new ManagerServiceImpl(dataSource, authRepository); UsersRepositoryImpl usersRepository = new UsersRepositoryImpl(dataSource); } } <file_sep>package repositories; import models.Auth; import models.User; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import javax.sql.DataSource; import java.sql.*; import java.util.List; import org.springframework.dao.EmptyResultDataAccessException; public class AuthRepositoryImpl implements AuthRepository { private JdbcTemplate jdbcTemplate; //language=SQL private static final String SQL_INSERT = "insert into auth(user_id, cookie_value) values (?, ?)"; //language=SQL private static final String SQL_SELECT_BY_COOKIE_VALUE = "select * from auth where cookie_value = ?"; private static final String URL = "jdbc:postgresql://localhost:5432/newshop"; private static final String USER = "postgres"; private static final String PASSWORD = "<PASSWORD>"; private static int numberOfBasket = 0; private static final String SQL_SELECT_BY_AUTH = "SELECT user_id FROM auth WHERE auth = ?"; Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement preparedStatement; public AuthRepositoryImpl(DataSource dataSource) throws SQLException { this.jdbcTemplate = new JdbcTemplate(dataSource); } private RowMapper<Auth> authRowMapper = new RowMapper<Auth>() { public Auth mapRow(ResultSet resultSet, int i) throws SQLException { return Auth.builder() .id(resultSet.getLong("user_id")) .cookieValue(resultSet.getString("cookie_value")) .build(); } }; public Auth findByCookieValue(String cookieValue) { try { return jdbcTemplate.queryForObject(SQL_SELECT_BY_COOKIE_VALUE, authRowMapper, cookieValue); } catch (EmptyResultDataAccessException e) { return null; } } public List<Auth> findAll() { return null; } public Auth find(Long id) { return null; } public void save(Auth model) { jdbcTemplate.update(SQL_INSERT, model.getUser().getId(), model.getCookieValue()); } public void delete(Long id) { } public void update(Auth model) { } //TODO: Сделать метод finduserbyAuth public User findUserByAuth(Auth auth) throws SQLException { preparedStatement = connection.prepareStatement(SQL_SELECT_BY_COOKIE_VALUE); ResultSet resultSet; preparedStatement.setString(1,auth.getCookieValue()); resultSet = preparedStatement.executeQuery(); resultSet.next(); return User.builder().id(resultSet.getLong(2)).build(); } } <file_sep>package repositories; import models.Card; public interface CardRepository extends CrudRepository<Card> { Integer getDiscontFromCard(Card card); } <file_sep>CREATE TABLE shop_user( id bigserial primary key, name varchar(40) ); CREATE TABLE product( id serial primary key, title varchar(30) ); CREATE TABLE basket( id bigserial primary key, user_id bigint, foreign key (user_id) references shop_user(id) ); CREATE TABLE basket_product( basket_id bigint, product_id bigint foreign key (basket_id) references basket(id), foreign key (product_id) references product(id), ); INSERT INTO product(title) VALUES ('trying'); INSERT INTO product(title) VALUES ('bubblegum'); INSERT INTO product (title) VALUES ('bubblegum');<file_sep>package servlets; import models.Card; import models.User; import org.springframework.jdbc.datasource.DriverManagerDataSource; import repositories.AuthRepositoryImpl; import repositories.UsersRepositoryImpl; import services.ManagerServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet("/addcard") public class AddCardServlet extends HttpServlet { ManagerServiceImpl managerService; @Override public void init() throws ServletException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setUrl("jdbc:postgresql://localhost:5432/time_cafe"); AuthRepositoryImpl authRepository = new AuthRepositoryImpl(dataSource); managerService = new ManagerServiceImpl(dataSource, authRepository); UsersRepositoryImpl usersRepository = new UsersRepositoryImpl(dataSource); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("jsp/addcard.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Long id = Long.parseLong(req.getParameter("id")); String name = req.getParameter("name"); String phone = req.getParameter("phone"); managerService.addNewUserWithCard(User.builder().card(Card.builder().id(id).build()) .name(name).numberOfPhone(phone).countOfVisiting(0).build()); } } <file_sep>ALTER TABLE shop_user ADD COLUMN mail varchar(40);<file_sep>package servlets; import forms.SignInForm; import org.springframework.jdbc.datasource.DriverManagerDataSource; import repositories.AuthRepositoryImpl; import repositories.UsersRepositoryImpl; import services.ManagerServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/auth") public class AuthServlet extends HttpServlet { private ManagerServiceImpl managerService; private AuthRepositoryImpl authRepository; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("jsp/auth.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { SignInForm form = SignInForm.builder() .login(req.getParameter("login")) .password(req.getParameter("password")) .build(); String cookieValue = managerService.signIn(form); if(cookieValue != null){ Cookie auth = new Cookie("auth", cookieValue); resp.addCookie(auth); resp.sendRedirect("/main"); } else{ resp.sendRedirect("/auth");//TODO: сделать надпись "некорректный пароль" } } @Override public void init() throws ServletException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setUrl("jdbc:postgresql://localhost:5432/time_cafe"); authRepository = new AuthRepositoryImpl(dataSource); managerService = new ManagerServiceImpl(dataSource, authRepository); UsersRepositoryImpl usersRepository = new UsersRepositoryImpl(dataSource); } } <file_sep>package repositories; import models.User; public interface UsersRepository extends CrudRepository<User> { User findByName(String name); void addNewClientWithCard(User user); }<file_sep>package servlets; import com.fasterxml.jackson.databind.ObjectMapper; import models.Card; import models.User; import org.springframework.jdbc.datasource.DriverManagerDataSource; import repositories.AuthRepositoryImpl; import repositories.UsersRepositoryImpl; import services.ManagerServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; @WebServlet("/main") public class MainServlet extends HttpServlet { private ManagerServiceImpl managerService; private AuthRepositoryImpl authRepository; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<User> list = new ArrayList<User>(); list = managerService.getAllClientsInCafe(); resp.setContentType("application/json"); req.setAttribute("clients", list); req.getRequestDispatcher("jsp/main.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override public void init() throws ServletException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setUrl("jdbc:postgresql://localhost:5432/time_cafe"); authRepository = new AuthRepositoryImpl(dataSource); managerService = new ManagerServiceImpl(dataSource, authRepository); UsersRepositoryImpl usersRepository = new UsersRepositoryImpl(dataSource); } } <file_sep>package services; import models.Product; import repositories.ProductsRepositoryJdbcImpl; import java.sql.SQLException; public class ProductServiceImpl implements ProductService { ProductsRepositoryJdbcImpl productsRepositoryJdbc; public ProductServiceImpl(ProductsRepositoryJdbcImpl productsRepositoryJdbc) throws SQLException { this.productsRepositoryJdbc = new ProductsRepositoryJdbcImpl(); } @Override public Product getProductById(Long id) { Product product = productsRepositoryJdbc.find(id); return product; } } <file_sep>package repositories; import models.Basket; import models.Product; public interface BasketRepository extends CrudRepository<Product> { void save(Product model, Basket basket); } <file_sep>package forms; public class AddUserInDatabase { private Long id; private String name; private String phone; private String email; }<file_sep>package servlets; import models.Card; import models.User; import org.springframework.jdbc.datasource.DriverManagerDataSource; import repositories.AuthRepositoryImpl; import repositories.UsersRepositoryImpl; import services.ManagerServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/closeOrder") public class CloseOrderServlet extends HttpServlet { AuthRepositoryImpl authRepository; ManagerServiceImpl managerService; @Override public void init() throws ServletException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("<PASSWORD>"); dataSource.setUrl("jdbc:postgresql://localhost:5432/time_cafe"); authRepository = new AuthRepositoryImpl(dataSource); managerService = new ManagerServiceImpl(dataSource, authRepository); UsersRepositoryImpl usersRepository = new UsersRepositoryImpl(dataSource); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Long id = Long.parseLong(req.getParameter("id")); long cost = managerService.closeOrder(User.builder().card(Card.builder().id(Long.parseLong(req.getParameter("id"))).build()).build()); req.setAttribute("cost", cost); resp.sendRedirect("/main"); } } <file_sep>package repositories; import models.Manager; import models.User; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; public class ManagerRepositoryImpl implements ManagerRepository { private JdbcTemplate jdbcTemplate; public ManagerRepositoryImpl(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } private final String SQL_SELECT_BY_LOGIN = "SELECT * FROM manager WHERE login = ?"; private RowMapper<Manager> managerRowMapper = new RowMapper<Manager>() { @Override public Manager mapRow(ResultSet rs, int rowNum) throws SQLException { return Manager.builder() .login(rs.getString("login")) .password(<PASSWORD>("<PASSWORD>")) .name(rs.getString("name")) .build(); } }; @Override public Manager findByLogin(String login) { try { return jdbcTemplate.queryForObject(SQL_SELECT_BY_LOGIN, managerRowMapper, login); } catch (EmptyResultDataAccessException e) { return null; } } } <file_sep>package repositories; import models.Card; import models.User; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.sql.Timestamp; public class UsersRepositoryImpl implements UsersRepository { private JdbcTemplate jdbcTemplate; public UsersRepositoryImpl(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } private RowMapper<User> userRowMapper = new RowMapper<User>() { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { return User.builder() .id(rs.getLong("user_id")) .countOfVisiting(rs.getInt("count_of_visiting")) .numberOfPhone(rs.getString("phone")) .name(rs.getString("name")) .card(Card.builder().id(rs.getLong("card_id")).build()) .build(); } }; private RowMapper<User> userInCafeRowMapper = new RowMapper<User>() { @Override public User mapRow(ResultSet resultSet, int i) throws SQLException { return User.builder() .card(Card.builder().id(resultSet.getLong("user_card_id")).build()) .name(resultSet.getString("name")) .timeOfArraving(resultSet.getTimestamp("in_time")) .timeOfLeave(resultSet.getTimestamp("out_time")) .build(); } }; private int cafeId = 1; private String SQL_SELECT_BY_NAME = "SELECT * FROM userofcafe where name = ?";//TODO: продумать private String SQL_WRITE_USER = "insert into cafe_user(cafe_id,user_card_id,in_time) VALUES (?,?,?)"; private static final String SQL_UPDATE_VISITING = "UPDATE userofcafe SET count_of_visiting = count_of_visiting+1 WHERE card_id = ?"; private static final String SQL_SELECT_ALL = "SELECT * FROM userofcafe JOIN card on userofcafe.card_id = card.card_id"; private String SQL_INSERT_INCOME = "INSERT INTO income(cafe_id, user_id, sum) VALUES (?,?,?)"; private String SQL_INSERT_OUTTIME = "UPDATE cafe_user SET out_time = ? WHERE user_card_id = ?"; private String SQL_SELECT_ALL_FROM_CAFE = "SELECT DISTINCT user_card_id,in_time,out_time,name FROM cafe_user JOIN userofcafe ON (cafe_user.user_card_id = userofcafe.card_id)"; private String SQL_DELETE = "DELETE FROM cafe_user WHERE user_card_id = ?"; private String SQL_SELECT_BY_ID = "SELECT DISTINCT * FROM cafe_user JOIN userofcafe ON (cafe_user.user_card_id = userofcafe.card_id) where user_card_id = ?"; private String SQL_INSERT_USER = "INSERT INTO userofcafe(name, card_id, count_of_visiting, phone) VALUES (?,?,?,?)"; private String SQL_INSERT_CARD = "INSERT INTO card(card_id, percent, description, cafe_id) VALUES (?,?,?,1)"; @Override public User findByName(String name) { try { return jdbcTemplate.queryForObject(SQL_SELECT_BY_NAME, userRowMapper, name); } catch (EmptyResultDataAccessException e) { return null; } } @Override public void addNewClientWithCard(User user) { jdbcTemplate.update(SQL_INSERT_CARD, user.getCard().getId(),user.getCard().getPercent(),user.getCard().getDescription()); jdbcTemplate.update(SQL_INSERT_USER, user.getName(), user.getCard().getId(),user.getCountOfVisiting(),user.getNumberOfPhone()); } public List<User> findAllFromCafe() { return jdbcTemplate.query(SQL_SELECT_ALL_FROM_CAFE,userInCafeRowMapper); } @Override public List<User> findAll() { return jdbcTemplate.query(SQL_SELECT_ALL,userRowMapper); } @Override public List<User> find(Long id) { return jdbcTemplate.query(SQL_SELECT_BY_ID,userInCafeRowMapper,id); } @Override public void save(User model) { jdbcTemplate.update(SQL_INSERT_USER, model.getName(), model.getNumberOfPhone()); } @Override public void delete(Long id) { jdbcTemplate.update(SQL_DELETE,id); } @Override public void update(User model) { } //"insert into cafe_user(cafe_id,user_card_id,in_time) VALUES (?,?,?)" public void write(User user) { Timestamp timeStamp = new Timestamp(new Date().getTime()); jdbcTemplate.update(SQL_WRITE_USER, cafeId,user.getCard().getId(),timeStamp); } public User unwrite(User user){ Timestamp timestamp = new Timestamp(new Date().getTime()); jdbcTemplate.update(SQL_INSERT_OUTTIME, timestamp,user.getCard().getId()); user = this.find(user.getCard().getId()).get(0); jdbcTemplate.update(SQL_UPDATE_VISITING,user.getCard().getId()); this.delete(user.getCard().getId()); return user; } } <file_sep>package repositories; import models.User; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import javax.sql.DataSource; import java.sql.*; import java.util.List; public class UsersRepositoryImpl implements UsersRepository { private JdbcTemplate jdbcTemplate; //language=SQL private static final String SQL_SELECT_USER_BY_ID = "select * from shop_user where id=?"; //language=SQL private static final String SQL_SELECT_ALL_USERS = "select * from shop_user"; //language=SQL private static final String SQL_SELECT_BY_Mail = "select * from shop_user where mail = ?"; //language=SQL private static final String SQL_INSERT_USER = "INSERT INTO shop_user(name,hash_password,mail) VALUES (?,?,?)"; private static final String URL = "jdbc:postgresql://localhost:5432/newshop"; private static final String USER = "postgres"; private static final String PASSWORD = "<PASSWORD>"; private static long numberOfUser = 6; Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement preparedStatement; private RowMapper<User> userRowMapper = (resultSet, i) -> User.builder() .id(resultSet.getLong("id")) .name(resultSet.getString("name")) .password(resultSet.getString("<PASSWORD>_password")) .mail("mail") .build(); public UsersRepositoryImpl(DataSource dataSource) throws SQLException { this.jdbcTemplate = new JdbcTemplate(dataSource); } public User findByMail(String mail) { try { return jdbcTemplate.queryForObject(SQL_SELECT_BY_Mail, userRowMapper, new Object[]{mail}); } catch (EmptyResultDataAccessException e) { return null; } } public List<User> findAll() { return jdbcTemplate.query(SQL_SELECT_ALL_USERS, userRowMapper);//userRowMapper? } public User find(Long id) { return jdbcTemplate.queryForObject(SQL_SELECT_USER_BY_ID, userRowMapper, new Object[]{id}); } public void save(User model, Long basketId) { ResultSet resultSet; Long id = null; try { preparedStatement = connection.prepareStatement("SELECT id FROM shop_user ORDER BY id DESC LIMIT 1"); resultSet = preparedStatement.executeQuery(); resultSet.next(); id = resultSet.getLong(1); } catch (SQLException e) { e.printStackTrace(); } jdbcTemplate.update(SQL_INSERT_USER, model.getName(), model.getPassword(), model.getMail()); try { preparedStatement = connection.prepareStatement("INSERT INTO basket(id, user_id) VALUES (?,?)"); preparedStatement.setLong(1,id+1); preparedStatement.setLong(2,id+1); preparedStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } } public void save(User user) throws SQLException { ResultSet resultSet; preparedStatement = connection.prepareStatement(SQL_INSERT_USER); preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getPassword()); preparedStatement.setString(3, user.getMail()); preparedStatement.execute(); } public void delete(Long id) { } public void update(User model) { } }
2e02f7dceb36a12dcfd914eba8bd1ee704ab225e
[ "Java", "SQL" ]
25
SQL
AminovE99/RepositoryWithHomeWork
197154123123b42be53973c1602270a0ff64d7ef
d0f74275910d614c2ea43eb26583398f36ccbfb2
refs/heads/master
<file_sep>var express = require('express'); var app = express(); //CORS // app.use(function(req, res, next) { // res.header("Access-Control-Allow-Origin", "*"); // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // next(); // }); app.get('/test', function (req, res) { console.log('req: ',req) res.json({ servStat: "connected to server" }); }); app.listen(5000, function () { console.log('Example app listening on port 5000!'); });
31d5faa9aedb81983d39db4170aa012d87cd459f
[ "JavaScript" ]
1
JavaScript
ferfromhell/dummyapp-server
be1b4be1e13b1e58bd34a8806d5a6612abd1a8d3
6e14c7ca39a5a7bac4fdfcc679ac9d5986b75754
refs/heads/master
<file_sep>This folder contains examples on how to use the CloudRail SI node.js library * The "simple" folder contains a very basic example of how to use a service where the redirectReceiver parameter to the service constructor can be null (interfaces Payment, Email, SMS, Point of Interest) * The "local-oauth" folder contains a simple example of how to use a service that needs a redirectReceiver implementation, using one that works for local testing (interfaces Cloud Storage, (Social) Profiles) * The "express-mongo-oauth" folder has an example that showcases how to proceed with a more complex real world setup including a server and a database on the example of the ME(A)N stack. It makes sure authentication with OAuth works even when there are mutliple instances of the server running behind the same address and redirects cannot be guaranteed to always land on the instance that started the authentication * The folder "typescript-promises" has an example that shows how to use the library with Typescript and how the library's API can be promisified to be used with Promises instead of callbacks * The folder "electron" has a tiny app that demonstrates how to use the SDK with the electron framework * The folder "express-oauth-cloudstorage" shows a minimalistic exmaple of a real world server setup for authentication <file_sep>const cloudrail = require("cloudrail-si"); cloudrail.Settings.setKey("[Your CloudRail license key]"); const {BrowserWindow} = require("electron").remote; const logoutButton = document.getElementById("logout-button"); const spaceButton = document.getElementById("space-button"); const spacePane = document.getElementById("space-pane"); const DB_CREDS = "dropboxCredentials"; const clientId = "[clientID]"; const clientSecret = "[clientSecret]"; const redirectUrl = "http://localhost:12345/auth"; // can be any redirect URL registered in your Dropbox app const state = "state"; const dropbox = new cloudrail.services.Dropbox( cloudrail.RedirectReceivers.getElectronAuthenticator(BrowserWindow, redirectUrl), clientId, clientSecret, redirectUrl, state ); // Restore credentials if present let credentials = window.localStorage.getItem(DB_CREDS); if (credentials) dropbox.loadAsString(credentials); spaceButton.addEventListener("click", event => { spacePane.textContent = "Please wait"; dropbox.getAllocation((err, allocation) => { if (err) { spacePane.textContent = "Could not get space allocation"; } else { window.localStorage.setItem(DB_CREDS, dropbox.saveAsString()); // save/update credentials persistently to avoid unnecessary logins spacePane.textContent = "Space used in Bytes: " + allocation.used + " of " + allocation.total; } }); }); logoutButton.addEventListener("click", event => { dropbox.logout(); // make the dropbox object forget about the user window.localStorage.removeItem(DB_CREDS); // remove the credentials from localstorage });
5ca9bf3fc541af183eaf007468197bf6395ebbca
[ "Markdown", "JavaScript" ]
2
Markdown
stefb965/cloudrail-si-node-sdk
d6c952997d7dd5eba064243c539037908151d9fd
da8b1655462e3fc6737609eb2c43178b935a3aba
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <unistd.h> #include <stdint.h> #define buf_size 32 #define N 624 #define M 397 #define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ void *Producer(); void *Consumer(); int buf_index = 0; int buf_c_index = 0; int counter = 300; int **buffer; /* Declaring thread signals and mutex */ pthread_cond_t buf_not_empty = PTHREAD_COND_INITIALIZER; pthread_cond_t buf_not_full = PTHREAD_COND_INITIALIZER; pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER; static unsigned long mt[N]; /* the array for the state vector */ static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ int X86SYSTEM; void init_genrand(unsigned long s) { mt[0]= s & 0xffffffffUL; for (mti=1; mti<N; mti++) { mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by <NAME> */ mt[mti] &= 0xffffffffUL; /* for >32 bit machines */ } } int checkSystemType() { unsigned int eax = 0x01; unsigned int ebx; unsigned int ecx; unsigned int edx; __asm__ __volatile__( "cpuid;" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(eax) ); if (ecx & 0x40000000) { X86SYSTEM = 1; } else{ X86SYSTEM = 0; } return X86SYSTEM; } unsigned long genrand_int32(void) { unsigned long y; static unsigned long mag01[2]={0x0UL, MATRIX_A}; /* mag01[x] = x * MATRIX_A for x=0,1 */ if (mti >= N) { /* generate N words at one time */ int kk; if (mti == N+1) /* if init_genrand() has not been called, */ init_genrand(5489UL); /* a default initial seed is used */ for (kk=0;kk<N-M;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } for (;kk<N-1;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } int genRandomNumber(int floor, int ceiling) { int num = 0; if(X86SYSTEM == 0) { num = (int)genrand_int32();//floor } else { __asm__ __volatile__("rdrand %0":"=r"(num)); } num = abs(num % (ceiling - floor)); if(num < floor) { return floor; } return num; } int rdrand16_step (uint16_t *rand) { unsigned char ok; asm volatile ("rdrand %0; setc %1" : "=r" (*rand), "=qm" (ok)); return (int) ok; } int rdrand32_step (uint32_t *rand) { unsigned char ok; __asm__ __volatile__ ("rdrand %0; setc %1" : "=r" (*rand), "=qm" (ok)); return (int) ok; } int rdrand64_step (uint64_t *rand) { unsigned char ok; asm volatile ("rdrand %0; setc %1" : "=r" (*rand), "=qm" (ok)); return (int) ok; } int main() { pthread_t ptid, ctid; int r=32,c=2,i; buffer = (int **)malloc(r * sizeof(int *)); for ( i=0; i<r; i++) buffer[i] = (int *)malloc(c * sizeof(int)); pthread_create(&ptid, NULL, Producer, NULL); pthread_create(&ctid, NULL, Consumer, NULL); pthread_join(ptid, NULL); pthread_join(ctid, NULL); return 0; } void *Producer() { int min,sec_i,i; srand (time(NULL)); for( i = 1; i <= counter; i++){ pthread_mutex_lock(&mux); if(buf_index == -1){ buf_index++; } if(buf_index == buf_size){ pthread_cond_wait(&buf_not_full, &mux); } buffer[buf_index][0] = i; /* Puting a value into the buffer to produce */ // sec_i= rand() % 7 + 2; sec_i=genRandomNumber(2, 9); buffer[buf_index][1] = sec_i; /* Puting a value into the buffer to produce */ printf("Producer produce, Index %d : %d \n", buf_index, buffer[buf_index][0]); buf_index++; pthread_mutex_unlock(&mux); pthread_cond_signal(&buf_not_empty); /* Signal Comsumer that buffer is not empty */ //min = rand() % 4 + 3; min=genRandomNumber(3, 7); sleep(min); } return NULL; } void *Consumer() { int temp; sleep(10); int j; for( j = 1; j <= counter; j++){ pthread_mutex_lock(&mux); buf_index--; /* Decrement to get adjusted index */ if(buf_index == -1){ pthread_cond_wait(&buf_not_empty, &mux); } else if(buf_index == buf_size){ /* Constraining the index */ buf_index--; } else{ buf_index++; printf("Consumer consume, Index: %d : %d \n", buf_index, buffer[0][0]); temp=buffer[0][1]; int i; for( i=0; i<buf_index-1;i++){ buffer[i][0]=buffer[i+1][0]; //buffer[i+1]=11111; //printf("buffer[%d]: %d\n",i,buffer[i]); } //sleep(temp); buf_index--; } pthread_mutex_unlock(&mux); pthread_cond_signal(&buf_not_full); /* Signal Producer that buffer is not full */ sleep(temp); } return NULL; }
e418e79fa0c221c0a0e1706831dc53670db3a4ca
[ "C" ]
1
C
cs444/hw1
8e3c385294940ade76f79091d272e87d9f1b800c
ac97292fb223973e39007528920c4b81af4ae40e
refs/heads/master
<file_sep>/* JS Document */ /****************************** [Table of Contents] 1. Vars and Inits 2. Set Header 3. Init Menu 4. Init Tabs 5. Init Scrolling 6. Init Gallery ******************************/ $(document).ready(function() { "use strict"; /* 1. Vars and Inits */ initTabs(); initwtabs(); initScrolling(); $(window).on('resize', function() { setHeader(); setTimeout(function() { $(window).trigger('resize.px.parallax'); }, 375); }); $(document).on('scroll', function() { setHeader(); }); /* 2. Set Header */ function setHeader() { var header = $('.header'); if($(window).scrollTop() > 91) { header.addClass('scrolled'); } else { header.removeClass('scrolled'); } } /* 3. Init Menu */ function initMenu() { if($('.menu').length && $('.hamburger').length) { var menu = $('.menu'); var menuCont = $('.menu_content'); var hamburger = $('.hamburger'); var close = $('.menu_close'); var Element = document.getElementById('menuId'); hamburger.on('click', function() { Element.style.display= "block"; hideOnClickOutside(Element) }); close.on('click', function() { Element.style.display= "none"; }); const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ) function hideOnClickOutside(Element) { const outsideClickListener = event => { if ( (Element.contains(event.target)) && isVisible(Element)) { Element.style.display = 'none' removeClickListener() } } const removeClickListener = () => { document.removeEventListener('click', outsideClickListener) } document.addEventListener('click', outsideClickListener) } } } /* 4. Init Tabs */ function initTabs() {$('.tab').removeClass('active'); $('.tab1').addClass('active'); if($('.tab').length) { $('.tab').on('click', function() { $('.tab').removeClass('active'); $(this).addClass('active'); var clickedIndex = $('.tab').index(this); var panels = $('.tab_panel'); panels.removeClass('active'); $(panels[clickedIndex]).addClass('active'); setTimeout(function() { $(window).trigger('resize.px.parallax'); }, 375); }); } } function initwtabs() { if($('.wtab').length) { $('.wtab').on('click', function() { $('.wtab').removeClass('active'); $(this).addClass('active'); var clickedIndex = $('.wtab').index(this); var panels = $('.wtab_panel'); panels.removeClass('active'); $(panels[clickedIndex]).addClass('active'); setTimeout(function() { $(window).trigger('resize.px.parallax'); }, 375); }); } } /* 5. Init Scrolling */ function initScrolling() { if($('.scroll_link').length) { var links = $('.scroll_link'); links.each(function() { var ele = $(this); var target = ele.data('scroll-to'); ele.on('click', function(e) { e.preventDefault(); $(window).scrollTo(target, 1500, {offset: -75, easing: 'easeInOutQuart'}); }); }); } } /* 6. Init Gallery */ function initGallery() { if($('.gallery_item').length) { $('.colorbox').colorbox( { rel:'colorbox', photo: true, maxWidth:'95%', maxHeight:'95%' }); } } });<file_sep>const openModalButtons = document.querySelectorAll('[data-modal-target]') const closeModalButtons = document.querySelectorAll('[data-close-button]') const overlay = document.getElementById('overlay') openModalButtons.forEach(button => { button.addEventListener('click', () => { const modal = document.querySelector(button.dataset.modalTarget) openModal(modal) }) }) overlay.addEventListener('click', () => { const modals = document.querySelectorAll('.modal.active') modals.forEach(modal => { closeModal(modal) }) }) closeModalButtons.forEach(button => { button.addEventListener('click', () => { const modal = button.closest('.modal') closeModal(modal) }) }) function openModal(modal) { if (modal == null) return modal.classList.add('active') overlay.classList.add('active') } function closeModal(modal) { if (modal == null) return modal.classList.remove('active') overlay.classList.remove('active') } // // $(document).ready(function() // // { // // lock('landscape'); // function lock (orientation) { // // Go into full screen first // if (document.documentElement.requestFullscreen) { // screen.orientation.lock('landscape'); // } // // Then lock orientation // screen.orientation.lock('landscape'); // } // function unlock () { // // Unlock orientation // screen.orientation.unlock(); // // Exit full screen // if (document.exitFullscreen) { // document.exitFullscreen(); // } // } // // }<file_sep><!DOCTYPE html> <html lang="en"> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-EFM7KDK600"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-EFM7KDK600'); </script> <title>Register</title> <link rel="shortcut icon" href="iasam.ico" type="image/x-icon"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="IAS Tunisia Annual Meeting"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="styles/bootstrap-4.1.2/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="plugins/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/owl.carousel.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/owl.theme.default.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/animate.css"> <link rel="stylesheet" type="text/css" href="plugins/colorbox/colorbox.css"> <link rel="stylesheet" type="text/css" href="styles/header.css"> <link rel="stylesheet" type="text/css" href="styles/footer.css"> <link rel="stylesheet" type="text/css" href="styles/menu.css"> <link rel="stylesheet" type="text/css" href="styles/CTA.css"> <link rel="stylesheet" type="text/css" href="styles/registration.css"> <link rel="stylesheet" type="text/css" href="styles/registration_responsive.css"> <link rel="stylesheet" type="text/css" href="styles/commun.css"> </head> <body> <div class="super_container"> <!-- Header --> <?php include "header.php" ?> <!-- Menu --> <?php include "menu.php" ?> <!-- Home --> <!-- <div class="home"> <div class="home_container"> <div class="container"> <div class="row"> <div class="col"> <div class="home_content"> <div class="home_title"><h1>Register2</h1></div> <div class="breadcrumbs"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li><a href="index">Home</a></li> <li>Register</li> </ul> </div> </div> </div> </div> </div> </div> </div> --> <div class="intro"> <div class="container"> <div class="row"> <div class="col text-center"> <div class="form"> <iframe src="https://docs.google.com/forms/d/e/1FAIpQLSfqkcW7c_8KrFXkqxmhFJe_EdmHsUSfHh2HOAsl84q4rzRMGg/viewform?embedded=true" width="100%" height="550" frameborder="0" marginheight="0" marginwidth="0">Chargement…</iframe> <!-- scrolling="no" --> </div> </div> </div> </div> </div> </div> </body> <!-- CTA --> <!-- Footer --> <?php include "footer.php"; ?> </div> <script src="js/jquery-3.3.1.min.js"></script> <script src="styles/bootstrap-4.1.2/popper.js"></script> <script src="styles/bootstrap-4.1.2/bootstrap.min.js"></script> <script src="plugins/greensock/TweenMax.min.js"></script> <script src="plugins/greensock/TimelineMax.min.js"></script> <script src="plugins/scrollmagic/ScrollMagic.min.js"></script> <script src="plugins/greensock/animation.gsap.min.js"></script> <script src="plugins/greensock/ScrollToPlugin.min.js"></script> <script src="plugins/OwlCarousel2-2.3.4/owl.carousel.js"></script> <script src="plugins/colorbox/jquery.colorbox-min.js"></script> <script src="plugins/easing/easing.js"></script> <script src="plugins/progressbar/progressbar.min.js"></script> <script src="plugins/parallax-js-master/parallax.min.js"></script> <script src="js/about.js"></script> <script src="js/commun.js"></script> <script> $(document).ready(function() { $('li.active').removeClass('active'); $('a[href="' + decodeURI(location.pathname).substring(1) + '"]').closest('li').addClass('active'); }) </script> </body> </html><file_sep><link rel="stylesheet" type="text/css" href="styles/workshops.css"> <!-- <link rel="stylesheet" type="text/css" href="styles/teams.css"> --> <div class="wtabs_section"> <div class="container"> <div class="row"> <div class="col"> <div class="section_title_container text-center"> <div class="section_subtitle">Workshops</div> <div class="section_title"> <h1>06/02/2021</h1> </div> </div> <div class="wtabs_container"> <div class="wtabs d-flex flex-row align-items-center justify-content-start flex-wrap"> <div class="wtab active">01. Workshop PNL</div> <div class="wtab">02. Workshop BMC</div> <!-- <div class="wtab">03. Workshop 3</div> --> <!-- <div class="wtab">04. Workshop 4</div> --> </div> <div class="wtab_panels"> <div class="wtab_panel active"> <div class="row"> <div class="wtab_panel_content"> <div class="wtab_title"> <h3>02:30 - 03:30PM</h3> </div> <div class="gridw"> <div class="team"> <div class="team_image"><img src="map/guests/hanen.webp" alt="<NAME>"></div> </div> <div class="desc"><span>Hanen Almia</span> with a masters degree in English ,a 3rd degree certificate in Italian and a training in Business English at Amideast, Mrs Hanen is a NLP coach. Rich in her professional experience and her knowledge in the field of personal development, Mrs Hanen now conducts, in addition to her activity within the Almia group, team coaching workshops.</div> </div> </div> <div class="col-lg-7"> </div> <div class="col-lg-5 wtab_col"> <div class="wtab_panel_image"><img src="" alt=""></div> </div> </div> </div> <div class="wtab_panel"> <div class="row"> <div class="wtab_panel_content"> <div class="wtab_title"> <h3>05:00 - 06:30PM</h3> </div> <div class="gridw"> <div class="team"> <div class="team_image"><img src="map/guests/Akrem saadaoui.webp" alt="<NAME>"></div> </div> <div class="desc"><span><NAME> </span> is Head of Talent Acquisition at DRÄXLMAIER Group in Tunisia . He has a Master Degree in Automation , Robotics and Data processing and has 6 years of experience operating in Talent Acquisition and business development field . “Building and nurturing the best talent community, leading the workforce of the future”. Starting from this , his intention is to empower people and to drive a new recruitment culture which contributes to the success of the organization .</div> </div> </div> </div> <div class="col-lg-6"> <div class="col-lg-6 wtab_col"> <div class="wtab_panel_image"><img src="" alt=""></div> </div> </div> </div> <div class="wtab_panel"> <div class="row"> <div class="col-lg-7"> <div class="wtab_panel_content"> <div class="wtab_title"> <h3>03. BMC</h3> </div> <div class="wtab_text"> <p>Coming soon</p> </div> </div> </div> <div class="col-lg-5 wtab_col"> <div class="wtab_panel_image"><img src="" alt=""></div> </div> </div> </div> <!-- <div class="wtab_panel"> <div class="row"> <div class="col-lg-7"> <div class="wtab_panel_content"> <div class="wtab_title"> <h3>04. Workshop 4</h3> </div> <div class="wtab_text"> <p>Coming soon</p> </div> </div> </div> <div class="col-lg-5 wtab_col"> <div class="wtab_panel_image"><img src="" alt=""></div> </div> </div> </div> --> </div> </div> </div> </div> </div> </div> </div> <?php ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-EFM7KDK600"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-EFM7KDK600'); </script> <title>Contact</title> <link rel="shortcut icon" href="iasam.ico" type="image/x-icon"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="IAS Tunisia Annual Meeting"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="styles/bootstrap-4.1.2/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="plugins/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="plugins/colorbox/colorbox.css"> <link rel="stylesheet" type="text/css" href="styles/contact.css"> <link rel="stylesheet" type="text/css" href="styles/contact_responsive.css"> <link rel="stylesheet" type="text/css" href="styles/header.css"> <link rel="stylesheet" type="text/css" href="styles/footer.css"> <link rel="stylesheet" type="text/css" href="styles/menu.css"> <link rel="stylesheet" type="text/css" href="styles/CTA.css"> <link rel="stylesheet" type="text/css" href="styles/commun.css"> </head> <body> <div class="super_container"> <!-- Header --> <?php include "header.php"?> <!-- Menu --> <?php include "menu.php" ?> <!-- Home --> <div class="home"> <div class="parallax_background parallax-window" data-parallax="scroll" data-image-src="images/contact_page.webp" data-speed="0.8"></div> <div class="home_container"> <div class="container"> <div class="row"> <div class="col"> <div class="home_content"> <div class="home_title"><h1>Contact</h1></div> <div class="breadcrumbs"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li><a href="index">Home</a></li> <li>Contact</li> </ul> </div> </div> </div> </div> </div> </div> </div> <!-- Contact --> <div class="contact container_wrapper"> <div class="container"> <div class="row row-eq-height"> <!-- Map --> <div class="col-xl-6 order-xl-1 order-2"> <div class="contact_map_container"> <div class="map"> <!--<div id="google_map" class="google_map"> <div class="map_container"> <div id="map"></div> </div> </div>--> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3192.9825912095375!2d10.194013314932276!3d36.8428929799398!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x12fd34c6d1e93bef%3A0x4153c4733f285343!2sInstitut%20national%20des%20sciences%20appliqu%C3%A9es%20et%20de%20technologie!5e0!3m2!1sfr!2stn!4v1571176548414!5m2!1sfr!2stn" width="100%" height="100%" frameborder="0" style="border:0;" allowfullscreen=""></iframe> </div> </div> </div> <!-- Contact Content --> <div class="col-xl-6 order-xl-2 order-1"> <div class="contact_content"> <div class="contact_title">Get in touch</div> <div class="contact_text"> </div> <div class="contact_list"> <ul> <li>1080 Tunis Cedex, Tunis 1080</li> <li>+216 96 671 872 </li> <li><EMAIL></li> </ul> </div> <div class="contact_form_container"> <form action="mailto:<EMAIL>" class="contact_form" id="contact_form"> <div class="d-flex flex-md-row flex-column align-items-start justify-content-between"> <div><input type="text" class="contact_input" placeholder="Your name" required="required"></div> <div><input type="email" class="contact_input" placeholder="Your email" required="required"></div> </div> <input type="text" class="contact_input" placeholder="Subject"> <textarea class="contact_textarea contact_input" placeholder="Message"></textarea> <button class="contact_button"><span>send<img src="images/arrow.webp" alt="fleche symbol"></span></button> </form> </div> </div> </div> </div> </div> </div> <!-- CTA --> <?php include "CTA.html"; ?> <!-- Footer --> <?php include "footer.php"; ?> </div> <script src="js/jquery-3.3.1.min.js"></script> <script src="styles/bootstrap-4.1.2/popper.js"></script> <script src="styles/bootstrap-4.1.2/bootstrap.min.js"></script> <script src="plugins/greensock/TweenMax.min.js"></script> <script src="plugins/greensock/TimelineMax.min.js"></script> <script src="plugins/scrollmagic/ScrollMagic.min.js"></script> <script src="plugins/greensock/animation.gsap.min.js"></script> <script src="plugins/greensock/ScrollToPlugin.min.js"></script> <script src="plugins/colorbox/jquery.colorbox-min.js"></script> <script src="plugins/easing/easing.js"></script> <script src="plugins/progressbar/progressbar.min.js"></script> <script src="plugins/parallax-js-master/parallax.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=<KEY>"></script> <script src="js/contact.js"></script> <script src="js/commun.js"></script> <script> $(document).ready(function () { $('li.active').removeClass('active'); $('a[href="' + decodeURI(location.pathname).substring(1) + '"]').closest('li').addClass('active'); }) </script> </body> </html><file_sep><?php ?> <style> footer{ height: 210px; } footer ul{ margin: 0 auto; width: 54%; } </style> <footer class="footer"> <div class="footer_container"> <div class="container"> <div class="test_grid"> <!-- Footer About --> <div class="footer_col"> <!-- Newsletter --> <div style="padding-top: 2.6rem;padding-bottom: 2.6rem;" class="footer_col"> <div style="margin-top:0" class="footer_text"> <p style="margin-bottom:0">IAS Insat Student Branch</p> <div style="margin-top:0" class="social"> <ul class="social_icons"> <li><a aria-label="fb" rel="noreferrer" target="_blank" href="https://web.facebook.com/IASINSAT"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a aria-label="Twitter" rel="noreferrer" target="_blank" href="https://twitter.com/ieee_ias_insat"><i class="fa fa-twitter" aria-hidden="true"></i></a></li> <li><a aria-label="in" rel="noreferrer" target="_blank" href="https://www.linkedin.com/company/ieee-insat-ias-sbc"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li> <li><a aria-label="insta" rel="noreferrer" target="_blank" href="https://www.instagram.com/ieee.ias.insat"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> </ul> </div> <p>IAS Tunisia Section</p> <div style="margin-top:0" class="social"> <ul class="social_icons"> <li><a aria-label="fb2" rel="noreferrer" target="_blank" href="https://www.facebook.com/iastunisia/"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a aria-label="Twitter2" rel="noreferrer" target="_blank" href="https://twitter.com/ieee_ias_insat"><i class="fa fa-twitter" aria-hidden="true"></i></a></li> <li><a aria-label="in2" rel="noreferrer" target="_blank" href="https://www.linkedin.com/company/ieee-ias-tunisia-section/"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li> <li><a aria-label="insta2" rel="noreferrer" target="_blank" href="https://www.instagram.com/ias_tunisia_section/?hl=fr"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> </ul> </div> </div> </div> </div> <!-- Logo --> <div> <div class="logo"> <img width="auto" height="210px" src="images/iasam2.webp" alt="ias logo"/> </div> <div style="top:-76px" class="social"> <ul class="social_icons"> <li><a aria-label="fb3" rel="noreferrer" target="_blank" href="https://www.facebook.com/IASTunisiaAM"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a aria-label="Twitter3" rel="noreferrer" target="_blank" href="https://twitter.com/IEEEIASTAM2020"><i class="fa fa-twitter" aria-hidden="true"></i></a></li> <li><a aria-label="in3" rel="noreferrer" target="_blank" href="https://www.linkedin.com/company/ieee-insat-ias-sbc"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li> <li><a aria-label="insta3" rel="noreferrer" target="_blank" href="https://www.instagram.com/iastnam/?hl=fr"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> </ul> </div> </div> </div> </div> </div> </footer> <file_sep><!DOCTYPE html> <html lang="en"> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-EFM7KDK600"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-EFM7KDK600'); </script> <title>Program</title> <link rel="shortcut icon" href="iasam.ico" type="image/x-icon"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="IAS Tunisia Annual Meeting"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="styles/bootstrap-4.1.2/bootstrap.min.css"> <link href="plugins/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="plugins/colorbox/colorbox.css"> <link rel="stylesheet" type="text/css" href="styles/schedule.css"> <link rel="stylesheet" type="text/css" href="styles/schedule_responsive.css"> <link rel="stylesheet" type="text/css" href="styles/header.css"> <link rel="stylesheet" type="text/css" href="styles/footer.css"> <link rel="stylesheet" type="text/css" href="styles/menu.css"> <link rel="stylesheet" type="text/css" href="styles/CTA.css"> <link rel="stylesheet" type="text/css" href="styles/commun.css"> <body> <div class="super_container"> <!-- Header --> <?php include "header.php" ?> <!-- Menu --> <?php include "menu.php" ?> <!-- Home --> <div class="home"> <div class="parallax_background parallax-window" data-parallax="scroll" data-image-src="images/schedule_page.webp" data-speed="0.8"></div> <div class="home_container"> <div class="container"> <div class="row"> <div class="col"> <div class="home_content"> <div class="home_title"> <h1>Program</h1> </div> <div class="breadcrumbs"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li><a href="index">Home</a></li> <li>Schedule</li> </ul> </div> </div> </div> </div> </div> </div> </div> <?php include "workshops.php" ?> <!-- Schedule --> <div class="schedule"> <div class="container"> <div class="row"> <div class="col"> <div class="schedule_container"> <!-- Tabs --> <div class="tabs d-flex flex-row align-items-start justify-content-start flex-wrap"> <div class="tab active tab1 d-flex flex-row align-items-center justify-content-center"> <div>Day 1. <span>February 6, 2021</span></div> </div> <div class="tab active d-flex flex-row align-items-center justify-content-center"> <div>Day 2. <span>February 7, 2021</span></div> </div> <!-- <div class="tab active d-flex flex-row align-items-center justify-content-center"> <div>Day 3. <span>December 28, 2020</span></div> </div> --> </div> <!-- Panels --> <div class="tab_panels"> <!-- Panel 1 --> <div class="tab_panel active"> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_2.webp" alt="speaker"></div> <div class="schedule_content"> <div class="schedule_time">02:00 PM - 02:30 PM</div> <div class="schedule_title">Opening Ceremony </div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>During our opening ceremony , we will be honoured by the presence of some of the people who helped the most the IAS IEEE community around the world and especially our IAS IEEE INSAT.</p> </div> </div> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_7.webp" alt="speaker"></div> <div class="schedule_content"> <div class="schedule_time">02:30 PM - 03:30 PM</div> <div class="schedule_title">Icebreaking : PNL Workshop</div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>NLP workshop : Neuro-linguistic programming is not only a workshop , it’s dedicated to smoothen the communication between our participants . </p> </div> </div> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_5.webp" alt="speakers"></div> <div class="schedule_content"> <div class="schedule_time">03:30 PM - 05:00 PM</div> <div class="schedule_title">Conference and Debate</div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>The Debate theme we will be discussing with our guests is “Can the merging of industry 4.0 replace the manpower and cause job dislocation or does it help in the economic growth accompanied with job opportunities.” </p> </div> </div> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_3.webp" alt="workspace"></div> <div class="schedule_content"> <div class="schedule_time">05:00 PM - 06:30 PM</div> <div class="schedule_title">Non Technical challenge: Pitching</div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>The IAS SBC will present their activities and Tunisia section will choose the SB to organize the next edition of IAS TUNISIA ANNUAL MEETING . </p> </div> </div> <!-- Schedule Item --> <!-- <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/latest_3.webp" alt=""></div> <div class="schedule_content"> <div class="schedule_time">09:00 PM - 12:00 PM</div> <div class="schedule_title">Teambuilding</div> <div class="schedule_info"> <a href="#"></a> </div> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>coming soon</p> </div> </div> --> </div> <!-- Panel 2 --> <div class="tab_panel"> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_5.webp" alt="workspace"></div> <div class="schedule_content"> <div class="schedule_time">09:30 AM - 10:30 AM</div> <div class="schedule_title">Technical Challenge: Pitching</div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>“SMARTINDUS” is a competition during which participants will innovate, and develop an idea in order to solve a specific problem related to Industry 4.0 and smart factories .</p> </div> </div> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_6.webp" alt="coffee"></div> <div class="schedule_content"> <div class="schedule_time">10:30 AM - 11:00 AM</div> <div class="schedule_title">Artistic Break</div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>We will be presenting for you a short play recorded by the talented members of THEATRO INSAT.</p> </div> </div> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_7.webp" alt="conference speaker"></div> <div class="schedule_content"> <div class="schedule_time">11:00 AM - 12:00 AM</div> <div class="schedule_title">Success Stories</div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>Two of the most successful tunisian people will join us to talk about their careers and how they got to the top in order to inspire us. </p> </div> </div> <!-- Schedule Item --> <div class="schedule_item"> <div class="schedule_title_bar d-flex flex-lg-row flex-column align-items-lg-end justify-content-start"> <div class="schedule_title_container d-flex flex-row align-items-end justify-content-start"> <div class="schedule_image"><img src="images/schedule_8.webp" alt="ceremony photo"></div> <div class="schedule_content"> <div class="schedule_time">11:00 AM - 12:00 AM</div> <div class="schedule_title">Winners annoucement and Closing ceremony </div> <!-- <div class="schedule_info"> <a href="#"></a> </div> --> </div> </div> </div> <div class="schedule_text"> <div class="schedule_text_title">Details</div> <p>We will be announcing the winning teams for the TECHNICAL CHALLENGE followed by the presentation of the winning IAS CHAPTER as well as the best Ambassador . </p> </div> </div> </div> <!-- Panel 3 --> </div> <!-- Scroll Up --> <div class="scroll_up scroll_link" data-scroll-to=".schedule">up</div> </div> </div> </div> </div> </div> <!-- CTA --> <?php include "CTA.html"; ?> <!-- Footer --> <?php include "footer.php"; ?> </div> <script src="js/jquery-3.3.1.min.js"></script> <script src="styles/bootstrap-4.1.2/popper.js"></script> <script src="styles/bootstrap-4.1.2/bootstrap.min.js"></script> <script src="plugins/greensock/TweenMax.min.js"></script> <script src="plugins/greensock/TimelineMax.min.js"></script> <script src="plugins/scrollmagic/ScrollMagic.min.js"></script> <script src="plugins/greensock/animation.gsap.min.js"></script> <script src="plugins/greensock/ScrollToPlugin.min.js"></script> <script src="plugins/colorbox/jquery.colorbox-min.js"></script> <script src="plugins/easing/easing.js"></script> <script src="plugins/progressbar/progressbar.min.js"></script> <script src="plugins/parallax-js-master/parallax.min.js"></script> <script src="plugins/scrollTo/jquery.scrollTo.min.js"></script> <script src="js/schedule.js"></script> <script src="js/commun.js"></script> <script> $(document).ready(function() { $('li.active').removeClass('active'); $('a[href="' + decodeURI(location.pathname).substring(1) + '"]').closest('li').addClass('active'); }) </script> </body> </html><file_sep>/* JS Document */ /****************************** [Table of Contents] 1. Vars and Inits 2. Set Header 3. Init Menu 4. Init Gallery ******************************/ $(document).ready(function() { "use strict"; /* 1. Vars and Inits */ var header = $('.header'); var ctrl = new ScrollMagic.Controller(); setHeader(); initMenu(); initGallery(); $(window).on('resize', function() { setHeader(); setTimeout(function() { $(window).trigger('resize.px.parallax'); }, 375); }); $(document).on('scroll', function() { setHeader(); }); /* 2. Set Header */ function setHeader() { var header = $('.header'); if($(window).scrollTop() > 91) { header.addClass('scrolled'); } else { header.removeClass('scrolled'); } } /* 3. Init Menu */ function initMenu() { if($('.menu').length && $('.hamburger').length) { var menu = $('.menu'); var menuCont = $('.menu_content'); var hamburger = $('.hamburger'); var close = $('.menu_close'); var Element = document.getElementById('menuId'); hamburger.on('click', function() { Element.style.opacity="1"; Element.style.visibility ="visible"; Element.style.display= "block"; hideOnClickOutside(Element) }); // close.on('click', function() // { // Element.style.display= "none"; // Element.style.opacity="0"; // Element.style.visibility ="hidden"; // }); const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ) function hideOnClickOutside(Element) { const outsideClickListener = event => { if ( (Element.contains(event.target)) && isVisible(Element)) { Element.style.display = 'none' Element.style.opacity="0"; Element.style.visibility ="hidden"; removeClickListener() } } const removeClickListener = () => { document.removeEventListener('click', outsideClickListener) } document.addEventListener('click', outsideClickListener) } } } /* 4. Init Gallery */ function initGallery() { if($('.gallery_item').length) { $('.colorbox').colorbox( { rel:'colorbox', photo: true, maxWidth:'95%', maxHeight:'95%' }); } } });<file_sep> <div id="menuId" class="menu"> <div class="menu_container"> <!-- <div class="menu_close"><i class="fa fa-times" aria-hidden="true"></i></div> --> <div id="menu_contentid" class="menu_content d-flex flex-column align-items-center justify-content-start"> <nav class="menu_nav"> <ul class="d-flex flex-column align-items-center justify-content-start"> <li><a href="index">Home</a></li> <li><a href="program">Program</a></li> <li><a href="committee">Committee</a></li> <li><a href="about">About us</a></li> <li><a href="iasjob">Job fair</a></li> <li><a href="contact">Contact</a></li> <li><a href="map/program">JOIN US</a></li> </ul> </nav> </div> <div class="menu_social"> <div class="social"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li><a rel="noreferrer" target="_blank" href="https://web.facebook.com/IASINSAT"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a rel="noreferrer" target="_blank" href="https://twitter.com/ieee_ias_insat"><i class="fa fa-twitter" aria-hidden="true"></i></a></li> <li><a rel="noreferrer" target="_blank" href="https://www.linkedin.com/company/ieee-insat-ias-sbc"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li> <li><a rel="noreferrer" target="_blank" href="https://www.instagram.com/ieee.ias.insat"><i class="fa fa-instagram" aria-hidden="true"></i></a></li> </ul> </div> </div> </div> </div> <?php ?><file_sep><!DOCTYPE html> <html lang="en"> <!-- head --> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-EFM7KDK600"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-EFM7KDK600'); </script> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="IAS Tunisia Annual Meeting"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta property="og:description" content="The IAS Tunisia Annual Meeting is a national scale congress. ✨ It is an opportunity for all IEEE members and non members to know more about Industry and Technology, and specifically: INDUSTRY 4.0 : technological innovations for industrial transition, since it is our theme for this first edition."> <title>IAS Tunisia Annual Meeting</title> <link rel="shortcut icon" href="iasam.ico" type="image/x-icon"> <link rel="stylesheet" type="text/css" href="styles/bootstrap-4.1.2/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="plugins/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/owl.carousel.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/owl.theme.default.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/animate.css"> <link rel="stylesheet" type="text/css" href="plugins/colorbox/colorbox.css"> <link rel="stylesheet" type="text/css" href="styles/main_styles.css"> <link rel="stylesheet" type="text/css" href="styles/responsive.css"> <link rel="stylesheet" type="text/css" href="styles/header.css"> <link rel="stylesheet" type="text/css" href="styles/footer.css"> <link rel="stylesheet" type="text/css" href="styles/menu.css"> <link rel="stylesheet" type="text/css" href="styles/CTA.css"> <link rel="stylesheet" type="text/css" href="styles/teams.css"> <link rel="stylesheet" type="text/css" href="styles/commun.css"> </head> <!-- body --> <body> <div class="super_container"> <?php include "header.php" ?> <!-- Menu --> <?php include "menu.php" ?> <!-- Home --> <div class="home"> <!-- Home Slider --> <!-- Slide --> <div class="background_image" style="background-image:url(images/cover.webp)"></div> <div class="home_container"> <div class="container"> <div class="row"> <div class="col" style="padding-top:100px;"> <div class="home_content"> <div class="home_title"> <h1> <span>IAS</span> <span>Annual</span> <span>Meeting</span> </h1> </div> <div class="home_info_container"> <div class="home_info"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li>Coming February 2021</li> <!-- <li>December 2020</li> --> <li>Online</li> </ul> </div> </div> <div class="button button_1 home_button"><a href="map/program"><span>JOIN US<img src="images/arrow_2.webp" alt="arrow"></span></a></div> </div> </div> </div> </div> </div> <!-- Slide --> </div> <!-- Home Slider Dots --> </div> <!-- Timer --> <div class="timer_section"> <!-- <div class="parallax_background parallax-window" data-parallax="scroll" data-image-src="images/timer (5).webp" data-speed="0.8"></div> --> <div class="timer_overlay"></div> <div class="container"> <div class="row"> <div class="col"> <div class="timer_container"> <ul class="timer d-flex flex-row align-items-center justify-content-start"> <li class="d-flex flex-column justify-content-start align-items-center"> <div id="day" class="timer_num">3</div> <div class="timer_unit">Days</div> </li> <li class="d-flex flex-column justify-content-start align-items-center"> <div id="hour" class="timer_num">00</div> <div class="timer_unit">Hours</div> </li> <li class="d-flex flex-column justify-content-start align-items-center"> <div id="minute" class="timer_num">00</div> <div class="timer_unit">Minutes</div> </li> <li class="d-flex flex-column justify-content-start align-items-center"> <div id="second" class="timer_num">00</div> <div class="timer_unit">Seconds</div> </li> </ul> </div> </div> </div> </div> </div> <!-- Intro --> <div class="intro"> <div class="container"> <div class="row"> <div class="col text-center"> <div class="section_title_container text-center"> <div class="section_title"> <h1>The IEEE Industry Applications Society Annual Meeting</h1> </div> </div> <div class="intro_text text-center"> <p> The IEEE IAS Annual Meeting has a long tradition of serving as an international forum for experts to present and discuss the latest developments in the application of electrical technology to industry and this year; a TUNISIAN version of this meeting will be held for the FIRST TIME. </p> </div> </div> </div> </div> </div> <!-- Milestones --> <div class="milestones"> <div class="container"> <div class="row"> <!-- Milestone --> <div class="col-xl-3 col-md-6 milestone_col"> <div class="milestone d-flex flex-row align-items-start justify-content-start"> <div class="milestone_icon d-flex flex-column align-items-center justify-content-center"> <img src="images/icon_1.svg" alt="https://www.flaticon.com/authors/freepik"> </div> <div class="milestone_content"> <div class="milestone_counter" data-end-value="100 +" data-sign-after="">0</div> <div class="milestone_text">Participants</div> </div> </div> </div> <!-- Milestone --> <div class="col-xl-3 col-md-6 milestone_col"> <div class="milestone d-flex flex-row align-items-start justify-content-start"> <div class="milestone_icon d-flex flex-column align-items-center justify-content-center"> <img src="images/icon_2.svg" alt="https://www.flaticon.com/authors/freepik"> </div> <div class="milestone_content"> <div class="milestone_counter" data-end-value="13">0</div> <div class="milestone_text">Schools</div> </div> </div> </div> <!-- Milestone --> <div class="col-xl-3 col-md-6 milestone_col"> <div class="milestone d-flex flex-row align-items-start justify-content-start"> <div class="milestone_icon d-flex flex-column align-items-center justify-content-center"> <img src="images/icon_3.svg" alt="https://www.flaticon.com/authors/freepik"> </div> <div class="milestone_content"> <div class="milestone_counter" data-end-value="2">0</div> <div class="milestone_text">Days</div> </div> </div> </div> <!-- Milestone --> <div class="col-xl-3 col-md-6 milestone_col"> <div class="milestone d-flex flex-row align-items-start justify-content-start"> <div class="milestone_icon d-flex flex-column align-items-center justify-content-center"> <img src="images/icon_4.svg" alt="https://www.flaticon.com/authors/freepik"> </div> <div class="milestone_content"> <div class="milestone_counter" data-end-value="15">0</div> <div class="milestone_text">Speakers</div> </div> </div> </div> </div> </div> </div> <!-- Schedule --> <div class="schedule"> <div class="container"> <div class="row"> <div class="col"> <div class="section_title_container text-center"> <div class="section_subtitle">see what's all about</div> <div class="section_title"> <h1>Program</h1> </div> </div> </div> </div> <div class="row schedule_row"> <!-- Schedule Column --> <div class="schedule_col"> <div class="schedule_container"> <div class="schedule_title_bar schedule_title_bar_1 text-center">Day 1. <span>February 6, 2021</span></div> <div class="schedule_list"> <ul> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_2.webp" alt="speaker"></div> <div class="schedule_content"> <div class="schedule_time">02:00 PM - 02:30 PM</div> <div class="schedule_title">Opening Ceremony</div> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_6.webp" alt="speaker"></div> <div class="schedule_content"> <div class="schedule_time">02:30 PM - 03:30 PM</div> <div class="schedule_title">Icebreaking : PNL Workshop</div> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_5.webp" alt="speaker2"></div> <div class="schedule_content"> <div class="schedule_time">03:30 PM - 05:00 PM</div> <div class="schedule_title">Panel Session</div> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_11.webp" alt="challenge photo"></div> <div class="schedule_content"> <div class="schedule_time">05:00 PM - 06:30 PM</div> <div class="schedule_title">Workshop BMC // IAS Presentations </div> <!-- <div class="schedule_title">// Workshop BMC</div> --> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> </ul> </div> </div> </div> <!-- Schedule Column --> <div class="schedule_col"> <div class="schedule_container"> <div class="schedule_title_bar schedule_title_bar_2 text-center">Day 2. <span>February 7, 2020</span></div> <div class="schedule_list"> <ul> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_3.webp" alt="speakers"></div> <div class="schedule_content"> <div class="schedule_time">09:30 AM - 10:30 AM</div> <div class="schedule_title">Technical Challenge : Pitching</div> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_6.webp" alt="singer"></div> <div class="schedule_content"> <div class="schedule_time">10:30 AM - 11:00 AM</div> <div class="schedule_title">Artistic Break</div> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_10.webp" alt="speaker"></div> <div class="schedule_content"> <div class="schedule_time">11:00 AM - 12:00 AM</div> <div class="schedule_title">Success Stories</div> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> <li class="d-flex flex-row align-items-center justify-content-start"> <div class="schedule_image"><img src="images/schedule_2.webp" style="height:65px; width:auto;" alt="speaker2"></div> <div class="schedule_content"> <div class="schedule_time">12:00 AM - 01:00 PM</div> <div class="schedule_title">Closing ceremony</div> <!-- <div class="schedule_info"><a href="#"></a> </div> --> </div> </li> </ul> </div> </div> </div> </div> </div> </div> <!-- Tabs Section --> <!-- teams --> <!-- ?php include "team.php"; ?> --> <!-- Logos --> <div class="logos"> <div class="container"> <div class="row"> <div class="col"> <div class="section_title text-center" style="margin-top : 40px"> <h1>Official Sponsors & Partners</h1> </div> <!-- Logos Slider --> <div class="logos_slider_container"> <div class="owl-carousel owl-theme logos_slider"> <!-- Slide --> <div class="slide"><img src="images/logo_1.webp" alt="leoni logo" onClick="window.open('https://www.leoni.com/en/');"></div> <!-- Slide --> <div class="slide"><img src="images/logo_3.webp" alt="novation city" onClick="window.open('https://www.novationcity.com/');"></div> <!-- Slide --> <div class="slide"><img src="images/logo_4.webp" alt="innovation" onClick="window.open('https://novationaccelerator.com/starti4/');"></div> <!-- Slide --> <div class="slide"><img src="images/logo_2.webp" alt="logo" onClick="window.open('https://www.novationcity.com/');"></div> </div> </div> </div> </div> </div> </div> <!-- Guests --> <?php include "Guests.php"; ?> <!-- CTA --> <?php include "CTA.html"; ?> <!-- Footer --> <?php include "footer.php"; ?> </div> <script src="js/jquery-3.3.1.min.js"></script> <script src="styles/bootstrap-4.1.2/popper.js"></script> <script src="styles/bootstrap-4.1.2/bootstrap.min.js"></script> <script src="plugins/greensock/TweenMax.min.js"></script> <script src="plugins/greensock/TimelineMax.min.js"></script> <script src="plugins/scrollmagic/ScrollMagic.min.js"></script> <script src="plugins/greensock/animation.gsap.min.js"></script> <script src="plugins/greensock/ScrollToPlugin.min.js"></script> <script src="plugins/OwlCarousel2-2.3.4/owl.carousel.js"></script> <script src="plugins/colorbox/jquery.colorbox-min.js"></script> <script src="plugins/easing/easing.js"></script> <script src="plugins/progressbar/progressbar.min.js"></script> <script src="plugins/parallax-js-master/parallax.min.js"></script> <script src="js/index.js"></script> <script src="js/commun.js"></script> <script> $(document).ready(function() { $('li.active').removeClass('active'); $('a[href="' + decodeURI(location.pathname).substring(1) + '"]').closest('li').addClass('active'); }) </script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-EFM7KDK600"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-EFM7KDK600'); </script> <title>About</title> <link rel="shortcut icon" href="iasam.ico" type="image/x-icon"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="IAS Tunisia Annual Meeting"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="styles/bootstrap-4.1.2/bootstrap.min.css"> <link href="plugins/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/owl.carousel.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/owl.theme.default.css"> <link rel="stylesheet" type="text/css" href="plugins/OwlCarousel2-2.3.4/animate.css"> <link rel="stylesheet" type="text/css" href="plugins/colorbox/colorbox.css"> <link rel="stylesheet" type="text/css" href="styles/about.css"> <link rel="stylesheet" type="text/css" href="styles/about_responsive.css"> <link rel="stylesheet" type="text/css" href="styles/header.css"> <link rel="stylesheet" type="text/css" href="styles/footer.css"> <link rel="stylesheet" type="text/css" href="styles/menu.css"> <link rel="stylesheet" type="text/css" href="styles/CTA.css"> <link rel="stylesheet" type="text/css" href="styles/commun.css"> <link rel="stylesheet" type="text/css" href="styles/menu2.css"> </head> <body> <div class="super_container"> <!-- Header --> <?php include "header.php"?> <!-- Menu --> <?php include "menu.php" ?> <!-- Home --> <div class="home"> <div class="parallax_background parallax-window" data-parallax="scroll" data-image-src="images/about_page.webp" data-speed="0.8"></div> <div class="home_container"> <div class="container"> <div class="row"> <div class="col"> <div class="home_content"> <div class="home_title"> <h1>About us</h1> </div> <div class="breadcrumbs"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li><a href="index">Home</a></li> <li>About us</li> </ul> </div> </div> </div> </div> </div> </div> </div> <!-- Milestones --> <!-- Intro Left --> <div class="intro intro_left container_wrapper"> <div class="container"> <div class="row row-eq-height"> <!-- Intro Content --> <div class="col-xl-6"> <div class="intro_left_content"> <div class="intro_title"> <h1>IEEE IAS INSAT Student Chapter</h1> </div> <div class="intro_text"> <p> IEEE IAS INSAT Student Chapter was formed on 16 October 2014. Since the founding of the student chapter. We aim to provide knowledge to our members through organizing various events such as: LabVIEW workshop, Lean Manufacturing Training, Industrial Visits etc. </p> </div> <div class="button button_2 intro_button"><a rel="noreferrer" target="_blank" href="https://www.facebook.com/IASINSAT/"><span>Follow us</span><img src="images/arrow.webp" alt="ias logo"></a></div> </div> </div> <!-- Intro Image --> <div class="col-xl-6"> <div class="intro_image"> <img src="images/iasinsat.webp" alt="logo"> <div class="background_image" style="background-image:url(images/iasinsat.webp)"></div> </div> </div> </div> </div> </div> <!-- Intro Right --> <div class="intro intro_right container_wrapper"> <div class="container"> <div class="row row-eq-height"> <!-- Intro Content --> <div class="col-xl-6 order-xl-2 order-1"> <div class="intro_right_content"> <div class="intro_title"> <h1>IEEE IAS Tunisia Section Chapter</h1> </div> <div class="intro_text"> <p>Surely one of the most active chapters of the IEEE Tunisian Chapters, the IEEE Industry Applications Society chapter is more specialized in the industrial field, with the purpose of development and advancing of technology and science. While linking theory and practice to the application of electrical and electronic systems for the benefit of humanity. </p> </div> <div class="button button_2 intro_button"><a rel="noreferrer" target="_blank" href="https://www.facebook.com/iastunisia/"><img src="images/arrow_3.webp" alt="arrow"><span> Follow us</span></a></div> </div> </div> <!-- Intro Image --> <div class="col-xl-6 order-xl-1 order-2"> <div class="intro_image"> <img src="images/iastunisia.webp" alt="ias logo"> <div class="background_image" style="background-image:url(images/iastunisia.webp)"></div> </div> </div> </div> </div> </div> <!-- CTA --> <?php include "CTA.html"; ?> <!-- Footer --> <?php include "footer.php"; ?> </div> <script src="js/jquery-3.3.1.min.js"></script> <script src="styles/bootstrap-4.1.2/popper.js"></script> <script src="styles/bootstrap-4.1.2/bootstrap.min.js"></script> <script src="plugins/greensock/TweenMax.min.js"></script> <script src="plugins/greensock/TimelineMax.min.js"></script> <script src="plugins/scrollmagic/ScrollMagic.min.js"></script> <script src="plugins/greensock/animation.gsap.min.js"></script> <script src="plugins/greensock/ScrollToPlugin.min.js"></script> <script src="plugins/OwlCarousel2-2.3.4/owl.carousel.js"></script> <script src="plugins/colorbox/jquery.colorbox-min.js"></script> <script src="plugins/easing/easing.js"></script> <script src="plugins/progressbar/progressbar.min.js"></script> <script src="plugins/parallax-js-master/parallax.min.js"></script> <script src="js/about.js"></script> <script src="js/commun.js"></script> <script> $(document).ready(function() { $('li.active').removeClass('active'); $('a[href="' + decodeURI(location.pathname).substring(1) + '"]').closest('li').addClass('active'); }) </script> </body> </html><file_sep> <!-- Header --> <header class="header"> <div class="header_content d-flex flex-row align-items-center justify-content-start"> <!-- Logo --> <div class="logo" style="width: 230px;"> <a href="index"> <img src="images/iasam.webp" width="100%" alt="ias logo 1"> </a> </div> <!-- Main Navigation --> <nav class="main_nav"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li class="active"><a href="index">Home</a></li> <li class=""><a href="program">Program</a></li> <li><a href="committee">Committee</a></li> <li class=""><a href="about">About us</a></li> <li><a href="contact">Contact</a></li> <li><a href="iasjob">Job fair</a></li> </ul> </nav> <div class="header_right ml-auto d-flex flex-row align-items-center justify-content-start"> <div class="social"> <ul class="d-flex flex-row align-items-center justify-content-start"> <li><a href="#"><i class="fa fa-pinterest" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-twitter" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-dribbble" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-behance" aria-hidden="true"></i></a></li> </ul> </div> <div class="header_link"> <a href="map/program"> <span>JOIN US<img src="images/arrow.webp" alt="arrow"></span> </a> </div> <div class="hamburger"><i class="fa fa-bars fa-xs" aria-hidden="true"></i></div> </div> </div> </header> <?php ?><file_sep>/* JS Document */ /****************************** [Table of Contents] 1. Vars and Inits 2. Set Header 3. Init Menu 4. Init Gallery 5. Init Milestones 6. Init Logos Slider ******************************/ $(document).ready(function() { "use strict"; /* 1. Vars and Inits */ var header = $('.header'); var ctrl = new ScrollMagic.Controller(); });
2573897ae2183fd4802555649bced2cc1b801203
[ "JavaScript", "PHP" ]
13
JavaScript
Rayen023/IASAM
9d4033f1fe9cf720dc501ec430ab5e516852182e
3f489d99cc944542866047e68cd3a57ca32f4dd8
refs/heads/main
<repo_name>AstrOOnauta/Clock<file_sep>/js/clock.js setInterval(clock, 1) //Call the function clock() to update time in web page //Function to work the digital clock function clock(){ var date = new Date() var hour = date.getHours() var minutes = date.getMinutes() var seconds = date.getSeconds() var utcOffset = Number((date.getTimezoneOffset())/60) //convert timezone of minutes to hours //Mechanism to format the time in digital clock if(hour<10){ hour = "0"+hour } if(minutes<10){ minutes = "0"+minutes } if(seconds<10){ seconds = "0"+seconds } //Switch the timezone's country switch(utcOffset){ case 3: document.getElementById("utcOffset").textContent = "(UTC-03:00 - Brasil)"; break; default: document.getElementById("utcOffset").textContent = "(Outro país)"; } //Format the time in digital clock and apply this time in web page var clockTime = hour+":"+minutes+":"+seconds document.getElementById("clock").textContent = clockTime } //Variables for support the timer in web pages var hourTimer = 0; var minutesTimer = 0; var secondsTimer = 0; var time = 1000 //1000miliseconds = 1second var aux //Function to start the timer function startTimer(){ aux = setInterval(function(){timer()}, time) //Call the mechanism to timer to work each 1second document.getElementById("startButton").disabled = true } //Function to stop the timer function stopTimer(){ clearInterval(aux) document.getElementById("startButton").disabled = false } //Function to restart the time in timer function restartTimer(){ clearInterval(aux) hourTimer = 0; minutesTimer = 0; secondsTimer = 0; document.getElementById("timer").innerHTML = "00:00:00" document.getElementById("startButton").disabled = false } //Function to the timer mechanism function timer(){ secondsTimer++ //Increment the seconds when timer is called each 1second //increment minutes and hours in timer display if(secondsTimer == 60){ secondsTimer = 0 minutesTimer++ if(minutesTimer == 60){ minutesTimer = 0 hourTimer++ } } //Mechanism to format the time in timer if(secondsTimer<10){ secondsNewTimer = "0"+secondsTimer }else{ secondsNewTimer = secondsTimer } if(minutesTimer<10){ minutesNewTimer = "0"+minutesTimer }else{ minutesNewTimer = minutesTimer } if(hourTimer < 10){ hourNewTimer = "0"+hourTimer }else{ hourNewTimer = hourTimer } //Format the time in timer and apply this time in web page var format = hourNewTimer+":"+minutesNewTimer+":"+secondsNewTimer document.getElementById("timer").innerHTML = format } <file_sep>/README.md # Clock Element Date() manipulation in JS Access through github pages: https://astroonauta.github.io/Clock
3c48dcd261caa3ca55c6209e0e25f4a9344ae22f
[ "JavaScript", "Markdown" ]
2
JavaScript
AstrOOnauta/Clock
ccceb7207bc49d0d25ce834168aa099119800eaf
dc7641abc08e52a7fb777a5901be83b88a9dd33a
refs/heads/master
<repo_name>ggentil/AMMO.UI<file_sep>/src/app/shared/services/produto/produto.service.ts import { Injectable } from '@angular/core'; import { RequestService } from '../request/request.service'; @Injectable({ providedIn: 'root' }) export class ProdutoService { constructor(private _requestService: RequestService) { } listarProdutos(qtdePorPagina: number, pagina: number, termo: string) { return this._requestService.requestMethod(`/produtos/${qtdePorPagina}/${pagina}/${termo}`, "GET", true); } } <file_sep>/src/app/app.routing.ts import { RouterModule, Routes } from "@angular/router"; import { ModuleWithProviders } from "@angular/core"; import { PageListaComponent } from "./page-lista/page-lista.component"; const APP_ROUTES: Routes = [ { path: ':qtdePorPagina/:pagina/:termo', component: PageListaComponent }, { path: ':pagina/:termo', component: PageListaComponent }, { path: ':pagina', component: PageListaComponent }, { path: '', component: PageListaComponent }, { path: '**', redirectTo: '/' } ]; export const routing: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES);<file_sep>/README.md # AMMO.UI Este projeto está publicado no Netlify (https://www.netlify.com), e pode ser acessado através da URL (https://ammoui.netlify.com). Seu código fonte pode ser visto no GitHub (https://github.com/ggentil/AMMO.UI). ## Rodar projeto local Com os arquivos já baixados, navegue para o diretório alvo do projeto, use "npm install" (já com node instalado) pra instalar os pacotes necessários. Talvez seja necessário instalar também o Angular-CLI globalmente, use "npm install -g @angular/cli". Em seguida use "ng serve" para emular localmente o projeto, ele estará disponível em ((http://localhost:4200)). Este projeto quando emulado localmente tentar acessar as APIs localmente pela URL (http://localhost:3000) do projeto AMMO.API (https://github.com/ggentil/AMMO.API), caso queira mudar isso, mude o valor de API_URL no arquivo (/src/environments/environment.ts).<file_sep>/src/app/shared/class/produto.class.ts import { Categoria } from './categorias.class'; export class Produto { constructor( public nome?: string, public precoDe?: number, public precoPor?: number, public imagens?: string[], public categorias?: Categoria[] ) { } }<file_sep>/src/app/page-lista/page-lista.component.ts import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { ProdutoService } from '../shared/services/produto/produto.service'; import { ActivatedRoute, Router, NavigationEnd } from '@angular/router'; @Component({ selector: 'lista', templateUrl: './page-lista.component.html', styleUrls: ['./page-lista.component.scss'] }) export class PageListaComponent implements OnInit { termo: string = ''; buscaTitulo: string = ""; qtdeTotalProdutos: number; produtosPorPagina: number = 16; produtos: Object[] = []; pages: any; @ViewChild('header') header: ElementRef; constructor(private _produtoService: ProdutoService, private _activatedRouteService: ActivatedRoute, private router: Router) { console.log('constructor'); this.router.events .subscribe(event => { if(event instanceof NavigationEnd) this.atualizarPagina(); }); } ngOnInit() { console.log('onInit'); }; atualizarPagina(){ this._activatedRouteService.params .subscribe(params => { this.carregarListagem(params.qtdePorPagina ? params.qtdePorPagina : this.produtosPorPagina, params.pagina ? params.pagina : 1, params.termo ? params.termo : ''); }, error => { console.log(error); this.carregarListagem(this.produtosPorPagina, 1, ''); }); } zerarBusca() { this.termo = ''; this.recarregarListagemBusca(); }; recarregarListagem() { this.router.navigate(['', this.produtosPorPagina, this.pages.paginaAtual, this.termo]); }; recarregarListagemBusca() { this.router.navigate(['', this.produtosPorPagina, 1, this.termo]); }; irParaPagina(pagina) { this.router.navigate(['', this.produtosPorPagina, pagina, this.pages.termo]); } montarPaginacao(termoUsado, paginaAtual) { let qtdeTotalPaginas = Math.ceil(this.qtdeTotalProdutos / this.produtosPorPagina); let disponiveis = []; qtdeTotalPaginas = qtdeTotalPaginas == 0 ? 1 : qtdeTotalPaginas; paginaAtual = parseInt(paginaAtual); this.pages = {}; //calcular páginas abaixo for (let i = paginaAtual - 1; i > paginaAtual - 3; i--) { if(i <= 0) break; disponiveis.unshift(i); } disponiveis.push(paginaAtual); //calcular páginas acima for (let i = paginaAtual + 1; i < paginaAtual + 3; i++) { if(i > qtdeTotalPaginas) break; disponiveis.push(i); } this.pages = { paginaAtual: paginaAtual, qtdeTotalPaginas: qtdeTotalPaginas, termo: termoUsado, disponiveis: disponiveis }; if(paginaAtual - 1 >= 1) this.pages.anterior = paginaAtual - 1; if(paginaAtual + 1 <= qtdeTotalPaginas) this.pages.proxima = paginaAtual + 1; }; carregarListagem(produtosPorPagina, pagina, termo) { this._produtoService.listarProdutos(produtosPorPagina, pagina, termo) .subscribe(response => { if(response.success) { this.produtos = response.data.produtos; this.qtdeTotalProdutos = response.data.total; this.produtosPorPagina = produtosPorPagina; this.termo = termo; this.montarPaginacao(termo, pagina); this.buscaTitulo = termo ? termo : "Lista de produtos"; this.header.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start' }); } else { console.log(response); alert("Ocorreu um erro ao processar a lista, por favor tente mais tarde."); } }, err => { console.log(err); if(err.error.message) alert(err.error.message); }); }; } <file_sep>/src/app/shared/components/produto/produto.component.ts import { Component, Input } from '@angular/core'; import { Produto } from '../../class/produto.class'; @Component({ selector: 'produto', templateUrl: './produto.component.html', styleUrls: ['./produto.component.scss'] }) export class ProdutoComponent { @Input('produto') produto: Produto; formatoReal: Object = { minimumFractionDigits: 2, style: 'currency', currency: 'BRL' }; constructor() { } }
b2217a7ca844813ed74a890d01357eed97a4b3d1
[ "Markdown", "TypeScript" ]
6
TypeScript
ggentil/AMMO.UI
4595be83be0928239b2543a35dcde00f99fbcf82
3ebb7b1f3914a864e8cfeb798c95c7a87337d133
refs/heads/master
<repo_name>ishynoris/Projeto-LFT-Compilador-Lua<file_sep>/src/models/ProjectTreeModel.java package models; import java.util.List; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; public class ProjectTreeModel implements TreeModel { private List<ProjectModel> projects; private String root = "Workspace"; public ProjectTreeModel(List<ProjectModel> projects) { this.projects = projects; } public void updateModel(List<ProjectModel> projects) { this.projects = projects; } public boolean hasChild() { return getChildCount(root) != 0; } public Object getChild(Object parent, int index) { if (parent == root) { return projects.get(index); } if (parent instanceof ProjectModel) { return ((ProjectModel) parent).getCodes().get(index); } throw new IllegalArgumentException("Invalid parent class" + parent.getClass().getSimpleName()); } @Override public int getChildCount(Object parent) { if (parent == root) { return projects.size(); } if (parent instanceof ProjectModel) { return ((ProjectModel) parent).getCodes().size(); } throw new IllegalArgumentException("Invalid parent class" + parent.getClass().getSimpleName()); } @Override public int getIndexOfChild(Object parent, Object child) { if (parent == root) { return projects.indexOf(child); } if (parent instanceof ProjectModel) { return ((ProjectModel) parent).getCodes().indexOf(child); } return 0; } @Override public Object getRoot() { return root; } @Override public boolean isLeaf(Object node) { return node instanceof SourceCodeModel; } @Override public void removeTreeModelListener(TreeModelListener arg0) {} @Override public void addTreeModelListener(TreeModelListener arg0) {} @Override public void valueForPathChanged(TreePath path, Object newValue) {} }<file_sep>/src/views/ViewNewFile.java package views; import controllers.NewFileController; import java.awt.*; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.border.LineBorder; public class ViewNewFile { private JDialog dialog; private JTextField txtFile; private JComboBox<String> cmbProject; private JButton btnConfirm, btnCancel; private NewFileController controller; public ViewNewFile(JFrame frame, String[] projects) { dialog = new JDialog(frame, "Novo arquivo", true); cmbProject = new JComboBox<>(projects); txtFile = new JTextField(); btnConfirm = new JButton("Ok"); btnCancel = new JButton("Cancelar"); controller = new NewFileController(dialog, cmbProject, txtFile); configButtons(); configLayout(frame); } public boolean hasConfirm(){ return controller.hasConfirm(); } public int getIndex() { return controller.getIndex(); } public String getTitleCode() { return controller.getTitle(); } private void configButtons() { ActionListener listener = (e) -> { if(e.getSource().equals(btnConfirm)){ controller.confirm(); } else if(e.getSource().equals(btnCancel)){ controller.cancel(); } }; btnConfirm.addActionListener(listener); btnCancel.addActionListener(listener); } private void configLayout(JFrame frame) { GridBagLayout mainLayout = new GridBagLayout(); mainLayout.columnWeights = new double[]{1.0}; mainLayout.rowWeights = new double[]{0.0, 1.0, 0.0}; Container container = dialog.getContentPane(); container.setLayout(mainLayout); JPanel mainPanel = new JPanel(); mainPanel.setBorder(new LineBorder(new Color(240, 240, 240), 15)); GridBagConstraints constMainPanel = new GridBagConstraints(); constMainPanel.anchor = GridBagConstraints.NORTH; constMainPanel.fill = GridBagConstraints.HORIZONTAL; constMainPanel.insets = new Insets(0, 0, 5, 0); container.add(mainPanel, constMainPanel); GridBagLayout componentsLayout = new GridBagLayout(); componentsLayout.columnWidths = new int[]{0, 0, 0}; componentsLayout.rowHeights = new int[]{0, 0, 0}; componentsLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; componentsLayout.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE}; mainPanel.setLayout(componentsLayout); GridBagConstraints constLblWorkspace = new GridBagConstraints(); constLblWorkspace.gridx = 0; constLblWorkspace.gridy = 0; constLblWorkspace.insets = new Insets(0, 0, 5, 5); constLblWorkspace.anchor = GridBagConstraints.EAST; mainPanel.add(new JLabel("Projetos"), constLblWorkspace); GridBagConstraints gbc_comboBox = new GridBagConstraints(); gbc_comboBox.insets = new Insets(0, 0, 5, 0); gbc_comboBox.fill = GridBagConstraints.HORIZONTAL; gbc_comboBox.gridx = 1; gbc_comboBox.gridy = 0; mainPanel.add(cmbProject, gbc_comboBox); GridBagConstraints constLblProject = new GridBagConstraints(); constLblProject.gridx = 0; constLblProject.anchor = GridBagConstraints.WEST; constLblProject.insets = new Insets(0, 0, 0, 5); constLblProject.gridy = 1; mainPanel.add(new JLabel("Arquivo"), constLblProject); GridBagConstraints constTxtProject = new GridBagConstraints(); constTxtProject.fill = GridBagConstraints.HORIZONTAL; constTxtProject.gridx = 1; constTxtProject.gridy = 1; mainPanel.add(txtFile, constTxtProject); txtFile.setColumns(10); //Separator JSeparator separator = new JSeparator(); GridBagConstraints constSeparator = new GridBagConstraints(); constSeparator.anchor = GridBagConstraints.SOUTH; constSeparator.fill = GridBagConstraints.HORIZONTAL; constSeparator.insets = new Insets(0, 0, 5, 0); constSeparator.gridy = 1; container.add(separator, constSeparator); //Panel for buttons JPanel buttonPanel = new JPanel(); buttonPanel.setBorder(new LineBorder(new Color(240, 240, 240), 5)); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); GridBagConstraints constButtonPane = new GridBagConstraints(); constButtonPane.anchor = GridBagConstraints.NORTH; constButtonPane.fill = GridBagConstraints.HORIZONTAL; constButtonPane.gridy = 2; container.add(buttonPanel, constButtonPane); buttonPanel.add(btnConfirm); buttonPanel.add(btnCancel); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setPreferredSize(new Dimension(300, 200)); dialog.pack(); dialog.setLocationRelativeTo(frame); dialog.setVisible(true); } } <file_sep>/src/controllers/NewFileController.java package controllers; import interfaces.IController; import models.SourceCodeModel; import javax.swing.*; public class NewFileController implements IController { private JDialog dialog; private int index; private String title; private JComboBox cmbProject; private JTextField txtFile; private boolean confirm; public NewFileController(JDialog dialog, JComboBox cmbProject, JTextField txtFile){ this.dialog = dialog; this.cmbProject = cmbProject; this.txtFile = txtFile; this.index = -1; this.title = ""; this.confirm = false; } public String getTitle(){ return title; } public boolean hasConfirm(){ return confirm; } public int getIndex(){ return index; } @Override public void confirm() { index = cmbProject.getSelectedIndex(); title = txtFile.getText(); if(!title.endsWith(SourceCodeModel.EXTENSION)){ title += SourceCodeModel.EXTENSION; } confirm = true; cancel(); } public void cancel(){ dialog.dispose(); } } <file_sep>/src/views/ViewCompiler.java package views; import controllers.CompilerController; import javax.swing.*; import javax.swing.tree.TreeModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; /** * Created by anail on 03/03/2017. */ public class ViewCompiler implements ActionListener { //private int quantAbas; private CompilerController controller; private JFrame frame; private JMenuBar barMenu; private JMenu menuArquivo, menuNovo, menuEditar, menuAjuda; private JMenuItem mNewProject, mNewFile, mImportFile, mSave, mSaveAs, mExit, mCompile, mMore, mAbout; private JButton btnNewFile, btnNewProject, btnImportFile, btnSave, btnCompile; private JSplitPane sptPaneExterno, sptPaneInterno; private JScrollPane scrPaneTree; private JTree projectTree; private JToolBar barStatus, barBotoes; public ViewCompiler() { controller = new CompilerController(this); frame = new JFrame("JShark - Compilador de código Lua"); barMenu = new JMenuBar(); menuArquivo = new JMenu("Arquivo"); menuNovo = new JMenu("Novo"); menuEditar = new JMenu("Editar"); menuAjuda = new JMenu("Ajuda"); mNewProject = new JMenuItem("Projeto"); mNewFile = new JMenuItem("Code fonte"); mImportFile = new JMenuItem("Importar"); mSave = new JMenuItem("Salvar"); mSaveAs = new JMenuItem("Salvar como..."); mExit = new JMenuItem("Sair"); mCompile = new JMenuItem("Compilar"); //mItemExtra = new JMenuItem("Extra"); //mMore = new JMenuItem("Mais..."); mAbout = new JMenuItem("Sobre"); btnNewFile = new JButton(); btnNewProject = new JButton(); btnImportFile = new JButton(); btnSave = new JButton(); btnCompile = new JButton(); sptPaneInterno = new JSplitPane(JSplitPane.VERTICAL_SPLIT); sptPaneExterno = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); projectTree = new JTree(); barStatus = new JToolBar(); barBotoes = new JToolBar(); scrPaneTree = new JScrollPane(); configMenus(); configButtons(); configLayout(); controller.newSourceCodeExample(); } public void updateTreeModel(TreeModel model) { projectTree = new JTree(model); scrPaneTree.setViewportView(projectTree); frame.repaint(); } private void configMenus() { mNewProject.addActionListener(this); mNewFile.addActionListener(this); mImportFile.addActionListener(this); mSave.addActionListener(this); mSaveAs.addActionListener(this); mExit.addActionListener(this); mCompile.addActionListener(this); mAbout.addActionListener(this); menuArquivo.add(menuNovo); menuNovo.add(mNewProject); menuNovo.add(mNewFile); menuArquivo.add(mImportFile); menuArquivo.add(mSave); menuArquivo.add(mSaveAs); menuArquivo.add(mExit); menuEditar.add(mCompile); menuAjuda.add(mAbout); barMenu.add(menuArquivo); barMenu.add(menuEditar); barMenu.add(menuAjuda); frame.setJMenuBar(barMenu); } private void configButtons() { barBotoes.add(btnNewProject); barBotoes.add(btnNewFile); barBotoes.add(btnImportFile); barBotoes.add(btnSave); barBotoes.add(new JSeparator(JSeparator.VERTICAL)); barBotoes.add(btnCompile); btnNewFile.addActionListener(this); btnNewProject.addActionListener(this); btnImportFile.addActionListener(this); btnSave.addActionListener(this); btnCompile.addActionListener(this); btnNewFile.setToolTipText("Criar novo código"); btnNewProject.setToolTipText("Criar novo projeto"); btnImportFile.setToolTipText("Importar codigo para projeto atual"); btnSave.setToolTipText("Salvar projeto atual"); btnCompile.setToolTipText("Compilar código fonte"); btnNewFile.setIcon(new ImageIcon(getClass().getResource("/img/newCode.png"))); btnNewProject.setIcon(new ImageIcon(getClass().getResource("/img/newProject.png"))); btnImportFile.setIcon(new ImageIcon(getClass().getResource("/img/import.png"))); btnSave.setIcon(new ImageIcon(getClass().getResource("/img/save.png"))); btnCompile.setIcon(new ImageIcon(getClass().getResource("/img/compile.png"))); } private void configLayout() { barStatus.setFloatable(false); barBotoes.setFloatable(false); //scrPaneCodigo.setPreferredSize(new Dimension(800, 800)); scrPaneTree.setPreferredSize(new Dimension(200, 0)); scrPaneTree.setViewportView(projectTree); sptPaneExterno.setLeftComponent(scrPaneTree); sptPaneExterno.setRightComponent(sptPaneInterno); sptPaneInterno.setResizeWeight(0.75); controller.updateProjectTabPane(sptPaneInterno); controller.updateConsoleTabPane(sptPaneInterno); controller.updateTreeModel(); GroupLayout layout = new GroupLayout(frame.getContentPane()); frame.getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(sptPaneExterno, GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE) .addComponent(barStatus, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(barBotoes, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(6, 6, 6) .addComponent(barBotoes, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(sptPaneExterno, GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(barStatus, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE))); frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/icon.png"))); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(800, 700)); frame.setMinimumSize(new Dimension(600, 500)); frame.pack(); frame.setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source.equals(mNewProject) || source.equals(btnNewProject)) { controller.newProject(frame); } else if (source.equals(mNewFile) || source.equals(btnNewFile)) { controller.newFile(frame); } else if (source.equals(mImportFile) || source.equals(btnImportFile)) { controller.importFile(frame); } else if (source.equals(mSave) || source.equals(btnSave)) { controller.save(frame); } else if (source.equals(mSaveAs)) { controller.saveAs(frame); } else if (source.equals(mCompile) || source.equals(btnCompile)) { controller.compile(); /* if (tabPaneCodigo.getQuantAbas() == 0) { JOptionPane.showMessageDialog(null, "Ainda não foi criado nenhum projeto.\n" + "Para continuar, crie um novo projeto.", "Nenhum projeto encontrado", JOptionPane.WARNING_MESSAGE); } else { String codigo = tabPaneCodigo.getSourceCode( tabPaneCodigo.getSelectedIndex()).getText(); if (codigo == "") { JOptionPane.showMessageDialog(null, "Nenhum código Java foi encontrado.", "Nenhum código encontrado", JOptionPane.WARNING_MESSAGE); } else { controller.compile(codigo); } } */ } else if (source.equals(mExit)) { int exit = JOptionPane.showConfirmDialog(null, "Você realmente deseja sair?", "Sair", JOptionPane.YES_NO_OPTION); if (exit == JOptionPane.YES_OPTION) { System.exit(10); } } else if (source.equals(mMore)) { controller.more(); } else if (source.equals(mAbout)) { controller.about(); } } public static void main(String args[]) throws IOException { try { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { e.printStackTrace(); } new ViewCompiler(); } } <file_sep>/src/interfaces/IController.java package interfaces; public interface IController { void confirm(); void cancel(); }<file_sep>/src/controllers/CompilerController.java package controllers; import jflex.Parser; import jflex.Token; import models.*; import views.*; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.*; import java.awt.*; import java.io.*; import java.util.ArrayList; import java.util.Objects; public class CompilerController { private final String PROJECT_NAME = "[Projeto LFT] Compilador Lua"; private final String WORKSPACE = "Workspace"; private File defaultPath; private ViewCompiler viewParent; private ArrayList<ProjectModel> projects; private ProjectTreeModel treeModel; private ProjectTabbedPaneModel projectTabPane; private ProjectTabbedPaneModel consoleTabPane; private JTextPane txtAreaConsole; public CompilerController(ViewCompiler viewParent) { this.viewParent = viewParent; this.defaultPath = new File(PROJECT_NAME); this.projects = new ArrayList<>(); this.treeModel = new ProjectTreeModel(projects); this.projectTabPane = new ProjectTabbedPaneModel(); this.consoleTabPane = new ProjectTabbedPaneModel(); this.txtAreaConsole = new JTextPane(); createWorkspace(defaultPath); txtAreaConsole.setEditable(false); } public void newSourceCodeExample(){ ProjectModel project = new ProjectModel(defaultPath, "Projeto Demo"); projects.add(project); SourceCodeModel souceCode = project.newFile("Exemplo1" + SourceCodeModel.EXTENSION); addFileToProject(0, project, souceCode); updateTreeModel(); } public void updateTreeModel() { treeModel.updateModel(projects); viewParent.updateTreeModel(treeModel); } public void updateProjectTabPane(JSplitPane pane) { pane.setTopComponent(projectTabPane); } public void updateConsoleTabPane(JSplitPane pane){ consoleTabPane.addConsole(txtAreaConsole); pane.setBottomComponent(consoleTabPane); } public void newProject(JFrame frame) { ViewNewProject view = new ViewNewProject(frame, defaultPath); defaultPath = view.getDefaultPath(); //TODO: REFATORAR if(view.hasConfirm()) { String projectName = view.getProjectName(); if (isValidTitle(projectName)) { projects.add(new ProjectModel(defaultPath, projectName)); updateTreeModel(); } else { Alerts.invalidProjectTitleError(frame, "O nome do projeto é invalido"); } } } public void newFile(JFrame frame) { if(!treeModel.hasChild()){ Alerts.hasNoChildError(frame, "Ainda não foi criado nenhum projeto. Crie um projeto para realizar essa ação"); return; } ViewNewFile view = new ViewNewFile(frame, nameProjects()); if(view.hasConfirm()){ int index = view.getIndex(); String title = view.getTitleCode(); if (isValidTitle(title)) { ProjectModel project = projects.get(index); SourceCodeModel code = project.newFile(title); addFileToProject(index, project, code); updateTreeModel(); } else { Alerts.invalidFileTitleError(frame, "O nome do arquivo inserido é invalido"); } } } public void importFile(JFrame frame) { if(!treeModel.hasChild()){ Alerts.hasNoChildError(frame, "Ainda não foi criado nenhum projeto. Crie um projeto para realizar essa ação"); return; } ViewImportFile view = new ViewImportFile(frame, nameProjects()); if(view.hasConfirm()) { int index = view.getIndex(); JFileChooser chooser = new JFileChooser(defaultPath); chooser.setFileFilter(new FileNameExtensionFilter("Arquivos Lua (*.lua)", SourceCodeModel.EXTENSION)); if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { defaultPath = chooser.getCurrentDirectory(); File selectedFile = chooser.getSelectedFile(); if (selectedFile.exists()) { ProjectModel project = projects.get(index); SourceCodeModel code = project.importFile(selectedFile); addFileToProject(index, project, code); updateTreeModel(); } } } } public void save(JFrame frame) { saveAs(frame); // JOptionPane.showMessageDialog(null, "NÃO IMPLEMENTADO", "SALVAR", // JOptionPane.ERROR_MESSAGE); } public void saveAs(JFrame frame) { if(!treeModel.hasChild()){ Alerts.hasNoChildError(frame, "Ainda não foi criado nenhum projeto. Crie um projeto para realizar essa ação"); return; } JFileChooser diretorioSaida = new JFileChooser(defaultPath); diretorioSaida.setFileFilter(new FileNameExtensionFilter( "Arquivos Lua (*.lua)", SourceCodeModel.EXTENSION)); if (diretorioSaida.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { String nomeArquivo = diretorioSaida.getSelectedFile().getName() + "." + SourceCodeModel.EXTENSION; try { defaultPath = diretorioSaida.getCurrentDirectory(); File arquivoSalvo = new File(defaultPath, nomeArquivo); BufferedWriter bw = new BufferedWriter(new FileWriter(arquivoSalvo)); int index = projectTabPane.getSelectedIndex(); String sourceCode = projectTabPane.getSourceCode(index); projectTabPane.uppdateTab(index, nomeArquivo, sourceCode); bw.write(sourceCode); bw.close(); } catch (IOException e) { e.printStackTrace(); } } } public void compile() { Parser parser = new Parser(); int index = projectTabPane.getSelectedIndex(); String out = parser.lexical(projectTabPane.getSourceCode(index)); ArrayList<Token> tokens = parser.getTokens(); new Thread(()->{ formatSourceCode(index, projectTabPane, tokens); }).start(); new Thread(()->{ showConsole(out); }).start(); } public void more() { JOptionPane.showMessageDialog(null, "NÃO IMPLEMENTADO", "MAIS", JOptionPane.ERROR_MESSAGE); } public void about() { JOptionPane.showMessageDialog(null, "NÃO IMPLEMENTADO", "SOBRE", JOptionPane.ERROR_MESSAGE); } private void createWorkspace(File path){ File newPath = new File(path, WORKSPACE); if(!newPath.exists()){ newPath.mkdir(); } defaultPath = newPath; } private boolean isValidTitle(String title) { return title != null && !title.matches(" *") && !title.equals(""); } private String[] nameProjects(){ int nProjects = projects.size(); String [] names = new String [nProjects]; for (int i = 0; i < nProjects; i++){ names[i] = projects.get(i).simpleName(); } return names; } private void addFileToProject(int index, ProjectModel project, SourceCodeModel code){ projectTabPane.newTab(code); projects.set(index, project); } private void showConsole(String out){ if(!Objects.equals(txtAreaConsole.getText(), "")){ txtAreaConsole.setText(""); } //txtAreaConsole.setText(out); consoleTabPane.formatDefaultSourceCode(txtAreaConsole, out, true, true, true); } private void formatSourceCode(int index, ProjectTabbedPaneModel tabPane, ArrayList<Token> tokens){ JTextPane txtPane = tabPane.getTabPaneProject(index); tabPane.formatDefaultSourceCode(txtPane); for(Token token: tokens){ if(token.isKeyword()){ tabPane.formatDefaultSourceCode("keyword", txtPane, token, Color.BLUE, true, false, false); } else if(token.isComent()){ tabPane.formatDefaultSourceCode("coments", txtPane, token, Color.GRAY, false, false, false); } else if(token.isLiteral()){ tabPane.formatDefaultSourceCode("literal", txtPane, token, Color.GREEN, true, false, false); } else if(token.isNumber()){ tabPane.formatDefaultSourceCode("number", txtPane, token, Color.BLUE, false, false, false); } else if(token.isUnexpected()){ tabPane.formatDefaultSourceCode("error", txtPane, token, Color.RED, true, false, true); } } } } <file_sep>/src/views/ViewImportFile.java package views; import controllers.ImportFileController; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.border.LineBorder; public class ViewImportFile { private JDialog dialog; private JComboBox<Object> cmbProjeto; private JButton btnConfirm, btnCancel; private ImportFileController controller; public ViewImportFile(JFrame frame, String[] projetos) { dialog = new JDialog(frame, "Importar arquivo", true); cmbProjeto = new JComboBox<>(projetos); btnConfirm = new JButton("Ok"); btnCancel = new JButton("Cancelar"); controller = new ImportFileController(dialog, cmbProjeto); configButtons(); configLayout(frame); } public int getIndex(){ return controller.getIndex(); } public boolean hasConfirm(){ return controller.hasConfirm(); } private void configButtons() { ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source.equals(btnConfirm)) { controller.confirm(); } else if (source.equals(btnCancel)) { controller.cancel(); } } }; btnConfirm.addActionListener(listener); btnCancel.addActionListener(listener); } private void configLayout(JFrame frame) { GridBagLayout mainLayout = new GridBagLayout(); mainLayout.columnWeights = new double[]{1.0}; mainLayout.rowWeights = new double[]{0.0, 1.0, 0.0}; Container container = dialog.getContentPane(); container.setLayout(mainLayout); JPanel mainPanel = new JPanel(); mainPanel.setBorder(new LineBorder(new Color(240, 240, 240), 15)); GridBagConstraints constMainPanel = new GridBagConstraints(); constMainPanel.anchor = GridBagConstraints.NORTH; constMainPanel.fill = GridBagConstraints.HORIZONTAL; constMainPanel.insets = new Insets(0, 0, 5, 0); container.add(mainPanel, constMainPanel); GridBagLayout componentsLayout = new GridBagLayout(); componentsLayout.columnWidths = new int[]{0, 0, 0}; componentsLayout.rowHeights = new int[]{0, 0}; componentsLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; componentsLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE}; mainPanel.setLayout(componentsLayout); GridBagConstraints constLblProjects = new GridBagConstraints(); constLblProjects.gridx = 0; constLblProjects.gridy = 0; constLblProjects.insets = new Insets(0, 0, 0, 5); constLblProjects.anchor = GridBagConstraints.EAST; mainPanel.add(new JLabel("Selecione o projeto"), constLblProjects); GridBagConstraints constCmbProjects = new GridBagConstraints(); constCmbProjects.fill = GridBagConstraints.HORIZONTAL; constCmbProjects.gridx = 1; constCmbProjects.gridy = 0; mainPanel.add(cmbProjeto, constCmbProjects); //Separator JSeparator separator = new JSeparator(); GridBagConstraints constSeparator = new GridBagConstraints(); constSeparator.anchor = GridBagConstraints.SOUTH; constSeparator.fill = GridBagConstraints.HORIZONTAL; constSeparator.insets = new Insets(0, 0, 5, 0); constSeparator.gridy = 1; container.add(separator, constSeparator); //Panel for buttons JPanel buttonPanel = new JPanel(); buttonPanel.setBorder(new LineBorder(new Color(240, 240, 240), 5)); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); GridBagConstraints constButtonPane = new GridBagConstraints(); constButtonPane.anchor = GridBagConstraints.NORTH; constButtonPane.fill = GridBagConstraints.HORIZONTAL; constButtonPane.gridy = 2; container.add(buttonPanel, constButtonPane); buttonPanel.add(btnConfirm); buttonPanel.add(btnCancel); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setPreferredSize(new Dimension(450, 170)); dialog.pack(); dialog.setLocationRelativeTo(frame); dialog.setVisible(true); } }<file_sep>/src/controllers/NewProjectController.java package controllers; import interfaces.IController; import views.ViewNewProject; import javax.swing.*; import java.io.File; public class NewProjectController implements IController{ private final String WORKSPACE = "Workspace"; private JDialog dialog; private JTextField txtProject; private String projectName; private boolean confirm; public NewProjectController(JDialog dialog, JTextField txtProject){ this.dialog = dialog; this.txtProject = txtProject; this.projectName = null; this.confirm = false; } public String getProjectName(){ return projectName; } public boolean hasConfirm(){ return confirm; } public File updateWorkspace(JDialog dialog, File defaultPath){ JFileChooser chooser = new JFileChooser(defaultPath); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if(chooser.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION){ return createWorkspace(chooser.getSelectedFile()); } return defaultPath; } private File createWorkspace(File path){ File newPath = new File(path, WORKSPACE); if(!newPath.exists()){ newPath.mkdir(); } return newPath; } @Override public void confirm() { projectName = txtProject.getText(); confirm = true; cancel(); } public void cancel(){ dialog.dispose(); } } <file_sep>/src/App.java import jflex.Main; import jflex.Parser; import java.io.File; /** * Created by anail on 08/03/2017. */ public class App { private static final String ROOT = new File("").getAbsolutePath(); private static final String PATH = "/[Projeto LFT] Compilador Lua/jflex"; private static final String LEXER_FILE = "/Lexer.flex"; private static void generateLexer(){ File file = new File(ROOT + PATH + LEXER_FILE); Main.generate(file); } public static void main(String[]args){ generateLexer(); Parser parser = new Parser(); String sourceCode = ". , .. ... --comentario de linha\n" + "--[[comentário em bloco" + "segunda linha do comentario ]]--\n" + "\'literal simples\'\n" + "\"literal duplo\"\n" + "( ) [ ] { } = # + - * / ^ %\n" + " > < > <= == ~= \n" + "10 -10 10.10 -10.10 \n" + "x va_r val_or10 -10valor\n" + "¨& _ §"; //sourceCode = "-- Author.\n\n" + "--[[This code was generated automatically]]"; String out = parser.lexical(sourceCode); System.out.println(out); } }
c3fdbea916ec81a8f61960cf64d78f8b800f7f30
[ "Java" ]
9
Java
ishynoris/Projeto-LFT-Compilador-Lua
c3c78696300292352b937a70cf1f8b646e61bfe2
6ac49797a3de5a65fa965903e3ad3a5ac6a2e018
refs/heads/master
<repo_name>HariHend1973/lcd_mpd<file_sep>/remote.sh #!/bin/sh stty -F /dev/ttyACM0 9600 cs8 -cstopb -parenb -icanon min 1 time 1 state="false" while true; do read -n 8 LINE < /dev/ttyACM0 LINE=$(echo -n $LINE | sed 's/[ \t\r\n]\+//g') echo $LINE # PREV if [[ "$LINE" == "FF22DD" ]] then mpc prev fi # NEXT if [[ "$LINE" == "FF02FD" ]] then mpc next fi # VOLUME DOWN -10 if [[ "$LINE" == "FFE01F" ]] then mpc volume -10 fi if [[ "$LINE" == "FFA857" ]] # VOLUME UP +10 then mpc volume +10 fi # mpc clear && mpc load Radio && mpc play if [[ "$LINE" == "FF906F" ]] then mpc clear && mpc load Radio && mpc play fi # mpc clear && mpc load "the beatles" && mpc play if [[ "$LINE" == "FF9867" ]] then mpc clear && mpc load "the beatles" && mpc play fi # POWER OFF if [[ "$LINE" == "FFA25D" ]] then poweroff fi # PLAY/PAUSE TOGGLE if [[ "$LINE" == "FFC23D" ]] && [[ "$state" == "false" ]] then mpc play state="true" elif [[ "$LINE" == "FFC23D" ]] && [[ "$state" == "true" ]] then mpc stop state="false" fi # Play #1 if [[ "$LINE" == "FF30CF" ]] then mpc play 1 fi # Play #2 if [[ "$LINE" == "FF18E7" ]] then mpc play 2 fi # Play #3 if [[ "$LINE" == "FF7A85" ]] then mpc play 3 fi # Play #4 if [[ "$LINE" == "FF10EF" ]] then mpc play 4 fi # Play #5 if [[ "$LINE" == "FF38C7" ]] then mpc play 5 fi # Play #6 if [[ "$LINE" == "FF5AA5" ]] then mpc play 6 fi # Play #7 if [[ "$LINE" == "FF42BD" ]] then mpc play 7 fi # Play #8 if [[ "$LINE" == "FF4AB5" ]] then mpc play 8 fi # Play #9 if [[ "$LINE" == "FF52AD" ]] then mpc play 9 fi # Play #0 if [[ "$LINE" == "FF6897" ]] then mpc play 10 fi done <file_sep>/lcd_mpd.py #!/usr/bin/python #-------------------------------------- # ___ ___ _ ____ # / _ \/ _ \(_) __/__ __ __ # / , _/ ___/ /\ \/ _ \/ // / # /_/|_/_/ /_/___/ .__/\_, / # /_/ /___/ # # lcd_i2c.py # LCD test script using I2C backpack. # Supports 16x2 and 20x4 screens. # # Author : <NAME> # Date : 20/09/2015 # # Edited by: <NAME> # Date : 18/02/2016 # # Modified by Pulpstone OpenWrt/LEDE # Date : 21/12/2017 # # Modified by <NAME>, january 2018 # hari.h -at- kutukupret.com , hari.hendaryanto -at- gmail.com # # http://www.raspberrypi-spy.co.uk/ # # Copyright 2015 <NAME> # # 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/>. # #-------------------------------------- import smbus import time import os, sys import time # Define some device parameters I2C_ADDR = 0x3F # I2C device address LCD_WIDTH = 20 # Maximum characters per line # Define some device constants LCD_CHR = 1 # Mode - Sending data LCD_CMD = 0 # Mode - Sending command LCD_CHARS = [0x40,0x48,0x50,0x58,0x60,0x68,0x70,0x78] LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line #LCD_LINE_2 = 0x0C # LCD RAM address for the 2nd line LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line LCD_BACKLIGHT = 0x08 # On #LCD_BACKLIGHT = 0x00 # Off ENABLE = 0b00000100 # Enable bit # Timing constants E_PULSE = 0.0005 E_DELAY = 0.0005 #Open I2C interface bus = smbus.SMBus(0) # Rev 1 Pi uses 0 #bus = smbus.SMBus(1) # Rev 2 Pi uses 1 def lcd_init(): # Initialise display lcd_byte(0x33,LCD_CMD) # 110011 Initialise lcd_byte(0x32,LCD_CMD) # 110010 Initialise lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size lcd_byte(0x01,LCD_CMD) # 000001 Clear display time.sleep(E_DELAY) def lcd_byte(bits, mode): # Send byte to data pins # bits = the data # mode = 1 for data # 0 for command bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT bits_low = mode | ((bits<<4) & 0xF0) | LCD_BACKLIGHT # High bits bus.write_byte(I2C_ADDR, bits_high) lcd_toggle_enable(bits_high) # Low bits bus.write_byte(I2C_ADDR, bits_low) lcd_toggle_enable(bits_low) def lcd_toggle_enable(bits): # Toggle enable time.sleep(E_DELAY) bus.write_byte(I2C_ADDR, (bits | ENABLE)) time.sleep(E_PULSE) bus.write_byte(I2C_ADDR,(bits & ~ENABLE)) time.sleep(E_DELAY) def lcd_string(message,line): # Send string to display message = message.ljust(LCD_WIDTH," ") lcd_byte(line, LCD_CMD) for i in range(LCD_WIDTH): lcd_byte(ord(message[i]),LCD_CHR) def lcd_custom(charPos,charDef): lcd_byte(LCD_CHARS[charPos],LCD_CMD) for line in charDef: lcd_byte(line,LCD_CHR) def ss_get(disk_list): if not disk_list: return b2="" # custom characters lcd_custom(1,[0x15,0x1F,0x15,0x04,0x04,0x04,0x0E,0x1F]) # wifiy lcd_custom(3,[0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F]) # full block lcd_custom(4,[0x1F,0x11,0x11,0x11,0x11,0x11,0x11,0x1F]) # empty block lcd_custom(5,[0x02,0x06,0x0E,0x1E,0x06,0x06,0x06,0x06]) # up lcd_custom(7,[0x0C,0x0C,0x0C,0x0C,0x0F,0x0E,0x0C,0x08]) # down # get tx/rx stats if len(disk_list[9]) == 20: b2=chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 19: b2=chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 18: b2=chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 17: b2=chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 16: b2= " " + chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 15: b2= " " + chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 14: b2= " " + chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 13: b2= " " + chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 12: b2= " " + chr(5) + chr(7) + disk_list[9] elif len(disk_list[9]) == 11: b2= " " + chr(5) + chr(7) + disk_list[9] lcd_string(b2,LCD_LINE_2) # get modem stats if disk_list[6] == "signal0": lcd_string("4G " + chr(4) + chr(4) + chr(4) + chr(4) + chr(4) + disk_list[7] + " " + chr(1) + disk_list[8],LCD_LINE_3) elif disk_list[6] == "signal20": lcd_string("4G " + chr(3) + chr(4) + chr(4) + chr(4) + chr(4) + disk_list[7] + " " + chr(1) + disk_list[8],LCD_LINE_3) elif disk_list[6] == "signal40": lcd_string("4G " + chr(3) + chr(3) + chr(4) + chr(4) + chr(4) + disk_list[7] + " " + chr(1) + disk_list[8],LCD_LINE_3) elif disk_list[6] == "signal60": lcd_string("4G " + chr(3) + chr(3) + chr(3) + chr(4) + chr(4) + disk_list[7] + " " + chr(1) + disk_list[8],LCD_LINE_3) elif disk_list[6] == "signal80": lcd_string("4G " + chr(3) + chr(3) + chr(3) + chr(3) + chr(4) + disk_list[7] + " " + chr(1) + disk_list[8],LCD_LINE_3) elif disk_list[6] == "signal100": lcd_string("4G " + chr(3) + chr(3) + chr(3) + chr(3) + chr(3) + disk_list[7] + " " + chr(1) + disk_list[8],LCD_LINE_3) def mpc_status_get(): global volume global repeat global random volume = "" repeat = "" random = "" g=os.popen("mpc status | grep volume") for line in g: status = line.strip().split() # Array indices start at 0 unlike AWK volume=status[0] + " " + status[1] repeat=status[2] + " " + status[3] random=status[4] + " " + status[5] volume=volume.replace("volume", "vol", 1) repeat=repeat.replace("repeat", "rep", 1) random=random.replace("random", "ran", 1) return (volume,repeat,random) def mpc_get(): mpc_status_get() f=os.popen("mpc current") global station station = "" for i in f.readlines(): station += i #station=station[:-1] station=station.rstrip() str_pad = " " * 20 str_head = str_pad + volume + " " + chr(2) + " " str_trail = " " + chr(2) + " " + volume + " " + repeat + " " + random station = str_head + station + str_trail return (station) def temp_time_get(b4): lcd_string(" " + chr(0) + b4 + " " + chr(6) + time.strftime("%H:%M:%S"),LCD_LINE_4) def mpd_head_get(): lcd_string(" " + chr(2) + " MPD " + chr(2) + " ", LCD_LINE_1) def disk_get(disk_list): if not disk_list: return lcd_custom(1,[0x07,0x0F,0x11,0x17,0x11,0x17,0x17,0x1F]) # flashdisk #lcd_custom(3,[0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F]) # reserved #lcd_custom(4,[0x1F,0x11,0x11,0x11,0x11,0x11,0x11,0x1F]) # reserved #lcd_custom(5,[0x02,0x06,0x0E,0x1E,0x06,0x06,0x06,0x06]) # reserved #lcd_custom(7,[0x0C,0x0C,0x0C,0x0C,0x0F,0x0E,0x0C,0x08]) # reserved lcd_string(chr(1) + " " + disk_list[0], LCD_LINE_2) lcd_string(chr(1) + " " + disk_list[1], LCD_LINE_3) def mem_get(disk_list): if not disk_list: return lcd_custom(1,[0x15,0x15,0x1F,0x1F,0x1F,0x1F,0x15,0x15]) # memory #lcd_custom(3,[0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F]) # reserved #lcd_custom(4,[0x1F,0x11,0x11,0x11,0x11,0x11,0x11,0x1F]) # reserved #lcd_custom(5,[0x02,0x06,0x0E,0x1E,0x06,0x06,0x06,0x06]) # reserved #lcd_custom(7,[0x0C,0x0C,0x0C,0x0C,0x0F,0x0E,0x0C,0x08]) # reserved lcd_string(chr(1) + disk_list[2], LCD_LINE_2) lcd_string(chr(1) + disk_list[3], LCD_LINE_3) def proc_get(disk_list): if not disk_list: return lcd_custom(1,[0x1F,0x19,0x17,0x17,0x17,0x17,0x19,0x1F]) # CPU C lcd_custom(3,[0x1F,0x13,0x15,0x15,0x13,0x17,0x17,0x1F]) # CPU P lcd_custom(4,[0x1F,0x15,0x15,0x15,0x15,0x15,0x1B,0x1F]) # CPU U #lcd_custom(5,[0x02,0x06,0x0E,0x1E,0x06,0x06,0x06,0x06]) # reserved #lcd_custom(7,[0x0C,0x0C,0x0C,0x0C,0x0F,0x0E,0x0C,0x08]) # reserved lcd_string(chr(1) + chr(3) + chr(4) + " " + disk_list[4], LCD_LINE_2) lcd_string(chr(1) + chr(3) + chr(4) + " " + disk_list[5], LCD_LINE_3) def file_stats_open(): global disk_list global b4 lcd_b4=open("/root/mpdlcd/lcd_b4.txt",'r') # temp disk_list=open("/root/mpdlcd/lcd_disk.txt").read().splitlines() b4=lcd_b4.read() lcd_b4.close() return(disk_list,b4) def main(): # Main program block # Initialise display lcd_init() lcd_custom(0,[0x04,0x0A,0x0A,0x0E,0x0E,0x1F,0x1F,0x0E]) # thermometer lcd_custom(2,[0x00,0x02,0x03,0x02,0x0e,0x1e,0x0c,0x00]) # music note lcd_custom(6,[0x1F,0x1F,0x0E,0x04,0x04,0x0A,0x11,0x1F]) # clock while True: file_stats_open() mpd_head_get() ss_get(disk_list) temp_time_get(b4) mpc_get() old_station = station while (len(station) == 0): file_stats_open() mpc_get() if len(station) != 0:break mpd_head_get() ss_get(disk_list) for h in range(20): file_stats_open() mpc_get() ss_get(disk_list) temp_time_get(b4) time.sleep(0.1) if len(station) != 0:break if len(station) != 0:break mpd_head_get() disk_get(disk_list) for h in range(20): file_stats_open() mpc_get() disk_get(disk_list) temp_time_get(b4) time.sleep(0.1) if len(station) != 0:break if len(station) != 0:break mpd_head_get() mem_get(disk_list) for h in range(20): file_stats_open() mpc_get() mem_get(disk_list) temp_time_get(b4) time.sleep(0.1) if len(station) != 0:break if len(station) != 0:break mpd_head_get() proc_get(disk_list) for h in range(20): file_stats_open() mpc_get() proc_get(disk_list) temp_time_get(b4) time.sleep(0.1) if len(station) != 0:break if len(station) != 0:break for j in xrange (0, len(station), 2): if j in range (0, len(station)//4): file_stats_open() lcd_text = station[j:(j+20)] lcd_string(lcd_text,LCD_LINE_1) temp_time_get(b4) #lcd_string(str_pad,LCD_LINE_1) ss_get(disk_list) mpc_get() if station != old_station: break old_station=station elif j in range ((len(station)//4)+1, (len(station)//4)*2): file_stats_open() lcd_text = station[j:(j+20)] lcd_string(lcd_text,LCD_LINE_1) disk_get(disk_list) temp_time_get(b4) mpc_get() if station != old_station: break old_station=station elif j in range (((len(station)//4)*2)+1, (len(station)//4)*3): file_stats_open() lcd_text = station[j:(j+20)] lcd_string(lcd_text,LCD_LINE_1) mem_get(disk_list) temp_time_get(b4) mpc_get() if station != old_station: break old_station=station elif j in range (((len(station)//4)*3)+1, (len(station)//4)*4): file_stats_open() lcd_text = station[j:(j+20)] lcd_string(lcd_text,LCD_LINE_1) proc_get(disk_list) temp_time_get(b4) mpc_get() if station != old_station: break old_station=station else: file_stats_open() lcd_text = station[j:(j+20)] lcd_string(lcd_text,LCD_LINE_1) temp_time_get(b4) mpc_get() if station != old_station: break old_station=station del disk_list[:] if __name__ == '__main__': try: main() except KeyboardInterrupt: pass finally: lcd_byte(0x01, LCD_CMD) lcd_string("Goodbye!",LCD_LINE_1)<file_sep>/temp.sh #!/bin/sh # only works on sbc temp="$(gigi sbc | grep Temperature | cut -f 3 -d' ')" temp=${temp%???} degree="$(echo $'\xDF'C)" echo -n "$temp$degree" <file_sep>/readme.txt LCD_MPD lede/pulpstone LCD 20x4 http://pulpstone.pw<file_sep>/disk.sh #!/bin/sh size=$(df -h | grep "/dev/root" | awk '{print $2}') used1=$(df -h | grep "/dev/root" | awk '{print $3}') avail=$(df -h | grep "/dev/root" | awk '{print $4}') mem=$(free | grep Mem) total=$(free | grep Mem | awk '{print $2}') used2=$(free | grep Mem | awk '{print $3}') free=$(free | grep Mem | awk '{print $4}') shared=$(free | grep Mem | awk '{print $5}') buffer=$(free | grep Mem | awk '{print $6}') cached=$(free | grep Mem | awk '{print $7}') total=$((total/1024)) used2=$((used2/1024)) free=$((free/1024)) shared=$((shared/1024)) buffer=$((buffer/1024)) cached=$((cached/1024)) cpu=$(top -bn 1 | head -n 5 | grep "CPU:" | awk '{print $1, $2}') usr=$(top -bn 1 | head -n 5 | grep "CPU:" | awk '{print $3, $4}') nic=$(top -bn 1 | head -n 5 | grep "CPU:" | awk '{print $7, $8}') irq=$(top -bn 1 | head -n 5 | grep "CPU:" | awk '{print $13, $14}') # 3ginfo ss="$(grep strength /tmp/3ginfotmp | awk '{print $3}' 2> /dev/null)" # wifi wifi="$(cat /proc/net/wireless | awk 'NR==3 {print $4}' | sed 's/\.//')" # tx/rx txrx=$(grep Rec /tmp/3ginfotmp | cut -d':' -f 2 | sed 's/ //g' | sed 's/i//g' 2> /dev/null) tx=$(printf $txrx | cut -d"/" -f 1) rx=$(printf $txrx | cut -d"/" -f 2) txB=$(printf $tx | sed 's/[0-9\.]*//g') rxB=$(printf $rx | sed 's/[0-9\.]*//g') signal=${ss%?}; echo "S:$size U:$used1" echo "available: $avail" echo "T:"$total"M U:"$used2"M S:"$shared"M" echo "B:"$buffer"M C:"$cached"M F:"$free"M" echo $cpu" "$usr echo $nic" "$irq if [ $signal -eq 0 ] then #echo -n "4G Signal: $(echo $'\xDB\xDB\xDB\xDB\xDB') $ss" echo "signal0" fi if [ $signal -gt 0 ] && [ $signal -lt 21 ] then #echo -n "4G Signal: $(echo $'\xFF\xDB\xDB\xDB\xDB') $ss" echo "signal20" fi if [ $signal -gt 20 ] && [ $signal -lt 41 ] then #echo -n "4G Signal: $(echo $'\xFF\xFF\xDB\xDB\xDB') $ss" echo "signal40" fi if [ $signal -gt 40 ] && [ $signal -lt 61 ] then #echo -n "4G Signal: $(echo $'\xFF\xFF\xFF\xDB\xDB') $ss" echo "signal60" fi if [ $signal -gt 60 ] && [ $signal -lt 81 ] then #echo -n "4G Signal: $(echo $'\xFF\xFF\xFF\xFF\xDB') $ss" echo "signal80" fi if [ $signal -gt 80 ] && [ $signal -lt 101 ] then #echo -n "4G Signal: $(echo $'\xFF\xFF\xFF\xFF\xFF') $ss" echo "signal100" fi echo " $ss" echo "${wifi}dBm" echo "$tx/$rx"<file_sep>/lcd_mpd.sh #!/bin/bash while true do echo "$(3ginfo 2> /dev/null)" > /tmp/3ginfotmp; # some delay :) for i in {1..1000}; do echo $i > /dev/null; done echo -n "$(/root/mpdlcd/temp.sh)" > /root/mpdlcd/lcd_b4.txt; echo "$(/root/mpdlcd/disk.sh)" > /root/mpdlcd/lcd_disk.txt; done & /etc/init.d/mpd start >/dev/null 2>&1 & cd /root/mpdlcd/ sleep 5 && /usr/bin/python lcd_mpd.py >/dev/null 2>&1 & #sleep 5 && sh /root/mpdlcd/remote.sh > /dev/null 2>&1 & exit 0
1332a767a5fe218e7a3dbbe1d130ccee1def4d2c
[ "Python", "Text", "Shell" ]
6
Shell
HariHend1973/lcd_mpd
1a874518b54a7d0137d3fc00956a3b4078444112
a72433f6fcc3add7affd1f8f115ea0d495ca3408
refs/heads/master
<repo_name>JoarGruneau/bio-alg<file_sep>/suffix_tree.py import math tree_depth = -1 class Node(object): def __init__(self, leaf_node): self.leaf_node = leaf_node self.parent = None self.children = {} self.string_pointers = [] self.start =None self.end = None self.suffix_link = None def length(self): if(self.start == -1): return 0 else: return self.end - self.start +1 def depth(self): length = self.length() node = self print("pp" + str(node.parent)) while node.parent != None: print("legtha com " + str(length)) print("edge " + node.get_edge('TGGAATTCTCGGGTGCCAAGGAACTCCAGTCACACAGTGATCTCGTATGC$')) node = node.parent length += node.length() print("legtha com " + str(node.length())) print("pp" + str(node.parent)) return length def __getattribute__(self, name): # print(name) if name == 'end': if self.leaf_node: return tree_depth return super(Node, self).__getattribute__(name) class Suffix_tree: def __init__(self, string): self.string = string self.active_node = None self.active_edge = -1 self.active_length = 0 self.remainder = 0 self.last_created_node = None self.root = None self.build_tree() def reset(): self.active_node = None self.active_edge = -1 self.active_length = 0 self.remainder = 0 self.last_created_node = None def get_edge(self, node): return string_list[node.string_pointers[0]][node.start: node.end + 1] def create_node(self, start, end=None, parent = None, leaf_node = False): node = Node(leaf_node = leaf_node) node.start = start node.end = end node.parent = parent node.suffix_link = self.root return node def new_node(self, start, end=None, leaf=False): """For root node, suffix_link will be set to NULL For internal nodes, suffix_link will be set to root by default in current extension and may change in next extension""" node = Node(leaf) node.suffix_link = self.root node.start = start node.end = end """suffixIndex will be set to -1 by default and actual suffix index will be set later for leaves at the end of all phases""" return node def build_tree(self): size = len(self.string) self.root = self.create_node(start = -1, end = -1) self.active_node = self.root for i in range(size): self.extend_tree(i) def walk_down(self, current_node): """Walk down from current node. activePoint change for walk down (APCFWD) using Skip/Count Trick (Trick 1). If active_length is greater than current edge length, set next internal node as active_node and adjust active_edge and active_length accordingly to represent same activePoint. """ length = current_node.length() if (self.active_length >= length): self.active_edge += length self.active_length -= length self.active_node = current_node return True return False def extend_tree(self, index): global tree_depth tree_depth = index self.remainder += 1 self.last_created_node = None while (self.remainder > 0): if (self.active_length == 0): self.active_edge = index if (self.active_node.children.get(self.string[self.active_edge]) is None): self.active_node.children[self.string[self.active_edge]] = self.create_node(index, parent = self.active_node, leaf_node=True) if (self.last_created_node is not None): self.last_created_node.suffix_link = self.active_node self.last_created_node = None else: child = self.active_node.children.get(self.string[self.active_edge]) length = child.length() if (self.active_length >= length): self.active_edge += length self.active_length -= length self.active_node = child continue if (self.string[child.start + self.active_length] == self.string[index]): if((self.last_created_node is not None) and (self.active_node != self.root)): self.last_created_node.suffix_link = self.active_node self.last_created_node = None self.active_length += 1 break split_end = child.start + self.active_length - 1 split = self.create_node(start = child.start, end =split_end, parent = self.active_node) self.active_node.children[self.string[self.active_edge]] = split split.children[self.string[index]] = self.create_node(start = index, parent = split, leaf_node=True) child.start += self.active_length split.children[self.string[child.start]] = child if (self.last_created_node is not None): self.last_created_node.suffix_link = split self.last_created_node = split self.remainder -= 1 if ((self.active_node == self.root) and (self.active_length > 0)): self.active_length -= 1 self.active_edge = index - self.remainder + 1 elif (self.active_node != self.root): self.active_node = self.active_node.suffix_link def print_clear(self, spacer, node): print(spacer + "node = " + self.string[node.start: node.end + 1]) spacer = spacer + " | " for _, child in node.children.items(): self.print_clear(spacer, child) def edge_matching(self, node, index, prefix): end = False length = 0 for char in self.string[node.start:node.end + 1]: if char == "$": end =True break elif char == prefix[index + length]: length += 1 else: break return end, length def imperfect_edge_matching(self, node, index, prefix): end = False miss_matches = 0 length = 0 for char in self.string[node.start:node.end + 1]: if char == "$": end =True break elif char != prefix[index + length]: miss_matches += 1 length += 1 return end, length, miss_matches def go_back(self, node): while (node.children.get("$") == None): node = node.parent node = node.children.get('$') return node def longest_suffix(self, prefix): size = len(prefix) node = self.root length = 0 index = 0 while index < size: if node.children.get('$') != None: length = index child = node.children.get(prefix[index]) # print("looking for" + prefix[index]) # print(node.children.items()) if child != None: # print("") # print("node = " + self.string[child.start: child.end + 1]) # print("len = " + str(child.length())) # print("pre =" +prefix[index:index + child.length()]) # print("depth = " + str(child.depth())) # print("") end, match_length = self.edge_matching(child, index, prefix) if end: length = index + match_length break elif match_length == child.length(): node = child index += match_length else: break else: break return length def imperfect_longest_suffix(self, missmatch_percentage, prefix): self.longest_match = 0 def imperfect(node, miss_matches, index): end, length, node_miss_matches = self.imperfect_edge_matching(node, index, prefix) total_miss_matches = miss_matches + node_miss_matches index += length if (float(total_miss_matches)/tree_depth <= missmatch_percentage): if ((index != 0) and (float(total_miss_matches)/index <= missmatch_percentage)): if ((end or node.children.get('$') != None) and self.longest_match < index): self.longest_match = index for key, child in node.children.items(): if(key != '$'): imperfect(child, total_miss_matches, index) imperfect(self.root, 0, 0) return self.longest_match if __name__ =="__main__": suf = Suffix_tree('XXX$') suf.print_clear("", suf.root) print(suf.imperfect_longest_suffix(1, "TGGAATTCTCGGGTGCCAAGGAACTCCAGTCACACAGTGATCTCGTATGCCGTCTTCTGCTTG")) # print(suf.longest_suffix("TGGAATTCTCGGGTGCCAAGGAACTCCAGTCACACAGTGATCTCGTATGCCGTCTTCTGCTTG")) <file_sep>/tasks.py from suffix_tree import Suffix_tree import matplotlib.pyplot as plt import numpy as np import pylab from multiprocessing import Pool adapter_seq = 'TGGAATTCTCGGGTGCCAAGGAACTCCAGTCACACAGTGATCTCGTATGCCGTCTTCTGCTTG' counter = 0 def longest_suffix(x): suffix_tree = Suffix_tree(line + "$") return suffix_tree.longest_suffix(adapter_seq) def imperfect_longest_suffix(x): suffix_tree = Suffix_tree(x + "$") return suffix_tree.imperfect_longest_suffix(0.25, adapter_seq) def task_1(): adapter_seq = 'TGGAATTCTCGGGTGCCAAGGAACTCCAGTCACACAGTGATCTCGTATGCCGTCTTCTGCTTG' file = open('../s_3_sequence_1M.txt', "r") output = open('task_1_out.txt', 'w') count = 0 lines = file.read().splitlines() # lines = lines[1:100] print(str(len(lines)) + " to process") result = [0]*(len(lines[0]) + 1) total_matches = 0 for line in lines: count += 1 if count%1000 == 0: print("processed " + str(count) +" lines") suffix_tree = Suffix_tree(line + "$") match = suffix_tree.longest_suffix(adapter_seq) output.write("match = " + str(match) + " " + line + " " + adapter_seq +'\n') result[match] += 1 if match > 0: total_matches +=1 file.close() output.close() save_r = open('task_1_resutlts.txt', 'w') save_r.write(str(result) +'\n') for i in range(len(result)): result[i] = float(result[i])/len(lines) width = 1/1.5 print(range(len(result) -1,-1,-1)) plt.bar(range(len(result) - 1,-1,-1), result, width, align='center', color="blue") plt.xticks(np.arange(0, 51, 2)) save_r.write(str(result) +'\n') save_r.write('total matches' + str(total_matches) +'\n') save_r.close() pylab.xlabel('Remaining length') pylab.ylabel('Percentage of elements in |S| with remaining length') pylab.show() def task_2(): adapter_seq = 'TGGAATTCTCGGGTGCCAAGGAACTCCAGTCACACAGTGATCTCGTATGCCGTCTTCTGCTTG' file = open('../s_3_sequence_1M.txt', "r") output = open('task_2_out.txt', 'w') count = 0 lines = file.read().splitlines() print(str(len(lines)) + " to process") result = [0]*(len(lines[0]) + 1) total_matches = 0 with Pool(4) as p: matches = p.map(imperfect_longest_suffix, lines) for match in matches: result[match] += 1 if match > 0: total_matches +=1 output.write("match = " + str(match) + " " + lines[match] + " " + adapter_seq +'\n') file.close() output.close() save_r = open('task_2_resutlts.txt', 'w') save_r.write(str(result) +'\n') for i in range(len(result)): result[i] = float(result[i])/len(lines) width = 1/1.5 plt.bar(range(len(result) - 1,-1,-1), result, width, align='center', color="blue") plt.xticks(np.arange(0, 51, 2)) save_r.write(str(result) +'\n') save_r.write('total matches' + str(total_matches) +'\n') save_r.close() pylab.xlabel('Remaining length') pylab.ylabel('Remaining length distrubutuion') pylab.show() if __name__ == '__main__': task_2()
3ec087d72ffa4d95be71cf690de336c6020f3a3c
[ "Python" ]
2
Python
JoarGruneau/bio-alg
f5e0fb440124531702577c39685a3bdfb6af7844
0f8e61c50dcfd2073ecd8ea5f0a1cb9f2a1c9d8b
refs/heads/master
<repo_name>ahmedfadhil/Binary-tree-insertion<file_sep>/testing_binarytree.py from binarytree import BinaryTree from tree_insert_left import insert_left from tree_insert_right import insert_right a_node = BinaryTree('a') a_node.insert_left('b') a_node.insert_right('c') b_node = a_node.left_child b_node.insert_right('d') c_node = a_node.right_child c_node.insert_left('e') c_node.insert_right('f') d_node = b_node.right_child e_node = c_node.left_child f_node = c_node.right_child print(a_node.value) print(b_node.value) print(c_node.value) print(d_node.value) print(e_node.value) print(f_node.value) <file_sep>/bst_remove_node.py def remove_node(self, value, parent): if value < self.value and self.left_child: return self.left_child.remove_node(self, value) elif value < self.value: return False elif value > self.value and self.right_child: return self.right_child.remove_node(self, value) elif value > self.value: return False else: if self.left_child is None and self.right_child is None and self == parent.left_child: parent.left_child = None self.clear_node() elif self.left_child is None and self.right_child is None and self == parent.right_child: parent.right_child = None self.clear_node() elif self.left_child and self.right_child is None and self == parent.right_child: parent.right_child = self.left_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.left_child: parent.left_child = self.right_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.right_child: parent.right_child = self.right_child self.clear_node() else: self.value = self.right_child.find_minimum_value() self.right_child.remove_node(self.value, self) return True <file_sep>/bst_find_minimum_value.py def find_minimum_value(self): if self.left_child: return self.left_child.find_minimum_value() else: return self.value <file_sep>/tree_bfs.py from asyncio import Queue from binarytree import BinaryTree def bfs(self): queue = Queue() queue.put(self) while not queue.empty(): current_node = queue.get() print(current_node.value) if current_node.left_child: queue.put(current_node.left_child) if current_node.right_child: queue.put(current_node.right_child) <file_sep>/bfs_find.py from bst_insert import BinarySearchTree bst = BinarySearchTree(45) bst.insert_node(10) bst.insert_node(8) bst.insert_node(12) bst.insert_node(20) bst.insert_node(17) bst.insert_node(25) bst.insert_node(19) # checking the find_node method print(bst.find_node(45)) print(bst.find_node(10)) print(bst.find_node(8)) print(bst.find_node(12)) # and so on... <file_sep>/tree_preorder.py from binarytree import BinaryTree def pre_order(self): print(self.value) if self.left_child: self.left_child.pre_order() if self.right_child: self.right_child.pre_order() def in_order(self): if self.left_child: self.left_child.in_order() print(self.value) if self.right_child: self.right_child.in_order() def post_order(self): if self.left_child: self.left_child.post_order() if self.right_child: self.right_child.post_order() print(self.value) <file_sep>/tree_insert_right.py from binarytree import BinaryTree def insert_right(self, value): if self.right_child == None: self.right_child = BinaryTree(value) else: new_node = BinaryTree(value) new_node.right_child = self.right_child self.right_child = new_node <file_sep>/README.md # Binary-tree-insertion A simple implemention of binary tree insertion with python. <file_sep>/bst_remove_node_test1.py from bfs_find import bst print(bst.remove_node(8, None)) bst.pre_order_traversal() print(bst.remove_node(17, None)) bst.pre_order_traversal()
9af322338db36e177065a8287489a29c4ac61b68
[ "Markdown", "Python" ]
9
Python
ahmedfadhil/Binary-tree-insertion
b424ec5c72e2e0c62b63be09a6a9d0a08b33ca35
26ce2384040b4bd6e4f49b36e4e8623189d26308
refs/heads/main
<file_sep>#!/usr/bin/env node const minimist = require("minimist"); const argv = minimist(process.argv.slice(2)); require('./index.js')(argv).then(() => { process.exit(0) }).catch((e) => { if (e.message) { console.error(`ERROR: ${e.message}`) } else { console.error(e) } process.exit(1) }) <file_sep>const tar = require("tar"); const { exec } = require("child_process"); const fs = require("fs"); const CONTENT_FOLDER_NAME = "package"; module.exports = async (options = {}) => { const renameTo = options["renameTo"] || "package"; const forceRewrite = options["forceRewrite"] || false; const archiveFileName = await new Promise((resolve, reject) => { exec("npm pack", (exception, stdout, stderr) => { if (exception != null) { reject(exception); return; } const outputLines = stdout.trim().split(/\r?\n/); const fileName = outputLines[outputLines.length - 1]; resolve(fileName); }); }); const dirExists = await new Promise((resolve, reject) => { fs.access(renameTo, fs.constants.R_OK, (err) => { resolve(err == null); }); }); if (dirExists) { if (!forceRewrite) { throw new Error( `Target directory already exists. Pass '--forceRewrite' option to remove target directory before unpacking` ); } await new Promise((resolve, reject) => { fs.rmdir(renameTo, { recursive: true }, (err) => { if (err != null) { reject(err); return; } resolve(); }); }); } try { await tar.x({ file: archiveFileName, }); } catch (e) { throw new Error( `Unable to unpack file ${archiveFileName}. ${ e.message || "Unknown error" }` ); } await new Promise((resolve, reject) => { fs.unlink(archiveFileName, (err) => { if (err) { reject(err); return; } resolve() }) }) if (renameTo !== CONTENT_FOLDER_NAME) { await new Promise((resolve, reject) => { fs.rename(CONTENT_FOLDER_NAME, renameTo, (err) => { if (err != null) { reject(err); return; } resolve(); }); }); } }; <file_sep># pack-to-folder Runs `npm pack` command and then extracts archive to folder ## Requirements `node >= 12` ## Installation `npm i pack-to-folder` or `yarn add pack-to-folder` ## Usage `npx pack-to-folder [--renameTo=package]` Options: - `--renameTo=package` (optional) - renames `package` folder, can be relative or absolute path - `--forceRewrite` (optional) - if target folder already exists, delete it before unpacking <file_sep>const fs = require("fs-extra"); const { constants } = require("fs"); const path = require("path"); const os = require("os"); const lib = require("../index.js"); beforeEach(async () => { await fs.rmdir('package', { recursive: true, }).catch(() => {}) }) test("extracting package twice without forcing should throw", async () => { await lib({}); await expect(lib({})).rejects.toThrow(); }); test("extracting package twice with forcing should not throw", async () => { await lib({}); await expect(lib({ forceRewrite: true, })).resolves.not.toThrow(); }); beforeEach(async () => { await fs.rmdir('package', { recursive: true, }).catch(() => {}) }) <file_sep>const fs = require("fs-extra"); const { constants } = require("fs"); const path = require("path"); const os = require("os"); const lib = require("../index.js"); const NEW_PACKAGE_NAME = "new-package-name"; beforeEach(async () => { await fs.rmdir(NEW_PACKAGE_NAME, { recursive: true, }).catch(() => {}) }) test("rename folder", async () => { await lib({ renameTo: NEW_PACKAGE_NAME }); expect(async () => { await fs.access(NEW_PACKAGE_NAME, constants.R_OK | constants.W_OK); }).not.toThrow() const files = await fs.readdir(NEW_PACKAGE_NAME) const expectedFiles = [ "package.json", "README.md", "cli.js", "index.js", ]; expect(files).toHaveLength(expectedFiles.length) expect(files).toEqual(expect.arrayContaining(expectedFiles)) }); afterEach(async () => { await fs.rmdir(NEW_PACKAGE_NAME, { recursive: true, }).catch(() => {}) })
39b9e80b5468e71f9ffe5e65ce0091b3531bca5b
[ "JavaScript", "Markdown" ]
5
JavaScript
koluch/pack-to-folder
3c9aa5108f6646e64064dd51cbe0e73a757a27dc
8ac1fcd42ca11a3da0bffaec6e46c10df34937a6
refs/heads/master
<file_sep># Serpentuino Snake for Arduino ## Requirements: You will need the following items to implement this project: - Arduino Uno - 8x8 (or any other size) LED Matrix - 2 Push Buttons ## Circuit Diagram ![Serpentuino](https://github.com/raulbojalil/serpentuino/blob/master/snake.png?raw=true "serpentuino") ## Video [![Serpentuino](https://github.com/raulbojalil/serpentuino/blob/master/video.png)](https://www.youtube.com/watch?v=j3Xj868APJs "Serpentuino") <file_sep># snake_arduino A snake game on a 8x8 led matrix with a arduino uno board <file_sep>#define PIN_ROW1 2 #define PIN_ROW2 3 #define PIN_ROW3 4 #define PIN_ROW4 5 #define PIN_ROW5 17 #define PIN_ROW6 16 #define PIN_ROW7 15 #define PIN_ROW8 14 #define PIN_COL1 6 #define PIN_COL2 7 #define PIN_COL3 8 #define PIN_COL4 9 #define PIN_COL5 10 #define PIN_COL6 11 #define PIN_COL7 12 #define PIN_COL8 13 #define PIN_INPUT_LEFT 18 #define PIN_INPUT_RIGHT 19 #define MAX_BODY_LENGTH 12 #define GAME_AREA_WIDTH 8 #define GAME_AREA_HEIGHT 8 #define GAME_OVER_TIME 3000 #define DIRECTION_UP 0 #define DIRECTION_RIGHT 1 #define DIRECTION_DOWN 2 #define DIRECTION_LEFT 3 typedef struct p { int x; int y; } Position; Position body[MAX_BODY_LENGTH]; int lastInput; int head; int tail; int bodyLength; int direction; Position food; int gameover; int score; int elapsedTime; bool readInput; unsigned long previousTime; void setPixel(int row, int column) { digitalWrite(PIN_ROW1, LOW); digitalWrite(PIN_ROW2, LOW); digitalWrite(PIN_ROW3, LOW); digitalWrite(PIN_ROW4, LOW); digitalWrite(PIN_ROW5, LOW); digitalWrite(PIN_ROW6, LOW); digitalWrite(PIN_ROW7, LOW); digitalWrite(PIN_ROW8, LOW); digitalWrite(PIN_COL1, HIGH); digitalWrite(PIN_COL2, HIGH); digitalWrite(PIN_COL3, HIGH); digitalWrite(PIN_COL4, HIGH); digitalWrite(PIN_COL5, HIGH); digitalWrite(PIN_COL6, HIGH); digitalWrite(PIN_COL7, HIGH); digitalWrite(PIN_COL8, HIGH); switch(column) { case 0: digitalWrite(PIN_COL1, LOW); break; case 1: digitalWrite(PIN_COL2, LOW); break; case 2: digitalWrite(PIN_COL3, LOW); break; case 3: digitalWrite(PIN_COL4, LOW); break; case 4: digitalWrite(PIN_COL5, LOW); break; case 5: digitalWrite(PIN_COL6, LOW); break; case 6: digitalWrite(PIN_COL7, LOW); break; case 7: digitalWrite(PIN_COL8, LOW); break; default: break; } switch(row) { case 0: digitalWrite(PIN_ROW1, HIGH); break; case 1: digitalWrite(PIN_ROW2, HIGH); break; case 2: digitalWrite(PIN_ROW3, HIGH); break; case 3: digitalWrite(PIN_ROW4, HIGH); break; case 4: digitalWrite(PIN_ROW5, HIGH); break; case 5: digitalWrite(PIN_ROW6, HIGH); break; case 6: digitalWrite(PIN_ROW7, HIGH); break; case 7: digitalWrite(PIN_ROW8, HIGH); break; default: break; } } bool foodPositionIsValid() { if (food.x < 0 || food.y < 0) return false; for (int i = tail; i <= (head > tail ? head : MAX_BODY_LENGTH - 1); i++) { if (body[i].x == food.x && body[i].y == food.y) return false; } if (head < tail) { for (int i = 0; i <= head; i++) { if (body[i].x == food.x && body[i].y == food.y) return false; } } return true; } void checkGameover() { for (int i = tail; i <= (head > tail ? head - 1 : MAX_BODY_LENGTH - 1); i++) { if (body[head].x == body[i].x && body[head].y == body[i].y) { gameover = GAME_OVER_TIME; return; } } if (head < tail) { for (int i = 0; i < head; i++) { if (body[head].x == body[i].x && body[head].y == body[i].y) { gameover = GAME_OVER_TIME; return; } } } } void spawnFood() { while (!foodPositionIsValid()) food = { random(GAME_AREA_WIDTH), random(GAME_AREA_HEIGHT) }; } void draw() { for (int i = tail; i <= (head > tail ? head : MAX_BODY_LENGTH - 1); i++) { setPixel(body[i].x, body[i].y); } if (head < tail) { for (int i = 0; i <= head; i++) { setPixel(body[i].x, body[i].y); } } setPixel(food.x, food.y); } void move() { tail = tail + 1 == MAX_BODY_LENGTH ? 0 : tail + 1; Position prevHead = body[head]; head = head + 1 == MAX_BODY_LENGTH ? 0 : head + 1; body[head] = { prevHead.x + (direction == DIRECTION_LEFT ? -1 : (direction == DIRECTION_RIGHT ? 1 : 0)), prevHead.y + (direction == DIRECTION_UP ? -1 : (direction == DIRECTION_DOWN ? 1 : 0)) }; body[head].x = body[head].x < 0 ? GAME_AREA_WIDTH - 1 : (body[head].x >= GAME_AREA_WIDTH ? 0 : body[head].x); body[head].y = body[head].y < 0 ? GAME_AREA_HEIGHT - 1 : (body[head].y >= GAME_AREA_HEIGHT ? 0 : body[head].y); } void eat() { if (body[head].x == food.x && body[head].y == food.y) { if (bodyLength < MAX_BODY_LENGTH) { bodyLength++; tail--; if (tail < 0) tail = MAX_BODY_LENGTH - 1; } score++; food = { -1, -1 }; spawnFood(); } } void reset() { body[0] = { 3,3 }; body[1] = { 3,4 }; body[2] = { 3,5 }; bodyLength = 3; head = 2; tail = 0; direction = DIRECTION_DOWN; food = {-1, -1}; gameover = 0; elapsedTime = 0; score = 0; spawnFood(); readInput = true; } void setup(){ pinMode(PIN_ROW1, OUTPUT); pinMode(PIN_ROW2, OUTPUT); pinMode(PIN_ROW3, OUTPUT); pinMode(PIN_ROW4, OUTPUT); pinMode(PIN_ROW5, OUTPUT); pinMode(PIN_ROW6, OUTPUT); pinMode(PIN_ROW7, OUTPUT); pinMode(PIN_ROW8, OUTPUT); pinMode(PIN_COL1, OUTPUT); pinMode(PIN_COL2, OUTPUT); pinMode(PIN_COL3, OUTPUT); pinMode(PIN_COL4, OUTPUT); pinMode(PIN_COL5, OUTPUT); pinMode(PIN_COL6, OUTPUT); pinMode(PIN_COL7, OUTPUT); pinMode(PIN_COL8, OUTPUT); pinMode(PIN_INPUT_LEFT, INPUT); pinMode(PIN_INPUT_RIGHT, INPUT); reset(); } void loop(){ unsigned long currentTime = millis(); if(!gameover) { draw(); elapsedTime += currentTime - previousTime; if(elapsedTime > 500) { move(); eat(); checkGameover(); elapsedTime = 0; readInput = true; } if(readInput) { if(digitalRead(PIN_INPUT_RIGHT) && !lastInput) { direction = (direction + 1) % 4; readInput = false; } if(digitalRead(PIN_INPUT_LEFT) && !lastInput) { direction = (4 + direction-1) % 4; readInput = false; } } lastInput = digitalRead(PIN_INPUT_RIGHT) || digitalRead(PIN_INPUT_LEFT); } else { if(currentTime % 800 > 400) draw(); gameover -= currentTime - previousTime; if(gameover <= 0) reset(); } previousTime = currentTime; }
c19c62f7e1f476bc4bdd298f23dc57797fc9d7cd
[ "Markdown", "C++" ]
3
Markdown
PaulakaPaul/snake_arduino
33ee728f5757ccb0c49dd531cc26240ba95b7a72
875048b46118f7b1f3c13783a219feb1743f7b05
refs/heads/master
<repo_name>Aloz1/iot-website<file_sep>/application.py #!/usr/bin/env python3 import boto3 import api_keys from boto3.dynamodb.conditions import Key, Attr from datetime import datetime from flask import Flask, render_template app = Flask(__name__) dynamo = boto3.resource('dynamodb') gps = dynamo.Table('gps-data') @app.route("/") def index(): response = gps.query(KeyConditionExpression=Key('deviceid').eq('gps-data/xps-9560')) entries = [] for e in (p['payload'] for p in response['Items']): lat_deg = e['latitude'][0:2] lat_min = e['latitude'][2:-1] lat_dir = e['latitude'][-1] lng_deg = e['longitude'][0:3] lng_min = e['longitude'][3:-1] lng_dir = e['longitude'][-1] e['datetime'] = datetime.fromtimestamp(e['datetime']).ctime() e['latitude'] = '{}\u00b0 {}\' {}'.format(lat_deg, lat_min, lat_dir) e['lat_deg'] = (float(lat_deg) + float(lat_min) / 60) * (1 if lat_dir == 'N' else -1) e['longitude'] = '{}\u00b0 {}\' {}'.format(lng_deg, lng_min, lng_dir) e['lng_deg'] = (float(lng_deg) + float(lng_min) / 60) * (1 if lng_dir == 'E' else -1) e['altitude'] = '{:.2f}'.format(float(e['altitude'][0:-1])) e['speed'] = '{:.2f}'.format(float(e['speed'])) e['direction'] = '{}\u00b0'.format(e['direction']) entries.append(e) entries.reverse() return render_template('index.html', entries=entries, maps_key=api_keys.google_maps_key) if __name__ == '__main__': app.debug = True app.run() <file_sep>/README.md # IoT vehicle tracking - web client A simple project demonstrating an IoT approach to vehicle tracking. The project has 3 software components: node devices, the edge device, and the web client. Node devices notify the edge device of new data via BLE GATT, which is then fetched by the edge device and cached locally in a redis database. Data is then pushed to the cloud (AWS) via MQTT. When AWS receives data via MQTT, it is stored in a dynamodb for later retreival. Finally, this data is pulled by the web client and presented as both a table of values and a path on google maps (for GPS data). This repository is specifically for the web client. For other software components, please see their corresponding repositories (in the [Other repositories](#other-repositories) section below). # Web client A simple flask app for viewing IoT data stored in an AWS DynamoDB. The web client only has 1 route/web page, which collects collects data from DynamoDB when requested. The relevant data is cached locally by the DynamoDB library, so the first request may take some time, but all subsequent requests are very quick. # Setup Connecting to AWS requires the machine that the web client is running from to be authenticated with AWS. For testing purposes, setting up and authenticating the `aws` command line was enough to allow the DynamoDB library to communicate with AWS. The app may also be pushed to an Elastic Beanstalk instance, which should have the same level of authentication granted. Additionally, a google maps API key is required, which should be placed in a file called `api_keys.py`. Here is an example file: ```python google_maps_key = '<KEY GOES HERE>' ``` To run the flask app, several python packges should be installed first. This can be done by setting up a virtual environment: ``` > python3 -m virtualenv venv > source venv/bin/activate > pip install -r requirements.txt ``` To run the flask app in debug mode, simply run the python script: ``` > ./application.py ``` # Other repositories - [Node firmware](https://github.com/Aloz1/iot-nodes) - [Edge application](https://github.com/Aloz1/iot-raspi) # The report For more details, take a look at the [corresponding report](https://github.com/Aloz1/iot-report) <file_sep>/requirements.txt boto3==1.9.156 botocore==1.12.156 Click==7.0 docutils==0.14 Flask==1.0.3 itsdangerous==1.1.0 Jinja2==2.10.1 jmespath==0.9.4 MarkupSafe==1.1.1 python-dateutil==2.8.0 s3transfer==0.2.0 six==1.12.0 urllib3==1.25.3 Werkzeug==0.15.4
37f93e2f460d4fc84fe0215c76cc7fec5f0fce27
[ "Markdown", "Python", "Text" ]
3
Python
Aloz1/iot-website
73ac7f99acf6cdf2afa6400104d18a4396f7f7bf
eb6c40c6ff7453f32b709daf98b146f030603f2f
refs/heads/master
<file_sep>import Link from 'next/link' export default () => ( <div className='container'> <div className='hero'><NAME>{' '}</div> <div className='hero-school'>ISTANBUL TECHNICAL UNIVERSTY {' '}</div> <h2 style={{textAlign:'center'}}>EDUCATION</h2> <div style={{textAlign:'center'}}>ISTANBUL TECHNICAL UNIVERSTY</div> <div style={{textAlign:'center'}}>BACHELOR DEGREE OF CIVIL ENGINEER</div> <h2 style={{textAlign:"center"}}>PROJECT</h2> <div style={{textAlign:'center'}}>----</div> <h2 style={{textAlign:'center'}}>LANGUAGE</h2> <div style={{textAlign:'center'}}>TURKISH(Natural)</div> <div style={{textAlign:'center'}}>ENGLISH(Advanced)</div> <h2 style={{textAlign:'center'}}>SOFTWARE</h2> <div style={{textAlign:'center'}}>Javascript</div> <div style={{textAlign:'center'}}>nextjs</div> <div style={{textAlign:'center'}}>phython</div> <h2 style={{textAlign:'center'}}>INTEREST</h2> <div style={{textAlign:'center'}}>Managment</div> <div style={{textAlign:'center'}}>Design</div> <div style={{textAlign:'center'}}>fashion</div> <div style={{textAlign:'center'}}>Computer and mobile phone technology</div> <h2 style={{textAlign:'center'}}>EXPERIENCE</h2> <div style={{textAlign:'center'}}>------</div> <h2 style={{textAlign:'center'}}>ACCOMPLISHMENT</h2> <div style={{textAlign:'center'}}>'ERICA GAME' my first game experience</div> </div> ) <file_sep>import Link from 'next/link' export default () => ( <div> <NAME>{' '} <div>ISTANBUL TECHNICAL UNIVERSTY {' '}</div> <div> <Link href='/https://www.instagram.com/extacyeffect/?hl=tr'> <a>INSTAGRAM</a> </Link> </div> <h1><NAME></h1> <div> merhaba arkadaşlar nasılsınız ben iyiyiym teşekkürler </div> </div> ) <file_sep>import Link from 'next/link' export default () => ( <div> <NAME>{' '} <div>ISTANBUL TECHNICAL UNIVERSTY {' '}</div> <div> <Link href='/https://www.instagram.com/extacyeffect/?hl=tr'> <a>INSTAGRAM</a> </Link> </div> <h1>TURKIYEDE YAZILIM</h1> <div>Yazılım Test ve Kalite Derneği (Turkish Testing Board - TTB), Uluslararası Yazılım Test Yeterlilik Kurulu’nun (ISTQB) sertifikasyon sınavlarında kullanılan en önemli kaynaklardan Foundation Level Syllabus 2018’i Türkçeye kazandırdı. 2006 yılında yazılım test ve kalite alanında dünyanın en saygın gönüllü organizasyonu olan Uluslararası Yazılım Test Yeterlilik Kurulu’na (ISTQB) bağlı olarak kurulan Yazılım Test ve Kalite Derneği (Turkish Testing Board - TTB), Türkiye’deki bilişim profesyonellerinin yazılım testi alanında uluslararası standartlara uygun olarak eğitilmesi amacıyla pek çok sertifikasyon programı düzenliyor. Bir süredir ISTQB’nin sertifikasyon sınavlarında kullanılan en önemli kaynaklardan Foundation Level Syllabus 2018’in Türkçeye çevrilmesi için çalışan TTB, yazılım testi alanında uzmanlaşmak isteyenlerin beklediği müjdeyi nihayet verdi. Söz konusu kaynağı “Sertifikalı Test Uzmanı Temel Seviye Ders Programı Versiyon 2018” adı ile Türkçeye kazandıran TTB, böylece en güncel bilgileri Türk yazılım testi uzmanı adaylarına kazandırmış oldu.</div> </div> )
a83bc27747c0115c7e31fd20809b7683c7530ca1
[ "JavaScript" ]
3
JavaScript
ilkermpolat/slm
132b5d5cfb6695605423ed872828a74fdbddad2b
698e41c4775792f3ec80d57aa9b4eb928eef9e88
refs/heads/main
<repo_name>Patrick-Santana/Starw<file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ use App\Http\Controllers\HomeController; use App\Http\Controllers\PokemonController; use App\Http\Controllers\TreinadorController; use App\Models\Pokemon; Route::get('/', function () { return view('welcome'); }); Route::post('/treinadors/novo', [TreinadorController::class, 'store'])->name('add-treinador'); Route::post('/pokemon/novo', [PokemonController::class, 'store'])->name('add-pokemon'); Route::model('pokemon', Pokemon::class); Route::get('/pokemon/remover/{pokemon}', [PokemonController::class, 'destroy'])->name('rm-pokemon'); /*Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');*/ Route::get('/dashboard', [HomeController::class, 'dashboard'])->middleware(['auth'])->name('dashboard'); require __DIR__.'/auth.php'; <file_sep>/app/Http/Controllers/PokemonController.php <?php namespace App\Http\Controllers; use App\Models\Pokemon; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; class PokemonController extends Controller { public function list() { return auth()->user()->pokemon; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Pokemon::create([ 'nome' => $request->nome, 'descricao'=> $request->descricao, 'type' => $request->type, 'user_id' => Auth::user()->id, ]); return redirect('dashboard'); } /** * Display the specified resource. * * @param \App\Models\Pokemon $pokemon * @return \Illuminate\Http\Response */ public function show(Pokemon $pokemon) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Pokemon $pokemon * @return \Illuminate\Http\Response */ public function edit(Pokemon $pokemon) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Pokemon $pokemon * @return \Illuminate\Http\Response */ public function update(Request $request, Pokemon $pokemon) { // } /** * Remove the specified resource from storage. * * @param \App\Models\Pokemon $pokemon * @return \Illuminate\Http\Response */ public function destroy(Pokemon $pokemon) { $pokemon->delete(); return redirect('dashboard'); } } <file_sep>/database/seeders/PokemonSeeder.php <?php namespace Database\Seeders; use App\Models\User; use App\Models\Pokemon; use App\Models\Treinador; use Illuminate\Database\Seeder; class PokemonSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { foreach(User::all() as $user) { Pokemon::factory(10)->create([ 'user_id' => $user->id ]); } } }
97967e96c22c57b523ab340d90be92be8715ea39
[ "PHP" ]
3
PHP
Patrick-Santana/Starw
f35b5695762d9c226251af4e8fee663aee58d67e
ad9d903eeb83e1994fb48bf25d1eef49b393e70c
refs/heads/master
<repo_name>pulsarian/webflux-jwt-impl<file_sep>/src/main/java/com/ard333/springbootwebfluxjjwt/service/UserService.java package com.ard333.springbootwebfluxjjwt.service; import com.ard333.springbootwebfluxjjwt.model.User; import com.ard333.springbootwebfluxjjwt.security.model.Role; import java.util.Arrays; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; /** * * @author ard333 */ @Service public class UserService { // this is just an example, you can load the user from the database from the repository //username:passwowrd -> user:user private final String userUsername = "user";// password: <PASSWORD> private final User user = new User(userUsername, "cBrlgyL2GI2GINuLUUwgojITuIufFycpLG4490dhGtY=", true, Arrays.asList(Role.ROLE_USER)); //username:passwowrd -> admin:admin private final String adminUsername = "admin";// password: <PASSWORD> private final User admin = new User(adminUsername, "dQNjUIMorJb8Ubj2+wVGYp6eAeYkdekqAcnYp+aRq5w=", true, Arrays.asList(Role.ROLE_ADMIN)); public Mono<User> findByUsername(String username) { if (username.equals(userUsername)) { return Mono.just(user); } else if (username.equals(adminUsername)) { return Mono.just(admin); } else { return Mono.empty(); } } }
655aaa83d5910f8f41fdac5bc8ed95ed2bdaeedf
[ "Java" ]
1
Java
pulsarian/webflux-jwt-impl
1b1e39c37cfdfb26a2fe224c62164eaa395e5fc3
1fa8055127e04f8d8610c199693bf81340bbf552
refs/heads/main
<file_sep>var numeroSecreto = parseInt(Math.random() * 101); var tentativas = 0; console.log("numero secreto " + numeroSecreto); function discover() { var palpite = parseInt(document.getElementById("inputguess").value); console.log(palpite); console.log("numero secreto " + numeroSecreto); if (numeroSecreto != palpite) { // var palpite = parseInt(prompt("Digite um número")); if (palpite > numeroSecreto) { tentativas += 1; document.getElementById("dica").innerHTML = "O número secreto é menor."; document.getElementById("numTentativas").innerHTML = "Você usou " + tentativas + " tentativa(s)"; } else if (palpite < numeroSecreto) { //alert("O número secreto é maior"); tentativas += 1; document.getElementById("dica").innerHTML = "O número secreto é maior."; document.getElementById("numTentativas").innerHTML = "Você usou " + tentativas + " tentativa(s)"; } } else { document.getElementById("dica").innerHTML = "Parabéns, você acertou o número secreto"; document.getElementById("numTentativas").innerHTML = "Você acertou com " + tentativas + " tentativa(s)"; } document.getElementById("inputguess").value = ""; } function dica() { document.getElementById("dicaalgoritmo").innerHTML = "A pesquisa ou busca binária (em inglês binary search algorithm ou binary chop) é um algoritmo de busca em vetores que segue o paradigma de divisão e conquista. A complexidade desse algoritmo é da ordem de Θ(log₂ N) em que N é o tamanho do vetor de busca. Logo Θ(log₂ 100) = 6.64, então em até 6.64 vezes você tem a chance de acertar usando a busca binária"; } <file_sep># Mentalista A Pen created on CodePen.io. Original URL: [https://codepen.io/AndreiaCristina/pen/dyNpWpV](https://codepen.io/AndreiaCristina/pen/dyNpWpV).
c1a54122be6dd4da678d88430e8f024bf5200541
[ "JavaScript", "Markdown" ]
2
JavaScript
deiacristina/Mentalista
4e361adcc8f1e8cd6d7027f7b944168c31cfe3c2
63dd2270a9c5569e1695312a0b5686078388b9a8
refs/heads/main
<file_sep>const express = require("express") const models = require("./models") const app = express() app.use(express.json()) // ----------- Buku ----------------------- app.get("/", (req, res) =>{ res.send({ messages : "success", body : "hore berhasil" }) }) app.get("/buku", (req, res) => { models.Buku.findAll().then((buku) => { res.send(buku) }) }) app.post("/buku", (req, res) => { models.Buku.create({ title : req.body.title, year : req.body.year }).then((data) => { res.send(data) }).catch((error) => { res.send(error) }) }) // ------------------------------------------ // ---------- Data Siswa -------------------- app.get("/data", (req, res) => { res.send({ messages: "success", body: "mantapu jiwaa" }) }) app.get("/siswa", (req, res) => { models.siswa.findAll().then((data_siswa) => { res.send(data_siswa) }) }) app.post("/siswa", (req, res) => { models.siswa.create({ nis : req.body.nis, nama_siswa : req.body.nama_siswa, kelas : req.body.kelas, jurusan : req.body.jurusan, sekolah : req.body.sekolah, alamat : req.body.alamat }).then((data_siswa) => { res.send(data_siswa) }).catch((error) => { res.send(error) }) }) // ------------------------------------------ app.listen(7000, ()=> { console.log("Berhasil"); })<file_sep># Latihan-CRUD-Squelize Bersama Bu Ratih
2845aa3f66fa56826a0b2ac60d0dc092a9dd5b5f
[ "JavaScript", "Markdown" ]
2
JavaScript
4mel1a/Latihan-CRUD-Squelize
d7a73d71ea220f6f1b3594e1661df498bb48e2c3
24e14975fe3d15dbefecf7552f5e789982e7236f
refs/heads/master
<repo_name>28ugur89/jhipsterdocker<file_sep>/src/main/java/com/huawei/train/service/ReservationService.java package com.huawei.train.service; import com.huawei.train.domain.Reservation; import java.util.List; /** * Service Interface for managing Reservation. */ public interface ReservationService { /** * Save a reservation. * * @param reservation the entity to save * @return the persisted entity */ Reservation save(Reservation reservation); /** * Get all the reservations. * * @return the list of entities */ List<Reservation> findAll(); /** * Get the "id" reservation. * * @param id the id of the entity * @return the entity */ Reservation findOne(Long id); /** * Delete the "id" reservation. * * @param id the id of the entity */ void delete(Long id); } <file_sep>/src/main/java/com/huawei/train/domain/package-info.java /** * JPA domain objects. */ package com.huawei.train.domain; <file_sep>/src/main/webapp/app/entities/customer/customer.controller.js 'use strict'; angular.module('jhipsterApp') .controller('CustomerController', ['$scope', 'CustomerService', function($scope, CustomerService) { var self = this; self.customer={id:null,email:'',name:'',surname:''}; self.customers=[]; self.submit = submit; self.edit = edit; self.remove = remove; self.reset = reset; fetchAllCustomers(); function fetchAllCustomers(){ CustomerService.fetchAllCustomers() .then( function(d) { self.customers = d; }, function(errResponse){ console.error('Error while fetching Customers'); } ); } function createCustomer(customer){ CustomerService.createCustomer(customer) .then( fetchAllCustomers, function(errResponse){ console.error('Error while creating Customer'); } ); } function updateCustomer(customer, id){ CustomerService.updateCustomer(customer, id) .then( fetchAllCustomers, function(errResponse){ console.error('Error while updating Customer'); } ); } function deleteCustomer(id){ CustomerService.deleteCustomer(id) .then( fetchAllCustomers, function(errResponse){ console.error('Error while deleting Customer'); } ); } function submit() { if(self.customer.id===null){ console.log('Saving New Customer', self.customer); createCustomer(self.customer); }else{ updateCustomer(self.customer, self.customer.customerId); console.log('Customer updated with id ', self.customer.id); } reset(); } function edit(id){ console.log('id to be edited', id); for(var i = 0; i < self.customers.length; i++){ if(self.customers[i].id === id) { self.customer = angular.copy(self.customers[i]); break; } } } function remove(id){ console.log('id to be deleted', id); if(self.customer.id === id) {//clean form if the customer to be deleted is shown there. reset(); } deleteCustomer(id); } function reset(){ self.customer={id:null,email:'',name:'',surname:''}; $scope.myForm.$setPristine(); //reset Form } }]); <file_sep>/src/main/webapp/app/entities/book/book.service.js 'use strict'; angular.module('jhipsterApp').factory('BookService', ['$http', '$q', function($http, $q){ var splitUrl = window.location.href.split('/#/')[0]; var REST_SERVICE_URI = splitUrl + '/api/books/'; var factory = { fetchAllBooks: fetchAllBooks, createBook: createBook, updateBook:updateBook, deleteBook:deleteBook }; return factory; function fetchAllBooks() { var deferred = $q.defer(); $http.get(REST_SERVICE_URI) .then( function (response) { deferred.resolve(response.data); }, function(errResponse){ console.error('Error while fetching Books'); deferred.reject(errResponse); } ); return deferred.promise; } function createBook(book) { var deferred = $q.defer(); $http.post(REST_SERVICE_URI, book) .then( function (response) { deferred.resolve(response.data); }, function(errResponse){ console.error('Error while creating Book'); deferred.reject(errResponse); } ); return deferred.promise; } function updateBook(book, id) { var deferred = $q.defer(); $http.put(REST_SERVICE_URI+id, book) .then( function (response) { deferred.resolve(response.data); }, function(errResponse){ console.error('Error while updating Book'); deferred.reject(errResponse); } ); return deferred.promise; } function deleteBook(id) { var deferred = $q.defer(); $http.delete(REST_SERVICE_URI+id) .then( function (response) { deferred.resolve(response.data); }, function(errResponse){ console.error('Error while deleting Book'); deferred.reject(errResponse); } ); return deferred.promise; } }]); <file_sep>/src/main/java/com/huawei/train/web/rest/package-info.java /** * Spring MVC REST controllers. */ package com.huawei.train.web.rest; <file_sep>/src/main/webapp/app/entities/reservation/reservation.controller.js 'use strict'; angular.module('jhipsterApp') .controller('ReservationController', ['$scope', 'ReservationService', function($scope, ReservationService) { var self = this; self.reservation={id:null,userid:'',bookid:'',startDate:'',finalDate:''}; self.reservations=[]; self.numbers=[]; self.numbersBook=[]; self.checkError=function(startDate,finalDate){ self.errMessage = ''; self.curDate = new Date(); if(new Date(startDate) > new Date(finalDate)){ self.errMessage = 'End Date should be greater than start date'; } if(new Date(startDate) < curDate){ self.errMessage = 'Start date should not be before today.'; return false; } }; self.checkError2=function(controlBookid,controlDate){ self.errMessage2=''; for(var i = 0; i < self.reservations.length; i++) { if (self.reservations[i].bookid==controlBookid && self.reservations[i].finalDate>controlDate) { self.errMessage2="This book is used by another user between these dates" self.reservation.bookid=''; } } }; self.submit = submit; self.edit = edit; self.remove = remove; self.reset = reset; fetchAllReservations(); function fetchAllReservations(){ ReservationService.fetchAllReservations() .then( function(d) { self.reservations = d; }, function(errResponse){ console.error('Error while fetching Reservations'); } ); } fetchAllNumbers(); //user tablosundan data çeker function fetchAllNumbers(){ ReservationService.fetchAllNumbers() .then( function(d) { self.numbers = d; }, function(errResponse){ console.error('Error while fetching Reservations'); } ); } fetchAllNumbersBook(); //book tablosundan data çeker function fetchAllNumbersBook(){ ReservationService.fetchAllNumbersBook() .then( function(d) { self.numbersBook = d; }, function(errResponse){ console.error('Error while fetching Reservations'); } ); } function createReservation(reservation){ ReservationService.createReservation(reservation) .then( fetchAllReservations, function(errResponse){ console.error('Error while creating Reservation'); } ); } function updateReservation(reservation, id){ ReservationService.updateReservation(reservation, id) .then( fetchAllReservations, function(errResponse){ console.error('Error while updating Reservation'); } ); } function deleteReservation(id){ ReservationService.deleteReservation(id) .then( fetchAllReservations, function(errResponse){ console.error('Error while deleting Reservation'); } ); } function submit() { if(self.reservation.id===null){ console.log('Saving New Reservation', self.reservation); createReservation(self.reservation); }else{ updateReservation(self.reservation, self.reservation.reservationId); console.log('Reservation updated with id ', self.reservation.reservationId); } reset(); } function edit(id){ console.log('id to be edited', id); for(var i = 0; i < self.reservations.length; i++){ if(self.reservations[i].reservationId === id) { self.reservation = angular.copy(self.reservations[i]); break; } } } function remove(id){ console.log('id to be deleted', id); if(self.reservation.id === id) {//clean form if the user to be deleted is shown there. reset(); } deleteReservation(id); } function reset(){ self.reservation={id:null,userId:'',bookId:'',startDate:'',finalDate:''}; $scope.myForm.$setPristine(); //reset Form } }]); <file_sep>/src/main/webapp/app/entities/book/book.controller.js 'use strict'; angular.module('jhipsterApp') .controller('BookController', ['$scope', 'BookService', function($scope, BookService) { var self = this; self.book={id:null,name:'',writer:'',year:''}; self.books=[]; self.submit = submit; self.edit = edit; self.remove = remove; self.reset = reset; fetchAllBooks(); function fetchAllBooks(){ BookService.fetchAllBooks() .then( function(d) { self.books = d; }, function(errResponse){ console.error('Error while fetching Books'); } ); } function createBook(book){ BookService.createBook(book) .then( fetchAllBooks, function(errResponse){ console.error('Error while creating Book'); } ); } function updateBook(book, id){ BookService.updateBook(book, id) .then( fetchAllBooks, function(errResponse){ console.error('Error while updating Book'); } ); } function deleteBook(id){ BookService.deleteBook(id) .then( fetchAllBooks, function(errResponse){ console.error('Error while deleting Book'); } ); } function submit() { if(self.book.id===null){ console.log('Saving New Book', self.book); createBook(self.book); }else{ updateBook(self.book, self.book.bookId); console.log('Book updated with id ', self.book.id); } reset(); } function edit(id){ //editlenecek objeyi ekrana yazdırıyor console.log('id to be edited', id); for(var i = 0; i < self.books.length; i++){ if(self.books[i].id === id) { self.book = angular.copy(self.books[i]); break; } } } function remove(id){ console.log('id to be deleted', id); if(self.book.id === id) {//clean form if the user to be deleted is shown there. reset(); } deleteBook(id); } function reset(){ self.book={id:null,name:'',writer:'',year:''}; $scope.myForm.$setPristine(); //reset Form } }]); <file_sep>/src/main/java/com/huawei/train/service/impl/ReservationServiceImpl.java package com.huawei.train.service.impl; import com.huawei.train.service.ReservationService; import com.huawei.train.domain.Reservation; import com.huawei.train.repository.ReservationRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Service Implementation for managing Reservation. */ @Service @Transactional public class ReservationServiceImpl implements ReservationService{ private final Logger log = LoggerFactory.getLogger(ReservationServiceImpl.class); private final ReservationRepository reservationRepository; public ReservationServiceImpl(ReservationRepository reservationRepository) { this.reservationRepository = reservationRepository; } /** * Save a reservation. * * @param reservation the entity to save * @return the persisted entity */ @Override public Reservation save(Reservation reservation) { log.debug("Request to save Reservation : {}", reservation); return reservationRepository.save(reservation); } /** * Get all the reservations. * * @return the list of entities */ @Override @Transactional(readOnly = true) public List<Reservation> findAll() { log.debug("Request to get all Reservations"); return reservationRepository.findAll(); } /** * Get one reservation by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Reservation findOne(Long id) { log.debug("Request to get Reservation : {}", id); return reservationRepository.findOne(id); } /** * Delete the reservation by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete Reservation : {}", id); reservationRepository.delete(id); } }
2d88b3c54379a7b75e45cbe9ff80af065a75ceef
[ "JavaScript", "Java" ]
8
Java
28ugur89/jhipsterdocker
f83999c9ee4142d42b218ffa8552f81175338f54
1e76ddc3ce9eacc2592e87a6649c3cfec3915b53
refs/heads/master
<file_sep>const http = require('http') const app = require('./app') const socketio = require('socket.io') // const serialport = require('serialport') const server = http.createServer(app) const io = socketio(server) server.listen(3000, () => { console.log('Server started') }); // const sp = new serialport('/dev/cu.usbmodem1421', { // baudRate: 9600 // }) // sp.on('data', (data) => { // console.log(data); // })
4bc6b1c67739bbcbd21c2c0a35fae7beab60d8b0
[ "JavaScript" ]
1
JavaScript
jpblopez/rfid
5b0f797ad0905f6233932e388ec96e24213d8250
490e9f164c9e6b1ed3e0b9d0288396da585084fa
refs/heads/master
<repo_name>BernardoModerno/Gobarber-Rocketseat<file_sep>/src/config/redis.js export default { host: process.enc.REDIS_HOST, port: process.enc.REDIS_PORT, }; <file_sep>/src/queue.js /** * Esse arquivo foi criado porque a fila não vai ser executada junta com a aplicação */ import 'dotenv/config'; import Queue from './lib/Queue'; Queue.processQueue(); <file_sep>/src/config/database.js require('dotenv').config(); // exporta um arquivo de configuração, precisa ser a sintaxe do comonjs por que vai ser acessado pelo sequelize cli module.exports = { dialect: 'postgres', host: process.env.DB_HOST, username: process.env.DB_USER, password: <PASSWORD>, database: process.env.DB_NAME, define: { timestamps: true, // define duas colunas de CreatedAt/UpdatedAt em cada tabela do db underscored: true, // define a nomenclatura da criação de tabelas e coluna do padrao underscored (ex: user_groups) underscoredAll: true, }, };
b84caf68a4edc951fd0c96283d5cce15e503e07d
[ "JavaScript" ]
3
JavaScript
BernardoModerno/Gobarber-Rocketseat
045d9940e45687503c7e4bef0f4926b68b0ced3f
e9f9efde49e05a1aa80a094aeaf072a64d9acf16
refs/heads/master
<repo_name>1813927768/movie-page<file_sep>/src/route/index.js import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) var routes = []; routes.push({ path: `/Visual`, name: 'Visual', component: () => import(`@/components/Visualization`), // props: true, }) routes.push({ path: `/List`, name: 'List', component: () => import(`@/components/MoviePage`), // props: true, }) routes.push({ path: `/`, name: 'FrontPage', component: () => import(`@/components/FrontPage`), // props: true, }) export default new Router({ routes }) <file_sep>/submit/src/components/getExeTime.js export default (function() { // 装饰器,在当前函数执行前先执行另一个函数 function decoratorBefore(fn, beforeFn) { return function() { var ret = beforeFn.apply(this, arguments); // 在前一个函数中判断,不需要执行当前函数 if (ret !== false) { fn.apply(this, arguments); } }; } // 装饰器,在当前函数执行后执行另一个函数 function decoratorAfter(fn, afterFn) { return function() { fn.apply(this, arguments); afterFn.apply(this, arguments); }; } // 执行次数 var funTimes = {}; // 给fun添加装饰器,fun执行前后计时 return function(fun, obj) { var funName = fun; // if (funTimes[funName]) { // return funTimes[funName]; // } // 绑定 funTimes[funName] = decoratorAfter(decoratorBefore(fun, function() { // 执行前 funTimes[funName].timestampStart = performance.now(); }), function() { // 执行后 funTimes[funName].timestampEnd = performance.now(); // 将执行耗时存入 funTimes[funName].valueOf = function() { return this.timestampEnd - this.timestampStart; }; // debugger var time = +funTimes[funName] obj.timeUse = time.toFixed(2) console.log(obj.timeUse) }); return funTimes[funName]; } })();
94d9ecf6155646e1009206b8b05b8226c22cf5b1
[ "JavaScript" ]
2
JavaScript
1813927768/movie-page
da53a8e9b46b3f587fe87345a6225212b9a137ba
ea126ab144229f886b347daf1ddff9a2acde4d9b
refs/heads/master
<repo_name>ksindhu06/ReactAssessment<file_sep>/script.jsx import React from 'react'; import ReactDOM from 'react-dom'; class MyComponent extends React.Component { getUser(){ // Clearing the git users div document.getElementById("git_users").innerHTML = ""; //fetching the changed value of input box const name = document.getElementById("name").value; //making request to API fetch('http://api.github.com/search/users?q='+name) .then(response => response.json()) .then(response=>{ var git_items = response.items; var len = response.total_count; for (var i = 0; i < len; i++) { //creating the elements dynamically var pele = document.createElement("p"); console.log(git_items[i].login); var iele = document.createElement("img"); iele.src = git_items[i].avatar_url; iele.width = 30; iele.height = 30; pele.appendChild(iele); var aele = document.createElement("a"); aele.href = git_items[i].html_url; aele.innerHTML = " "+git_items[i].login; aele.target = '_blank'; pele.appendChild(aele); document.getElementById("git_users").appendChild(pele); } }) } render(){ return ( <input type='text' onChange={this.getUser} ref='name' id='name'/> ); } } ReactDOM.render(<MyComponent/>, document.getElementById('content'));
44254995556adce24e0c0335bbf09da848d9ce9e
[ "JavaScript" ]
1
JavaScript
ksindhu06/ReactAssessment
02b1f146a3a04c085bcd0bc132bb2426b24eadd6
9e241e893847cbb6645ca0930fe1335aeecbf96c
refs/heads/main
<file_sep># Code-Lou-Python-Project Author: <NAME> ----Info---- golfTracker.py is a simple program that asks the user for the names of 2 golf players then asks for the number of strokes they made on each hole, storing the name and values (as ints) in lists, p1 (player 1) and p2 (player 2), the name of the player is p1[0] or p2[0]. On p1's turn, the user is given the option to quit. To do this, they must type "done" as their input, ValueErrors are handled with an error message and the loop continues. When a game is ended, the name of the winner and their score is printed and the user is asked if they want to play again, then the user is asked if they want to save their score cards to a .txt file, if so, the values from that game's p1 and p2 are written to a .txt file with the name given by the user.
066e72f501d2a466a52db02e8020f9f8ea0cf496
[ "Markdown" ]
1
Markdown
Churchboy44/Golf-scorecard-reader-and-writer
eb9f8e1cab36533089d057606937b2f35d729cc5
5f887a1ddc2adf7e36ad9974c005f2c3c9b6b074
refs/heads/master
<file_sep># DATA (Implied_Scenarios) In this folder the data used for our results is presented. Each model studied has its own subfolder, and each one of those subfolders are organized as follows: ``` [System Name]/ ├ Model/ │ ├ [System Name]_ArchitectureModel.lts │ ├ [System Name]_ConstrainedModel.lts │ ├ [System Name].lts │ ├ [System Name].txt │ └ [System Name].xml │ ├ Results/ │ ├ CBs_for_[System Name]_traces.txt │ ├ dendro_for_lev_[System Name]_traces.pdf │ ├ dendro_for_sw_[System Name]_traces.pdf │ ├ lev_for_[System Name]_traces.csv │ ├ lev_for_[System Name]_traces.txt │ ├ sw_for_[System Name]_traces.csv │ ├ sw_for_[System Name]_traces.txt │ └ tests_for_[System Name]_traces.txt │ ├ [System Name]_ref.bib └ [System Name]_traces.txt ``` Model and Results are both subfolders, while ref.bib and traces.txt are both single files. **_\[System Name\]\_ref.bib_** is a reference to a work that used that better explains the system, if a better explanation of its functionality is needed. **_\[System Name\]\_traces.txt_** is a file that contains detected implied scenarios of that system. Even though in our works we used different number of ISs, only the file with most ISs have been provided (up to 500). However, if a different number of ISs is desired, all required files (mscplugin and model specification) have been provided. ## Model Folder Inside _Model_, 3 files with the same model specification will be present: * \[System Name\].lts * \[System Name\].txt * \[System Name\].xml The **_lts_** model, is the behaviour model generated by the mscplugin, with the addition of constraint(s) that remove all implied scenarios. The **_txt_** model, is a simplified view of the MSC specification. It can used as input to the _model_parser.py_ script (inside [code folder](../code/)) to generate a xml accepted by the mscplugin. Its syntax is well explained in the _example.txt_ that's provided alongside the script in the code folder. Finally, **_xml_** model is simply a better (visually) formatted version of the system specification in LTSA. It's completely equivalent to the generated output by the model_parser script, the bMSCs have simply been rearranged to look better visually in the presented hMSC. The information itself is the same. Besides those 3 files, there are two other files: **_\[System Name\]\_ArchitectureModel.lts_** and **_\[System Name\]\_ConstrainedModel.lts_**. These files are simply the composition of the different components specified in the **_lts_** file. _Architecture_ file has only the composition of the components and nothing else, that is, it follows the model's specification. _Constrained_ composes that result with the constraint(s) that resolve all ISs. These files can be used alongside the _tests_ file inside the Results folder as input for the _check_scenarios.py_ script (inside [code folder](../code/)). This allows us to check if ISs were removed with the constraints added. ## Results Folder All 8 files inside _Results_ can be generated using the _traces_ file as input for _analyze.py_ script. All these files are explained in the [_analyze.py_ script explanation](../code#analyzepy). Only three files (_dendro\_lev_, _dendro\_sw_, and _tests_) are different from the generated ones, and those differences are explained below. ###### dendro\_for\_lev\_[System Name]\_traces.pdf The only difference between this file and the one generated by the script is that this provided one is anotated in the first page, showing which CBs are resolved by which constraints. ###### dendro\_for\_sw\_[System Name]\_traces.pdf The only difference between this file and the one generated by the script is that this provided one is anotated in the first page, showing which CBs are resolved by which constraints. ###### tests\_for\_[System Name]\_traces.txt The only difference between this file and the one generated is that this also includes the positive scenarios. Positive scenarios can be generated by the [_model\_parser.py_ script](../code#model_parserpy), as explained inside the [code folder](../code/). <file_sep># analyze.py # Author: <NAME> # Date created: 2018-06-04 # Last modified: 2018-08-07 # Description: This scripts takes a list of ISs traces as input and exports results # that helps the user to analyze what similarities those ISs have. # # New addition (2018-08-07): added the Levenshtein distance to compare CBs. # # Note: to time this script, simply remove all '##', the lines to calculate and output # times are commented that way and they are correctly idented already, so simply # removing those double hashes should do the trick. from anytree import Node from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from scipy.cluster.hierarchy import dendrogram, linkage from timeit import default_timer as timer import matplotlib import numpy import sys # this class contains information of a single IS trace class Trace(object): _id = None messages = None messages_loopless = None def __init__ (self, string): index = string.index(':') self._id = int(float(string[:index])) self.messages = [] data = string[index+2:] data = data[1:-1] data = data.split() for d in data: if d[-1] == ',': self.messages.append(d[:-1]) else: self.messages.append(d) self.removeLoops() def __str__ (self): return str(self._id) + ": " + str(self.messages) # this method is used to remove repeated messages from the trace def removeLoops(self): nodes = [] nodes_names = [] length = len(self.messages) for i, message in zip(range(length), self.messages): if (message in nodes_names) and (i != length-1): while message != nodes_names[-1]: current_node = nodes[-1] current_node.parent = None nodes.pop(-1) nodes_names.pop(-1) else: current_node = Node(message) if i == 0: nodes.append(current_node) nodes_names.append(message) else: current_node.parent = nodes[-1] nodes.append(current_node) nodes_names.append(message) self.messages_loopless = nodes_names def popFirst(self): self.messages_loopless.pop(0) # this class is used to calculate the Smith-Waterman scores class Smith_Waterman(object): match = None mismatch = None gap = None # default values for the algorithm can be changed when constructing the object def __init__ (self, match_score = 3, mismatch_penalty = -3, gap_penalty = -2): self.match = match_score self.mismatch = mismatch_penalty self.gap = gap_penalty # main method to compare two sequences with the algorithm def compare (self, sequence_1, sequence_2, index1, index2): rows = len(sequence_1) + 1 cols = len(sequence_2) + 1 # first we calculate the scoring matrix scoring_matrix = numpy.zeros((rows, cols)) for i, element_1 in zip(range(1, rows), sequence_1): for j, element_2 in zip(range(1, cols), sequence_2): similarity = self.match if element_1 == element_2 else self.mismatch scoring_matrix[i][j] = self._calculate_score(scoring_matrix, similarity, i, j) # now we find the max value in the matrix score = numpy.amax(scoring_matrix) index = numpy.argmax(scoring_matrix) # and decompose its index into x, y coordinates x, y = int(index / cols), (index % cols) # now we traceback to find the aligned sequences # and accumulate the scores of each selected move alignment_1, alignment_2 = [], [] DIAGONAL, LEFT= range(2) gap_string = "#GAP#" while scoring_matrix[x][y] != 0: move = self._select_move(scoring_matrix, x, y) if move == DIAGONAL: x -= 1 y -= 1 alignment_1.append(sequence_1[x]) alignment_2.append(sequence_2[y]) elif move == LEFT: y -= 1 alignment_1.append(gap_string) alignment_2.append(sequence_2[y]) else: # move == UP x -= 1 alignment_1.append(sequence_1[x]) alignment_2.append(gap_string) # now we reverse the alignments list so they are in regular order alignment_1 = list(reversed(alignment_1)) alignment_2 = list(reversed(alignment_2)) return SW_Result([alignment_1, alignment_2], score, [sequence_1, sequence_2], [index1, index2]) # inner method to assist the calculation def _calculate_score (self, scoring_matrix, similarity, x, y): max_score = 0 try: score = similarity + scoring_matrix[x - 1][y - 1] if score > max_score: max_score = score except: pass try: score = self.gap + scoring_matrix[x][y - 1] if score > max_score: max_score = score except: pass try: score = self.gap + scoring_matrix[x - 1][y] if score > max_score: max_score = score except: pass return max_score # inner method to assist the calculation def _select_move (self, scoring_matrix, x, y): scores = [] try: scores.append(scoring_matrix[x-1][y-1]) except: scores.append(-1) try: scores.append(scoring_matrix[x][y-1]) except: scores.append(-1) try: scores.append(scoring_matrix[x-1][y]) except: scores.append(-1) max_score = max(scores) return scores.index(max_score) # this class contains the results of the SW applied to a pair of CBs # it's only used to export the results class SW_Result(object): aligned_sequences = None traceback_score = None elements = None indices = None def __init__ (self, sequence, score, compared_sequences, indices): self.aligned_sequences = sequence self.traceback_score = score self.elements = compared_sequences self.indices = indices def __str__ (self): out = "Alignment of\n\t" + str(self.indices[0]) + ": " + str(self.elements[0]) + "\nand\n\t" out += str(self.indices[1]) + ": " +str(self.elements[1]) + ":\n\n\n" for sequence in self.aligned_sequences: out += "\t" + str(sequence) + "\n" out += "\n\tScore: " + str(self.traceback_score) return out def __gt__(self, result_2): return self.traceback_score > result_2.traceback_score def __eq__(self, result_2): return self.traceback_score == result_2.traceback_score # this class calculates and exports the Levenshtein distance between two elements class Levenshtein (object): cb1 = None cb2 = None index1 = None index2 = None _distance = None _calculated = None # gets the elements that will be compared and sets that the distance has not been calculated yet def __init__ (self, cb1, cb2, index1 = 0, index2 = 0): self.cb1 = cb1 self.cb2 = cb2 self.index1 = index1 self.index2 = index2 self._calculated = False # method to return the result as a string def __str__ (self): out = "Levenshtein distance between\n\t" + str(self.index1) + ": " + str(self.cb1) + "\nand\n\t" out += str(self.index2) + ": " + str(self.cb2) + "\nis " + str(self.get_distance()) return out # method used to allow the comparison between various Levenshtein distances def __gt__(self, Lev2): return self.get_distance() > Lev2.get_distance() # method used to allow the comparison between various Levenshtein distances def __eq__(self, Lev2): return self.get_distance() == Lev2.get_distance() # returns the Levenhstein distance between the elements cb1 and cb2 def get_distance (self): if not self._calculated: self._calculate() self._calculated = True return self._distance # calculates the distance, that is, the number of required changes to go from cb1 to cb2 def _calculate (self): # there will be len(cb1)+1 columns and len(cb2)+1 rows cols, rows = len(self.cb1)+1, len(self.cb2)+1 mx = numpy.zeros((rows, cols)) # loop that populate the entire matrix # j will go over the rows (i.e., cb2 elements) and i over the columns (i.e., cb1 elements) # NOTE: numpy uses [colum][row] as the order of indices! for j in range(rows): for i in range(cols): # intializes the first row if i == 0: mx[j][0] = j # intializes the first column elif j == 0: mx[0][i] = i # calculates the other values in the matrix (i.e., values that are neither in the first column or in the first row) else: # checks if the current elements (cb1[i-1] and cb2[j-1]) are equal or not # if they are, 0 will be added to the distance, as there is no need for another change, # if they are not, however, 1 will be added, as a new change is required new_change = 0 if self.cb1[i-1] == self.cb2[j-1] else 1 # finds the minimum changes among the 3 previous adjacent positions (i.e., [j-1][i-1], [j-1][i], and [j][i-1]) + the cost to get this position, # the cost is 1 if it is not the diagonal neighbor (i.e., [j-1][i-1]), because it doesn't represents an insertion in one of the sequences; the cost is # new_change if it is diagonal, because it will represent either an insertion (cost 0) or substitution (cost 1). number_of_changes = [mx[j][i-1]+1, mx[j-1][i-1]+new_change, mx[j-1][i]+1] # then sets the current number of changes ([j][i]) as the minimum number among the ones calculated above mx[j][i] = min(number_of_changes) # after populating the whole matrix, sets the Levenshtein distance, # which is the last value calculated in the matrix (i.e., bottom right value) self._distance = mx[rows-1][cols-1] # this method is used to create the dendrogram that shows which CBs are closer to each other def create_dendrogram (filename, distance_matrix, inverse_score): condensed_matrix = [] matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) # condenses the distance matrix into one dimension, according if the score needs to be inversed or not # that is, if the higher the score the more similar the elements, the score needs to be inversed (i.e., 1/score) # so that the most similar elements have a lower score among them if inverse_score == True: for i in range(len(distance_matrix)): for j in range(i+1, len(distance_matrix)): if distance_matrix[i][j] == 0: condensed_matrix.append(1.0) else: condensed_matrix.append(1.0 / distance_matrix[i][j]) else: for i in range(len(distance_matrix)): for j in range(i+1, len(distance_matrix)): condensed_matrix.append(distance_matrix[i][j]) figs = [] # linkage methods considered methods = ['ward', 'single', 'complete', 'average'] # draws one dendrogram for each linkage method # and the distance used is: # ┌ 0, if cb1 = cb2 # dist (cb1, cb2) = ├ 1, if SW(cb1, cb2) = 0 # └ 1 / SW(cb1, cb2), otherwise. # # if the score inverse_score == True. If inverse_score == False, the distance used is the Levenshtein distance. for method in methods: Z = linkage(condensed_matrix, method) fig = plt.figure(figsize=(25, 10)) fig.suptitle(method, fontsize=20, fontweight='bold') dn = dendrogram(Z, leaf_font_size=20) figs.append(fig) try: # exports each dendrogram drawn in a separate page in the pdf pdf = PdfPages(str("dendro_for_" + filename + ".pdf")) for fig in figs: pdf.savefig(fig) pdf.close() except: print("ERROR: unable to create output file with dendrogram.") quit() # this method parses the traces from the input file def parse_traces (filename): file_in = None try: file_in = open(filename, "r") except: print("ERROR: unable to open '" + filename + "'!") quit() text_traces = file_in.read().split("\n") file_in.close() traces = [] # includes only lines formatted as ISs export from our modified LTSA-MSC for text_trace in text_traces: if len(text_trace) > 1 and text_trace[0].isdigit(): t = Trace(text_trace) traces.append(t) return traces # this method removes the extension of a filename def remove_extension (filename): last_period = filename.rfind(".") return filename[:last_period] # this method applies the SW algorithm to all detected common behaviors (CBs) # it returns the matrix where each element A(i,j) contains the SW score between # CB[i] and CB[j], with i!=j def compare_sequences (CBs): results = [] matrix = [[0 for x in range(len(CBs))] for y in range(len(CBs))] SW = Smith_Waterman() for i, cb1 in zip(range(len(CBs)), CBs): for j, cb2 in zip(range(i+1, len(CBs)), CBs[i+1:]): new_result = SW.compare(cb1, cb2, i, j) matrix[j][i] = matrix[i][j] = new_result.traceback_score results.append(new_result) return list(sorted(results, reverse = True)), matrix # this method calculates the Levenshtein distance between all pairs of detected common behaviors (CBs) # it returns the matrix where each element A(i,j) contains the distance score between CBi and CBj def compare_sequences_lev (CBs): results = [] matrix = [[0 for x in range(len(CBs))] for y in range(len(CBs))] for i, cb1 in zip(range(len(CBs)), CBs): for j, cb2 in zip(range(i+1, len(CBs)), CBs[i+1:]): lev = Levenshtein(cb1, cb2, i, j) matrix[j][i] = matrix[i][j] = lev.get_distance() results.append(lev) return list(sorted(results, reverse = False)), matrix # here we export the test cases to be used with the check_scenarios.py file # it groups all analyzed ISs by common behavior, this way it is possible to see # that ISs in the same CB are being treated together and if all ISs are being resolved def export_test_cases (common_behaviors, filename): out = "! Test file for " + filename + "\n\n" out += "!\n! Here you can manually add the expected behaviors to check that they're still reachable.\n!\n! You can generate them with the model_parser.py script.\n!\n" for i, common_behavior in zip(range(len(common_behaviors)), common_behaviors): out += "\n### Common Behavior " + str(i) + "\n\n" out += "!\n! " + str(common_behavior[0][0].messages_loopless) + "\n!\n\n" for scenario in common_behavior: messages = str(scenario[0].messages).replace('[', '').replace(']', '').replace("'", "") out += str(scenario[1]) + ": " + messages + "\n" try: filename = str("tests_" + filename + ".txt") file_out = open(filename, "w") file_out.write(out) file_out.close() except: pass # this is the main method to analyze the input data def analyze_main (input_file, traces): CBs = [] # we find the unique common behaviors among the given traces for i, trace in zip(range(len(traces)), traces): new_CB = True for CB in CBs: if CB[0][0].messages_loopless == trace.messages_loopless: CB.append([trace, i]) new_CB = False if new_CB: CBs.append([[trace, i]]) # and export them filename = str("CBs_for_" + input_file + ".txt") output = "Common Behaviors for " + input_file + ":\n" for i, CB in zip(range(len(CBs)), CBs): output += "\n" output += " " + str(i) + ": " + str(CB[0][0].messages_loopless) try: file_out = open(filename, "w") file_out.write(output) file_out.close() except: print("ERROR: unable to create output file!") quit() # now we generate the test file for the check_scenarios.py export_test_cases(CBs, input_file) # now we analyze all possible pairs of CBs with the SW algorithm cbs_only = [] for CB in CBs: cbs_only.append(CB[0][0].messages_loopless) # all comments with double # are lines to measure time of the script # if it's desired to time a run, simply remove all '##' ##start_sw = timer() results, score_matrix = compare_sequences(cbs_only) output = "CB" for i in range(len(cbs_only)): output += ", " + str(i) for i in range(len(cbs_only)): output += "\n" + str(i) for j in range(len(cbs_only)): output += ", " + str(score_matrix[i][j]) try: filename = str("sw_for_" + input_file + ".csv") file_out = open(filename, "w") file_out.write(output) file_out.close() except: pass output = "" for i, result in zip(range(len(results)), results): if i > 0: output += "\n\n--- --- --- --- ---\n\n" output += str(result) try: filename = str("sw_for_" + input_file + ".txt") file_out = open(filename, "w") file_out.write(output) file_out.close() except: pass ##end_sw = timer() ##print("Time for SW: %fs" % (end_sw-start_sw)) try: ##start_dendro = timer() create_dendrogram(str('sw_' + input_file), score_matrix, inverse_score=True) ##print("Time for Dendrogram: %fs" % (timer()-start_dendro)) except: print("Unable to export a dendrogram.") ##return (timer() - start_sw) # now we do the same thing but using the Levenhstein distance intead of the Smith-Waterman algorithm results, score_matrix = compare_sequences_lev(cbs_only) output = "CB" for i in range(len(cbs_only)): output += ", " + str(i) for i in range(len(cbs_only)): output += "\n" + str(i) for j in range(len(cbs_only)): output += ", " + str(score_matrix[i][j]) try: filename = str("lev_for_" + input_file + ".csv") file_out = open(filename, "w") file_out.write(output) file_out.close() except: pass output = "" for i, result in zip(range(len(results)), results): if i > 0: output += "\n\n--- --- --- --- ---\n\n" output += str(result) try: filename = str("lev_for_" + input_file + ".txt") file_out = open(filename, "w") file_out.write(output) file_out.close() except: pass #try: create_dendrogram(str('lev_' + input_file), score_matrix, inverse_score=False) #except: # print("Unable to export a dendrogram.") # this main method simply checks if the files have been passed. # it can also time the run of the analysis. def main(): ##start = timer() if len(sys.argv) < 2: print("ERROR: a file should be passed as argument!") print("Example of usage: python3 analyze.py traces.txt") quit() traces = parse_traces(sys.argv[1]) sw_time = analyze_main(remove_extension(sys.argv[1]), traces) ##end = timer() ##total = end-start ##find_CBs = total - sw_time ##print("Time for CBs: %fs" % find_CBs) ##print("Total Time: %fs" % total) if __name__ == "__main__": main()<file_sep># Implied Scenarios This repository contains relevant files used for [_the paper published at the Journal of Systems and Software_](https://doi.org/10.1016/j.jss.2019.110425) and the project named after the paper: _Characterization of Implied Scenarios as Families of Common Behavior_. ## How do I get set up? [Code](code/) and [Data](data/) are in their respective folders, while the modified LTSA-MSC plugin is in this root folder. **Each folder contains a readme that better explains their files usage**. An overview of the contents is presented below: ###### Python code Everything was developed and tested on version 3.6.3, and libraries used are in the [requirements file (inside code folder).](code/requirements.txt) Note that you need [_Graphviz_](https://www.graphviz.org) installed to be able to use anytree's export method. ###### How to run this LTSA MSC-plugin version The provided plugin (mscplugin_mod.jar) is a modified version of [the original LTSA-MSC by Uchitel et al.](https://www.doc.ic.ac.uk/ltsa/msc/) It is able to collect multiple implied scenarios iteratively and export them to a text file. To use it, simply replace the original one in LTSA's plugins folder. ## Who do I talk to? caio[dot]batista[at]gmail[dot]com *or* genainarodrigues[at]gmail[dot]com <file_sep># CODE (Implied_Scenarios) In this folder the code used for our results is presented. **_requirements.txt_** list the required libraries for these scripts to run. Sample files can be found inside the [examples folder](examples/) to run these scripts. More examples can also be found inside the [data folder](../data/). All scripts have comments that (I believe) explain ~~well~~ what they're doing. However, all 3 files are detailed below: ## analyze.py This is the main script used to analyze a list of implied scenarios. It takes as input the _txt_ file exported by our modified version of the LTSA-MSC plugin and exports the detected Common Behaviors (CBs), the results of the SW algorithm applied to the pairs of CBs detected, the Levenshtein distance between the pairs of CBs detected, two dendrograms showing the most similar CBs, and a test file to be used with the _check\_scenarios.py_ script (detailed below). The usage of this script is as follows: ``` python analyze.py traces_file ``` where traces_file is a file containing the collected ISs by LTSA-MSC (such as [example_traces](examples/example_traces.txt)). Finally, all exported files are explained below: ###### CBs\_for\_[input file\].txt This file contains the detected Common Behaviors (CBs) among the collected ISs. This file is simply a list with one CB per line. ###### dendro\_for\_lev\_[input file\].pdf This is a pdf with 4 pages. Each page shows the [agglomerative hierarchical clustering](https://en.wikipedia.org/wiki/Hierarchical_clustering) with a different linkage method. Through a qualitative analysis, we realized that [Ward's method](https://en.wikipedia.org/wiki/Ward%27s_method) provided the best results overall, even though they were not that different. This dendrogram was obtained by hierarchical clustering the CBs with the Levenshtein distance. ###### dendro\_for\_sw\_[input file\].pdf This file is similar to the above one, however, the dissimilarity between two CBs for this dendrogram is calculated as follows: ``` ┌ 0, if cb1 = cb2 diss (cb1, cb2) = ├ 1, if SW(cb1, cb2) = 0 └ 1 / SW(cb1, cb2), otherwise. ``` where _cb1_ and _cb2_ are CBs, and _SW(cb1, cb2)_ is the SW score for that pair of CBs. ###### lev\_for\_[input file\].csv This file contains the Levenshtein distance for each pair of CBs. It is a matrix and an element _A[i,j]_ is the distance between CB[i] and CB[j]. ###### lev\_for\_[input file\].txt This file also presents the Levenshtein distances. It shows the distance and the messages of each CB for all pairs of CBs, and it's sorted in descending order, that is, the pairs with lowest distance will show up first. ###### sw\_for\_[input file\].csv This file contains the Smith-Waterman (SW) score for each pair of CBs. It is a matrix and an element _A[i,j]_ is the SW score between CB[i] and CB[j]. ###### sw\_for\_[input file\].txt This file also presents the SW results. However, it's not simply the traceback scores. It shows the score and alignment for all pairs of CBs, and it's sorted in descending order, that is, the pairs with higher score (i.e., most similar) will show up first. ###### tests\_for\_[input file\].txt Finally, this file can be used to test the presence of ISs in the model. This is achieved by using the check_scenarios.py script and the Architecture or Constrained model. ## check_traces.py This file can be used to check if traces are reachable in a FSP specification. That is, it is possible to check if ISs are present in the architecture model generated by LTSA. The usage of this script is as follows: ``` python check_scenarios.py fsp_spec [test_file] [-DRAW] ``` where _fsp\_spec_ is the system's composition from LTSA (such as [example_fsp](examples/example_fsp.lts)), _tests\_file_ is a file containing the ISs that should be tested (such as [example_tests](examples/example_tests.txt)), and the _-DRAW_ is an optional flag to draw the automata for the given specification. As LTSA doesn't draw automatas that are too large, this is an alternative to visualize the model's specification. Note that this can be used with 2 or 3 parameters, but the first one always has to be the FSP specification. It can be used to only test for reachable traces, only draw the specification's automata, or both checking and drawing. For the latter (3 parameters), it is important to keep the order stated above: fsp_spec test_file -DRAW. Examples for FSP specifications and tests files can be found in the [data folder](../data/). Each model subfolder has its own Architecture and Constrained models in FSP format, and inside their results folder there is the test file to be used with those models. ## model_parser.py This script is used to generate a XML file that works with LTSA-MSC tool containing the scenarios of a model's specification. Its input is a file that has a much simpler syntax, and can generate both the XML file and a the positive scenarios to be used with the script above (_check\_scenarios_). These positives scenarios ~~should~~ can be included in the output test file from the _analyze.py_ script. [**_example\_model.txt_**](examples/example_model.txt) is a sample file that explains well how the syntax for the input file works. Inside the [data folder](../data/) more examples of this kind of file can be found. The usage of this script is as follows: ``` python model_parser.py input_file [-t] ``` where _input\_file_ is the _txt_ file using the syntax stated above, and _-t_ is an optional flag used to export the positive scenarios of the model's specification. <file_sep># model_parser.py # Author: <NAME> # Date Created: 2018-05-03 # Last Modified: 2018-08-08 # Description: Parses an easier to understand model into LTSA's xml. # New Addition (2018-05-09): can export expected behaviors to be included in the test file. # New Addition (2018-08-08): can export more expected behaviors to be included in the test file with the export_expected_behaviors method. # The original one (simple_expected_behaviors) was also kept to preserve the original functionality, if wanted it # can also be used as it is simpler to understand. import re import sys import networkx as nx # declared globally so error messages are better explained line_number = None class Indentation (): # class used to indent the XML indent = '' # Indentation size size = 2 def increase (): for _ in range(Indentation.size): Indentation.indent += ' ' def decrease (): try: Indentation.indent = Indentation.Indent[Indentation.size:] except: Indentation.indent = '' class Transition (object): # stores a transition between bmscs To = None From = None def __init__ (self, From, To): self.To = To self.From = From def __str__ (self): return self.From + "->" + self.To class Message (object): # holds information of a single message To = None From = None msg = None time = None def __init__ (self, From, To, msg, time): self.To = To self.From = From self.msg = msg self.time = time def __eq__ (self, other): if other == None: return False else: return self.msg == other.msg and self.To == other.To and self.From == other.From and self.time == other.time def __str__ (self): return self.From.lower() + "." + self.To.lower() + "." + self.msg class Instance (object): # holds information of an instance inside a single scenario name = None output = None Input = None def __init__ (self, name): self.name = name self.output = [] self.Input = [] def add_out (self, msg): self.output.append(msg) def add_in (self, msg): self.Input.append(msg) def add_message (self, msg): ret = 0 if msg.To == self.name: self.add_in(msg) ret += 1 if msg.From == self.name: self.add_out(msg) ret += 1 return ret class Scenario (object): name = None instances = None empty = None def __init__ (self, name, instance_names): self.name = name self.instances = [] self.empty = True for instance_name in instance_names: self.instances.append(Instance(instance_name)) # goes through instances trying to add the message # returns how many times the message has been added def add_message (self, message): found = 0 for inst in self.instances: found += inst.add_message(message) if found > 0: self.empty = False return found def get_ordered_messages (self): total_count = 0 for instance in self.instances: total_count += len(instance.output) messages = [] last_timeindex = 0 while len(messages) < total_count: next_timeindex = last_timeindex + 1000 instance_index = 0 message_index = 0 last_message_added = None for i, instance in zip(range(len(self.instances)), self.instances): for j, message in zip(range(len(instance.output)), instance.output): if message.time <= next_timeindex and message.time >= last_timeindex: # this condition allows us to have two messages with the same timeindex if message.time == last_timeindex: found = False for k in range(len(messages)-1, -1, -1): if messages[k] == message: found = True break if found: continue next_timeindex = message.time instance_index = i message_index = j messages.append(self.instances[instance_index].output[message_index]) last_timeindex = next_timeindex return messages def __eq__ (self, string): return self.name == string class Model (object): instances = None transitions = None scenarios = None scenario_titles = None title = None timeindex = None def __init__ (self, title): self.title = title self.instances = [] self.transitions = [] self.scenarios = [] self.scenario_titles = [] def add_transition (self, transition): info = transition.split('->') # checks if scenarios have already been encountered if info[0] not in self.scenario_titles: self.scenario_titles.append(info[0]) if info[1] not in self.scenario_titles: self.scenario_titles.append(info[1]) # adds the new transition self.transitions.append(Transition(info[0], info[1])) def add_instance (self, instance): self.instances.append(instance) def add_scenario (self, scenario_title): self.scenarios.append(Scenario(scenario_title, self.instances)) # restarts the timeindex for current scenario self.timeindex = 1 def add_message (self, message): global line_number try: insts, msg = message.split(':') From, To = insts.split('->') # checks if the message isn't to itself if From == To: print("ERROR (line %d): LTSA doesn't allow a component to send itself a message." % line_number) print("Hint: you could create an auxiliary instance to go around this.") return # a '&' in the end of a message indicates that timeindex # shouldn't be increased for the next message if (msg[-1] == '&'): m = Message(From, To, msg[:-1], self.timeindex) else: m = Message(From, To, msg, self.timeindex) # increases the timeindex for next message self.timeindex += 1 # adds the message and tests if both instances are known if self.scenarios[-1].add_message(m) < 2: print("ERROR (line %d): unknown instance on message." % line_number) except ValueError: print("ERROR (line %d): badly formatted message." % line_number) except IndexError: print("ERROR (line %d): a scenario should be created before a message." % line_number) except TypeError: print("ERROR (line %d): a scenario should be created before a message." % line_number) def generate (self): # headers of the xml xml = Indentation.indent + '<?xml version="1.0" encoding="UTF-8"?>\n' xml += Indentation.indent + '<specification>\n' Indentation.increase() # hmsc part xml += Indentation.indent + '<hmsc>\n\n' Indentation.increase() init_x = 50 init_y = 30 step_x = 120 step_y = 100 pos_x = 50 pos_y = init_y - step_y # first the bmscs are added if 'init' not in self.scenario_titles: self.scenario_titles = ['init'] + self.scenario_titles len_x = int(round(len(self.scenario_titles) ** .5 + .5)) # +.5 just to round up for i, inst in zip(range(len(self.scenario_titles)), self.scenario_titles): if i % len_x == 0: pos_x = init_x pos_y += step_y xml += Indentation.indent + '<bmsc name="' + inst + '" x="' + str(pos_x) + '" y="' + str(pos_y) + '"/>\n' pos_x += step_x xml += '\n' # now we add the transitions for transition in self.transitions: xml += Indentation.indent + '<transition>\n' Indentation.increase() xml += Indentation.indent + '<from>' + transition.From + '</from>\n' xml += Indentation.indent + '<to>' + transition.To + '</to>\n' Indentation.decrease() xml += Indentation.indent + '</transition>\n\n' Indentation.decrease() xml += Indentation.indent + '</hmsc>\n\n' # end of hmsc part # now the bmscs are added # fist empty scenarios that only show up in hmsc for scenario in self.scenario_titles: if scenario not in self.scenarios: xml += Indentation.indent + '<bmsc name="' + scenario + '" />\n\n' # now we add the model's scenarios that actually have things for scenario in self.scenarios: # checks if it's an empty scenario if scenario.empty: xml += Indentation.indent + '<bmsc name="' + scenario.name + '" />\n\n' else: xml += Indentation.indent + '<bmsc name="' + scenario.name + '">\n' Indentation.increase() for instance in scenario.instances: # checks if it's an empty instance if (len(instance.output) + len(instance.Input)) == 0: xml += Indentation.indent + '<instance name="' + instance.name + '" />\n' else: # starts this instance xml += Indentation.indent + '<instance name="' + instance.name + '">\n' Indentation.increase() # first write the outgoing messages for message in instance.output: xml += Indentation.indent + '<output timeindex="' + str(message.time) + '">\n' Indentation.increase() xml += Indentation.indent + '<name>' + message.From.lower() + ',' + message.To.lower() + ',' + message.msg + '</name>\n' xml += Indentation.indent + '<to>' + message.To + '</to>\n' Indentation.decrease() xml += Indentation.indent + '</output>\n' # then the incoming messages for message in instance.Input: xml += Indentation.indent + '<input timeindex="' + str(message.time) + '">\n' Indentation.increase() xml += Indentation.indent + '<name>' + message.From.lower() + ',' + message.To.lower() + ',' + message.msg + '</name>\n' xml += Indentation.indent + '<from>' + message.From + '</from>\n' Indentation.decrease() xml += Indentation.indent + '</input>\n' # end of this instance Indentation.decrease() xml += Indentation.indent + '</instance>\n' Indentation.decrease() xml += Indentation.indent + '</bmsc>\n\n' # lastly, we close the specification tag Indentation.decrease() xml += Indentation.indent + '</specification>' try: with open(self.title + '.xml', 'w') as file_out: file_out.write(xml) except: print("ERROR: unable to create file: '" + self.title + ".xml'.") # exports the expected behaviors to be included in the test file # this method exports the sequences of scenarios that start from # the initial node and ends either in the original node again, or # in a terminal node. It also removes loops. def simple_expected_behaviors(self): G = nx.DiGraph() G.add_nodes_from(self.scenario_titles) for transition in self.transitions: G.add_edge(transition.From, transition.To) if len(list(G.predecessors('init'))) > 0 or len(list(G.successors('init'))) > 1: root = 'init' else: root = list(G.successors('init'))[0] paths = [] restarting_nodes = list(G.predecessors(root)) # first we add the paths that come back to the inicial scenario for node in restarting_nodes: current_paths = list(nx.all_simple_paths(G, root, node)) for path in current_paths: # includes the start state so we know the system can execute again paths.append(path + [root]) # now we add the paths that start on the intiial and end on a terminal node for node in G.nodes: if len(list(G.successors(node))) == 0: paths += list(nx.all_simple_paths(G, root, node)) try: filename = self.title + '_expected_behaviors.txt' with open(filename, 'w') as file_out: out = '### Expected Behaviors\n\n' for i, path in zip(range(len(paths)), paths): out += "! " for scenario in path: out += scenario + ', ' try: out = out[:-2] + '\n' except: pass out += str(i) + ": " for scenario in path: try: index = self.scenarios.index(scenario) except: continue messages = self.scenarios[index].get_ordered_messages() for msg in messages: out += str(msg) + ', ' out = out[:-2] + "\n\n" file_out.write(out) except: print("ERROR: unable to create file: '" + filename + "'.") # exports the expected behaviors to be included in the test file # this method exports more scenarios than the original one above; # it exports paths that start in the root node and are not prefixes # of other paths (i.e., maximal paths). It also includes one iteration # of the loops that are of two scenarios (e.g., s1->s2->s1). def export_expected_behaviors(self): # creates a directed graph which will serve as the hMSC G = nx.DiGraph() # adds the scenarios (bMSCs) as the nodes G.add_nodes_from(self.scenario_titles) # adds the transitions between scenarios as edges for transition in self.transitions: G.add_edge(transition.From, transition.To) root = 'init' # sets the current scenario as init (initial scenario in LTSA-MSC) paths = [[root]] # will contains all expected sequences of scenarios visited = [root] # list that contains the already visited scenarios, used to prevend infinite loops to_go = list(G.successors(root)) # nodes that still need to be visited previous_future_nodes = [(root,node) for node in list(G.predecessors(root)) if node in to_go] # contains the nodes that are both predecessors and successors of the current node # loops while there are nodes to be visited while len(to_go) > 0: # visits the next node and removes it from the ones to go current = to_go.pop(0) # adds the current node to the list of visited ones visited.append(current) # gets the previous nodes that can reach the current one previous_nodes = list(G.predecessors(current)) # gets the nodes that can be reached from this one future_nodes = list(G.successors(current)) # adds the new nodes reachable from this one to the next nodes to be visited for node in future_nodes: # checks if the node is not already in the list nor has it been already visited if node not in to_go and node not in visited: to_go.append(node) # checks if this is a node that both reaches current and is reached by current if node in previous_nodes and node != current and (node, current) not in previous_future_nodes: previous_future_nodes.append((current, node)) # gets all paths that can get here from the root node and adds them to the list of paths new_paths = list(nx.all_simple_paths(G, root, current)) paths += new_paths # now it adds the transitions that goes to a node and comes back to the same one # therefore, loops all pairs that were added as previous and future nodes new_paths = [] # stores the new created paths for this first loop insertion for i, (node1, node2) in enumerate(previous_future_nodes): # goes through the original paths to make the new inclusions for path in paths: # finds all positions that node1 occurs in path positions1 = [index for index,scenario in enumerate(path) if scenario == node1] # finds all positions that node1 occurs in path positions2 = [index for index,scenario in enumerate(path) if scenario == node2] # finds the positions where node1 occurs in path and it is not proceeded by node2, so we do not add repeated loops positions = [pos for pos in positions1 if (pos+1) not in positions2] # loops 2^n times to allow all possibilities of changes in the positions for k in range(2**len(positions)): # makes a copy in memory to not mess up the original path new_path = path.copy() # used to keep the index correct when the new messages are added changes = 0 # checks if each position should be replaced or not for j in range(len(positions)): # checks if the bit for the current position is to be fixed (1) or not (0) if 2**j & k: # if the insertion is needed, then keep the same scenarios before and after, and add the expansion in the position new_path = new_path[:positions[j]+changes] + [node1, node2] + new_path[positions[j]+changes:] changes += 1 new_paths.append(new_path) # adds the new path to the list of new paths # finally adds the new paths created # notice that only two levels of loops are created, however we could go further with this process if desired paths += new_paths # removes paths that are prefixes of other paths, that is, # paths that are subpaths for other paths also included # to achieve this, we add the unique paths that are not prefix of other paths in the new list unique_paths = [] for p1 in paths: # checks if p1 is already inserted if p1 not in unique_paths: unique_paths.append(p1) else: continue # converts the sequence of scenarios to a string containing only letters and numbers # this is done to allow the use of the 'startswith' method of the string class s1 = re.sub(r"[^A-Za-z0-9]+", '', str(p1)) for p2 in paths: # checks if the elements are equal and if p2 is further down in the list, so we keep the first appearence of the path if p1 == p2: continue # converts the sequence of scenarios to a string containing only letters and numbers s2 = re.sub(r"[^A-Za-z0-9]+", '', str(p2)) # if p1 is a prefix to another path, remove p1 from the unique paths and breaks the inner loop if s2.startswith(s1): unique_paths.remove(p1) break try: filename = self.title + '_expected_behaviors.txt' with open(filename, 'w') as file_out: out = '### Expected Behaviors\n\n' for i, path in zip(range(len(unique_paths)), unique_paths): out += "! " for scenario in path: out += scenario + ', ' try: out = out[:-2] + '\n' except: pass out += str(i) + ": " for scenario in path: try: index = self.scenarios.index(scenario) except: continue messages = self.scenarios[index].get_ordered_messages() for msg in messages: out += str(msg) + ', ' out = out[:-2] + "\n\n" file_out.write(out) except: print("ERROR: unable to create file: '" + filename + "'.") # exports a list with all messages of this model def export_all_messages (self): all_messages = [] for scenario in self.scenarios: messages = scenario.get_ordered_messages() for message in messages: msg = str(message) if msg not in all_messages: all_messages.append(msg) try: filename = self.title + '_all_messages.txt' with open(filename, 'w') as file_out: out = '' for msg in all_messages: out += msg + '\n' file_out.write(out) except: print("ERROR: unable to create file: '" + filename + "'.") def parse_model (filename): try: with open(filename, 'r') as file_in: lines = file_in.read().split('\n') except: print("ERROR: unable to open file: '" + filename + "'.") return model = None try: global line_number for line_number, line in zip(range(1,len(lines)+1), lines): # not done before so the error shows on the correct line line = line.replace(' ', '').replace('\t', '') if line.startswith('//') or line == '': # ignore comments and blank lines continue elif line.startswith('!'): # title line if model != None: print("ERROR (line %d): title has already been defined." % line_number) model = Model(line[1:]) elif line.startswith('@'): # transitions between scenarios model.add_transition(line[1:]) elif line.startswith('#'): # instances model.add_instance(line[1:]) elif line.startswith('$'): # scenarios if line == '$init': print("ERROR (line %d): 'init' is a reserved scenario in LTSA." % line_number) else: model.add_scenario(line[1:]) elif line.startswith('%'): # messages model.add_message(line[1:]) else: print("ERROR (line %d): unexpected syntax." % line_number) except AttributeError: print("ERROR: title hasn't been defined yet.") return model if __name__ == "__main__": try: model = parse_model(sys.argv[1]) model.generate() if "-t" in sys.argv or "-T" in sys.argv: model.export_expected_behaviors() # the following line of code can be uncommented to export a file # that contains all messages in the specification. It's useful # for creating constraints in the lts (LTSA architecture) model. # model.export_all_messages() else: print("HINT: you can export positive scenarios with '-t'.") except IndexError: print("ERROR: a file should be passes as argument.")<file_sep># check_traces.py # Author: <NAME> # Date created: 2018-01-24 # Last modified: 2018-08-10 # Description: checks if a list of traces is reachable in a FSP system model; # can optionally draw an automata of said FSP specification. # Requires 'graphviz' in order to export the automata. # TO-DO: change anytree to networkx from anytree import Node, RenderTree from anytree.render import AsciiStyle from anytree.exporter.dotexporter import DotExporter import sys # declared globally to ease the multiple methods that use this info states = [] class State(object): name = None transitions = None checked_transitions = None # somewhat confusing method, but it's only dealing with FSP syntax def __init__ (self, string): # switches commas(,) for / inside {} so they're not replaced further down flag = False for i in range(len(string)): if flag == False: if string[i] == "{": flag = True else: if string[i] == ",": string = (string[:i] + "/" + string[i+1:]) elif string[i] == "}": flag = False #clean up the string by removing empty spaces and commas string = string.replace(" ", "") string = string.replace("\t", "") string = string.replace(",", "") string = string.replace("(", "") string = string.replace(")", "") #breaks up the information info = string.split("=") self.name = info[0] if info[1] == 'STOP': self.transitions = [str("STOP->"+self.name)] else: self.transitions = info[1].split("|") self.checked_transitions = 0 #print(self) def find_label(self, dest): for transition in self.transitions: info = transition.split("->") if info[1] == dest: return info[0] # this method creates a Tree (anytree) in a recursive way. # for each transition, an edge is added between the current state and the next one. def to_anytree_node (self, parent, msg): global states n = Node(self.name, parent = parent, edge = msg) #checks which transitions have been dealt with #so repeated edges don't reappear due to recursion while True: try: transition = self.transitions[self.checked_transitions] self.checked_transitions += 1 info = transition.split("->") index = states.index(info[1]) states[index].to_anytree_node(n, info[0]) except: break return n # tries to find the next state given a message label def next_state (self, message): for transition in self.transitions: [labels, dest] = transition.split("->") labels = labels.replace("{", "").replace("}", "") for label in labels.split("/"): if label == message: return int(float((dest[1:]))) raise Exception("Transition not found.") def __str__ (self): ret_string = "State: " + self.name + "\n" ret_string += "Transitions:" if len(self.transitions) > 0: for transition in self.transitions: ret_string += "\n\t" + transition return ret_string def __eq__ (self, other): if isinstance(other, str): return self.name == other elif isinstance(other, State): return self.name == other.name else: return False # this is the main method to parse the FSP spec. def parse_fsp (filename): global states with open(filename, 'r') as myfile: data = myfile.read().replace('\n', ',') # find the starting point of the state machine. this way, there is no need to cut pieces # of the FSP specification out before using that as input. index = data.find("Q0\t=") data = data[index:].split(",,") for i, state in zip(range(len(data)), data): #removes the last period from the file #this allows for periods in messages' names if (i == len(data)-1): state = state[:-1] states.append(State(state)) # method defined to assis exporting anytree def edgeattrfunc(node, child): global states index = states.index(node.name) s = states[index] msg = s.find_label(child.name) return str('label="'+msg+'"') # method defined to assis exporting anytree def edgetypefunc(node, child): return '->' # this method is used to export the anytree to a PDF file. # it requires graphviz, if it is not installed, change # flag (export_dot) to True, so the .dot is exported instead. def draw_anytree (filename, export_dot): global states root = states[0].to_anytree_node(None, None) if export_dot: DotExporter(root, graph="digraph", edgeattrfunc=edgeattrfunc, edgetypefunc=edgetypefunc).to_dotfile(filename+".dot") else: DotExporter(root, graph="digraph", edgeattrfunc=edgeattrfunc, edgetypefunc=edgetypefunc).to_picture(filename+".pdf") # this method gets a list of messages that represent a trace from the test file. # it will check if that trace is realizable from the starting state. # in other words, this method runs a single test. def run_test(messages): # starts at state 0 current_state = 0 try: # for each message, gets the next state from the pair (current_state, current_message). # if no transition exists, an exception will be raised and thus this trace is not reached. for msg in messages: current_state = states[current_state].next_state(msg) result = "reached" except: result = "NOT reached" return result # this method is used to run multiple tests and control the output to the user. def prepare_tests(file): with open(file, 'r') as myfile: lines = myfile.read().split("\n") total_count = 0 total_passed = 0 local = False local_titles = [] local_counts = [] local_passeds = [] # this is the main loop, where each test will be executed. for line in lines: if line.startswith("###"): if local: print("\n----------\n") local_passeds.append(local_passed) local_counts.append(local_count) print(line + "\n") local_titles.append(line[4:]) local = True local_count = 0 local_passed = 0 elif line.startswith("!"): continue else: line = line.replace(" ", "").replace("\t", "") if line == "": continue [number, test] = line.split(":") result = run_test(test.split(",")) out = " " + line + ": " + result print(out) local_count += 1 total_count += 1 if result == "reached": local_passed += 1 total_passed += 1 print("\n----------") print("----------\n") print("RESULTS SUMMARY:\n") if local: local_passeds.append(local_passed) local_counts.append(local_count) for title, count, passed in zip(local_titles, local_counts, local_passeds): print("%s -> traces reached: %d out of %d" % (title, passed, count)) print("\nTotal traces reached: %d out of %d\n" % (total_passed, total_count)) def main(): if len(sys.argv) < 2: print("Error: a file should be passed as parameter!\n") exit(1) # parses the first file provided as a FSP specification. filename = sys.argv[1] parse_fsp(filename) # if the optional -DRAw flag was passed, exports the anytree to a PDF # if no graphviz installed, change the bool value to True so a .dot is exported. if "-DRAW" in sys.argv: draw_anytree(filename, False) # tries to run the tests inside a second file that may have been passed or not try: prepare_tests(sys.argv[2]) except: pass if __name__ == "__main__": main()
c363c3934de40e72edf4ee48ec3f8566200f0e8c
[ "Markdown", "Python" ]
6
Markdown
cbdm/Implied_Scenarios
dcc4a7a6a39ce461d7082fe6b37637531edbdcaf
53e05fe08b9b23aba96572fd8fa14d15882b752a
refs/heads/master
<repo_name>paulpsan/prueba-Node<file_sep>/readme.md # RESOLUCION DE PRUEBA NODEJS iDO learning ## Requisitos - **GIT** - **CURL** - **NODEJS**(>= 6.X.X) ## Instalar Proyecto Clonar proyecto ```bash git clone <EMAIL>:paulpsan/prueba-Node.git ``` abrir proyecto ```bash cd prueba-Node ``` Instalar las dependencias del proyecto ```bash npm install ``` Iniciar el proyecto ```bash node server/index.js ``` ## Prueba de servicios Endpoint http://localhost:3000/login ```bash curl --location --request POST 'localhost:3000/login' \ --header 'Content-Type: application/json' \ --data-raw '{ "username": "username" }' ``` Endpoint http://localhost:3000/verify ```bash curl --location --request GET 'localhost:3000/verify' \ --header 'Authorization: Bearer <KEY>' ``` <file_sep>/server/auth/authController.js const authService = require("./authService"); function login(username) { return new Promise((resolve, reject) => { //comparamos si existe el usuario if (username === "username") return resolve(authService.sign(username)); else reject(new Error("Informacion incorrecta")); }); } function verify(req) { return authService.verify(req); } module.exports = { login, verify }; <file_sep>/server/auth/authAPI.js const express = require("express"); const router = express.Router(); const authController = require("./authController"); router.post("/login", (req, res, next) => { authController.login(req.body.username).then(token => { res.status(200).send({ token }); }); }); router.get("/verify", (req, res, next) => { authController .verify(req) .then(() => { res.status(200).send({ mesage: "Verificado" }); }) .catch(() => { res.status(401).send({ mesage: "Token no valido" }); }); }); module.exports = router;
697eb233f688e1ca3b1b54c13dfe52969e65d651
[ "Markdown", "JavaScript" ]
3
Markdown
paulpsan/prueba-Node
2780c6e4dab1e74bf955cccd46a141460cc3bfb6
c0e46b12661760c6d30e3d91e9f70f44e458df56
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HZDPackTool { class Program { static void Main(string[] args) { string packedDir = @"E:\SteamLibrary\SteamApps\common\Horizon Zero Dawn\Packed_DX12"; Console.WriteLine(packedDir); string[] idxFiles = Directory.GetFiles(packedDir, "*.idx"); if (File.Exists("hzd_fileList.csv")) File.Delete("hzd_fileList.csv"); File.WriteAllText("hzd_fileList.csv", "container,filePath\n"); foreach (string idxFile in idxFiles) { Console.WriteLine(idxFile); string[] files = GetAllFilesFromIdx(idxFile); File.AppendAllLines("hzd_fileList.csv", files); } Console.Read(); } static string[] GetAllFilesFromIdx(string idxFile) { string idxName = Path.GetFileNameWithoutExtension(idxFile); List<string> files = new List<string>(); using (BinaryReader idxReader = new BinaryReader(File.OpenRead(idxFile))) { idxReader.BaseStream.Seek(4, SeekOrigin.Begin); // Skip header int fileCount = idxReader.ReadInt32(); for (int i = 0; i < fileCount; i++) { int fileNameLength = idxReader.ReadInt32(); string fileName = Helper.ByteArrayToString(idxReader.ReadBytes(fileNameLength)); idxReader.BaseStream.Seek(32, SeekOrigin.Current); // Skip other data to next entry files.Add($"{idxName},{fileName}"); } } return files.ToArray(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HZDPackTool { class Helper { public static string ByteArrayToString(byte[] array) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); return encoding.GetString(array); } } }<file_sep># HZDPackTool WIP tool for (un)packing Horizon: Zero Dawn PC files.
102a09f3fa5e76542b09d6538d402722179b2d4d
[ "Markdown", "C#" ]
3
C#
Hengle/HZDPackTool
e7052dcd7986c9b5b686898c3e74aaebbf79fc00
109526753c79e5b20b12f56a9dcfd20832c9a25d
refs/heads/main
<file_sep>import os import numpy as np import scipy.io as sio from typing import Tuple from splearn.data.pytorch_dataset import PyTorchDataset class OPENBMI(PyTorchDataset): """ EEG dataset and OpenBMI toolbox for three BCI paradigms: an investigation into BCI illiteracy. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. https://academic.oup.com/gigascience/article/8/5/giz002/5304369 Target frequencies: 5.45, 6.67, 8.57, 12 Hz Sampling rate: 1000 Hz """ def __init__(self, root: str, subject_id: int, session: int, verbose: bool = False) -> None: self.root = root self.sampling_rate = 1000 self.data, self.targets, self.channel_names = _load_data( self.root, subject_id, session, verbose) self.stimulus_frequencies = np.array([12.0,8.57,6.67,5.45]) self.targets_frequencies = self.stimulus_frequencies[self.targets] def __getitem__(self, n: int) -> Tuple[np.ndarray, int]: return (self.data[n], self.targets[n]) def __len__(self) -> int: return len(self.data) def _load_data(root, subject_id, session, verbose): path = os.path.join(root, 'session'+str(session), 's'+str(subject_id)+'/EEG_SSVEP.mat') data_mat = sio.loadmat(path) objects_in_mat = [] for i in data_mat['EEG_SSVEP_train'][0][0]: objects_in_mat.append(i) # data data = objects_in_mat[0][:, :, :].copy() data = np.transpose(data, (1, 2, 0)) data = data.astype(np.float32) # label targets = [] for i in range(data.shape[0]): targets.append([objects_in_mat[2][0][i], 0, objects_in_mat[4][0][i]]) targets = np.array(targets) targets = targets[:, 2] targets = targets-1 # channel channel_names = [v[0] for v in objects_in_mat[8][0]] if verbose: print('Load path:', path) print('Objects in .mat', len(objects_in_mat), data_mat['EEG_SSVEP_train'].dtype.descr) print() print('Data shape', data.shape) print('Targets shape', targets.shape) return data, targets, channel_names <file_sep># -*- coding: utf-8 -*- """Task-related component analysis for frequency classification. Code adapt from https://github.com/nbara/python-meegkit Authors: <NAME> <<EMAIL>> <NAME> <<EMAIL>> """ import numpy as np import scipy.linalg as linalg from scipy.signal import filtfilt, cheb1ord, cheby1 from ..classes.classifier import Classifier class TRCA(Classifier): """Task-Related Component Analysis (TRCA). Args: sampling_rate : float Sampling rate. filterbank : list[[2-tuple, 2-tuple]] Filterbank frequencies. Each list element is itself a list of passband `Wp` and stopband `Ws` edges frequencies `[Wp, Ws]`. For example, this creates 3 bands, starting at 6, 14, and 22 hz respectively:: [[(6, 90), (4, 100)], [(14, 90), (10, 100)], [(22, 90), (16, 100)]] See :func:`scipy.signal.cheb1ord()` for more information on how to specify the `Wp` and `Ws`. ensemble : bool If True, perform the ensemble TRCA analysis (default=False). References: [1] <NAME>, <NAME>, <NAME>, Y. -T. Wang, <NAME>, and <NAME>, "Enhancing detection of SSVEPs for a high-speed brain speller using task-related component analysis", IEEE Trans. Biomed. Eng, 65(1):104-112, 2018. [2] <NAME>., <NAME>., <NAME>., & <NAME>. (2010, October). Common spatial pattern revisited by Riemannian geometry. In 2010 IEEE International Workshop on Multimedia Signal Processing (pp. 472-476). IEEE. """ def __init__(self, sampling_rate, filterbank=None, ensemble=False): self.sampling_rate = sampling_rate self.ensemble = ensemble self.filterbank = filterbank if self.filterbank is None: self.filterbank = [[(6, 90), (4, 100)], # passband, stopband freqs [(Wp), (Ws)] [(14, 90), (10, 100)], [(22, 90), (16, 100)], [(30, 90), (24, 100)], [(38, 90), (32, 100)], [(46, 90), (40, 100)], [(54, 90), (48, 100)]] self.n_bands = len(self.filterbank) self.coef_ = None self.can_train = True def fit(self, X, y): """Training stage of the TRCA-based SSVEP detection. Args: X : ndarray, shape (trial, channels, samples) Training EEG data. Y : ndarray, shape (trial) True label corresponding to each trial of the data array. """ X = np.transpose(X, (2,1,0)) n_samples, n_chans, _ = X.shape classes = np.unique(y) trains = np.zeros((len(classes), self.n_bands, n_samples, n_chans)) W = np.zeros((self.n_bands, len(classes), n_chans)) for class_i in classes: # Select data with a specific label eeg_tmp = X[..., y == class_i] for fb_i in range(self.n_bands): # Filter the signal with fb_i eeg_tmp = self._bandpass(eeg_tmp, self.sampling_rate, Wp=self.filterbank[fb_i][0], Ws=self.filterbank[fb_i][1]) if (eeg_tmp.ndim == 3): # Compute mean of the signal across trials trains[class_i, fb_i] = np.mean(eeg_tmp, -1) else: trains[class_i, fb_i] = eeg_tmp # Find the spatial filter for the corresponding filtered signal and label w_best = self._trca(eeg_tmp) W[fb_i, class_i, :] = w_best # Store the spatial filter self.trains = trains self.coef_ = W self.classes = classes def predict(self, X): """Test phase of the TRCA-based SSVEP detection. Args: X : ndarray, shape (trial, channels, samples) Test data. Returns: pred: np.array, shape (trials) The target estimated by the method. """ X = np.transpose(X, (2,1,0)) if self.coef_ is None: raise RuntimeError('TRCA is not fitted') # Alpha coefficients for the fusion of filterbank analysis # fb_coefs = [(x + 1)**(-1.25) + 0.25 for x in range(self.n_bands)] fb_coefs = np.arange(1, self.n_bands+1)**(-1.25) + 0.25 _, _, n_trials = X.shape r = np.zeros((self.n_bands, len(self.classes))) pred = np.zeros((n_trials), 'int') # To store predictions for trial in range(n_trials): test_tmp = X[..., trial] # pick a trial to be analysed for fb_i in range(self.n_bands): # filterbank on testdata testdata = self._bandpass(test_tmp, self.sampling_rate, Wp=self.filterbank[fb_i][0], Ws=self.filterbank[fb_i][1]) for class_i in self.classes: # Retrieve reference signal for class i # (shape: n_chans, n_samples) traindata = np.squeeze(self.trains[class_i, fb_i]) if self.ensemble: # shape = (n_chans, n_classes) w = np.squeeze(self.coef_[fb_i]).T else: # shape = (n_chans) w = np.squeeze(self.coef_[fb_i, class_i]) # Compute 2D correlation of spatially filtered test data with ref r_tmp = np.corrcoef((testdata @ w).flatten(), (traindata @ w).flatten()) r[fb_i, class_i] = r_tmp[0, 1] rho = np.dot(fb_coefs, r) # fusion for the filterbank analysis tau = np.argmax(rho) # retrieving index of the max pred[trial] = int(tau) return pred def _trca(self, X): """Task-related component analysis. This function implements the method described in [1]_. Parameters ---------- X : array, shape=(n_samples, n_chans[, n_trials]) Training data. Returns ------- W : array, shape=(n_chans,) Weight coefficients for electrodes which can be used as a spatial filter. References ---------- .. [1] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, "Enhancing detection of SSVEPs for a high-speed brain speller using task-related component analysis", IEEE Trans. Biomed. Eng, 65(1):104-112, 2018. """ n_samples, n_chans, n_trials = X.shape # 1. Compute empirical covariance of all data (to be bounded) # ------------------------------------------------------------------------- # Concatenate all the trials to have all the data as a sequence UX = np.zeros((n_chans, n_samples * n_trials)) for trial in range(n_trials): UX[:, trial * n_samples:(trial + 1) * n_samples] = X[..., trial].T # Mean centering UX -= np.mean(UX, 1)[:, None] # Covariance Q = UX @ UX.T # 2. Compute average empirical covariance between all pairs of trials # ------------------------------------------------------------------------- S = np.zeros((n_chans, n_chans)) for trial_i in range(n_trials - 1): x1 = np.squeeze(X[..., trial_i]) # Mean centering for the selected trial x1 -= np.mean(x1, 0) # Select a second trial that is different for trial_j in range(trial_i + 1, n_trials): x2 = np.squeeze(X[..., trial_j]) # Mean centering for the selected trial x2 -= np.mean(x2, 0) # Compute empirical covariance between the two selected trials and # sum it S = S + x1.T @ x2 + x2.T @ x1 # 3. Compute eigenvalues and vectors # ------------------------------------------------------------------------- lambdas, W = linalg.eig(S, Q, left=True, right=False) # Select the eigenvector corresponding to the biggest eigenvalue W_best = W[:, np.argmax(lambdas)] return W_best def _bandpass(self, eeg, sampling_rate, Wp, Ws): """Filter bank design for decomposing EEG data into sub-band components. Parameters ---------- eeg : np.array, shape=(n_samples, n_chans[, n_trials]) Training data. sampling_rate : int Sampling frequency of the data. Wp : 2-tuple Passband for Chebyshev filter. Ws : 2-tuple Stopband for Chebyshev filter. Returns ------- y: np.array, shape=(n_trials, n_chans, n_samples) Sub-band components decomposed by a filter bank. See Also -------- scipy.signal.cheb1ord : Chebyshev type I filter order selection. """ # Chebyshev type I filter order selection. N, Wn = cheb1ord(Wp, Ws, 3, 40, fs=sampling_rate) # Chebyshev type I filter design B, A = cheby1(N, 0.5, Wn, btype="bandpass", fs=sampling_rate) # the arguments 'axis=0, padtype='odd', padlen=3*(max(len(B),len(A))-1)' # correspond to Matlab filtfilt : https://dsp.stackexchange.com/a/47945 y = filtfilt(B, A, eeg, axis=0, padtype='odd', padlen=3 * (max(len(B), len(A)) - 1)) return y ######## # """Task-related component analysis for frequency classification. # """ # import numpy as np # from scipy.signal import cheb1ord, cheby1, filtfilt # from scipy.sparse.linalg import eigs # from ..classes.classifier import Classifier # class TRCA(Classifier): # r""" # Task-related component analysis for frequency classification. # Args: # sampling_rate: int # Sampling frequency # num_filterbanks : int, default: 5 # Number of filterbanks # ensemble : boolean, default: True # Use ensemble # Reference: # - <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, “Enhancing detection of SSVEPs for a high-speed brain speller using task-related component analysis”, IEEE Trans. Biomed. Eng, 65(1): 104-112, 2018. # - <NAME>, <NAME>, <NAME>, <NAME> and <NAME>, “Filter bank canonical correlation analysis for implementing a high-speed SSVEP-based brain-computer interface”, J. Neural Eng., 12: 046008, 2015. # - https://github.com/okbalefthanded/BCI-Baseline # - https://github.com/nbara/python-meegkit # - https://github.com/mnakanishi/TRCA-SSVEP # """ # def __init__(self, sampling_rate, num_filterbanks=5, ensemble=True): # self.sampling_rate = sampling_rate # self.num_filterbanks = num_filterbanks # self.ensemble = ensemble # self.trains = [] # self.w = [] # self.num_targs = 0 # self.can_train = True # def fit(self, X, Y): # r""" # Construction of the spatial filter. # Args: # X : ndarray, shape (trial, channels, samples) # 3-dim signal data by trial # Y : ndarray, shape (trial) # Target labels, targets are int, starts from 0 # """ # epochs, channels, samples = X.shape # targets_count = len(np.unique(Y)) # idx = np.argsort(Y) # X = X[idx, :, :] # if isinstance(epochs/targets_count, int): # X = X.reshape((epochs/targets_count, targets_count, # channels, samples), order='F') # else: # tr = np.floor(epochs/targets_count).astype(int) # X = X[0:tr*targets_count, :, # :].reshape((tr, targets_count, channels, samples), order='F') # X = X.transpose((1, 2, 3, 0)) # num_targs, num_chans, num_smpls, _ = X.shape # self.num_targs = num_targs # self.trains = np.zeros((num_targs, self.num_filterbanks, num_chans, num_smpls)) # self.w = np.zeros((self.num_filterbanks, num_targs, num_chans)) # for targ_i in range(num_targs): # eeg_tmp = X[targ_i, :, :, :] # for fb_i in range(self.num_filterbanks): # eeg_tmp = self._filterbank(eeg_tmp, fb_i) # self.trains[targ_i, fb_i, :, :] = np.mean(eeg_tmp, axis=-1) # w_tmp = self._trca(eeg_tmp) # self.w[fb_i, targ_i, :] = w_tmp[:, 0] # def predict(self, X): # r""" # Predict the label for each trial. # Args: # X : ndarray, shape (trial, channels, samples) # 3-dim signal data by trial # Returns: # results : array # Predicted targets # """ # epochs = X.shape[0] # fb_coefs = np.arange(1, self.num_filterbanks+1)**(-1.25) + 0.25 # r = np.zeros((self.num_filterbanks, self.num_targs)) # results = [] # for trial_i in range(epochs): # test_tmp = X[trial_i, :, :] # for fb_i in range(self.num_filterbanks): # testdata = self._filterbank(test_tmp, fb_i) # for class_i in range(self.num_targs): # traindata = self.trains[class_i, fb_i, :, :] # if self.ensemble: # w = self.w[fb_i, :, :].T # # Follows corrcoef MATLAB function implementation # r_tmp = np.corrcoef(np.matmul(testdata.T, w).flatten(), np.matmul(traindata.T, w).flatten()) # else: # w = self.w[fb_i, class_i, :] # r_tmp = np.corrcoef(np.matmul(testdata.T, w), np.matmul(traindata.T, w)) # r[fb_i, class_i] = r_tmp[0, 1] # rho = np.matmul(fb_coefs, r) # tau = np.argmax(rho) # results.append(tau) # results = np.array(results) # return results # def _trca(self, eeg): # num_chans, num_smpls, num_trials = eeg.shape # S = np.zeros((num_chans, num_chans)) # for trial_i in range(num_trials-1): # x1 = eeg[:, :, trial_i] # x1 = x1 - np.mean(x1, axis=1)[:, None] # for trial_j in range(trial_i+1, num_trials): # x2 = eeg[:, :, trial_j] # x2 = x2 - np.mean(x2, axis=1)[:, None] # S = S + np.matmul(x1, x2.T) + np.matmul(x2, x1.T) # UX = eeg.reshape((num_chans, num_smpls*num_trials)) # UX = UX - np.mean(UX, axis=1)[:, None] # Q = np.matmul(UX, UX.T) # _, W = eigs(S, M=Q) # #_, W = np.linalg.eig(np.dot(np.linalg.inv(Q), S)) # return np.real(W) # def _filterbank(self, eeg, idx_fbi): # r""" # We use the filterbank specification described in <NAME>, <NAME>, <NAME>, <NAME> and <NAME>, “Filter bank canonical correlation analysis for implementing a high-speed SSVEP-based brain-computer interface”, J. Neural Eng., 12: 046008, 2015. # """ # if eeg.ndim == 2: # num_chans = eeg.shape[0] # num_trials = 1 # else: # num_chans, _, num_trials = eeg.shape # fs = self.sampling_rate / 2 # passband = [6, 14, 22, 30, 38, 46, 54, 62, 70, 78] # stopband = [4, 10, 16, 24, 32, 40, 48, 56, 64, 72] # Wp = [passband[idx_fbi]/fs, 90/fs] # Ws = [stopband[idx_fbi]/fs, 100/fs] # [N, Wn] = cheb1ord(Wp, Ws, 3, 40) # [B, A] = cheby1(N, 0.5, Wn, 'bp') # yy = np.zeros_like(eeg) # if num_trials == 1: # yy = filtfilt(B, A, eeg, axis=1) # else: # for trial_i in range(num_trials): # for ch_i in range(num_chans): # yy[ch_i, :, trial_i] = filtfilt(B, A, eeg[ch_i, :, trial_i], padtype='odd', padlen=3*(max(len(B),len(A))-1)) # return yy # if __name__ == "__main__": # from splearn.cross_decomposition.trca import TRCA # from splearn.data.sample_ssvep import SampleSSVEPData # from splearn.cross_validate.leave_one_out import leave_one_block_evaluation # data = SampleSSVEPData() # eeg = data.get_data() # labels = data.get_targets() # print("eeg.shape:", eeg.shape) # print("labels.shape:", labels.shape) # trca_classifier = TRCA(sampling_rate=data.sampling_rate) # test_accuracies = leave_one_block_evaluation(trca_classifier, eeg, labels) <file_sep># -*- coding: utf-8 -*- """A 40-target SSVEP dataset recorded from a single subject. """ import numpy as np from scipy.io import loadmat import os class SampleSSVEPData(): r""" A 40-target SSVEP dataset recorded from a single subject. Data description: Original Data shape : (40, 9, 1250, 6) [# of targets, # of channels, # of sampling points, # of blocks] Stimulus frequencies : 8.0 - 15.8 Hz with an interval of 0.2 Hz Stimulus phases : 0pi, 0.5pi, 1.0pi, and 1.5pi Number of channels : 9 (1: Pz, 2: PO5,3: PO3, 4: POz, 5: PO4, 6: PO6, 7: O1, 8: Oz, and 9: O2) Number of recording blocks : 6 Length of an epoch : 5 seconds Sampling rate : 250 Hz Args: path: str, default: None Path to ssvepdata.mat file Usage: >>> from splearn.cross_decomposition.trca import TRCA >>> from splearn.data.sample_ssvep import SampleSSVEPData >>> >>> data = SampleSSVEPData() >>> eeg = data.get_data() >>> labels = data.get_targets() >>> print("eeg.shape:", eeg.shape) >>> print("labels.shape:", labels.shape) Reference: https://www.pnas.org/content/early/2015/10/14/1508080112.abstract """ def __init__(self, path=None): if path is None: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sample") # Get EEG data data = loadmat(os.path.join(path,"ssvep.mat")) data = data["eeg"] data = data.transpose([3,0,1,2]) self.data = data # Prepare targets n_blocks, n_targets, n_channels, n_samples = self.data.shape targets = np.tile(np.arange(0, n_targets+0), (1, n_blocks)) targets = targets.reshape((n_blocks, n_targets)) self.targets = targets # Prepare targets frequencies self.stimulus_frequencies = np.array([8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,8.2,9.2,10.2,11.2,12.2,13.2,14.2,15.2,8.4,9.4,10.4,11.4,12.4,13.4,14.4,15.4,8.6,9.6,10.6,11.6,12.6,13.6,14.6,15.6,8.8,9.8,10.8,11.8,12.8,13.8,14.8,15.8]) targets_frequencies = np.tile(self.stimulus_frequencies, (1, n_blocks)) targets_frequencies = targets_frequencies.reshape((n_blocks, n_targets)) self.targets_frequencies = targets_frequencies self.sampling_rate = 250 self.channels = ["Pz", "PO5","PO3", "POz", "PO4", "PO6", "O1", "Oz", "O2"] def get_data(self): r""" Data shape: (6, 40, 9, 1250) [# of blocks, # of targets, # of channels, # of sampling points] """ return self.data def get_targets(self): r""" Targets index from 0 to 39. Shape: (6, 40) [# of blocks, # of targets] """ return self.targets def get_stimulus_frequencies(self): r""" A list of frequencies of each stimulus: [8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,8.2,9.2,10.2,11.2,12.2,13.2,14.2,15.2,8.4,9.4,10.4,11.4,12.4,13.4,14.4,15.4,8.6,9.6,10.6,11.6,12.6,13.6,14.6,15.6,8.8,9.8,10.8,11.8,12.8,13.8,14.8,15.8] """ return self.stimulus_frequencies def get_targets_frequencies(self): r""" Targets by frequencies, range between 8.0 Hz to 15.8 Hz. Shape: (6, 40) [# of blocks, # of targets] """ return self.targets_frequencies if __name__ == "__main__": from splearn.data.sample_ssvep import SampleSSVEPData data = SampleSSVEPData() eeg = data.get_data() labels = data.get_targets() print("eeg.shape:", eeg.shape) print("labels.shape:", labels.shape) <file_sep># -*- coding: utf-8 -*- """Generate signals """ import numpy as np import matplotlib.pyplot as plt def generate_signal(length_seconds, sampling_rate, frequencies, func="sin", add_noise=0, plot=False, include_amplitude=False, normalize=False): r""" Generate a n-D array, `length_seconds` seconds signal at `sampling_rate` sampling rate. Args: length_seconds : float Duration of signal in seconds (i.e. `10` for a 10-seconds signal, `3.5` for a 3.5-seconds signal) sampling_rate : int The sampling rate of the signal. frequencies : 1 or 2 dimension python list a floats An array of floats, where each float is the desired frequencies to generate (i.e. [5, 12, 15] to generate a signal containing a 5-Hz, 12-Hz and 15-Hz) 2 dimension python list, i.e. [[5, 12, 15],[1]], to generate a signal with 2 channels, where the second channel containing 1-Hz signal func : string, optional, default: sin The periodic function to generate signal, either `sin` or `cos` add_noise : float, optional, default: 0 Add random noise to the signal, where `0` has no noise plot : boolean, optional, default: False Plot the generated signal include_amplitude : boolean, optional, default: False Amplitude for each frequency is included in the `frequencies` param. See Usage. normalize : boolean, optional, default: False Normalize signal between 0 to 1 Returns: signal : n-d ndarray Generated signal, a numpy array of length `sampling_rate*length_seconds` Usage: >>> # 1 channel, contains 2hz >>> s = generate_signal( >>> length_seconds=4, >>> sampling_rate=100, >>> frequencies=[2], >>> plot=True >>> ) >>> >>> # 1 channel, 2 frequencies, 1hz and 2hz, with noise >>> s = generate_signal( >>> length_seconds=4, >>> sampling_rate=100, >>> frequencies=[1,2], >>> func="cos", >>> add_noise=0.5, >>> plot=True >>> ) >>> >>> # 3 channels >>> s = generate_signal( >>> length_seconds=3.5, >>> sampling_rate=100, >>> frequencies=[[1,2],[1],[2]], >>> plot=True >>> ) >>> >>> # single channel containing 1hz and 2hz frequencies, where 1hz's amplitude is 1, and 2hz's amplitude is 4 >>> s = generate_signal( >>> length_seconds=3.5, >>> sampling_rate=100, >>> frequencies=[[6,1],[2,4]], >>> plot=True, >>> include_amplitude=True, >>> ) >>> >>> # 2-dim channels. First channel contains 1hz (1 amplitude), and 2hz (4 amplitude). Second channel contains 4hz (10 amplitude), 8hz (1 amplitude) and 10hz (4 amplitude). >>> s = generate_signal( >>> length_seconds=3.5, >>> sampling_rate=100, >>> frequencies=[ [[1,1],[2,4]], [[4,10],[8,1],[10,4]] ], >>> plot=True, >>> include_amplitude=True, >>> ) """ frequencies = np.array(frequencies, dtype=object) assert len(frequencies.shape) == 1 or len(frequencies.shape) == 2 or len(frequencies.shape) == 3, "frequencies must be 1d, 2d ore 3d python list" expanded = False if isinstance(frequencies[0], int): frequencies = np.expand_dims(frequencies, axis=0) expanded = True if not include_amplitude: frequencies = np.expand_dims(frequencies, axis=-1) if len(frequencies.shape) == 2 and include_amplitude: frequencies = np.expand_dims(frequencies, axis=0) expanded = True sampling_rate = int(sampling_rate) npnts = int(sampling_rate*length_seconds) # number of time samples time = np.arange(0, npnts)/sampling_rate signal = np.zeros((frequencies.shape[0],npnts)) for channel in range(0,frequencies.shape[0]): for this_freq in frequencies[channel]: freq_signal = None if func == "cos": freq_signal = np.cos(2*np.pi*this_freq[0]*time) else: freq_signal = np.sin(2*np.pi*this_freq[0]*time) if include_amplitude: freq_signal = freq_signal * this_freq[1] signal[channel] = signal[channel] + freq_signal if normalize: # normalize max = np.repeat(signal[channel].max()[np.newaxis], npnts) min = np.repeat(signal[channel].min()[np.newaxis], npnts) signal[channel] = (2*(signal[channel]-min)/(max-min))-1 if add_noise: noise = np.random.uniform(low=0, high=add_noise, size=(frequencies.shape[0],npnts)) signal = signal + noise if plot: plt.plot(time, signal.T) plt.title('Signal with sampling rate of '+str(sampling_rate)+', lasting '+str(length_seconds)+'-seconds') plt.xlabel('Time (sec.)') plt.ylabel('Amplitude') plt.show() if expanded: signal = signal[0] return signal if __name__ == "__main__": # 1 channel, contains 2hz s = generate_signal( length_seconds=4, sampling_rate=100, frequencies=[2], plot=True ) # 1 channel, 2 frequencies, 1hz and 2hz s = generate_signal( length_seconds=4, sampling_rate=100, frequencies=[1,2], func="cos", add_noise=0.5, plot=True ) # 3 channels s = generate_signal( length_seconds=3.5, sampling_rate=100, frequencies=[[1,2],[1],[2]], plot=True ) # single channel containing 1hz and 2hz frequencies, where 1hz's amplitude is 1, and 2hz's amplitude is 4 s = generate_signal( length_seconds=3.5, sampling_rate=100, frequencies=[[6,1],[2,4]], plot=True, include_amplitude=True, ) # 2-dim channels. First channel contains 1hz (1 amplitude), and 2hz (4 amplitude). Second channel contains 4hz (10 amplitude), 8hz (1 amplitude) and 10hz (4 amplitude). s = generate_signal( length_seconds=3.5, sampling_rate=100, frequencies=[ [[1,1],[2,4]], [[4,10],[8,1],[10,4]] ], plot=True, include_amplitude=True, ) <file_sep># -*- coding: utf-8 -*- """Canonical Correlation Analysis (CCA). http://en.wikipedia.org/wiki/Canonical_correlation """ import numpy as np from sklearn.metrics import confusion_matrix import functools from ..classes.classifier import Classifier from .reference_frequencies import generate_reference_signals class CCA(Classifier): r""" Calculates the canonical correlation coefficient and corresponding weights which maximize a correlation coefficient between linear combinations of the two specified multivariable signals. Args: sampling_rate: int Sampling frequency target_frequencies : array Frequencies for SSVEP classification signal_size : int Window/segment length in time samples sampling_rate : int Sampling frequency num_harmonics : int, default: 2 Generate till n-th harmonics """ def __init__(self, sampling_rate, target_frequencies, signal_size, num_harmonics=2): self.sampling_rate = sampling_rate self.reference_frequencies = generate_reference_signals( target_frequencies, size=signal_size, sampling_rate=sampling_rate, num_harmonics=num_harmonics ) self.can_train = False def predict(self, X): r""" Predict the label for each trial. Args: X : ndarray, shape (trial, channels, samples) 3-dim signal data by trial Returns: results : array Predicted targets """ predicted_class, _, _, _, _ = perform_cca(X, self.reference_frequencies, labels=None) return predicted_class def calculate_cca(dat_x, dat_y, time_axis=-2): r""" Calculate the Canonical Correlation Analysis (CCA). This method calculates the canonical correlation coefficient and corresponding weights which maximize a correlation coefficient between linear combinations of the two specified multivariable signals. Args: dat_x : continuous Data object these data should have the same length on the time axis. dat_y : continuous Data object these data should have the same length on the time axis. time_axis : int, optional the index of the time axis in ``dat_x`` and ``dat_y``. Returns: rho : float the canonical correlation coefficient. w_x, w_y : 1d array the weights for mapping from the specified multivariable signals to canonical variables. Raises: AssertionError : If: * ``dat_x`` and ``dat_y`` is not continuous Data object * the length of ``dat_x`` and ``dat_y`` is different on the ``time_axis`` Dependencies: functools : functools package np : numpy package Reference: https://github.com/venthur/wyrm/blob/master/wyrm/processing.py http://en.wikipedia.org/wiki/Canonical_correlation """ assert (len(dat_x.data.shape) == len(dat_y.data.shape) == 2 and dat_x.data.shape[time_axis] == dat_y.data.shape[time_axis]) if time_axis == 0 or time_axis == -2: x = dat_x.copy() y = dat_y.copy() else: x = dat_x.T.copy() y = dat_y.T.copy() # calculate covariances and it's inverses x -= x.mean(axis=0) y -= y.mean(axis=0) n = x.shape[0] c_xx = np.dot(x.T, x) / n c_yy = np.dot(y.T, y) / n c_xy = np.dot(x.T, y) / n c_yx = np.dot(y.T, x) / n ic_xx = np.linalg.pinv(c_xx) ic_yy = np.linalg.pinv(c_yy) # calculate w_x w, v = np.linalg.eig(functools.reduce(np.dot, [ic_xx, c_xy, ic_yy, c_yx])) w_x = v[:, np.argmax(w)].real w_x = w_x / np.sqrt(functools.reduce(np.dot, [w_x.T, c_xx, w_x])) # calculate w_y w, v = np.linalg.eig(functools.reduce(np.dot, [ic_yy, c_yx, ic_xx, c_xy])) w_y = v[:, np.argmax(w)].real w_y = w_y / np.sqrt(functools.reduce(np.dot, [w_y.T, c_yy, w_y])) # calculate rho rho = abs(functools.reduce(np.dot, [w_x.T, c_xy, w_y])) return rho, w_x, w_y def find_correlation_cca(signal, reference_signals): r""" Perform canonical correlation analysis (CCA) Args: signal : ndarray, shape (channel,time) Input signal in time domain reference_signals : ndarray, shape (len(flick_freq),2*num_harmonics,time) Required sinusoidal reference templates corresponding to the flicker frequency for SSVEP classification Returns: result : array, size: (reference_signals.shape[0]) Probability for each reference signals wx : array, size: (reference_signals.shape[0],signal.shape[0]) Wx obtain from CCA wy : array, size: (reference_signals.shape[0],signal.shape[0]) Wy obtain from CCA Dependencies: np : numpy package calculate_cca : function """ result = np.zeros(reference_signals.shape[0]) wx = np.zeros((reference_signals.shape[0],signal.shape[0])) wy = np.zeros((reference_signals.shape[0],reference_signals.shape[1])) for freq_idx in range(0, reference_signals.shape[0]): dat_y = np.squeeze(reference_signals[freq_idx, :, :]).T rho, w_x, w_y = calculate_cca(signal.T, dat_y) result[freq_idx] = rho wx[freq_idx,:] = w_x wy[freq_idx,:] = w_y return result, wx, wy def perform_cca(signal, reference_frequencies, labels=None): r""" Perform canonical correlation analysis (CCA) Args: signal : ndarray, shape (trial,channel,time) or (trial,channel,segment,time) Input signal in time domain reference_frequencies : ndarray, shape (len(flick_freq),2*num_harmonics,time) Required sinusoidal reference templates corresponding to the flicker frequency for SSVEP classification labels : ndarray shape (classes,) True labels of `signal`. Index of the classes must be match the sequence of `reference_frequencies` Returns: predicted_class : ndarray, size: (classes,) Predicted classes according to reference_frequencies accuracy : double If `labels` are given, `accuracy` denote classification accuracy predicted_probabilities : ndarray, size: (classes,) Predicted probabilities for each target wx : array, size: (reference_signals.shape[0],signal.shape[0]) Wx obtain from CCA wy : array, size: (reference_signals.shape[0],signal.shape[0]) Wy obtain from CCA Dependencies: confusion_matrix : sklearn.metrics.confusion_matrix find_correlation_cca : function """ assert (len(signal.shape) == 3 or len(signal.shape) == 4), "signal shape must be 3 or 4 dimension" actual_class = [] predicted_class = [] predicted_probabilities = [] accuracy = None Wx = [] Wy = [] for trial in range(0, signal.shape[0]): if len(signal.shape) == 3: if labels is not None: actual_class.append(labels[trial]) tmp_signal = signal[trial, :, :] result, wx, wy = find_correlation_cca(tmp_signal, reference_frequencies) predicted_class.append(np.argmax(result)) result = np.around(result, decimals=3, out=None) predicted_probabilities.append(result) Wx.append(wx) Wy.append(wy) if len(signal.shape) == 4: for segment in range(0, signal.shape[2]): if labels is not None: actual_class.append(labels[trial]) tmp_signal = signal[trial, :, segment, :] result, wx, wy = find_correlation_cca(tmp_signal, reference_frequencies) predicted_class.append(np.argmax(result)) result = np.around(result, decimals=3, out=None) predicted_probabilities.append(result) Wx.append(wx) Wy.append(wy) actual_class = np.array(actual_class) predicted_class = np.array(predicted_class) if labels is not None: # creating a confusion matrix of true versus predicted classification labels c_mat = confusion_matrix(actual_class, predicted_class) # computing the accuracy from the confusion matrix accuracy = np.divide(np.trace(c_mat), np.sum(np.sum(c_mat))) Wx = np.array(Wx) Wy = np.array(Wy) return predicted_class, accuracy, predicted_probabilities, Wx, Wy <file_sep>from .channels import pick_channels from .butterworth import butter_bandpass_filter from .notch import notch_filter<file_sep>from torch.utils.data import Dataset import numpy as np class PyTorchDataset(Dataset): def __init__(self, data, targets): self.data = data self.data = self.data.astype(np.float32) self.targets = targets self.channel_names = None def __getitem__(self, index): return self.data[index], self.targets[index] def __len__(self): return len(self.data) def set_data_targets(self, data: [] = None, targets: [] = None) -> None: if data is not None: self.data = data.copy() if targets is not None: self.targets = targets.copy() self.targets = self.targets.astype(int) def set_channel_names(self,channel_names): self.channel_names = channel_names def get_data(self): r""" Data shape: (6, 40, 9, 1250) [# of blocks, # of targets, # of channels, # of sampling points] """ return self.data def get_targets(self): r""" Targets index from 0 to 39. Shape: (6, 40) [# of blocks, # of targets] """ return self.targets def get_stimulus_frequencies(self): r""" A list of frequencies of each stimulus: [8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,8.2,9.2,10.2,11.2,12.2,13.2,14.2,15.2,8.4,9.4,10.4,11.4,12.4,13.4,14.4,15.4,8.6,9.6,10.6,11.6,12.6,13.6,14.6,15.6,8.8,9.8,10.8,11.8,12.8,13.8,14.8,15.8] """ return self.stimulus_frequencies def get_targets_frequencies(self): r""" Targets by frequencies, range between 8.0 Hz to 15.8 Hz. Shape: (6, 40) [# of blocks, # of targets] """ return self.targets_frequencies <file_sep># -*- coding: utf-8 -*- """Generate sinusoidal signals for CCA. """ import numpy as np def get_reference_signals(target_frequencies, size, sampling_rate, num_harmonics=2): r""" Generating a single sinusoidal template for SSVEP classification Args: target_frequencies : array Frequencies for SSVEP classification size : int Window/segment length in time samples sampling_rate : int Sampling frequency num_harmonics : int, default: 2 Generate till n-th harmonics Returns: reference_signals : ndarray, shape (len(flick_freq),4,time) Reference frequency signals Example: Refer to `generate_reference_signals()` Dependencies: np : numpy package """ reference_signals = [] t = np.arange(0, (size/sampling_rate), step=1.0/sampling_rate) for i in range(1, num_harmonics+1): j = i*2 reference_signals.append(np.sin(np.pi*j*target_frequencies*t)) reference_signals.append(np.cos(np.pi*j*target_frequencies*t)) reference_signals = np.array(reference_signals) return reference_signals def generate_reference_signals(flick_freq, size, sampling_rate, num_harmonics=2): r""" Generating the required sinusoidal templates for SSVEP classification Args: flick_freq : array Frequencies for SSVEP classification size : int Window/segment length in time samples sampling_rate : int Sampling frequency num_harmonics : int Generate till n-th harmonics Returns: reference_signals : ndarray, shape (len(flick_freq),2*num_harmonics,time) Reference frequency signals Example: reference_frequencies = generate_reference_signals( [5,7.5,10,12], size=4000, sampling_rate=1000, num_harmonics=3) Dependencies: np : numpy package get_reference_frequencies : function """ reference_frequencies = [] for fr in range(0, len(flick_freq)): ref = get_reference_signals(flick_freq[fr], size, sampling_rate, num_harmonics) reference_frequencies.append(ref) reference_frequencies = np.array(reference_frequencies, dtype='float32') return reference_frequencies <file_sep>import numpy as np def pick_channels(data: np.ndarray, channel_names: [str], selected_channels: [str], verbose: bool = False) -> np.ndarray: picked_ch = pick_channels_mne(channel_names, selected_channels) data = data[:, picked_ch, :] if verbose: print('picking channels: channel_names', len(channel_names), channel_names) print('picked_ch', picked_ch) print() del picked_ch return data def pick_channels_mne(ch_names, include, exclude=[], ordered=False): """Pick channels by names. Returns the indices of ``ch_names`` in ``include`` but not in ``exclude``. Taken from https://github.com/mne-tools/mne-python/blob/master/mne/io/pick.py Parameters ---------- ch_names : list of str List of channels. include : list of str List of channels to include (if empty include all available). .. note:: This is to be treated as a set. The order of this list is not used or maintained in ``sel``. exclude : list of str List of channels to exclude (if empty do not exclude any channel). Defaults to []. ordered : bool If true (default False), treat ``include`` as an ordered list rather than a set, and any channels from ``include`` are missing in ``ch_names`` an error will be raised. .. versionadded:: 0.18 Returns ------- sel : array of int Indices of good channels. See Also -------- pick_channels_regexp, pick_types """ if len(np.unique(ch_names)) != len(ch_names): raise RuntimeError('ch_names is not a unique list, picking is unsafe') # _check_excludes_includes(include) # _check_excludes_includes(exclude) if not ordered: if not isinstance(include, set): include = set(include) if not isinstance(exclude, set): exclude = set(exclude) sel = [] for k, name in enumerate(ch_names): if (len(include) == 0 or name in include) and name not in exclude: sel.append(k) else: if not isinstance(include, list): include = list(include) if len(include) == 0: include = list(ch_names) if not isinstance(exclude, list): exclude = list(exclude) sel, missing = list(), list() for name in include: if name in ch_names: if name not in exclude: sel.append(ch_names.index(name)) else: missing.append(name) if len(missing): raise ValueError('Missing channels from ch_names required by ' 'include:\n%s' % (missing,)) return np.array(sel, int) <file_sep>from .trca import TRCA from .cca import CCA<file_sep># Python Signal Processing [![Awesome](https://awesome.re/badge.svg)](https://awesome.re) This repository contains tutorials on understanding and applying signal processing using NumPy and PyTorch. **splearn** is a package for signal processing and machine learning with Python. It is built on top of [NumPy](https://numpy.org) and [SciPy](https://www.scipy.org), to provide easy to use functions from common signal processing tasks to machine learning. ## Contents - [Tutorials](#tutorials) - [Getting Started](#getting-started) - [Disclaimer on Datasets](#disclaimer-on-datasets) --- ## Tutorials Signal processing can be daunting; we aim to bridge the gap for anyone who are new signal processings to get started, check out the [tutorials](https://github.com/jinglescode/python-signal-processing/tree/main/tutorials) to get started on signal processings. ### 1. Signal composition (time, sampling rate and frequency) In order to begin the signal processing adventure, we need to understand what we are dealing with. In the first tutorial, we will uncover what is a signal, and what it is made up of. We will look at how the sampling rate and frequency can affect a signal. We will also see what happens when we combine multiple signals of different frequencies. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Signal%20composition%20-%20time%2C%20sampling%20rate%20and%20frequency.ipynb) ### 2. Fourier Transform Now we know what are signals made of and we learned that combining multiple signals of various frequencies will jumbled up all the frequencies. In this tutorial, we will learn about Fourier Transform and how it can take a complex signal and decompose it to the frequencies that made it up. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Fourier%20Transform.ipynb) ### 3. Denoising with mean-smooth filter We know that signals can be noisy, and this tutorial will focus on removing these noise. We learn to apply the simplest filter to perform denoising, the running mean filter. We will also understand what are edge effects. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Denoising%20with%20mean-smooth%20filter.ipynb) ### 4. Denoising with Gaussian-smooth filter Next, we will look at a slight adaptation of the mean-smooth filter, the Gaussian smoothing filter. This tends to smooth the data to be a bit smoother compared to mean-smooth filter. This does not mean that one is better than the other, it depends on the specific applications. So, it is important to be aware of different filters type and how to use them. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Denoising%20with%20Gaussian-smooth%20filter.ipynb) ### 5. Canonical correlation analysis Canonical correlation analysis (CCA) is applied to analyze the frequency components of a signal. In this tutorials, we use CCA for feature extraction and classification. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Canonical%20Correlation%20Analysis.ipynb) ### 6. Task-related component analysis Task-related component analysis (TRCA) is a classification method originally for steady-state visual evoked potentials (SSVEPs) detection. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Task-Related%20Component%20Analysis.ipynb) --- ## Getting Started ### Installation Currently, this has not been released. Use `git clone`, and install the dependencies: ``` git clone https://github.com/jinglescode/python-signal-processing.git pip install -r requirements.txt ``` ### Dependencies See [requirements.txt](https://github.com/jinglescode/python-signal-processing/tree/main/requirements.txt). ### Usage Let's generate a 2D-signal, sampled at 100-Hz. Design and apply a 4th-order bandpass Butterworth filter with a cutoff frequency between 5-Hz and 20-Hz. ```python from splearn.data.generate import generate_signal from splearn.filter.butter import butter_bandpass signal_2d = generate_signal( length_seconds=4, sampling_rate=100, frequencies=[[4,7,11,17,40, 50],[1, 3]], plot=True ) signal_2d_filtered = butter_bandpass( signal=signal_2d, lowcut=5, highcut=20, sampling_rate=100, type='sos', order=4, plot=True, plot_xlim=[3,20] ) ``` --- ## Disclaimer on Datasets We do not host or distribute these datasets, vouch for their quality or fairness, or claim that you have license to use the dataset. It is your responsibility to determine whether you have permission to use the dataset under the dataset's license. If you're a dataset owner and wish to update any part of it (description, citation, etc.), or do not want your dataset to be included in this library, please get in touch through a GitHub issue. Thanks for your contribution to the ML community! <file_sep>import numpy as np from sklearn.metrics import accuracy_score def leave_one_block_evaluation(classifier, X, Y, block_seq_labels=None): r""" Estimate classification performance with a Leave-One-Block-Out cross-validation approach. Iteratively select a block for testing and use all other blocks for training. Args: X : ndarray, shape (blocks, targets, channels, samples) 4-dim signal data Y : ndarray, shape (blocks, targets) Targets are int, starts from 0 block_seq_labels : list A list of labels for each block Returns: test_accuracies : list Test accuracies by block Usage: >>> from splearn.cross_decomposition.trca import TRCA >>> from splearn.data.sample_ssvep import SampleSSVEPData >>> from splearn.cross_validate.leave_one_out import leave_one_block_evaluation >>> >>> data = SampleSSVEPData() >>> eeg = data.get_data() >>> labels = data.get_targets() >>> print("eeg.shape:", eeg.shape) >>> print("labels.shape:", labels.shape) >>> >>> trca_classifier = TRCA(sampling_rate=data.sampling_rate) >>> test_accuracies = leave_one_block_evaluation(trca_classifier, eeg, labels) """ test_accuracies = [] blocks, targets, channels, samples = X.shape for block_i in range(blocks): test_acc = block_evaluation(classifier, X, Y, block_i, block_seq_labels[block_i] if block_seq_labels is not None else None) test_accuracies.append(test_acc) print(f'Mean test accuracy: {np.array(test_accuracies).mean().round(3)*100}%') return test_accuracies def block_evaluation(classifier, X, Y, block_i, block_label=None): r""" Select a block for testing, use all other blocks for training. Args: X : ndarray, shape (blocks, targets, channels, samples) 4-dim signal data Y : ndarray, shape (blocks, targets) Targets are int, starts from 0 block_i: int Index of the selected block for testing block_label : str or int Labels for this block, for printing Returns: train_acc : float Train accuracy test_acc : float Test accuracy of the selected block """ blocks, targets, channels, samples = X.shape train_acc = 0 if classifier.can_train: x_train = np.delete(X, block_i, axis=0) x_train = x_train.reshape((blocks-1*targets, channels, samples)) y_train = np.delete(Y, block_i, axis=0) y_train = y_train.reshape((blocks-1*targets)) classifier.fit(x_train, y_train) # p1 = classifier.predict(x_train) # train_acc = accuracy_score(y_train, p1) x_test = X[block_i,:,:,:] y_test = Y[block_i] p2 = classifier.predict(x_test) test_acc = accuracy_score(y_test, p2) if block_label is None: block_label = 'Block:' + str(block_i+1) # if classifier.can_train: # print(f'{block_label} | Train acc: {train_acc*100:.2f}% | Test acc: {test_acc*100:.2f}%') # else: # print(f'{block_label} | Test acc: {test_acc*100:.2f}%') print(f'{block_label} | Test acc: {test_acc*100:.2f}%') return test_acc <file_sep># -*- coding: utf-8 -*- """Digital filter bandpass zero-phase implementation (filtfilt). Apply a digital filter forward and backward to a signal. """ import numpy as np import matplotlib.pyplot as plt from scipy.signal import butter, filtfilt, sosfiltfilt, freqz from splearn.fourier import fast_fourier_transform def butter_bandpass_filter(signal, lowcut, highcut, sampling_rate, order=4, verbose=False): r""" Digital filter bandpass zero-phase implementation (filtfilt) Apply a digital filter forward and backward to a signal Args: signal : ndarray, shape (trial,channel,time) Input signal by trials in time domain lowcut : int Lower bound filter highcut : int Upper bound filter sampling_rate : int Sampling frequency order : int, default: 4 Order of the filter verbose : boolean, default: False Print and plot details Returns: y : ndarray Filter signal """ sos = _butter_bandpass(lowcut, highcut, sampling_rate, order=order, output='sos') y = sosfiltfilt(sos, signal, axis=2) if verbose: tmp_x = signal[0, 0] tmp_y = y[0, 0] # time domain plt.plot(tmp_x, label='signal') plt.show() plt.plot(tmp_y, label='Filtered') plt.show() # freq domain lower_xlim = lowcut-10 if (lowcut-10) > 0 else 0 fast_fourier_transform( tmp_x, sampling_rate, plot=True, plot_xlim=[lower_xlim, highcut+20], plot_label='Signal') fast_fourier_transform( tmp_y, sampling_rate, plot=True, plot_xlim=[lower_xlim, highcut+20], plot_label='Filtered') plt.xlim([lower_xlim, highcut+20]) plt.ylim([0, 2]) plt.legend() plt.xlabel('Frequency (Hz)') plt.show() print('Input: Signal shape', signal.shape) print('Output: Signal shape', y.shape) return y def butter_bandpass_filter_signal_1d(signal, lowcut, highcut, sampling_rate, order=4, verbose=False): r""" Digital filter bandpass zero-phase implementation (filtfilt) Apply a digital filter forward and backward to a signal Args: signal : ndarray, shape (time,) Single input signal in time domain lowcut : int Lower bound filter highcut : int Upper bound filter sampling_rate : int Sampling frequency order : int, default: 4 Order of the filter verbose : boolean, default: False Print and plot details Returns: y : ndarray Filter signal """ b, a = _butter_bandpass(lowcut, highcut, sampling_rate, order) y = filtfilt(b, a, signal) if verbose: w, h = freqz(b, a) plt.plot((sampling_rate * 0.5 / np.pi) * w, abs(h), label="order = %d" % order) plt.plot([0, 0.5 * sampling_rate], [np.sqrt(0.5), np.sqrt(0.5)], '--', label='sqrt(0.5)') plt.xlabel('Frequency (Hz)') plt.ylabel('Gain') plt.grid(True) plt.legend(loc='best') low = max(0, lowcut-(sampling_rate/100)) high = highcut+(sampling_rate/100) plt.xlim([low, high]) plt.ylim([0, 1.2]) plt.title('Frequency response of filter - lowcut:' + str(lowcut)+', highcut:'+str(highcut)) plt.show() # TIME plt.plot(signal, label='Signal') plt.title('Signal') plt.show() plt.plot(y, label='Filtered') plt.title('Bandpass filtered') plt.show() # FREQ lower_xlim = lowcut-10 if (lowcut-10) > 0 else 0 fast_fourier_transform( signal, sampling_rate, plot=True, plot_xlim=[lower_xlim, highcut+20], plot_label='Signal') fast_fourier_transform( y, sampling_rate, plot=True, plot_xlim=[lower_xlim, highcut+20], plot_label='Filtered') plt.xlim([lower_xlim, highcut+20]) plt.ylim([0, 2]) plt.legend() plt.xlabel('Frequency (Hz)') plt.show() print('Input: Signal shape', signal.shape) print('Output: Signal shape', y.shape) return y def _butter_bandpass(lowcut, highcut, sampling_rate, order=4, output='ba'): r""" Create a Butterworth bandpass filter Design an Nth-order digital or analog Butterworth filter and return the filter coefficients. Args: lowcut : int Lower bound filter highcut : int Upper bound filter sampling_rate : int Sampling frequency order : int, default: 4 Order of the filter output : string, default: ba Type of output {‘ba’, ‘zpk’, ‘sos’} Returns: butter : ndarray Butterworth filter Dependencies: butter : scipy.signal.butter """ nyq = sampling_rate * 0.5 low = lowcut / nyq high = highcut / nyq return butter(order, [low, high], btype='bandpass', output=output) #### ver 1 # def butter_bandpass(signal, lowcut, highcut, sampling_rate, type="sos", order=4, plot=False, **kwargs): # r""" # Design a `order`th-order bandpass Butterworth filter with a cutoff frequency between `lowcut`-Hz and `highcut`-Hz, which, for data sampled at `sampling_rate`-Hz. # Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.butter.html # https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.filtfilt.html # https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.sosfiltfilt.html # Args: # signal : ndarray, shape (time,) or (channel,time) or (trial,channel,time) # Input signal (1D/2D/3D), where last axis is time samples. # lowcut : int # Lower bound filter # highcut : int # Upper bound filter # sampling_rate : int # Sampling frequency # type: string, optional, default: sos # Type of output: numerator/denominator (‘ba’), or second-order sections (‘sos’). # Default is ‘ba’ for backwards compatibility, but ‘sos’ should be used for general-purpose filtering. # order : int, optional, default: 4 # Order of the filter # plot : boolean, optional, default: False # Plot signal and filtered signal in frequency domain # plot_xlim : array of shape [lower, upper], optional, default: [lowcut-10 if (lowcut-10) > 0 else 0, highcut+20] # If `plot=True`, set a limit on the X-axis between lower and upper bound # plot_ylim : array of shape [lower, upper], optional, default: None # If `plot=True`, set a limit on the Y-axis between lower and upper bound # Returns: # y : ndarray # Filtered signal that has same shape in input `signal` # Usage: # >>> from splearn.data.generate import generate_signal # >>> # >>> signal_1d = generate_signal( # >>> length_seconds=4, # >>> sampling_rate=100, # >>> frequencies=[4,7,11,17,40, 50], # >>> plot=True # >>> ) # >>> print('signal_1d.shape', signal_1d.shape) # >>> # >>> signal_2d = generate_signal( # >>> length_seconds=4, # >>> sampling_rate=100, # >>> frequencies=[[4,7,11,17,40, 50],[1, 3]], # >>> plot=True # >>> ) # >>> print('signal_2d.shape', signal_2d.shape) # >>> # >>> signal_3d = np.expand_dims(s1, 0) # >>> print('signal_3d.shape', signal_3d.shape) # >>> # >>> signal_1d_filtered = butter_bandpass( # >>> signal=signal_1d, # >>> lowcut=5, # >>> highcut=20, # >>> sampling_rate=100, # >>> plot=True, # >>> ) # >>> print('signal_1d_filtered.shape', signal_1d_filtered.shape) # >>> # >>> signal_2d_filtered = butter_bandpass( # >>> signal=signal_2d, # >>> lowcut=5, # >>> highcut=20, # >>> sampling_rate=100, # >>> type='sos', # >>> order=4, # >>> plot=True, # >>> plot_xlim=[3,20] # >>> ) # >>> print('signal_2d_filtered.shape', signal_2d_filtered.shape) # >>> # >>> signal_3d_filtered = butter_bandpass( # >>> signal=signal_3d, # >>> lowcut=5, # >>> highcut=20, # >>> sampling_rate=100, # >>> type='ba', # >>> order=4, # >>> plot=True, # >>> plot_xlim=[0,40] # >>> ) # >>> print('signal_3d_filtered.shape', signal_3d_filtered.shape) # """ # dim = len(signal.shape)-1 # if type == 'ba': # b, a = _butter_bandpass(lowcut, highcut, sampling_rate, order) # y = filtfilt(b, a, signal) # else: # sos = _butter_bandpass(lowcut, highcut, sampling_rate, # order=order, output='sos') # y = sosfiltfilt(sos, signal, axis=dim) # if plot: # tmp_x = signal # tmp_y = y # if dim == 1: # tmp_x = signal[0] # tmp_y = y[0] # elif dim == 2: # tmp_x = signal[0, 0] # tmp_y = y[0, 0] # if type == 'ba': # # plot frequency response of filter # w, h = freqz(b, a) # plt.plot((sampling_rate * 0.5 / np.pi) * w, # abs(h), label="order = %d" % order) # plt.plot([0, 0.5 * sampling_rate], [np.sqrt(0.5), np.sqrt(0.5)], # '--', label='sqrt(0.5)') # plt.xlabel('Frequency (Hz)') # plt.ylabel('Gain') # plt.grid(True) # plt.legend(loc='best') # low = max(0, lowcut-(sampling_rate/100)) # high = highcut+(sampling_rate/100) # plt.xlim([low, high]) # plt.ylim([0, 1.2]) # plt.title('Frequency response of filter - lowcut:' + # str(lowcut)+', highcut:'+str(highcut)) # plt.show() # plot_xlim = kwargs['plot_xlim'] if 'plot_xlim' in kwargs else [lowcut-10 if (lowcut-10) > 0 else 0, highcut+20] # plot_ylim = kwargs['plot_ylim'] if 'plot_ylim' in kwargs else None # # frequency domain # fast_fourier_transform( # tmp_x, # sampling_rate, # plot=True, # plot_xlim=plot_xlim, # plot_ylim=plot_ylim, # plot_label='Signal' # ) # fast_fourier_transform( # tmp_y, # sampling_rate, # plot=True, # plot_xlim=plot_xlim, # plot_ylim=plot_ylim, # plot_label='Filtered' # ) # plt.title('Signal and filtered signal in frequency domain, type:' + type + ',lowcut:' + str(lowcut) + ',highcut:' + str(highcut) + ',order:' + str(order)) # plt.legend() # plt.show() # return y # def _butter_bandpass(lowcut, highcut, sampling_rate, order=4, output='ba'): # r""" # Create a Butterworth bandpass filter. Design an Nth-order digital or analog Butterworth filter and return the filter coefficients. # Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.butter.html # Args: # lowcut : int # Lower bound filter # highcut : int # Upper bound filter # sampling_rate : int # Sampling frequency # order : int, default: 4 # Order of the filter # output : string, default: ba # Type of output {‘ba’, ‘zpk’, ‘sos’}. Type of output: numerator/denominator (‘ba’), pole-zero (‘zpk’), or second-order sections (‘sos’). # Default is ‘ba’ for backwards compatibility, but ‘sos’ should be used for general-purpose filtering. # Returns: # butter : ndarray # Scipy butterworth filter # Dependencies: # butter : scipy.signal.butter # """ # nyq = sampling_rate * 0.5 # low = lowcut / nyq # high = highcut / nyq # return butter(order, [low, high], btype='bandpass', output=output) # if __name__ == "__main__": # from splearn.data.generate import signal # signal_1d = generate_signal( # length_seconds=4, # sampling_rate=100, # frequencies=[4,7,11,17,40, 50], # plot=True # ) # print('signal_1d.shape', signal_1d.shape) # signal_2d = generate_signal( # length_seconds=4, # sampling_rate=100, # frequencies=[[4,7,11,17,40, 50],[1, 3]], # plot=True # ) # print('signal_2d.shape', signal_2d.shape) # signal_3d = np.expand_dims(s1, 0) # print('signal_3d.shape', signal_3d.shape) # signal_1d_filtered = butter_bandpass( # signal=signal_1d, # lowcut=5, # highcut=20, # sampling_rate=100, # plot=True, # ) # print('signal_1d_filtered.shape', signal_1d_filtered.shape) # signal_2d_filtered = butter_bandpass( # signal=signal_2d, # lowcut=5, # highcut=20, # sampling_rate=100, # type='sos', # order=4, # plot=True, # plot_xlim=[3,20] # ) # print('signal_2d_filtered.shape', signal_2d_filtered.shape) # signal_3d_filtered = butter_bandpass( # signal=signal_3d, # lowcut=5, # highcut=20, # sampling_rate=100, # type='ba', # order=4, # plot=True, # plot_xlim=[0,40] # ) # print('signal_3d_filtered.shape', signal_3d_filtered.shape) <file_sep># Tutorials We aim to bridge the gap for anyone who are new signal processings to get started, check out the these tutorials to get started on signal processings. ### 1. Signal composition (time, sampling rate and frequency) In order to begin the signal processing adventure, we need to understand what we are dealing with. In the first tutorial, we will uncover what is a signal, and what it is made up of. We will look at how the sampling rate and frequency can affect a signal. We will also see what happens when we combine multiple signals of different frequencies. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Signal%20composition%20-%20time%2C%20sampling%20rate%20and%20frequency.ipynb) ### 2. Fourier Transform In the first tutorial, we learned that combining multiple signals will produce a new signal where all the frequencies are jumbled up. In this tutorial, we will learn about Fourier Transform and how it can take a complex signal and decompose it to the frequencies that made it up. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Fourier%20Transform.ipynb) ### 3. Denoising with mean-smooth filter Introduce the running mean filter, we learn to apply the simplest filter to perform denoising, we can remove noise that is normally distributed relative to the signal of interest. We will also understand what are edge effects. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Denoising%20with%20mean-smooth%20filter.ipynb) ### 4. Denoising with Gaussian-smooth filter We will look at a slight adaptation of the mean-smooth filter, the Gaussian smoothing filter. This tends to smooth the data to be a bit smoother compared to mean-smooth filter. This does not mean that one is better than the other, it depends on the specific applications. It is important to be aware of different filters type and how to use them. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Denoising%20with%20Gaussian-smooth%20filter.ipynb) ### 5. Canonical correlation analysis Canonical correlation analysis (CCA) is applied to analyze the frequency components of a signal. In this tutorials, we use CCA for feature extraction and classification. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Canonical%20Correlation%20Analysis.ipynb) ### 6. Task-related component analysis Task-related component analysis (TRCA) is a classification method originally for steady-state visual evoked potentials (SSVEPs) detection. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jinglescode/python-signal-processing/blob/main/tutorials/Task-Related%20Component%20Analysis.ipynb) <file_sep>torch>=1.4.0 numpy scipy matplotlib sklearn<file_sep># -*- coding: utf-8 -*- """Fourier analysis is a method for expressing a function as a sum of periodic components, and for recovering the signal from those components. """ import numpy as np from scipy.fft import fft import matplotlib.pyplot as plt def fast_fourier_transform(signal, sampling_rate, plot=False, **kwargs): r""" Use Fourier transforms to find the frequency components of a signal buried in noise. Args: signal : ndarray, shape (time,) or (channel,time) or (trial,channel,time) Single input signal in time domain sampling_rate: int Sampling frequency plot : boolean, optional, default: False To plot the single-sided amplitude spectrum plot_xlim : array of shape [lower, upper], optional, default: [0, int(`sampling_rate`/2)] If `plot=True`, set a limit on the X-axis between lower and upper bound plot_ylim : array of shape [lower, upper], optional, default: None If `plot=True`, set a limit on the Y-axis between lower and upper bound plot_label : string, optional, default: '' If `plot=True`, text label for this signal in plot, shown in legend plot_line_freq : int or float or list, option, default: None If `plot=True`, plot a vertical line to mark the target frequency. If a list is given, will plot multiple lines. Returns: P1 : ndarray Frequency domain. Compute the two-sided spectrum P2. Then compute the single-sided spectrum P1 based on P2 and the even-valued signal length L. See https://www.mathworks.com/help/matlab/ref/fft.html Usage: >>> from splearn.data.generate import generate_signal >>> from splearn.fourier import fast_fourier_transform >>> >>> s1 = generate_signal( >>> length_seconds=3.5, >>> sampling_rate=100, >>> frequencies=[4,7], >>> plot=True >>> ) >>> >>> p1 = fast_fourier_transform( >>> signal=s1, >>> sampling_rate=100, >>> plot=True, >>> plot_xlim=[0, 10], >>> plot_line_freq=7 >>> ) Reference: - https://www.mathworks.com/help/matlab/ref/fft.html - https://docs.scipy.org/doc/scipy/reference/tutorial/fft.html - https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fft.html """ plot_xlim = kwargs['plot_xlim'] if 'plot_xlim' in kwargs else [0, int(sampling_rate/2)] plot_ylim = kwargs['plot_ylim'] if 'plot_ylim' in kwargs else None plot_label = kwargs['plot_label'] if 'plot_label' in kwargs else '' plot_line_freq = kwargs['plot_line_freq'] if 'plot_line_freq' in kwargs else None plot_label = kwargs['plot_label'] if 'plot_label' in kwargs else '' fft_p1 = None if len(signal.shape) == 1: fft_p1 = _fast_fourier_transform(signal, sampling_rate) fft_p1 = np.expand_dims(fft_p1,0) if len(signal.shape) == 2: for ch in range(signal.shape[0]): fft_c = _fast_fourier_transform(signal[ch, :], sampling_rate=sampling_rate) if fft_p1 is None: fft_p1 = np.zeros((signal.shape[0], fft_c.shape[0])) fft_p1[ch] = fft_c if len(signal.shape) == 3: for trial in range(signal.shape[0]): for ch in range(signal.shape[1]): fft_c = _fast_fourier_transform(signal[trial, ch, :], sampling_rate=sampling_rate) if fft_p1 is None: fft_p1 = np.zeros((signal.shape[0], signal.shape[1], fft_c.shape[0])) fft_p1[trial,ch,:] = fft_c if plot: signal_length = signal.shape[ len(signal.shape)-1 ] f = sampling_rate*np.arange(0, (signal_length/2)+1)/signal_length if len(fft_p1.shape) == 3: means = np.mean(fft_p1, 0) stds = np.std(fft_p1, 0) for c in range(fft_p1.shape[1]): plt.plot(f, means[c], label=plot_label) plt.xlim(plot_xlim) plt.fill_between(f, means[c]-stds[c],means[c]+stds[c],alpha=.1) else: for c in range(fft_p1.shape[0]): plt.plot(f, fft_p1[c], label=plot_label) plt.xlim(plot_xlim) if plot_ylim is not None: plt.ylim(plot_ylim) if plot_label != '': plt.legend() if plot_line_freq is not None: if isinstance(plot_line_freq, list): for i in plot_line_freq: plt.axvline(x=i, color='r', linewidth=1.5) else: plt.axvline(x=plot_line_freq, color='r', linewidth=1.5) if len(signal.shape) == 1: fft_p1 = fft_p1[0] return fft_p1 def _fast_fourier_transform(signal, sampling_rate): r""" Use Fourier transforms to find the frequency components of a signal buried in noise. Args: signal : ndarray, shape (time,) Single input signal in time domain sampling_rate: int Sampling frequency Returns: P1 : ndarray Frequency domain. Compute the two-sided spectrum P2. Then compute the single-sided spectrum P1 based on P2 and the even-valued signal length L. See https://www.mathworks.com/help/matlab/ref/fft.html. Usage: See `fast_fourier_transform` Reference: - https://www.mathworks.com/help/matlab/ref/fft.html - https://docs.scipy.org/doc/scipy/reference/tutorial/fft.html - https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fft.html """ signal_length = signal.shape[0] if signal_length % 2 != 0: signal_length = signal_length+1 y = fft(signal) p2 = np.abs(y/signal_length) p1 = p2[0:round(signal_length/2+1)] p1[1:-1] = 2*p1[1:-1] return p1 if __name__ == "__main__": from splearn.data.generate import generate_signal from splearn.fourier import fast_fourier_transform s1 = generate_signal( length_seconds=3.5, sampling_rate=100, frequencies=[4,7], plot=True ) p1 = fast_fourier_transform( signal=s1, sampling_rate=100, plot=True, plot_xlim=[0, 10], plot_line_freq=7 ) <file_sep># -*- coding: utf-8 -*- """Use CCA for spatial filtering to improve the signal. """ import numpy as np from splearn.cross_decomposition.cca import perform_cca def cca_spatial_filtering(signal, reference_frequencies): r""" Use CCA for spatial filtering is to find a spatial filter that maximizes the correlation between the spatially filtered signal and the average evoked response, thereby improving the signal-to-noise ratio of the filtered signal on a single-trial basis. Read more: https://github.com/jinglescode/papers/issues/90, https://github.com/jinglescode/papers/issues/89 Args: signal : ndarray, shape (trial,channel,time) Input signal in time domain reference_frequencies : ndarray, shape (len(flick_freq),2*num_harmonics,time) Required sinusoidal reference templates corresponding to the flicker frequency for SSVEP classification Returns: filtered_signal : ndarray, shape (reference_frequencies.shape[0],signal.shape[0],signal.shape[1],signal.shape[2]) Signal after spatial filter Dependencies: np : numpy package perform_cca : function """ _, _, _, wx, _ = perform_cca(signal, reference_frequencies) filtered_signal = np.zeros((reference_frequencies.shape[0], signal.shape[0], signal.shape[1], signal.shape[2])) swapped_s = np.swapaxes(x_train, 1, 2) for target_i in range(reference_frequencies.shape[0]): for trial_i in range(swapped_s.shape[0]): t_trial = swapped_s[trial_i] t_w = wx[trial_i,target_i,:] filtered_s = np.matmul(t_trial, t_w) filtered_signal[target_i,trial_i,:,:] = filtered_s return filtered_signal <file_sep>from scipy.signal import filtfilt, iirnotch def notch_filter(data, sampling_rate=1000, notch_freq=50.0, quality_factor=30.0): b_notch, a_notch = iirnotch(notch_freq, quality_factor, sampling_rate) data_notched = filtfilt(b_notch, a_notch, data) return data_notched <file_sep>import numpy as np from splearn.data.pytorch_dataset import PyTorchDataset class MultipleSubjects(PyTorchDataset): def __init__(self, dataset: PyTorchDataset, root: str, subject_ids: [], verbose: bool = False, ) -> None: self.root = root self.subject_ids = subject_ids self._load_multiple(root, subject_ids, verbose) self.targets_frequencies = self.stimulus_frequencies[self.targets] def _load_multiple(self, root, subject_ids: [], verbose: bool = False) -> None: is_first = True for subject_i in range(len(subject_ids)): subject_id = subject_ids[subject_i] print('Load subject:', subject_id) subject_dataset = HSSSVEP(root="../data/hsssvep", subject_id=subject_id) sub_data = subject_dataset.data sub_targets = subject_dataset.targets if is_first: self.data = np.zeros((len(subject_ids), sub_data.shape[0], sub_data.shape[1], sub_data.shape[2])) self.targets = np.zeros((len(subject_ids), sub_targets.shape[0])) self.sampling_rate = subject_dataset.sampling_rate self.stimulus_frequencies = subject_dataset.stimulus_frequencies self.channel_names = subject_dataset.channel_names is_first = False self.data[subject_i, :, :, :] = sub_data self.targets[subject_i] = sub_targets self.targets = self.targets.astype(np.int32)
27726d15da30c2bc8c3a3f8ca605f287a219c1a6
[ "Markdown", "Python", "Text" ]
19
Python
datastreaming/python-signal-processing
c3de02b12905f14a2350377d7f4a868bd7a40bc7
2db3a8eed259aca413c946df20e58e4ea858b002
refs/heads/master
<file_sep>var express = require('express'); var router = express.Router(); var fs = require("fs"); var url = './db/data.json'; /* GET home page. */ router.get('/', function(req, res, next) { fs.readFile(url, "utf8", function (err, data) { // отправляем на клиента res.render('index', { title: 'Express', data: data !== '' ? JSON.parse(data) : '' }); }); }); module.exports = router; <file_sep>var express = require('express'); var app = express(); var fs = require("fs"); var url = './db/data.json'; /* GET home page. */ app.get('/', function (req, res, next) { var name = req.query.data.toUpperCase(); // данные из клиента var resolut = []; fs.readFile(url, "utf8", function (err, data) { data = JSON.parse(data); for (var i = 0; i < data.length; i++) { if(name.indexOf(data[i].name.toUpperCase()) >= 0){ resolut.push(data[i]) } } res.send(resolut); }); }); module.exports = app;<file_sep> $('#add').click(function () { var data = { name: $(this).siblings('.name').val(), grade: $(this).siblings('.grade').val() }; $.ajax({ type: 'GET', // отправляем в POST формате, можно GET url: '/add', // путь до обработчика, у нас он лежит в той же папке // dataType: 'json', // ответ ждем в json формате data: data, // данные для отправки success: function (data) { $('.tasks').html(' '); for(var i in data){ $('.tasks').append('<div>'+JSON.stringify(data[i])+'</div>') } } }); }); $('#friends').click(function () { var data = { id1: $(this).siblings('.id1').val(), id2: $(this).siblings('.id2').val() }; $.ajax({ type: 'GET', // отправляем в POST формате, можно GET url: '/friends', // путь до обработчика, у нас он лежит в той же папке // dataType: 'json', // ответ ждем в json формате data: data, // данные для отправки success: function (data) { $('.friends').html(' '); for(var i in data){ $('.friends').append('<div>'+JSON.stringify(data[i])+'</div>') } } }); }); $('#likes').click(function () { var data = { id1: $(this).siblings('.id1').val(), id2: $(this).siblings('.id2').val() }; $.ajax({ type: 'GET', // отправляем в POST формате, можно GET url: '/likes', // путь до обработчика, у нас он лежит в той же папке // dataType: 'json', // ответ ждем в json формате data: data, // данные для отправки success: function (data) { $('.likes').html(' '); for(var i in data){ $('.likes').append('<div>'+JSON.stringify(data[i])+'</div>') } } }); });<file_sep>var express = require('express'); var app = express(); var fs = require("fs"); var mysql = require('mysql'); var db_config = require('../database/database.config.json'); var pool = mysql.createPool(db_config); /* GET home page. */ app.get('/', function (req, res, next) { var user = { name: req.query.name, grade: req.query.grade }; pool.query('INSERT INTO Highschooler SET ?', user , function(err, result) { pool.query('SELECT * FROM Highschooler', function (error, results, fields) { res.send(results); }); }); }); module.exports = app;<file_sep>var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var db_config = require('../database/database.config.json'); var pool = mysql.createPool(db_config); /* GET home page. */ router.get('/', function (req, res, next) { //подключение к базе данных var request = { Highschooler: '', Friend: '', Likes: '' }; pool.query('SELECT * FROM Highschooler', function (error, results, fields) { request.Highschooler = results; pool.query('SELECT * FROM Friend', function (error, results, fields) { request.Friend = results; pool.query('SELECT * FROM Likes', function (error, results, fields) { request.Likes = results; res.render('index', { title: 'Express', data: request }); }); }); }); }); module.exports = router; <file_sep>var express = require('express'); var app = express(); var fs = require("fs"); var mysql = require('mysql'); var db_config = require('../database/database.config.json'); var pool = mysql.createPool(db_config); app.get('/', function (req, res, next) { var id = { id1: req.query.id1, id2: req.query.id2 }; pool.query('INSERT INTO Friend SET ?', id , function(err, result) { pool.query('SELECT * FROM Friend', function (error, results, fields) { res.send(results); }); }); }); module.exports = app;
7d4e7b4df2ebbcabae821072c5f719bf2b73b02a
[ "JavaScript" ]
6
JavaScript
IllyaHorbatenko/my-database
82a6de42fa35a9ebf3fac184c87ba46f8f83b9ec
e9786b8b288c7442602a5768de110a2d1ea9d9cc
refs/heads/master
<repo_name>viramgodhaniya/expleo_test<file_sep>/src/test/java/testRunner/AcceptanceTest.java package testRunner; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import com.vimalselvam.cucumber.listener.Reporter; //import com.relevantcodes.extentreports.ExtentReports; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/features", glue = "stepDef", tags = {"@currencyConvCheck"} , plugin = {"com.vimalselvam.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"} ) public class AcceptanceTest { // public static ExtentReports extent; // // @BeforeClass // public static void initializeReport(){ // Date date = new Date(); // DateFormat df = new SimpleDateFormat("ddMMyyHHmmss"); // extent = new ExtentReports("target/reports/ExecutionReport_" + df.format(date) + ".html"); // } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Starting Test...."); } @AfterClass public static void writeExtentReport(){ Reporter.setSystemInfo("User Name", System.getProperty("user.name")); Reporter.setSystemInfo("Time Zone", System.getProperty("user.timezone").toString()); } } <file_sep>/src/test/java/stepLib/XeCurrencyConvertorStepLib.java package stepLib; import java.math.BigDecimal; import java.math.MathContext; import org.openqa.selenium.WebDriver; import config.BrowserLaunch; import config.Environment; import junit.framework.Assert; import pom.XeCurrencyConvertorConvertionPage; import pom.XeCurrencyConvertorHomePage; import support.PropertiesLoader; public class XeCurrencyConvertorStepLib { public static Environment xeEnv; //protected static ExtentTest test; static{ xeEnv = PropertiesLoader.loadAll(); } public static WebDriver xeWebDriver; public String fromCcy; public String toCcy; public String amount; //////////////////////////Step Defn Implementations///////////////////////////// public void user_is_on_Xe_currency_convertor_Landing_Page(){ navigateToXeCurrencyConvertorHomePage(); } public void user_selects_the_from_currency_as_x_to_currency_as_x_and_amount_as_x(String fromCcy, String toCcy, String amount){ try{ this.fromCcy = fromCcy; this.toCcy = toCcy; this.amount = amount; XeCurrencyConvertorHomePage objXeCurrencyConvertorHomePage = new XeCurrencyConvertorHomePage(xeWebDriver); objXeCurrencyConvertorHomePage.acceptCookies(); objXeCurrencyConvertorHomePage.enterConvertionDetails(amount, fromCcy, toCcy); }catch(Exception e){ Assert.fail("Error while selecting Convertion Details on Home Page"); } } public void user_clicks_on_convert_button(){ XeCurrencyConvertorHomePage objXeCurrencyConvertorHomePage = new XeCurrencyConvertorHomePage(xeWebDriver); objXeCurrencyConvertorHomePage.clickConvertButton(); } public void user_verifies_the_converted_currency_on_the_proceeding_page(){ XeCurrencyConvertorConvertionPage objXeCurrencyConvertorConvertionPage = new XeCurrencyConvertorConvertionPage(xeWebDriver); String convertionRate = objXeCurrencyConvertorConvertionPage.getCurrentConvertionRate(fromCcy); String rate = convertionRate.split("=")[1].trim().split(" ")[0]; MathContext m = new MathContext(6); BigDecimal expectedToAmount = new BigDecimal(amount).multiply(new BigDecimal(rate),m); Reporter.addStepLog("Verifying 'From Amount': Expected {"+amount+"}. Actual {"+objXeCurrencyConvertorConvertionPage.getFromAmount() + "}"); Assert.assertEquals(amount, objXeCurrencyConvertorConvertionPage.getFromAmount()); Reporter.addStepLog("Verifying 'From Currency': Expected {"+fromCcy+"}. Actual {"+objXeCurrencyConvertorConvertionPage.getFromCcy() + "}"); Assert.assertEquals(fromCcy, objXeCurrencyConvertorConvertionPage.getFromCcy()); Reporter.addStepLog("Verifying 'To Amount': Expected {"+expectedToAmount+"}. Actual {"+objXeCurrencyConvertorConvertionPage.getToAmount() + "}"); Assert.assertEquals(expectedToAmount, new BigDecimal(objXeCurrencyConvertorConvertionPage.getToAmount())); Reporter.addStepLog("Verifying 'To Currency': Expected {"+toCcy+"}. Actual {"+objXeCurrencyConvertorConvertionPage.getToCcy() + "}"); Assert.assertEquals(toCcy, objXeCurrencyConvertorConvertionPage.getToCcy()); } public void user_closes_the_web_browser(){ xeWebDriver.quit(); } ////////////////////////Step Defn - Library Functions/////////////////////////// public void navigateToXeCurrencyConvertorHomePage(){ xeWebDriver = BrowserLaunch.launch(); xeWebDriver.navigate().to(xeEnv.WEB_URL); if(xeWebDriver.getTitle().equals("XE Currency Converter - Live Rates")) Reporter.addStepLog("XE Currency Converter Home Page Loaded Sucessfully"); else{ Reporter.addStepLog("XE Currency Converter Home Page not Loaded Sucessfully"); Assert.fail("Unable to load XE Currency Converter Home Page"); } } } <file_sep>/src/test/resources/environments/currencyConvertor.properties web.Url = http://www.xe.com/currencyconverter/<file_sep>/src/main/java/extend/CommonUIFunctions.java package extend; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class CommonUIFunctions { public static void click(WebDriver driver, WebElement element, String elementName){ element.click(); } public static void sendKeys(WebDriver driver, WebElement element, String textToBeEntered, String elementName){ element.sendKeys(textToBeEntered); } public static String getText(WebElement element){ return element.getText(); } } <file_sep>/src/main/java/pom/XeCurrencyConvertorConvertionPage.java package pom; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import extend.CommonUIFunctions; public class XeCurrencyConvertorConvertionPage { protected WebDriver driver; public XeCurrencyConvertorConvertionPage(WebDriver driver) { PageFactory.initElements(driver, this); this.driver = driver; } @FindBy(className = "converterresult-toAmount") private WebElement txtToAmount; @FindBy(className = "converterresult-toCurrency") private WebElement txtToCcy; @FindBy(className = "converterresult-fromAmount") private WebElement txtFromAmount; @FindBy(className = "converterresult-fromCurrency") private WebElement txtFromCcy; String conversionRate = "//span[contains(text(),'1 @fromCcy@ =')]"; public String getCurrentConvertionRate(String fromCcy){ WebElement eleConversionRate = driver.findElement(By.xpath(conversionRate.replaceAll("@fromCcy@", fromCcy))); return CommonUIFunctions.getText(eleConversionRate); } public String getToAmount(){ return CommonUIFunctions.getText(txtToAmount); } public String getToCcy(){ return CommonUIFunctions.getText(txtToCcy); } public String getFromAmount(){ return CommonUIFunctions.getText(txtFromAmount); } public String getFromCcy(){ return CommonUIFunctions.getText(txtFromCcy); } } <file_sep>/readme.txt Setup the the Solution: Unzip the file into any location in the computer. Now using the IDE import the maven Project into the work space. Build the solution from within the IDE and maven will automatically download the required java dependencies. Running the Test cases: Corresponding Tag has been provided to the feature file in order to run it. The test here can be executed using the tag @currencyConvCheck. Inorder to run the test case, goto Acceptance test class present under '/src/main/java/testRunner/AcceptanceTest.java'. Provide the tag name under tags field and run the AcceptanceTest Class as junit. Wait for Test Execution to be completed (approx 5 mins). Analyzing the Test Results with help of Extent Reports: An extent Report will be generated at '/target/cucumber-reports/report.html' inside the project folder after the test run is completed. Open the report into a web browser (Chrome is highly recomended for better results). Each and every scenario has been detiled in the report, each step being the gherkin line of the feature file and gherkin step lines are having the description of exactly what was tested within a gherkin wherever required. A Dashboard view having entire test summary can also be found in the report by clicking on small circular icon present on the left hand side pane. A sample report is already present in the '/target/cucumber-reports/' folder of the current solution.<file_sep>/src/main/java/config/Environment.java package config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class Environment { public String WEB_URL; public Environment loadEnv(String envSettingsPath){ Properties prop = new Properties(); File envFile = new File(envSettingsPath); FileInputStream envFileStream = null; try { envFileStream = new FileInputStream(envFile); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { prop.load(envFileStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } WEB_URL = prop.getProperty("web.Url"); return this; } public static Environment getEnvironment(String envFilePath){ return new Environment().loadEnv(envFilePath); } } <file_sep>/src/test/resources/execution.properties default.browser=chrome chrome.driver.path=src/test/resources/webdrivers/chromedriver.exe ie.driver.path=src/test/resources/chromedriver.exe execution.env=CurrencyConvertorProd code.version=""
63cc1c641631afc96e0a5739e12781858326269d
[ "Java", "Text", "INI" ]
8
Java
viramgodhaniya/expleo_test
5aebae50c6e880145f5ce7b107109ccd2cc89eaf
b95307488412e6f70f79e2473792da409162e32a
refs/heads/main
<file_sep># predict_human_intention_facing_lane_change_merge_request data driven approach to predict human driver reaction facing a merge request of surrounding drivers <file_sep># Dataset, code, and results of Hua's dissertation ## Dataset Data extraction process: 1. Use extract_lane_change.py to extract lane change sequences from both dataset, and extract_lane_change_merge_after.py to extract lane change abortions. 2. Use extract_sample.py and extract_sample_merge_after.py to extract the exact snapshot from the lane change sequences for the downstream prediction task. 3. Use data_preprocess.py to assemble the extracted samples; split to training and testing; generate OOD samples. Dataset | Description | Generating program | ----|----|---- us80.npz| Raw lane changes from US80, each row is one sample, with record [merge in front/after(0/1), u0, du0, du1, du2, dx0, dx1, dx2, dy0, dy1, dy2, y].| extract_sample.py, extract_sample_merge_after.py, and preprocess_both_dataset() in data_preprocess.py us101.npz| Raw lane changes from US101, each row is one sample, with record [merge in front/after(0/1), u0, du0, du1, du2, dx0, dx1, dx2, dy0, dy1, dy2, y]| extract_sample.py, extract_sample_merge_after.py, and preprocess_both_dataset() in data_preprocess.py| samples_relabeled_by_decrease_in_dx.npz| Samples with label based on $\Delta x$, each row is a sample with record [index, dt, u0, du0, du1, du2, dx0, dx1, dx2, dy0, dy1, dy2, y]| extract_samples_relabel_as_change_in_distance() in extract_sample.py | combined_dataset.npz| Combine us80 and us101 datasets, do feature selection, and normalize them to have 0 mean and 1 std, in which f['a']=x_train, f['b'']=y_train, f['c']=x_test, f['d']=y_test, f['e']=xGenerated), each sample is of feature x = [dv0, dv1, dx0, dx1] | prepare_validate_and_generate_ood() in data_process.py | combined_dataset_before_feature_selection.npz| Combine us80 and us101 datasets and normalize them to have 0 mean and 1 std, in which f['a']=x_train, f['b'']=y_train, f['c']=x_test, f['d']=y_test), each sample is of feature x = [v_ego, dv0, dv1, dv2, dx0, dx1, dx2, dy0, dy1, dy2]| prepare_validate_and_feature_selection() in data_process.py| combined_dataset_trainUs80_testUs101.npz| us80 as training dataset, us101 as testing dataset. Normalize samples to have 0 mean and 1 std, in which f['a']=x_train, f['b'']=y_train, f['c']=x_test, f['d']=y_test, f['e']=xGenerated), each sample is of feature x = [dv0, dv1, dx0, dx1] | prepare_validate_and_generate_ood_trainUs80_testUs101() in data_process.py| combined_dataset_trainUs101_testUs80.npz| us101 as training dataset, us80 as testing dataset. Normalize samples to have 0 mean and 1 std, in which f['a']=x_train, f['b'']=y_train, f['c']=x_test, f['d']=y_test, f['e']=xGenerated), each sample is of feature x = [dv0, dv1, dx0, dx1] | prepare_validate_and_generate_ood_trainUs80_testUs101() in data_process.py| lane_changes_trajectories.csv| demonstrative lane change trajectories | extract_lane_changes.py | min_dis_within_us80.npz| percentage of minimum distance to other samples in dataset us80 | cal_distance() in data_preprocess.py| min_dis_within_us101.npz| percentage of minimum distance to other samples in dataset us101 | cal_distance() in data_preprocess.py| # Results Figure/table| Supporting data| Generating program| Plot function (in plot_utils.py) ----|----|----|---- Figure 3.2: Lane changes| lane_changes_trajectories.csv|extract_lane_changes.py | plot_trajectory()| Figure 3.3: Label based on the change in ∆x.| samples_relabeled_by_decrease_in_dx.npz| extract_samples_relabel_as_change_in_distance() in extract_sample.py | visualize_sample_labeled_by_dx()| Figure 3.4: Accelerations of lag vehicles.| lane_changes_trajectories.csv| extract_lane_changes.py| plot_accelerations()| Figure 3.5: Lane changes in dataset I-80. | us80.npz | preprocess_both_dataset() in data_preprocess.py | plot_ngsim_scatter()| Figure 3.6: Lane changes in dataset US-101. | us101.npz | preprocess_both_dataset() in data_preprocess.py| plot_ngsim_scatter()| Figure 4.1: Confidence map for α = 0 (left) and α = 1 (right).| moons_confidence_alpha0.npz, moons_confidence_alpha1.npz|moons_csnn_alpha_effect_demo.py| plot_confidence_map_alpha_impact()| Figure 4.2: Evolution of the support circles during training.| /evolvement|moons_csnn_evolvement.py| plot_evolvement() | Figure 4.3: Evolution of the confidence during training.| /evolvement|moons_csnn_evolvement.py| plot_evolvement()| Figure 4.4: The radius penalty effect. | /redius_penalty_effect|moons_csnn_radius_penalty_effect.py|plot_radius_penalty_effect() Figure 4.5: Samples in the moons dataset. |moons_train_test_ood.npz| moons_csnn.py|plot_moons_scatter() Figure 4.6: Convergence of test accuracy, non-zero output ratio, and AUROC.|moons_acc_nzs_auroc.npz| moons_csnn.py|plot_save_acc_nzs_auroc()| Figure 4.7: Histograms of confidences for in-distribution and OOD samples.|moons_hist_confidence.npz|moons_csnn.py|plot_distribution()| Figure 4.8: ROC curve of the moons dataset|moons_roc.npz|moons_csnn.py|plot_save_roc()| Figure 4.9: Best test set accuracy vs. number of selected features| |ngsim_feature_selection.py|plot_feautre_selection_results() Figure 4.10: Minimum distance to other in-distribution samples.|min_dis_within_us80.npz, min_dis_within_us101.npz|cal_distance() in data_preprocess.py|plot_min_distance_within_dataset() Figure 4.11: Histograms of confidences on the NGSIM dataset and the generated OOD samples.|ngsim_hist_confidence_epoch240.npz|ngsim_csnn.py|plot_distribution()| Figure 4.12: OOD detection ROC curve for one run of training the CSNN on the NGSIM dataset.|ngsim_roc_epoch240.npz|ngsim_csnn.py|plot_save_roc()| Figure 4.13: Test accuracy and AUROC vs α for the CSNN.|/ngsim_lambda_effect|ngsim_csnn.py|plot_auc_acc_csnn()| Table 4.2: Test accuracy and AUROC in OOD detection, averaged of 10 independent runs. (MLP)|mlp_mean_std_accs_aucs_net4.npz|ngsim_mlp.py| | Table 4.2: Test accuracy and AUROC in OOD detection, averaged of 10 independent runs. (DUQ)|/duq|ngsim_duq.py| | Table 4.2: Test accuracy and AUROC in OOD detection, averaged of 10 independent runs. (Deep ensemble)|/deep_ensemble|ngsim_deep_ensemble.py| | Figure 4.14: Entropy distribution of in-distribution and OOD samples.|/deep_ensemble/ngsim_hist_confidence.npz| ngsim_deep_ensemble.py| plot_distribution()| Figure 4.15: ROC curve obtained with deep ensemble.|/deep_ensemble/ngsim_roc.npz| ngsim_deep_ensemble.py| plot_save_roc()| Figure 4.16: Entropy of average prediction.|moons_confidence_map_deep_ensemble.npz| moons_deep_ensemble.py| plot_moons_de()| Table 4.3: Generalization of network with compact support.|/train_us80_test_us101 and /train_us101_test_us80| ngsim_mlp.py, ngsim_csnn.py, ngsim_duq.py, ngsim_deep_ensemble.py| | <file_sep>import torch.utils.data from torch.nn import functional as F import numpy as np import sklearn.datasets from sklearn.metrics import roc_curve, auc from utils.plot_utils import plot_distribution, plot_save_roc, plot_save_acc_nzs_auroc from utils.data_preprocess import get_threshold, extract_ood from models import nnz, step, eval_step, eval_combined, csnn_learnable_r, pre_train #def vis(model, X_grid, xx, x_lin, y_lin, X_vis, mask, epoch, dir0, alpha=1., learnable_r = False): # with torch.no_grad(): # if learnable_r: # output = model(torch.from_numpy(X_grid).float(), alpha, model.r * model.r) # else: # output = model(torch.from_numpy(X_grid).float(), alpha, 1.) # output = F.softmax(output, dim=1) # confidence = output.max(1)[0].numpy() # # z = confidence.reshape(xx.shape) # # # plt.figure() # # l = np.linspace(0.5, 1., 21) # # plt.contourf(x_lin, y_lin, z, cmap=plt.get_cmap('inferno'), levels=l) # , extend='both') # # plt.colorbar() # # plt.scatter(X_vis[mask, 0], X_vis[mask, 1], s=6, c='r') # # plt.scatter(X_vis[~mask, 0], X_vis[~mask, 1], s=6) # # axs = plt.gca() # # axs.set(xlim=(-2.4, 2.4), ylim=(-2.4, 2.4)) # # axs.set_aspect('equal') # # # plt.axis([-3, 3., -3, 3]) # # # dir0 = '/home/hh/data/moons/' # # dir = dir0 + '/confidence_epoch_{}.png'.format(epoch) # # plt.savefig(dir) # # # plt.show() # # if(epoch == 190): # # dir = dir0 + '/moons_confidence_alpha0.npz' # # np.savez(dir, a=x_lin, b=y_lin, c=z, d=X_vis, e=mask) # seeds = [0, 100057, 300089, 500069, 700079] num_classes = 2 batchSize = 64 features = 64 learningRate = 0.001 l2Penalty = 1.0e-3 runs = 1 r2 = 1. maxAlpha = 1. LAMBDA = 0.64 # LAMBDA = 0.004 MIU = 0.0 epochs = 201 outputDir='results/' learnable_r = True BIAS = False percentage = 0.99 # Moons # noise = 0.1 # for visual demonstration of effectiveness of CSNN, use 0.1 noise = 0.18 # for OOD detection, enlarge it to 0.18 to make seperation harder # sklearn has no random seed, it depends on numpy to get random numbers np.random.seed(0) torch.manual_seed(0) x_train, y_train = sklearn.datasets.make_moons(n_samples=1500, noise=noise) x_train0 = x_train x_test, y_test = sklearn.datasets.make_moons(n_samples=500, noise=noise) mean = np.mean(x_train, axis=0) std = np.std(x_train, axis=0) print('mean, std', mean, std) x_train = (x_train-mean)/std/np.sqrt(2) x_test = (x_test-mean)/std/np.sqrt(2) # dataset for image output domain = 3 x_lin = np.linspace(-domain+0.5, domain+0.5, 100) y_lin = np.linspace(-domain, domain, 100) x_lin = (x_lin-mean[0])/std[0]/np.sqrt(2) y_lin = (y_lin-mean[1])/std[1]/np.sqrt(2) xx, yy = np.meshgrid(x_lin, y_lin) X_grid = np.column_stack([xx.flatten(), yy.flatten()]) minDis, oodLabel = get_threshold(x_train, percentage, outputDir) x_inDis = x_train[~oodLabel] y_inDis = y_train[~oodLabel] mask, x_ood = extract_ood(x_inDis, X_grid, minDis) dir = outputDir + 'moons_train_test_ood.npz' np.savez(dir, a=x_inDis, b=y_inDis, c=x_test, d=y_test, e=x_ood) x_combined = np.concatenate((x_test, x_ood)) print('in-dis {}, ood {}'.format(x_test.shape[0], x_ood.shape[0])) label_ood = np.zeros(x_combined.shape[0]) label_ood[x_test.shape[0]:] = 1 ds_train = torch.utils.data.TensorDataset(torch.from_numpy(x_train).float(), F.one_hot(torch.from_numpy(y_train)).float()) ds_test = torch.utils.data.TensorDataset(torch.from_numpy(x_test).float(), F.one_hot(torch.from_numpy(y_test)).float()) ds_combined = torch.utils.data.TensorDataset(torch.from_numpy(x_combined).float()) # pre_train # accs = [] # losses = [] # accs_test = [] # losses_test = [] for run in range(runs): dl_train = torch.utils.data.DataLoader(ds_train, batch_size=batchSize, shuffle=True, drop_last=False) dl_test = torch.utils.data.DataLoader(ds_test, batch_size=x_test.shape[0], shuffle=False) model = csnn_learnable_r(2, features, bias=BIAS) if learnable_r: model.set_lambda(LAMBDA) model.set_miu(MIU) optimizer = torch.optim.Adam(model.parameters(), lr=learningRate, weight_decay=l2Penalty) accuracy, loss, accuracy_test, loss_test = pre_train(model, optimizer, dl_train, dl_test, x_train, y_train, x_test, y_test, run, outputDir, maxEpoch=50) # accs.append(accuracy) # losses.append(loss) # accs_test.append(accuracy_test) # losses_test.append(loss_test) # dir = outputDir + 'pre_train_acc_loss_csnn.npz' # np.savez(dir, a=np.mean(accs, axis=0), b=np.std(accs, axis=0), # c=np.mean(losses, axis=0), d=np.std(losses, axis=0), # e=np.mean(accs_test, axis=0), f=np.std(accs_test, axis=0), # g=np.mean(losses_test, axis=0), h=np.std(losses_test, axis=0)) ACCs = [] ACCs_test = [] LOSSs = [] LOSSs_test = [] AUCs = [] ALPHAs = None for run in range(runs): dl_train = torch.utils.data.DataLoader(ds_train, batch_size=batchSize, shuffle=True, drop_last=False) dl_test = torch.utils.data.DataLoader(ds_test, batch_size=x_test.shape[0], shuffle=False) dl_combined = torch.utils.data.DataLoader(ds_combined, batch_size=x_combined.shape[0], shuffle=False) PATH = outputDir + '/csnn_run{}_epoch{}.pth'.format(run, 0) l = torch.load(PATH) model = l['net'] optimizer = torch.optim.Adam(model.parameters(), lr=learningRate, weight_decay=l2Penalty) losses = [] accuracies = [] losses_test = [] accuracies_test = [] alphas = [] mmcs = [] nzs = [] aucs = [] rs = [] np.set_printoptions(precision=4) for epoch in range(epochs): # alpha = maxAlpha * (epoch+1)/epochs alpha = maxAlpha for i, batch in enumerate(dl_train): if learnable_r: loss_ce, loss_penalty, loss_l2, x, y, y_pred, z = step(model, optimizer, batch, alpha, r2, learnable_r=True) else: loss, x, y, y_pred, z = step(model, optimizer, batch, alpha, r2) if learnable_r: accuracy, loss_ce, loss_penalty, loss_l2 = eval_step(model, x_train, y_train, alpha, r2, learnable_r=True) testacc, testloss_ce, testloss_penalty, testloss_l2 = eval_step(model, x_test, y_test, alpha, r2, learnable_r=True) else: accuracy, loss = eval_step(model, x_train, y_train, alpha, r2) testacc, testloss = eval_step(model, x_test, y_test, alpha, r2) if epoch % 5 == 0: if learnable_r: losses.append(loss_ce+loss_penalty) losses_test.append(testloss_ce+testloss_penalty) else: losses.append(loss) losses_test.append(testloss) accuracies.append(accuracy) accuracies_test.append(testacc) if learnable_r: nz, mmc = nnz(x_ood, model, alpha, model.r * model.r) else: nz, mmc = nnz(x_ood, model, alpha, r2) alphas.append(epoch) mmcs.append(mmc) nzs.append(nz) uncertainties = eval_combined(model, dl_combined, alpha, r2, learnable_r) falsePositiveRate, truePositiveRate, _ = roc_curve(label_ood, -uncertainties) AUC = auc(falsePositiveRate.astype(np.float32), truePositiveRate.astype(np.float32)) aucs.append(AUC) if learnable_r: rs.append([torch.norm(model.r, p=float('inf')).detach().item(), torch.norm(model.r, p=2).detach().item()]) rNorm = (torch.norm(model.r, p=2)).detach().numpy() w = model.fc1.weight.data.numpy() r = model.r.detach().numpy() radius2 = r * r + np.sum(w * w, axis=1) * (1 / alpha / alpha - 1) if BIAS: w0 = model.fc1.bias.detach().numpy() radius2 += w0 * w0 * (1 / alpha / alpha - 1) print('loss: cross_entropy {:.4f}, r penalty {:.4f}, w penalty {:.4f}'.format(loss_ce, loss_penalty, loss_l2)) print('epoch {}, alpha {:.2f}, r2 {:.1f}, nz {:.3f}, train {:.3f}, test {:.3f}, auroc {:.3f}, ||r||2 {:.3f}' .format(epoch, alpha, r2, 1. - nz, accuracy, testacc, AUC, rNorm)) # if epoch%10 == 0 or epoch<10: # vis(model, X_grid, xx, x_lin, y_lin, X_vis, maskVis, epoch, outputDir, alpha, learnable_r) # plot_circles(model.fc1, x_train, y_train, alpha, model.r.detach().numpy(), epoch, outputDir, BIAS) if epoch == epochs-1: dir = outputDir + '/moons_hist_confidence.npz' np.savez(dir, a=uncertainties, b=x_test.shape[0], c=epochs-1) dir = outputDir + '/moons_roc.npz' np.savez(dir, a=falsePositiveRate, b=truePositiveRate, c=AUC) # plot_save_loss(losses, losses_test, outputDir+'/loss_run{}.png'.format(run)) # plot_save_acc(accuracies, accuracies_test, outputDir+'/acc_run{}.png'.format(run)) if run == 0: dir = outputDir + '/moons_acc_nzs_auroc.npz' np.savez(dir, a=alphas, b=accuracies_test, c=nzs, d=aucs) AUCs.append(aucs) ACCs.append(accuracies) ACCs_test.append(accuracies_test) LOSSs.append(losses) LOSSs_test.append(losses_test) if ALPHAs is None: ALPHAs = alphas # AUCs = np.array(AUCs) # ACCs = np.array(ACCs) # ACCs_test = np.array(ACCs_test) # LOSSs = np.array(LOSSs) # LOSSs_test = np.array(LOSSs_test) # dir = outputDir + '/moons_csnn_mean_std_accs_aucs.npz' # np.savez(dir, a=np.mean(AUCs, axis=0), b=np.std(AUCs, axis=0), # c=np.mean(ACCs, axis=0), d=np.std(ACCs, axis=0), # e=np.mean(ACCs_test, axis=0), f=np.std(ACCs_test, axis=0), # g=np.mean(LOSSs, axis=0), h=np.std(LOSSs, axis=0), # i=np.mean(LOSSs_test, axis=0), j=np.std(LOSSs_test, axis=0), # k=ALPHAs, l=np.array(rs))
e7637ed179331730b1b1ca2a696d610631bbda53
[ "Markdown", "Python" ]
3
Markdown
huanghua1668/dissertation_HuaHuang
8e0567d4f7618b8f7bdc0bd89a273b58f3a646be
1752f32d61f4910c2a3fef6b9a9d6008e928feb5
refs/heads/master
<repo_name>asr1191/FOSSLab<file_sep>/EXP 6/unames.sh #!/bin/bash if [ "$#" -ne 2 ] then echo "Wrong number of parameters" exit 1 else if [ ! -f "$1" ] then echo "File does not exist" exit 1 else t=1 input="$1" while IFS= read -r line do if [ "$line" == "$2" ] then echo "Username exists in the file" t=0 exit 1 fi done < "$1" if [ "$t" == 1 ] then echo "Username does not exist in the file" echo "$2" >> "$1" echo "Username appended to the end of the file" exit 1 fi fi fi <file_sep>/EXP 10/GUI Calculator/demo.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'demo.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.lineEdit = QtGui.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(22, 16, 761, 61)) self.lineEdit.setObjectName(_fromUtf8("lineEdit")) self.widget = QtGui.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(20, 80, 761, 481)) self.widget.setObjectName(_fromUtf8("widget")) self.gridLayout = QtGui.QGridLayout(self.widget) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.pushButton = QtGui.QPushButton(self.widget) self.pushButton.setMaximumSize(QtCore.QSize(16777215, 27)) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1) self.pushButton_2 = QtGui.QPushButton(self.widget) self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) self.gridLayout.addWidget(self.pushButton_2, 0, 1, 1, 1) self.pushButton_3 = QtGui.QPushButton(self.widget) self.pushButton_3.setObjectName(_fromUtf8("pushButton_3")) self.gridLayout.addWidget(self.pushButton_3, 0, 2, 1, 1) self.pushButton_13 = QtGui.QPushButton(self.widget) self.pushButton_13.setObjectName(_fromUtf8("pushButton_13")) self.gridLayout.addWidget(self.pushButton_13, 0, 3, 1, 1) self.pushButton_15 = QtGui.QPushButton(self.widget) self.pushButton_15.setObjectName(_fromUtf8("pushButton_15")) self.gridLayout.addWidget(self.pushButton_15, 1, 0, 1, 1) self.pushButton_6 = QtGui.QPushButton(self.widget) self.pushButton_6.setObjectName(_fromUtf8("pushButton_6")) self.gridLayout.addWidget(self.pushButton_6, 1, 1, 1, 1) self.pushButton_14 = QtGui.QPushButton(self.widget) self.pushButton_14.setObjectName(_fromUtf8("pushButton_14")) self.gridLayout.addWidget(self.pushButton_14, 1, 2, 1, 1) self.pushButton_12 = QtGui.QPushButton(self.widget) self.pushButton_12.setObjectName(_fromUtf8("pushButton_12")) self.gridLayout.addWidget(self.pushButton_12, 1, 3, 1, 1) self.pushButton_7 = QtGui.QPushButton(self.widget) self.pushButton_7.setObjectName(_fromUtf8("pushButton_7")) self.gridLayout.addWidget(self.pushButton_7, 2, 0, 1, 1) self.pushButton_5 = QtGui.QPushButton(self.widget) self.pushButton_5.setObjectName(_fromUtf8("pushButton_5")) self.gridLayout.addWidget(self.pushButton_5, 2, 1, 1, 1) self.pushButton_4 = QtGui.QPushButton(self.widget) self.pushButton_4.setObjectName(_fromUtf8("pushButton_4")) self.gridLayout.addWidget(self.pushButton_4, 2, 2, 1, 1) self.pushButton_11 = QtGui.QPushButton(self.widget) self.pushButton_11.setObjectName(_fromUtf8("pushButton_11")) self.gridLayout.addWidget(self.pushButton_11, 2, 3, 1, 1) self.pushButton_16 = QtGui.QPushButton(self.widget) self.pushButton_16.setObjectName(_fromUtf8("pushButton_16")) self.gridLayout.addWidget(self.pushButton_16, 3, 0, 1, 1) self.pushButton_8 = QtGui.QPushButton(self.widget) self.pushButton_8.setObjectName(_fromUtf8("pushButton_8")) self.gridLayout.addWidget(self.pushButton_8, 3, 1, 1, 1) self.pushButton_9 = QtGui.QPushButton(self.widget) self.pushButton_9.setObjectName(_fromUtf8("pushButton_9")) self.gridLayout.addWidget(self.pushButton_9, 3, 2, 1, 1) self.pushButton_10 = QtGui.QPushButton(self.widget) self.pushButton_10.setObjectName(_fromUtf8("pushButton_10")) self.gridLayout.addWidget(self.pushButton_10, 3, 3, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.pushButton.setText(_translate("MainWindow", "1", None)) self.pushButton_2.setText(_translate("MainWindow", "2", None)) self.pushButton_3.setText(_translate("MainWindow", "3", None)) self.pushButton_13.setText(_translate("MainWindow", "/", None)) self.pushButton_15.setText(_translate("MainWindow", "4", None)) self.pushButton_6.setText(_translate("MainWindow", "5", None)) self.pushButton_14.setText(_translate("MainWindow", "6", None)) self.pushButton_12.setText(_translate("MainWindow", "%", None)) self.pushButton_7.setText(_translate("MainWindow", "7", None)) self.pushButton_5.setText(_translate("MainWindow", "8", None)) self.pushButton_4.setText(_translate("MainWindow", "9", None)) self.pushButton_11.setText(_translate("MainWindow", "*", None)) self.pushButton_16.setText(_translate("MainWindow", "0", None)) self.pushButton_8.setText(_translate("MainWindow", "+", None)) self.pushButton_9.setText(_translate("MainWindow", "-", None)) self.pushButton_10.setText(_translate("MainWindow", "=", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) <file_sep>/EXP 3/username.sh #!/bin/sh echo -e "User name: $USER (Login name: $LOGNAME)" echo -e "Current Shell: $SHELL" echo -e "Home Directory: $HOME" echo -e "Your O/s Type: $OSTYPE" echo -e "PATH: $PATH" echo -e "Current directory: `pwd`" echo -e "Currently Logged: $nouser user(s)" <file_sep>/EXP 11/Experiment 11.md # Experiment 11 ### Php installation * sudo apt-get install apache2 * sudo apt-get install mysql-server * sudo apt-get install php5 libapache2-mod-php5 * Restarting apache: sudo /etc/init.d/apache2 restart * Checking php is properly installion "php -r 'echo "\n\nYour PHP installation is working fine.\n\n\n";'" ### General * Use Maxcdn to get Bootstarp. ### register.php * On submit the php check whether the value of password and username is set in post.\ * Mysql is used as the database. * mysqli is a relational database driver. * mysqli is used to insert data into the database. * If the values are not set in post then the registration fail. ### login.php * Implement sessions to stay logged in. * Create two forms to take password and email. ### connect.php * mysqli is used to connect to the database using the appropriate credentials and mysqi_connect. * If the connection fails an error is thrown using DIE. * mysqli_select_db is used to select the database. ### welcome.php * sessions is used to show the logged in user. ### style.css * style.css is used to design the website <file_sep>/EXP 11/lamp.md # Experiment 11 ##LAMP Stack Implementation ### Installation * **Install Apache:** >>```bash sudo apt-get install apache2``` * **Install MySQL:** >>sudo apt-get install mysql-server * **Install php5 with apache module:** >>sudo apt-get install php5 libapache2-mod-php5 * **Restart Apache**: >>sudo /etc/init.d/apache2 restart * **Verify Proper php Installation:** >>php -r 'echo "\n\nYour PHP installation is working fine.\n\n\n";' ### General *Use m<file_sep>/EXP 5/calc.sh #!/bin/sh y=0 while [ "$y" -eq 0 ] do echo "Please enter the first operand" read a echo "Please enter the second operand" read b x=0 while [ "$x" -eq 0 ] do echo "Enter 1 for addition\nEnter 2 for subtraction" echo "Enter 3 for multiplication" echo "Enter 4 for division" echo "Enter 5 for modulus operator" read e if [ "$e" -eq 1 ] then c=$(expr "$a" + "$b") echo "The result of addition is $c" elif [ "$e" -eq 2 ] then c=$(expr "$a" - "$b") echo "The result of subtraction is $c" elif [ "$e" -eq 3 ] then c=$(expr "$a" \* "$b") echo "The result of multiplication is $c" elif [ "$e" -eq 4 ] then c=$(expr "$a" / "$b") echo "The result of division is $c" elif [ "$e" -eq 5 ] then c=$(expr "$a" % "$b") echo "The result of modulus is $c" else echo "Invalid operation selected" fi echo "Enter 0 to perform a different operation on the two variables\nEnter 1 to exit or to choose different variables" read x done echo "Enter 0 to choose two different variables\nEnter 1 to exit" read y done <file_sep>/EXP 4/infomouse.sh #!/bin/sh echo -e "..........................OS............................." echo -e "`cat /etc/os-release`" echo -e " ............................Available Shells..................." echo "`cat /etc/shells`" echo -e "................................Mouse information...................................." echo -e "`xset q`" echo "............................Memmory Information.........................." echo -e "`cat /proc/meminfo` " echo "..............................Hard disk information......................." echo -e "Driver: ` sudo hdparm -I /dev/sda` " echo -e " ..........................File mounted.................................." echo " `cat /proc/mounts `"
c6352609229870df9ee6677f663084e4fcc884b6
[ "Markdown", "Python", "Shell" ]
7
Shell
asr1191/FOSSLab
5dcc81e38ad243e60c9ec24866f3fd5566fff7e6
bbbb9efa868538aa4a4931a3fbb0c6fb87dcb81a
refs/heads/master
<repo_name>dpolyak/LoginPageQA<file_sep>/conf_login_hw.js // conf.js exports.config = { framework: 'jasmine', seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['spec_login_hw.js'], params: { validEmail: '<EMAIL>', validPassword: '<PASSWORD>', userFullName: 'D P', empty: '', wrongEmail_1: 'a', wrongEmail_2: '<EMAIL>', invalidPassword: '123', wrongPassword: '<PASSWORD>' } }<file_sep>/login_page.js var LoginPage = function() { // login page URL var page_url = 'http://automationpractice.com/index.php?controller=authentication&back=my-account'; // page elements var lostPassword = element(by.css('.lost_password.form-group a')); var alert_message = element(by.css('.alert.alert-danger ol li')); var loginFormHeader = element(by.css('#login_form h3.page-subheading')); var email = element(by.id('email')); var password = element(by.id('passwd')); var submitLogin = element(by.id('SubmitLogin')); // login alert messages and form titles this.LOGIN_FORM_HEADER = 'ALREADY REGISTERED?'; this.LOST_PASSWORD_MSG = '<PASSWORD>?'; this.EMAIL_ADDRESS_REQUIRED_MSG = 'An email address required.'; this.INVALID_EMAIL_ADDRESS_MSG = 'Invalid email address.'; this.PASSWORD_REQUIRED_MSG = 'Password is required.'; this.INVALID_PASSWORD_MSG = 'Invalid password.'; this.AUTHENTICATION_FAILDED_MSG = 'Authentication failed.'; this.get = function() { browser.get(page_url); }; this.isEmailElementPresent = function() { return email.isPresent(); }; this.isPasswordElementPresent = function() { return password.isPresent(); }; this.isSubmitButtonPresent = function() { return submitLogin.isPresent(); }; this.isLostPasswordLinkPresent = function() { return lostPassword.isPresent(); }; this.setEmail = function(user) { email.clear(); email.sendKeys(user); }; this.setPassword = function(pwd) { password.clear(); password.sendKeys(pwd); }; this.submit = function() { submitLogin.click(); }; this.lostPassword = function() { lostPassword.click(); }; this.getAlertText = function() { return alert_message.getText(); }; this.getLoginFormHeader = function() { return loginFormHeader.getText(); }; this.getLostPasswordText = function() { return lostPassword.getText(); }; }; module.exports = new LoginPage();<file_sep>/my_account_page.js var MyAccountPage = function() { var userInfo = element(by.css('.header_user_info .account span')); var logout = element(by.css('a.logout')); this.getUserInfo = function() { return userInfo.getText(); }; this.logout = function() { logout.click(); }; }; module.exports = new MyAccountPage();<file_sep>/forgot_pwd_page.js var forgotPasswordPage = function() { var page_url = "http://automationpractice.com/index.php?controller=password"; this.PAGE_TITLE = 'Forgot your password - My Store'; }; module.exports = new forgotPasswordPage();<file_sep>/spec_login_hw.js var loginPage = require('./login_page.js'); var accoutPage = require('./my_account_page.js'); var passwordPage = require('./forgot_pwd_page.js'); describe('Login - My Store', function() { function login(email, pwd) { loginPage.setEmail(email); loginPage.setPassword(pwd); loginPage.submit(); } beforeAll(function() { browser.waitForAngularEnabled(false); }); beforeEach(function() { loginPage.get(); }); it('should have login form elements', function() { expect(loginPage.getLoginFormHeader()).toEqual(loginPage.LOGIN_FORM_HEADER); expect(loginPage.isEmailElementPresent()).toBe(true); expect(loginPage.isPasswordElementPresent()).toBe(true); expect(loginPage.isSubmitButtonPresent()).toBe(true); expect(loginPage.getLostPasswordText()).toEqual(loginPage.LOST_PASSWORD_MSG); }); it('should login and have a user info', function() { // lower case email var lowerCaseEmail = browser.params.validEmail.toLowerCase(); login(lowerCaseEmail, browser.params.validPassword); expect(accoutPage.getUserInfo()).toEqual(browser.params.userFullName); accoutPage.logout(); // upper case email var upperCaseEmail = browser.params.validEmail.toUpperCase(); login(upperCaseEmail, browser.params.validPassword); expect(accoutPage.getUserInfo()).toEqual(browser.params.userFullName); accoutPage.logout(); }); it('should have forgot password action', function() { loginPage.lostPassword(); expect(browser.getTitle()).toEqual(passwordPage.PAGE_TITLE); }); it('should have an email', function() { login(browser.params.empty, browser.params.empty); expect(loginPage.getAlertText()).toEqual(loginPage.EMAIL_ADDRESS_REQUIRED_MSG); }); it('should have a valide email', function() { login(browser.params.wrongEmail_1, browser.params.empty); expect(loginPage.getAlertText()).toEqual(loginPage.INVALID_EMAIL_ADDRESS_MSG); login(browser.params.wrongEmail_2, browser.params.invalidPassword); expect(loginPage.getAlertText()).toEqual(loginPage.INVALID_EMAIL_ADDRESS_MSG); }); it('should have a password', function() { login(browser.params.validEmail, browser.params.empty); expect(loginPage.getAlertText()).toEqual(loginPage.PASSWORD_REQUIRED_MSG); }); it('should have a valid password', function() { login(browser.params.validEmail, browser.params.invalidPassword); expect(loginPage.getAlertText()).toEqual(loginPage.INVALID_PASSWORD_MSG); }); it('should have a correct password', function() { login(browser.params.validEmail, browser.params.wrongPassword); expect(loginPage.getAlertText()).toEqual(loginPage.AUTHENTICATION_FAILDED_MSG); }); });
8d2aa42d39a3d4fbddd0a0b583b894b254d8cadf
[ "JavaScript" ]
5
JavaScript
dpolyak/LoginPageQA
2428a359cb3527b33a5ce221771a92fa23523e5e
4cad6d8f4cee473dbd4a9228c0b729f0a35a7bb4
refs/heads/master
<repo_name>bnmxavier/packetcatcher<file_sep>/sniffer_clean.c #include "header.h" int main() { int saddr_size , data_size; struct sockaddr saddr; struct in_addr in; unsigned char *buffer = (unsigned char *)malloc(65536); //Its Big! logfile=fopen("log.txt","a"); if(logfile==NULL) printf("Unable to create file."); printf("Starting...\n"); //Create a raw socket that shall sniff sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP); if(sock_raw < 0) { printf("Socket Error\n"); return 1; } //Bind to local interface for testing char *opt; opt = "enp0s3"; setsockopt(sock_raw, SOL_SOCKET, SO_BINDTODEVICE, opt, 2); while(1) { saddr_size = sizeof saddr; //Receive a packet data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , &saddr_size); if(data_size <0 ) { printf("Recvfrom error , failed to get packets\n"); return 1; } //Now process the packet ProcessPacket(buffer , data_size); } close(sock_raw); printf("Finished"); return 0; } <file_sep>/header.h #define _SVID_SOURCE #ifndef ETHER_HDRLEN #define ETHER_HDRLEN 14 #endif #include<stdio.h> //For standard things #include<stdlib.h> //malloc #include<string.h> //memset #include<netinet/ip_icmp.h> //Provides declarations for icmp header #include<netinet/udp.h> //Provides declarations for udp header #include<netinet/tcp.h> //Provides declarations for tcp header #include<netinet/ip.h> //Provides declarations for ip header #include<net/if.h> #include<sys/socket.h> #include<arpa/inet.h> #include <linux/if_packet.h> #include <net/ethernet.h> #include <unistd.h> // for close #include <sys/socket.h> #include <sys/ioctl.h> #include <errno.h> #include <netinet/in.h> #include <netinet/if_ether.h> #include <netinet/ether.h> #include <pcap.h> #include <netdb.h> #include <ctype.h> // Structs /* * Structure of an internet header * */ struct my_ip { u_int8_t ip_vhl; /* header length, version */ #define IP_V(ip) (((ip)->ip_vhl & 0xf0) >> 4) #define IP_HL(ip) ((ip)->ip_vhl & 0x0f) u_int8_t ip_tos; /* type of service */ u_int16_t ip_len; /* total length */ u_int16_t ip_id; /* identification */ u_int16_t ip_off; /* fragment offset field */ #define IP_DF 0x4000 /* dont fragment flag */ #define IP_MF 0x2000 /* more fragments flag */ #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ u_int8_t ip_ttl; /* time to live */ u_int8_t ip_p; /* protocol */ u_int16_t ip_sum; /* checksum */ struct in_addr ip_src,ip_dst; /* source and dest address */ }; /* UDP header */ struct sniff_udp { u_short uh_sport; /* source port */ u_short uh_dport; /* destination port */ u_short uh_ulen; /* udp length */ u_short uh_sum; /* udp checksum */ }; #define SIZE_UDP 8 /* length of UDP header */ #define SIZE_ETHERNET 14 /*length of ethernet header*/ //Function definitions u_int16_t handle_ethernet (u_char *args,const struct pcap_pkthdr* pkthdr,const u_char* packet); u_char* handle_IP (u_char *args,const struct pcap_pkthdr* pkthdr,const u_char* packet); // Global vars int sock_raw; FILE *logfile; struct sockaddr_in source,dest; <file_sep>/mysniffer.c #include "header.h" void my_callback(u_char *args,const struct pcap_pkthdr* pkthdr,const u_char* packet) { // ProcessPacket(packet,BUFSIZ); u_int16_t type = handle_ethernet(args,pkthdr,packet); if(type == ETHERTYPE_IP) {/* handle IP packet */ handle_IP(args,pkthdr,packet); }else if(type == ETHERTYPE_ARP) {/* handle arp packet */ handle_IP(args,pkthdr,packet); } else if(type == ETHERTYPE_REVARP) {/* handle reverse arp packet */ handle_IP(args,pkthdr,packet); } } int main(int argc,char **argv) { char *dev; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* descr; struct bpf_program fp; /* hold compiled program */ bpf_u_int32 maskp; /* subnet mask */ bpf_u_int32 netp; /* ip */ u_char* args = NULL; /* Options must be passed in as a string because I am lazy */ if(argc < 2){ fprintf(stdout,"Usage: %s numpackets \"options\"\n",argv[0]); return 0; } /* grab a device to peak into... */ dev = pcap_lookupdev(errbuf); if(dev == NULL) { printf("%s\n",errbuf); exit(1); } /* ask pcap for the network address and mask of the device */ pcap_lookupnet(dev,&netp,&maskp,errbuf); /* open device for reading.*/ descr = pcap_open_live(dev,BUFSIZ,1,-1,errbuf); if(descr == NULL) { printf("pcap_open_live(): %s\n",errbuf); exit(1); } if(argc > 2) { /* Lets try and compile the program.. non-optimized */ if(pcap_compile(descr,&fp,argv[2],0,netp) == -1) { fprintf(stderr,"Error calling pcap_compile\n"); exit(1); } /* set the compiled program as the filter */ if(pcap_setfilter(descr,&fp) == -1) { fprintf(stderr,"Error setting filter\n"); exit(1); } } /* ... and loop */ pcap_loop(descr,atoi(argv[1]),my_callback,args); fprintf(stdout,"\nfinished\n"); return 0; } <file_sep>/makefile mymakefile: mysniffer.c sniffer_functions.c; gcc -o psniff sniffer_functions.c mysniffer.c -lpcap; <file_sep>/sniffer_functions.c #include "header.h" //Packet handleing functions /* looking at ethernet headers */ void print_hex_ascii_line(const u_char *payload, int len, int offset) // Function to convert hex to ASCII { int i; int gap; const u_char *ch; /* offset */ printf("%05d ", offset); /* hex */ ch = payload; for(i = 0; i < len; i++) { printf("%02x ", *ch); ch++; /* print extra space after 8th byte for visual aid */ if (i == 7) printf(" "); } /* print space to handle line less than 8 bytes */ if (len < 8) printf(" "); /* fill hex gap with spaces if not full line */ if (len < 16) { gap = 16 - len; for (i = 0; i < gap; i++) { printf(" "); } } printf(" "); /* ascii (if printable) */ ch = payload; for(i = 0; i < len; i++) { if (isprint(*ch)) printf("%c", *ch); else printf("."); ch++; } printf("\n"); return; } void print_payload(const u_char *payload, int len) // Function to print the contents of packet { int len_rem = len; int line_width = 16; /* number of bytes per line */ int line_len; int offset = 0; /* zero-based offset counter */ const u_char *ch = payload; if (len <= 0) return; /* data fits on one line */ if (len <= line_width) { print_hex_ascii_line(ch, len, offset); return; } /* data spans multiple lines */ for ( ;; ) { /* compute current line length */ line_len = line_width % len_rem; /* print line */ print_hex_ascii_line(ch, line_len, offset); /* compute total remaining */ len_rem = len_rem - line_len; /* shift pointer to remaining bytes to print */ ch = ch + line_len; /* add offset */ offset = offset + line_width; /* check if we have line width chars or less */ if (len_rem <= line_width) { /* print last line and get out */ print_hex_ascii_line(ch, len_rem, offset); break; } } return; } /* param1@ the udp header, struct in header.h param2@ the ethernet header, lvl2 OSI, part of the pcap library param3@ the ip header, lvl3 OSI, struct found in header.h param4@ char array containing the packets payload param5@ char array that will hold our reconstructed packet param6@ the total amount of bytes we need to allocate for packet param7@ size in bytes of the ip header param8@ size in bytes of the payload */ void buildPacket(struct sniff_udp *udp,struct ether_header *ethh, // function to assemble packet from the structures we've modified struct my_ip *ip, const char *payload, u_char *buffer,size_t bufferLen, size_t ipSize, size_t payloadSize) { //print_payload(payload,payloadSize); printf("buf len check: %d \n", bufferLen); // checks the total size of the buffer memset(buffer,0, bufferLen+1); // allocates memory for the new packet memcpy(buffer, ethh, SIZE_ETHERNET); // copies the bytes form the eth hdr into the new packet memcpy(buffer+SIZE_ETHERNET,ip,ipSize); // copies the bytes from the ip header into the new packet, starting where the eth hdr left off memcpy(buffer+SIZE_ETHERNET+ipSize, udp, SIZE_UDP); // continues to fill the packet memcpy(buffer+SIZE_ETHERNET+ipSize+SIZE_UDP, payload, payloadSize); // adds payload to the end of the packet print_payload(buffer, bufferLen); // takes a look at the packet we've just creeated return; } // param1@ ethernet header struct void getHMac(struct ether_header *myMac) // function to change the source mac of the packet to our mac { int s; struct ifreq buffer; // mac addr struct s = socket(PF_INET, SOCK_DGRAM, 0); // opens a socket with the neccesary protocols memset(&buffer, 0x00, sizeof(buffer)); // gives buffer a block of memory strcpy(buffer.ifr_name, "enp0s3"); // sets the interface name to the interface we want to use, IMPORTANT must be changed to the interface you want to use. ioctl(s, SIOCGIFHWADDR, &buffer); // gets the mac address of our interface close(s); // closes socket that we no longer need memcpy(myMac->ether_shost,buffer.ifr_hwaddr.sa_data,6); // copies the memory from our struct to the packet we have captured and dissected printf("\n"); return; } //param1@ ip header struct void getHip(struct my_ip *ip) // function to change the source ip of our captured packet to our own ip { struct addrinfo hints; struct addrinfo *servinfo; // will point to the results memset(&hints, 0, sizeof(hints)); // make sure the struct is empty int status; if((status=getaddrinfo("ben-VirtualBox",NULL,&hints,&servinfo))!=0) // gets address of host system // IMPORTANT!!! requires the hostname of the local system as the first argument { printf("status is %d \n",status); fprintf(stdout, "getaddrinfo: %s \n",gai_strerror(status)); exit(1); } struct sockaddr *tmp=servinfo->ai_addr; // creates a temporary struct to store the address ip->ip_src=((struct sockaddr_in*)tmp)->sin_addr; // move the memory from our tmp struct to the packet memory freeaddrinfo(servinfo); // frees the linked list } /* param1@ the buffer storing our reconstructed packet param2@ char array holding the dst address, purely for asthetic purposes param3@ size of the reconstructed packet in bytes */ void sendPacket(u_char *buffer,const u_char *dstAddr, size_t bufferLen) // sends the packet we constructed onto the wire { pcap_t *fp; char errbuf[PCAP_ERRBUF_SIZE]; int i; if ( (fp= pcap_open_live("enp0s3", //opens the raw socket // name of the device BUFSIZ, // portion of the packet to capture (only the first 100 bytes) 1, // promiscuous mode 1000, // read timeout errbuf // error buffer ) ) == NULL) { printf("Unable to open the adapter\n"); return; } int numbytes; if ((numbytes=pcap_inject(fp, &buffer,bufferLen /* size */)) == -1) // sends the packet without the kernel messing with the headers in our paacket { fprintf(stdout,"Error sending the packet:%s \n", pcap_geterr(fp)); return; } printf("sent %d bytes\n",numbytes); // error check return; } u_char* handle_IP // extracts the ip header from the packet and includes all modification and transmission functions (u_char *args,const struct pcap_pkthdr* pkthdr,const u_char* packet) { struct ether_header *eptr; eptr = (struct ether_header *) packet; struct my_ip* ip; struct sniff_udp* udp; const char *payload; /* Packet payload */ u_char *buffer; const u_char *dstAddr; u_int length = pkthdr->len; u_int hlen,off,version; int i; int size_payload; int len; logfile=fopen("log.txt","a"); printf("Packet recived is %d bytes long\n",sizeof(packet)); /* jump pass the ethernet header */ ip = (struct my_ip*)(packet + sizeof(struct ether_header)); // puts the ip hdr from the cp into a more usable struct length -= sizeof(struct ether_header); /* check to see we have a packet of valid length */ if (length < sizeof(struct my_ip)) { printf("truncated ip %d",length); return NULL; } len = ntohs(ip->ip_len); hlen = IP_HL(ip)*4; /* header length */ version = IP_V(ip);/* ip version */ /* check version */ if(version != 4) { fprintf(stdout,"Unknown version %d\n",version); return NULL; } /* check header length */ if(hlen < 20 ) { fprintf(stdout,"bad-hlen %d \n",hlen); } /* see if we have as much packet as we should */ if(length < len) printf("\ntruncated IP - %d bytes missing\n",len - length); /* Check to see if we have the first fragment */ off = ntohs(ip->ip_off); if((off & 0x1fff) == 0 )/* aka no 1's in first 13 bits */ {/* print SOURCE DESTINATION hlen version len offset */ fprintf(stdout,"IP: "); fprintf(stdout,"%s ", inet_ntoa(ip->ip_src)); fprintf(stdout,"%s header length:%d version:%d length:%d offset%d\n", inet_ntoa(ip->ip_dst), hlen,version,len,off); dstAddr=inet_ntoa(ip->ip_dst); // prints to file fprintf(logfile,"IP: "); fprintf(logfile,"%s ", inet_ntoa(ip->ip_src)); fprintf(logfile,"%s header length:%d version:%d length:%d offset%d\n", inet_ntoa(ip->ip_dst), hlen,version,len,off); getHip(ip); // changes the packets mac to our own switch(ip->ip_p) // checks protocol is udp { case IPPROTO_TCP: printf(" Protocol: TCP\n"); exit(1); case IPPROTO_UDP: printf(" Protocol: UDP\n"); break; case IPPROTO_ICMP: printf(" Protocol: ICMP\n"); exit(1); case IPPROTO_IP: printf(" Protocol: IP\n"); exit(1); default: printf(" Protocol: unknown\n"); exit(1); } udp = (struct sniff_udp*)(packet + SIZE_ETHERNET + SIZE_UDP); // puts the protocol header into a more usable struct printf(" Src port: %d\n", ntohs(udp->uh_sport)); printf(" Dst port: %d\n", ntohs(udp->uh_dport)); /* define/compute udp payload (segment) offset */ payload = (u_char *)(packet + SIZE_ETHERNET + SIZE_UDP + hlen); // puts the payload into a readable buffer /* compute udp payload (segment) size */ size_payload = ntohs(ip->ip_len) - (hlen + SIZE_UDP); if (size_payload > ntohs(udp->uh_ulen)) size_payload = ntohs(udp->uh_ulen); printf("payload size is %d\n",size_payload ); print_payload(payload, size_payload); size_t bufferLen=(SIZE_UDP+SIZE_ETHERNET+hlen+size_payload); // sets the size of our new packet to include all headers and the payload u_char buffer[bufferLen+1];// defines and allocates memort buildPacket(udp, eptr,ip,payload,buffer,bufferLen, hlen,size_payload);// fills the new packet sendPacket(buffer, dstAddr, bufferLen); // sends the new packet fclose(logfile); // close the log file return NULL; } } /* handle ethernet packets, uses * print-ether.c from tcpdump source as a referance */ u_int16_t handle_ethernet (u_char *args,const struct pcap_pkthdr* pkthdr,const u_char* packet) { u_int caplen = pkthdr->caplen; u_int length = pkthdr->len; struct ether_header *eptr; /* net/ethernet.h */ u_short ether_type; if (caplen < ETHER_HDRLEN) { fprintf(stdout,"Packet length less than ethernet header length\n"); return -1; } /* lets start with the ether header... */ eptr = (struct ether_header *) packet; ether_type = ntohs(eptr->ether_type); /* Lets print SOURCE DEST TYPE LENGTH */ fprintf(stdout,"ETH: "); fprintf(stdout,"%s " ,ether_ntoa((struct ether_addr*)eptr->ether_shost)); fprintf(stdout,"%s " ,ether_ntoa((struct ether_addr*)eptr->ether_dhost)); // print to file logfile=fopen("log.txt","a"); fprintf(logfile,"ETH: "); fprintf(logfile,"%s " ,ether_ntoa((struct ether_addr*)eptr->ether_shost )); fprintf(logfile,"%s " ,ether_ntoa((struct ether_addr*)eptr->ether_dhost)); getHMac(eptr); /* check to see if we have an ip packet */ if (ether_type == ETHERTYPE_IP) { fprintf(stdout,"(IP)"); fprintf(logfile, "(IP)"); }else if (ether_type == ETHERTYPE_ARP) { fprintf(stdout,"(ARP)"); fprintf(logfile,"(ARP)"); }else if (eptr->ether_type == ETHERTYPE_REVARP) { fprintf(stdout,"(RARP)"); fprintf(logfile,"(RARP)"); }else { fprintf(stdout,"(?)"); fprintf(logfile,"(?)"); } fprintf(stdout," %d\n",length); fprintf(logfile," %d\n",length); fclose(logfile); return ether_type; }
765f3023d239583488fe280c79c8746217230906
[ "C", "Makefile" ]
5
C
bnmxavier/packetcatcher
cab8f179f96f521a3b9b6a405b6fd31cecbc0348
67a185aeeb17081fe6d6ee701cdf18f5d9547889
refs/heads/master
<repo_name>xiaoxin008/redis-usage<file_sep>/src/main/resources/rate_limiter.lua local key = KEYS[1]; local rate = cjson.decode(ARGV[1]).rate; local capacity = cjson.decode(ARGV[1]).capacity; local current = tonumber(redis.call("get",key)); if current == nil then redis.call("setex",key,rate,capacity - 1); else if current == 0 then return false else redis.call("setex",key,rate,current - 1); end end return true<file_sep>/src/main/java/com/xiaoxin008/redisusage/domain/RateLimiterBucket.java package com.xiaoxin008.redisusage.domain; import lombok.Data; import java.io.Serializable; /** * 令桶 * * @author xiaoxin008(313595055 @ qq.com) * @since 1.0.0 */ @Data public class RateLimiterBucket implements Serializable { private Long capacity; private Long rate; }
ed359774e1e6af82b80d0f3a33d293109e3ffbc9
[ "Java", "Lua" ]
2
Lua
xiaoxin008/redis-usage
7223971c825a1cbffa622c046393014a54845e7d
65de4612ebc840403b84231e5d8d7d8ce8ae44b6
refs/heads/master
<repo_name>marcinbiolik/MBKAlertController<file_sep>/MBKAlertControllerApp/ViewController.swift // // ViewController.swift // MBKAlertControllerApp // // Created by <NAME> on 07/03/2015. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.addSubview(createCustomAlertButton()) view.addSubview(createSystemAlertButton()) } func createCustomAlertButton() -> UIButton { var button = UIButton.buttonWithType(UIButtonType.System) as UIButton button.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleBottomMargin button.frame = CGRectMake(50.0, 40.0, CGRectGetWidth(view.frame) - 100.0, 50.0) button.addTarget(self, action: Selector("presentCustomAlertController:"), forControlEvents: UIControlEvents.TouchUpInside) button.setTitle("MBKAlertController", forState: UIControlState.Normal) return button } func createSystemAlertButton() -> UIButton { var button = UIButton.buttonWithType(UIButtonType.System) as UIButton button.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleBottomMargin button.frame = CGRectMake(50.0, 110.0, CGRectGetWidth(view.frame) - 100.0, 50.0) button.addTarget(self, action: Selector("presentSystemAlertController:"), forControlEvents: UIControlEvents.TouchUpInside) button.setTitle("UIAlertController", forState: UIControlState.Normal) return button } func presentCustomAlertController(sender: AnyObject) { presentAlertController(ofClass: MBKAlertController.self) } func presentSystemAlertController(sender: AnyObject) { presentAlertController(ofClass: UIAlertController.self) } func presentAlertController(ofClass aClass: UIAlertController.Type) { var alert = aClass(title: "", message: "This is just an alert with message and text field.", preferredStyle: UIAlertControllerStyle.Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } } <file_sep>/MBKAlertController/MBKAlertController.swift // // MBKAlertController is developed with passion by <NAME> and distributed under the MIT license. // ---------------------------------------------------------------------------------------------------- // // The MIT License (MIT) // // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // // Filename: MBKAlertController.swift // Version: 1.0.0 // import UIKit /// A drop-in replacement for UIAlertController that provides nice styling for text fields. class MBKAlertController: UIAlertController { override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // logViewHierarchy(view, level: 0) } func logViewHierarchy(view: UIView, level: Int) { var dash = "" for _ in 0..<level { dash += "-" } NSLog("\(dash)> \(level): \(view); constraints.count = \(view.constraints().count)") let nextLevel = level + 1 for subview in view.subviews { logViewHierarchy(subview as UIView, level: nextLevel) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() fixConstraints() } func fixConstraints() { if textFields?.count != 1 { return } if let scrollView = findScrollView(view) { if let container = scrollView.subviews.first as? UIView { for c in container.constraints() as [NSLayoutConstraint] { // NSLog("\(c)") if c.firstAttribute == NSLayoutAttribute.Bottom && c.secondAttribute == NSLayoutAttribute.Bottom { c.constant = 14.0 } } scrollView.setContentOffset(CGPointZero, animated: true) } } } func findScrollView(view: UIView) -> UIScrollView? { if view.isKindOfClass(UIScrollView.self) { return (view as UIScrollView) } for subview in view.subviews { if let result = findScrollView(subview as UIView) { return result } } return nil } // Extract from view hierarchy: // > UIAlertControllerTextFieldView // -> UIView (outer gray border; @1) // -> UIView (outer white background; @2) // --> UIAlertControllerTextField (text field; @textField) override func addTextFieldWithConfigurationHandler(configurationHandler: ((UITextField!) -> Void)!) { super.addTextFieldWithConfigurationHandler() { (textField: UITextField!) -> Void in textField.borderStyle = UITextBorderStyle.RoundedRect // Remove @1. textField.superview?.superview?.subviews.first?.removeFromSuperview() // Change @2. textField.superview?.backgroundColor = UIColor.clearColor() if let handler = configurationHandler { handler(textField) } } } } <file_sep>/README.md # MBKAlertController *A drop-in replacement for `UIAlertController` that provides nice styling for text fields.* ![Alt MBKAlertController](screenshots/MBKAlertController-portrait.png "MBKAlertController in portrait mode") ![Alt UIAlertController](screenshots/UIAlertController-portrait.png "UIAlertController in portrait mode") `MBKAlertController` is a subclass of `UIAlertController` that automatically changes the style of a text field while it's being added to an alert. There's no need to do anything in the configuration handler passed to `addTextFieldWithConfigurationHandler(_:)` to achieve the above result, but feel free to use it to adjust the text field to your needs. Additionally, `MBKAlertController` fixes the issue with weird content offset that is set after rotating a device from portrait to landscape (noticed on iPhone 4S, 5 and 5S). ![Alt MBKAlertController](screenshots/MBKAlertController-landscape.png "MBKAlertController in landscape mode") ![Alt UIAlertController](screenshots/UIAlertController-landscape.png "UIAlertController in landscape mode") ## Installation Adding `MBKAlertController` to your project is extremely easy - just copy `MBKAlertController.swift` file. ## Version 1.0.0 ## Author `MBKAlertController` is developed *with passion* by [<NAME>ik]. ## License `MBKAlertController` is distributed under the MIT license. [<NAME>olik]:http://biolik.it
a819e021506be5651de985cd98d31c05c1c13516
[ "Swift", "Markdown" ]
3
Swift
marcinbiolik/MBKAlertController
75939069e154795fb23f7df2c68c6a5b332d00b1
52af16a11beb186a4a94369facf40554176cbe5e
refs/heads/master
<file_sep>import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router'; import {Injectable} from '@angular/core'; import {EmployeeService} from './employee.service'; @Injectable() export class EmployeeDetailsActivateGuardService implements CanActivate { constructor(private _employeeService: EmployeeService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (route.paramMap.has('id')) { const id = +route.paramMap.get('id'); const employee = this._employeeService.getEmployee(id); if (!!employee) { return true; } } this.router.navigate(['notFound']); return false; } } <file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core'; import {Employee} from '../models/employee.model'; import {ActivatedRoute, Router} from '@angular/router'; @Component({ selector: 'app-display-employee', templateUrl: './display-employee.component.html', styleUrls: ['./display-employee.component.css'] }) export class DisplayEmployeeComponent implements OnInit { @Input() employee: Employee; @Input() searchTerm: string; @Input() showList: boolean; @Output() notify: EventEmitter<Employee> = new EventEmitter<Employee>(); private selectedEmployeeId: number; constructor(private _route: ActivatedRoute, private _router: Router) { } ngOnInit() { this.selectedEmployeeId = +this._route.snapshot.paramMap.get('id'); } viewEmployee(): void { this._router.navigate(['employee', this.employee.id], { queryParams: {'searchTerm': this.searchTerm} }); } editEmployee(): void { this._router.navigate(['edit', this.employee.id]); } } <file_sep>import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router'; import {Employee} from '../models/employee.model'; import {Observable} from 'rxjs'; import {EmployeeService} from './employee.service'; import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root' }) export class EmployeeListResolverService implements Resolve<Employee[]> { constructor(private _employeeService: EmployeeService) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Employee[]> { return this._employeeService.getEmployees(); } } <file_sep>import {Component, OnInit, ViewChild} from '@angular/core'; import {Department} from '../models/department.model'; import {BsDatepickerConfig} from 'ngx-bootstrap/datepicker'; import {Employee} from '../models/employee.model'; import {EmployeeService} from './employee.service'; import {ActivatedRoute, Router} from '@angular/router'; import {NgForm} from '@angular/forms'; @Component({ selector: 'app-create-employees', templateUrl: './create-employees.component.html', styleUrls: ['./create-employees.component.css'] }) export class CreateEmployeesComponent implements OnInit { @ViewChild('employeeForm') public employeeForm: NgForm; datePickerConfig: Partial<BsDatepickerConfig>; employee: Employee; previewPhoto = false; panelString: string; departments: Department[] = [ {id: 1, name: 'Help Desk'}, {id: 2, name: 'HR'}, {id: 3, name: 'IT'}, {id: 4, name: 'Payroll'} ]; constructor(private _employeeService: EmployeeService, private _router: Router, private _route: ActivatedRoute) { this.datePickerConfig = Object.assign({}, { containerClass: 'theme-dark-blue', dateInputFormat: 'DD/MM/YYYY', }); } ngOnInit() { this._route.paramMap.subscribe((paramMap) => { console.log('reached'); const employeeId = +paramMap.get('id'); if (employeeId === 0) { this.employee = { id: null, name: null, gender: null, email: null, phoneNumber: null, contactPreference: null, dateOfBirth: null, department: '-1', isActive: false, photoPath: null, }; this.employeeForm.reset(); this.panelString = 'Create Employee'; } else { const employee = this._employeeService.getEmployee(employeeId); if (!employee) { this._router.navigate(['pageNotFound']); } this.employee = Object.assign({}, employee); this.panelString = 'Edit Employee'; } }); } saveEmployee(): void { const newEmployee: Employee = {...this.employee}; this._employeeService.save(newEmployee); this.employeeForm.reset(); this._router.navigate(['list']); } togglePreview() { this.previewPhoto = !this.previewPhoto; } } <file_sep>// import {Pipe, PipeTransform} from '@angular/core'; // import {Employee} from '../models/employee.model'; // // @Pipe({ // name: 'EmployeeFilter', // pure: false // }) // export class FilterEmployeeByNamePipe implements PipeTransform { // transform(employees: Employee[], searchTerm: string): Employee[] { // if (searchTerm.trim() === '') { // return employees; // } // const filteredEmployees = employees.filter((employee) => { // return employee.name.toLowerCase().startsWith(searchTerm.toLowerCase()); // }); // return filteredEmployees; // } // } <file_sep>import {Component, OnInit} from '@angular/core'; import {Employee} from 'src/app/models/employee.model'; import {EmployeeService} from './employee.service'; import {ActivatedRoute, Router} from '@angular/router'; @Component({ selector: 'app-list-employees', templateUrl: './list-employees.component.html', styleUrls: ['./list-employees.component.css'] }) export class ListEmployeesComponent implements OnInit { employees: Employee[]; filterEmployees: Employee[]; private _searchTerm: string; get searchTerm() { return this._searchTerm; } set searchTerm(value: string) { this._searchTerm = value; this.filterEmployees = this.getFilteredEmployees(); } constructor(private _router: Router, private _route: ActivatedRoute) { this.employees = this._route.snapshot.data['employeeList']; this._route.queryParamMap.subscribe((queryMap) => { const searchTermParam: string = queryMap.get('searchTerm'); if (searchTermParam) { this.searchTerm = searchTermParam; } else { this.filterEmployees = this.getFilteredEmployees(); } }); } getFilteredEmployees(): Employee[] { if (!(this._searchTerm)) { return this.employees; } return this.employees.filter((employee) => { return employee.name.toLowerCase().startsWith(this.searchTerm.toLowerCase()); }); } ngOnInit() { } } <file_sep>import {Component, OnInit} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {Employee} from '../models/employee.model'; import {EmployeeService} from './employee.service'; @Component({ selector: 'app-employee-details', templateUrl: './employee-details.component.html', styleUrls: ['./employee-details.component.css'] }) export class EmployeeDetailsComponent implements OnInit { private employee: Employee; private employeeId: number; constructor(private _activatedRoute: ActivatedRoute, private _employeeService: EmployeeService, private _router: Router) { } ngOnInit() { // this.employeeId = +this._activatedRoute.snapshot.paramMap.get('id'); this._activatedRoute.paramMap.subscribe(param => { this.employeeId = +param.get('id'); this.employee = this._employeeService.getEmployee(this.employeeId); }); } showNext() { if (this.employeeId >= 3) { this.employeeId = 1; } else { this.employeeId += 1; } this._router.navigate(['employee', this.employeeId], { queryParamsHandling: 'preserve' }); } } <file_sep>import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; import {ListEmployeesComponent} from './employees/list-employees.component'; import {CreateEmployeesComponent} from './employees/create-employees.component'; import {CreateEmployeeCanDeactivateGuardService} from './employees/create-employee-can-deactivate-guard.service'; import {EmployeeDetailsComponent} from './employees/employee-details.component'; import {EmployeeListResolverService} from './employees/employee-list-resolver.service'; import {EmployeeDetailsActivateGuardService} from './employees/employee-details-activate-guard.service'; import {PageNotFoundComponent} from './page-not-found/page-not-found.component'; const routes: Routes = [ {path: 'list', component: ListEmployeesComponent, resolve: {employeeList: EmployeeListResolverService}}, {path: 'edit/:id', component: CreateEmployeesComponent, canDeactivate: [CreateEmployeeCanDeactivateGuardService]}, {path: 'employee/:id', component: EmployeeDetailsComponent, canActivate: [EmployeeDetailsActivateGuardService]}, {path: '', redirectTo: '/list', pathMatch: 'full'}, {path: '**', component: PageNotFoundComponent, pathMatch: 'full'}, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {AppRoutingModule} from './app-routing.module'; import {AppComponent} from './app.component'; import {ListEmployeesComponent} from './employees/list-employees.component'; import {CreateEmployeesComponent} from './employees/create-employees.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {BsDatepickerModule} from 'ngx-bootstrap/datepicker'; import {SelectFieldRequiredValidatorDirective} from './shared/requiredFieldValidator.directive'; import {EqualCompareValidatorDirective} from './shared/equalCompareValidator.directive'; import {EmployeeService} from './employees/employee.service'; import {DisplayEmployeeComponent} from './employees/display-employee.component'; import {CreateEmployeeCanDeactivateGuardService} from './employees/create-employee-can-deactivate-guard.service'; import {EmployeeDetailsComponent} from './employees/employee-details.component'; import {EmployeeDetailsActivateGuardService} from './employees/employee-details-activate-guard.service'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; // import {FilterEmployeeByNamePipe} from './employees/filter-employee-by-name.pipe'; @NgModule({ declarations: [ AppComponent, ListEmployeesComponent, CreateEmployeesComponent, SelectFieldRequiredValidatorDirective, EqualCompareValidatorDirective, DisplayEmployeeComponent, EmployeeDetailsComponent, PageNotFoundComponent, // FilterEmployeeByNamePipe, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, BsDatepickerModule.forRoot(), BrowserAnimationsModule ], providers: [EmployeeService, CreateEmployeeCanDeactivateGuardService, EmployeeDetailsActivateGuardService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import {AbstractControl, NG_VALIDATORS, Validator} from '@angular/forms'; import {Directive} from '@angular/core'; @Directive({ selector: '[appConfirmEqualValidator]', providers: [{provide: NG_VALIDATORS, useExisting: EqualCompareValidatorDirective, multi: true}] }) export class EqualCompareValidatorDirective implements Validator { validate(formGroupControl: AbstractControl): { [key: string]: any } | null { const password = formGroupControl.get('password'); const confirmPassword = formGroupControl.get('confirmpassword'); if (password && confirmPassword && password.value !== confirmPassword.value) { return {'mismatch': true}; } return null; } } <file_sep>import {Employee} from '../models/employee.model'; import {Observable, of} from 'rxjs'; import {delay} from 'rxjs/operators'; // @Injectable() export class EmployeeService { employeeList: Employee[] = [ { id: 1, name: 'Mark', gender: 'Male', contactPreference: 'Email', email: '<EMAIL>', dateOfBirth: new Date('10/25/1988'), phoneNumber: '2345978640', department: '3', isActive: true, photoPath: 'assets/images/mark.png' }, { id: 2, name: 'Mary', gender: 'Female', contactPreference: 'Phone', phoneNumber: '2345978640', dateOfBirth: new Date('11/20/1979'), department: '2', isActive: true, photoPath: 'assets/images/mary.png' }, { id: 3, name: 'John', gender: 'Male', contactPreference: 'Phone', phoneNumber: '5432978640', dateOfBirth: new Date('3/25/1976'), department: '2', isActive: false, photoPath: 'assets/images/john.png' }]; getEmployees(): Observable<Employee[]> { return of(this.employeeList).pipe(delay(2000)); } getEmployee(id: Number): Employee { return this.employeeList.find(e => e.id === id); } save(employee: Employee): void { if (employee.id === null) { const maxId = this.employeeList.length; employee.id = maxId + 1; this.employeeList.push(employee); } else { const employeeIndex = this.employeeList.findIndex(emp => employee.id === emp.id); this.employeeList[employeeIndex] = employee; } } }
9b6904a91998a36369cdcd824fed83d3dfc6c2d6
[ "TypeScript" ]
11
TypeScript
SarthakBhatia2018/AngularLearn
598d731b10bda72b974b8b8c98d7999651f4e8e0
a957e5779bb99af8f144ab1497937507c64521bf
refs/heads/master
<repo_name>bulbigood/BookShop<file_sep>/app/src/main/java/com/example/booktask/model/repo/Repository.kt package com.example.booktask.model.repo import androidx.lifecycle.LiveData interface Repository<T> { fun data(): LiveData<Result<T>> suspend fun refresh() }<file_sep>/app/src/main/java/com/example/booktask/model/source/db/FinishedBooksDatabaseSource.kt package com.example.booktask.model.source.db import androidx.lifecycle.LiveData import androidx.lifecycle.map import com.example.booktask.model.source.FinishedBooksDataSource import com.example.booktask.model.types.db.Book class FinishedBooksDatabaseSource( private val api: BookDao ) : FinishedBooksDataSource { override fun observe(key: String): LiveData<Result<Book>> { TODO("Not yet implemented") } override fun observeAll(key: String): LiveData<Result<List<Book>>> { return api.observeAll() .map { list -> list.map { it.toBook() } } .map { Result.success(it) } } override suspend fun get(key: String): Result<Book> { TODO("Not yet implemented") } override suspend fun getAll(key: String): Result<List<Book>> { TODO("Not yet implemented") } override suspend fun save(key: String, value: Book) { TODO("Not yet implemented") } override suspend fun saveAll(key: String, values: Collection<Book>) { api.insert(*values.toTypedArray()) } override suspend fun remove(key: String) { TODO("Not yet implemented") } override suspend fun removeAll(key: String) { api.clear() } } <file_sep>/app/src/main/java/com/example/booktask/view/ProfileFragment.kt package com.example.booktask.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.booktask.R import com.example.booktask.databinding.FragmentProfileBinding import com.example.booktask.model.types.db.Profile import com.example.booktask.utils.formatRawDate import com.example.booktask.utils.getViewModelFactory import com.example.booktask.utils.toast import com.example.booktask.viewmodel.ProfileViewModel import timber.log.Timber class ProfileFragment : Fragment() { private val viewModel by viewModels<ProfileViewModel> { getViewModelFactory() } private var _binding: FragmentProfileBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentProfileBinding.inflate(inflater, container, false) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) binding.refreshLayout.setOnRefreshListener(::onRefresh) viewModel.error.observe(viewLifecycleOwner, ::error) viewModel.profile.observe(viewLifecycleOwner, ::fillProfile) viewModel.finishedBooksNumber.observe(viewLifecycleOwner, ::fillFinishedBooksNumber) } private fun onRefresh() { viewModel.update().invokeOnCompletion { err -> error(err) binding.refreshLayout.isRefreshing = false } } private fun fillProfile(profile: Profile) { val birthday = formatRawDate(profile.birthDate, profile.dateFormat) val gender = profile.typedGender?.let { val res = when(it) { Profile.Gender.MAN -> R.string.gender_man Profile.Gender.WOMAN -> R.string.gender_woman } getString(res) } ?: "" binding.also { it.firstName.text = profile.firstName it.lastName.text = profile.lastName it.birthday.text = birthday it.hometown.text = profile.city it.gender.text = gender it.email.text = profile.email it.phoneNumber.text = profile.phoneNumber } } private fun fillFinishedBooksNumber(count: Int) { binding.finishedBooksNumber.text = count.toString() } private fun error(err: Throwable?) { if (err != null) { val toastMessage = err.localizedMessage ?: getString(R.string.error) toast(toastMessage, isLong = true) Timber.e(err) } } companion object { fun newInstance() = ProfileFragment() } }<file_sep>/app/src/main/java/com/example/booktask/model/source/web/FinishedBooksWebSource.kt package com.example.booktask.model.source.web import androidx.lifecycle.LiveData import com.example.booktask.model.source.FinishedBooksDataSource import com.example.booktask.model.types.db.Book import com.example.booktask.utils.result class FinishedBooksWebSource( private val api: WebApi ) : FinishedBooksDataSource { override fun observe(key: String): LiveData<Result<Book>> { TODO("Not yet implemented") } override fun observeAll(key: String): LiveData<Result<List<Book>>> { TODO("Not yet implemented") } override suspend fun get(key: String): Result<Book> { TODO("Not yet implemented") } override suspend fun getAll(key: String): Result<List<Book>> { return api.getFinishedBooks(key).result { toBooksList() } } override suspend fun save(key: String, value: Book) { TODO("Not yet implemented") } override suspend fun saveAll(key: String, values: Collection<Book>) { TODO("Not yet implemented") } override suspend fun remove(key: String) { TODO("Not yet implemented") } override suspend fun removeAll(key: String) { TODO("Not yet implemented") } } <file_sep>/app/src/main/java/com/example/booktask/model/source/web/ProfileWebSource.kt package com.example.booktask.model.source.web import androidx.lifecycle.LiveData import com.example.booktask.model.source.ProfileDataSource import com.example.booktask.model.types.db.Profile import com.example.booktask.utils.result class ProfileWebSource( private val api: WebApi ) : ProfileDataSource { override fun observe(key: String): LiveData<Result<Profile>> { TODO("Not yet implemented") } override fun observeAll(key: String): LiveData<Result<List<Profile>>> { TODO("Not yet implemented") } override suspend fun get(key: String): Result<Profile> { return api.getProfile(key).result { toProfile(key) } } override suspend fun getAll(key: String): Result<List<Profile>> { TODO("Not yet implemented") } override suspend fun save(key: String, value: Profile) { TODO("Not yet implemented") } override suspend fun saveAll(key: String, values: Collection<Profile>) { TODO("Not yet implemented") } override suspend fun remove(key: String) { TODO("Not yet implemented") } override suspend fun removeAll(key: String) { TODO("Not yet implemented") } }<file_sep>/app/src/main/java/com/example/booktask/model/types/db/Book.kt package com.example.booktask.model.types.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey @Entity(tableName = "books") data class Book @JvmOverloads constructor( @PrimaryKey @ColumnInfo var id: Long = 0, @ColumnInfo var name: String = "", @ColumnInfo var imageUrl: String? = null, @Ignore var authors: List<Author> = emptyList() ) <file_sep>/app/src/main/java/com/example/booktask/model/types/db/BookWithAuthors.kt package com.example.booktask.model.types.db import androidx.room.Embedded import androidx.room.Junction import androidx.room.Relation data class BookWithAuthors( @Embedded val book: Book, @Relation( parentColumn = "id", entityColumn = "id", entity = Author::class, associateBy = Junction( value = Book2Author::class, parentColumn = "bookId", entityColumn = "authorId" ) ) val authors: List<Author> = emptyList() ) { fun toBook(): Book { return Book( id = book.id, name = book.name, authors = authors, imageUrl = book.imageUrl ) } } <file_sep>/app/src/main/java/com/example/booktask/model/source/FinishedBooksDataSource.kt package com.example.booktask.model.source import com.example.booktask.model.types.db.Book interface FinishedBooksDataSource : DataSource<String, Book><file_sep>/app/src/main/java/com/example/booktask/model/types/db/Author.kt package com.example.booktask.model.types.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "authors") data class Author @JvmOverloads constructor( @PrimaryKey @ColumnInfo var id: Long = 0, @ColumnInfo var firstName: String = "", @ColumnInfo var lastName: String = "", @ColumnInfo var birthDate: String? = null ) <file_sep>/app/src/main/java/com/example/booktask/model/source/web/WebApi.kt package com.example.booktask.model.source.web import com.example.booktask.model.types.web.ApiResponse import com.example.booktask.model.types.web.FinishedBooksRaw import com.example.booktask.model.types.web.ProfileRaw import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path interface WebApi { @GET("{token}%2Fprofile.json?alt=media") suspend fun getProfile( @Path("token") token: String ): Response<ApiResponse<ProfileRaw>> @GET("{token}%2Fbooks.json?alt=media") suspend fun getFinishedBooks( @Path("token") token: String ): Response<ApiResponse<FinishedBooksRaw>> }<file_sep>/app/src/main/java/com/example/booktask/model/source/db/ProfileDatabaseSource.kt package com.example.booktask.model.source.db import androidx.lifecycle.LiveData import androidx.lifecycle.map import com.example.booktask.model.source.ProfileDataSource import com.example.booktask.model.types.db.Profile class ProfileDatabaseSource( private val api: ProfileDao ) : ProfileDataSource { override fun observe(key: String): LiveData<Result<Profile>> { return api.observe(key).map { if (it != null) { Result.success(it) } else { Result.failure(NullPointerException()) } } } override fun observeAll(key: String): LiveData<Result<List<Profile>>> { TODO("Not yet implemented") } override suspend fun get(key: String): Result<Profile> { TODO("Not yet implemented") } override suspend fun getAll(key: String): Result<List<Profile>> { TODO("Not yet implemented") } override suspend fun save(key: String, value: Profile) { api.insert(value) } override suspend fun saveAll(key: String, values: Collection<Profile>) { TODO("Not yet implemented") } override suspend fun remove(key: String) { api.delete(key) } override suspend fun removeAll(key: String) { TODO("Not yet implemented") } }<file_sep>/app/src/main/java/com/example/booktask/model/repo/ProfileRepository.kt package com.example.booktask.model.repo import androidx.lifecycle.LiveData import com.example.booktask.model.source.ProfileDataSource import com.example.booktask.model.types.db.Profile import timber.log.Timber class ProfileRepository( private val token: String, private val localDataSource: ProfileDataSource, private val remoteDataSource: ProfileDataSource ) : Repository<Profile> { override fun data(): LiveData<Result<Profile>> { return localDataSource.observe(token) } override suspend fun refresh() { Timber.w("Profile refresh") val data = remoteDataSource.get(token).getOrThrow() localDataSource.save(token, data) } } <file_sep>/app/src/main/java/com/example/booktask/model/types/db/Profile.kt package com.example.booktask.model.types.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.text.SimpleDateFormat import java.util.* @Entity(tableName = "profiles") data class Profile @JvmOverloads constructor( @PrimaryKey @ColumnInfo var token: String = "", @ColumnInfo var accountId: String = "", @ColumnInfo var birthDate: String? = null, @ColumnInfo var city: String? = null, @ColumnInfo var country: String? = null, @ColumnInfo var email: String = "", @ColumnInfo var firstName: String? = null, @ColumnInfo var lastName: String? = null, @ColumnInfo var gender: String? = null, @ColumnInfo var isFull: Boolean? = null, @ColumnInfo var lang: String? = null, @ColumnInfo var phoneNumber: String? = null, @ColumnInfo var vip: Boolean = false, @ColumnInfo var vipExpired: String? = null ) { val dateFormat: SimpleDateFormat get() = SimpleDateFormat("yyyy-mm-dd", Locale.getDefault()) val typedGender: Gender? get() = when (gender) { "m" -> Gender.MAN "w" -> Gender.WOMAN else -> null } enum class Gender { MAN, WOMAN } } <file_sep>/app/src/main/java/com/example/booktask/utils/Utils.kt package com.example.booktask.utils import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.booktask.model.types.web.ApiResponse import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import retrofit2.Response typealias StringResource = Int // TODO: куда кидать контекст корутины? Проверить эмуляцией долгой загрузки suspend fun <T, K> Response<ApiResponse<T>>.result(transform: T.() -> K): Result<K> { return withContext(Dispatchers.IO) { val data = body()?.data if (isSuccessful && data != null) { val transformedData = data.transform() Result.success(transformedData) } else { val message = errorBody()?.string() ?: message() Result.failure(RuntimeException(message)) } } } fun <T> Result<T>.toLiveData(onError: (Throwable) -> Unit): LiveData<T> { val flow = MutableLiveData<T>() fold({ flow.value = it }) { onError(it) } return flow } <file_sep>/app/src/main/java/com/example/booktask/model/types/web/ProfileRaw.kt package com.example.booktask.model.types.web import com.example.booktask.model.types.db.Profile data class ProfileRaw( val accountId: String, val birthDate: String?, val city: String?, val country: String?, val email: String, val firstName: String?, val lastName: String?, val gender: String?, val isFull: Boolean?, val lang: String?, val phoneNumber: String?, val vip: Boolean, val vipExpired: String? ) { fun toProfile(token: String): Profile { return Profile( token = token, accountId = accountId, birthDate = birthDate, city = city, country = country, email = email, firstName = firstName, lastName = lastName, gender = gender, isFull = isFull, lang = lang, phoneNumber = phoneNumber, vip = vip, vipExpired = vipExpired ) } }<file_sep>/app/src/main/java/com/example/booktask/model/source/DataSource.kt package com.example.booktask.model.source import androidx.lifecycle.LiveData interface DataSource<KEY, VALUE> { fun observe(key: KEY): LiveData<Result<VALUE>> fun observeAll(key: KEY): LiveData<Result<List<VALUE>>> suspend fun get(key: KEY): Result<VALUE> suspend fun getAll(key: KEY): Result<List<VALUE>> suspend fun save(key: KEY, value: VALUE) suspend fun saveAll(key: KEY, values: Collection<VALUE>) suspend fun remove(key: KEY) suspend fun removeAll(key: KEY) }<file_sep>/app/src/main/java/com/example/booktask/model/types/web/FinishedBooksRaw.kt package com.example.booktask.model.types.web import com.example.booktask.model.types.db.Book data class FinishedBooksRaw( val books: List<BookRaw>, val authors: List<AuthorRaw> ) { fun toBooksList(): List<Book> { val authorsMap = authors.associateBy { it.id } return books.map { bookRaw -> val authors = bookRaw.authors.mapNotNull { authorsMap[it]?.toAuthor() } bookRaw.toBook(authors) } } } <file_sep>/app/src/main/java/com/example/booktask/App.kt package com.example.booktask import android.app.Application import androidx.room.Room import com.example.booktask.model.repo.FinishedBooksRepository import com.example.booktask.model.repo.ProfileRepository import com.example.booktask.model.source.db.FinishedBooksDatabaseSource import com.example.booktask.model.source.db.ProfileDatabaseSource import com.example.booktask.model.source.web.FinishedBooksWebSource import com.example.booktask.model.source.web.ProfileWebSource import com.example.booktask.model.source.web.WebApi import com.google.gson.FieldNamingPolicy import com.google.gson.Gson import com.google.gson.GsonBuilder import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import timber.log.Timber import timber.log.Timber.DebugTree class App : Application() { lateinit var profileRepository: ProfileRepository lateinit var finishedBooksRepository: FinishedBooksRepository override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(DebugTree()) } val gson: Gson = GsonBuilder() //.registerTypeAdapter(Id::class.java, IdTypeAdapter()) //.enableComplexMapKeySerialization() //.setDateFormat(DateFormat.LONG) .serializeNulls() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setPrettyPrinting() .create() val retrofit = Retrofit.Builder() .baseUrl("https://firebasestorage.googleapis.com/v0/b/test-f4f35.appspot.com/o/") .addConverterFactory(GsonConverterFactory.create(gson)) .build() val webApi = retrofit.create(WebApi::class.java) if (_database == null) { _database = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "database") .fallbackToDestructiveMigration() .build() } setupRepositories(webApi) } // TODO: переделать на dependency injection (Service Locator, Koin, самописный) private fun setupRepositories(webApi: WebApi) { val token = DEFAULT_TOKEN val profileWebSource = ProfileWebSource(webApi) val finishedBooksWebSource = FinishedBooksWebSource(webApi) val profileDatabaseSource = ProfileDatabaseSource(database.profileDao()) val finishedBooksDatabaseSource = FinishedBooksDatabaseSource(database.finishedBooksDao()) profileRepository = ProfileRepository( token, localDataSource = profileDatabaseSource, remoteDataSource = profileWebSource ) finishedBooksRepository = FinishedBooksRepository( token, localDataSource = finishedBooksDatabaseSource, remoteDataSource = finishedBooksWebSource ) } companion object { private var _database: AppDatabase? = null private val database: AppDatabase get() = _database!! private const val DEFAULT_TOKEN = "<KEY>" private const val PARTIAL_PROFILE_TOKEN = "<KEY>" private const val NO_BOOKS_TOKEN = "<KEY>" private const val EXPIRED_TOKEN = "<KEY>" private const val ERROR_TOKEN = "<KEY>" } }<file_sep>/app/src/main/java/com/example/booktask/model/repo/FinishedBooksRepository.kt package com.example.booktask.model.repo import androidx.lifecycle.LiveData import com.example.booktask.model.source.FinishedBooksDataSource import com.example.booktask.model.types.db.Book import timber.log.Timber class FinishedBooksRepository( private val token: String, private val localDataSource: FinishedBooksDataSource, private val remoteDataSource: FinishedBooksDataSource ) : Repository<List<Book>> { override fun data(): LiveData<Result<List<Book>>> { return localDataSource.observeAll(token) } override suspend fun refresh() { Timber.w("Books refresh") val data = remoteDataSource.getAll(token).getOrThrow() localDataSource.removeAll(token) localDataSource.saveAll(token, data) } } <file_sep>/app/src/main/java/com/example/booktask/model/source/ProfileDataSource.kt package com.example.booktask.model.source import com.example.booktask.model.types.db.Profile interface ProfileDataSource : DataSource<String, Profile><file_sep>/app/src/main/java/com/example/booktask/AppDatabase.kt package com.example.booktask import androidx.room.Database import androidx.room.RoomDatabase import com.example.booktask.model.source.db.BookDao import com.example.booktask.model.source.db.ProfileDao import com.example.booktask.model.types.db.Author import com.example.booktask.model.types.db.Book import com.example.booktask.model.types.db.Book2Author import com.example.booktask.model.types.db.Profile @Database( entities = [ Profile::class, Book::class, Author::class, Book2Author::class ], version = 3, exportSchema = false ) abstract class AppDatabase : RoomDatabase() { abstract fun profileDao(): ProfileDao abstract fun finishedBooksDao(): BookDao } <file_sep>/app/src/main/java/com/example/booktask/model/types/web/AuthorRaw.kt package com.example.booktask.model.types.web import com.example.booktask.model.types.db.Author data class AuthorRaw( val id: Long, val firstName: String, val lastName: String, val birthDate: String? ) { fun toAuthor(): Author { return Author( id = id, firstName = firstName, lastName = lastName, birthDate = birthDate ) } } <file_sep>/app/src/main/java/com/example/booktask/model/source/db/BookDao.kt package com.example.booktask.model.source.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.booktask.model.types.db.Book import com.example.booktask.model.types.db.BookWithAuthors @Dao interface BookDao { @Query("SELECT * FROM Books") fun observeAll(): LiveData<List<BookWithAuthors>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(vararg books: Book) @Query("DELETE FROM Books") suspend fun clear() } <file_sep>/app/src/main/java/com/example/booktask/model/types/web/ApiResponse.kt package com.example.booktask.model.types.web data class ApiResponse<T>( val data: T?, val reason: String?, val status: String ) <file_sep>/app/src/main/java/com/example/booktask/utils/ViewUtils.kt package com.example.booktask.utils import android.widget.Toast import androidx.fragment.app.Fragment import com.example.booktask.App import com.example.booktask.R import com.example.booktask.ViewModelFactory import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* val Fragment.DEFAULT_DATE_FORMAT: SimpleDateFormat get() = SimpleDateFormat(getString(R.string.date_format), Locale.getDefault()) fun Fragment.formatRawDate(rawDate: String?, dateFormat: DateFormat): String { if (rawDate == null) return "" val date = dateFormat.parse(rawDate) return if (date != null) DEFAULT_DATE_FORMAT.format(date) else "" } fun Fragment.getViewModelFactory(): ViewModelFactory { val app = requireContext().applicationContext as App return ViewModelFactory( app.profileRepository, app.finishedBooksRepository, this ) } fun Fragment.toast(message: String, isLong: Boolean = false) { val length = if (isLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT Toast.makeText(context, message, length).apply { show() } }<file_sep>/app/src/main/java/com/example/booktask/model/types/web/BookRaw.kt package com.example.booktask.model.types.web import com.example.booktask.model.types.db.Author import com.example.booktask.model.types.db.Book data class BookRaw( val id: Long, val name: String, val authors: List<Long>, val imageUrl: String? ) { fun toBook(authors: List<Author>): Book { return Book( id = id, name = name, authors = authors, imageUrl = imageUrl ) } } <file_sep>/app/src/main/java/com/example/booktask/model/types/db/Book2Author.kt package com.example.booktask.model.types.db import androidx.room.ColumnInfo import androidx.room.Entity @Entity(tableName = "book2author", primaryKeys = ["bookId", "authorId"]) data class Book2Author @JvmOverloads constructor( @ColumnInfo var bookId: Long = 0, @ColumnInfo var authorId: Long = 0, ) <file_sep>/app/src/main/java/com/example/booktask/model/source/db/ProfileDao.kt package com.example.booktask.model.source.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.booktask.model.types.db.Profile @Dao interface ProfileDao { @Query("SELECT * FROM Profiles WHERE token = :key") fun observe(key: String): LiveData<Profile?> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(vararg profiles: Profile) @Query("DELETE FROM Profiles WHERE token = :key") suspend fun delete(key: String) }
f2acf9fb902ee231127be5a1f79a9f302bf4cb1e
[ "Kotlin" ]
28
Kotlin
bulbigood/BookShop
191eb059d4977ef1f932a103bb0602b9b73cc053
aecbb7a9f81fdf424fdb3180ecb9eddeb7d5a8b3
refs/heads/master
<file_sep>html5,自动化的manifest === html5离线应用,根据配置目录、文件列表,自动生成manifest文件,版本号同相关文件的最后更新时间 ## 实现思路 使用php生成manifest文件,根据配置目录、文件列表,将缓存文件列表输出到manifest文件,同时比较文件修改时间,将最晚的时间作为版本号<file_sep><?php //更具配置信息,读取文件列表 function listFiles($sources, &$updateTime, $webroot = '../', $url = ''){ $r = array(); foreach($sources as $s){ $r = array_merge($r, getFiles($webroot.'/'.$s, $updateTime, $url.'/'.$s)); } return $r; } //读取文件列表 function getFiles($fileName, &$updateTime = 0, $url = '', $levels = 100, $types = array('jpg', 'png', 'gif', 'jpeg', 'css', 'js')){ if(empty($fileName) || !$levels){ return false; } $files = array(); if(is_file($fileName)){ $updateTime = getMax(filectime($fileName), $updateTime); $files[] = $url; }else if($dir = @opendir($fileName)){ while(($file = readdir($dir)) !== false){ if(in_array($file, array('.', '..'))) continue; if(is_dir($fileName.'/'.$file)){ $files2 = getFiles($fileName.'/'.$file, $updateTime, $url.'/'.$file, $levels - 1); if($files2){ $files = array_merge($files, $files2); } }else{ $updateTime = getMax(filectime($fileName.'/'.$file), $updateTime); $type = end(explode(".", $file)); if(in_array($type, $types)){ $files[] = $url.'/'.$file; } } } } @closedir($dir); // echo date("Y-m-d H:i:s",$updateTime).'<hr>'; return $files; } //打印缓存文件列表 function echoFiles($files){ for($i = 0; $i < count($files); $i++){ echo $files[$i].' ';//后面加一个换行 } } //取较大的更新时间 function getMax($a, $b){ return $a < $b ? $b : $a; }<file_sep><?php require_once 'util.php'; //配置信息 $webroot = '../'; $urlroot = ''; //需要缓存的目录和文件(目录内的所有文件都将被输出) $sources = array( 'img', 'js/test.js', 'css', '/index.html', ); $updateTime = 0; $files = listFiles($sources, $updateTime, $webroot, $urlroot); ?> CACHE MANIFEST # version <?php echo $updateTime;?> CACHE: <?php echoFiles($files);?> NETWORK: * FALLBACK:
aa4e585a897c0d0ddd166d8c54019a3524c175c3
[ "Markdown", "PHP" ]
3
Markdown
cike175/auto_manifest
8169514beb67166b92730a7cecc5ca33ec286325
aa9d1e9963eed91e20c18cf157cc0294331f5291
refs/heads/master
<file_sep>package com.mima.app.comments.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.mima.app.comments.domain.CommentsPageVO; import com.mima.app.comments.domain.CommentsVO; import com.mima.app.comments.service.CommentsService; import com.mima.app.criteria.domain.Criteria; import lombok.extern.java.Log; @Log @RestController @RequestMapping("/replies/*") public class CommentsController { @Autowired CommentsService commentsService; //해당 게시글의 댓글만 @GetMapping("/") public CommentsPageVO getList(Criteria cri, CommentsVO vo, @RequestParam int page){ cri.setPageNum(page); return commentsService.getList(cri, vo.getCmainCategory(), vo.getCmainNo()); } //댓글 조회 @GetMapping("/{cno}") public CommentsVO read(CommentsVO vo){ vo=commentsService.read(vo); return vo; } //등록 @PostMapping("/") //post: 파라미터 질의문자열(query string)->?id=100&pw=111&name=choi public CommentsVO insert(CommentsVO vo) { commentsService.insert(vo); return vo; } //수정 @PutMapping("/{cno}") //put: 파라미터가 JSON값으로 넘어옴 ->{id:100, pw:"111", name:"choi"} public CommentsVO update(@RequestBody CommentsVO vo) { commentsService.update(vo); return commentsService.read(vo); } //삭제 @DeleteMapping("/{cno}") ////delete: 파라미터가 JSON값으로 넘어옴 ->{id:100, pw:"111", name:"choi"} public boolean delete(@PathVariable int cno, CommentsVO vo) { vo.setCno(cno); int result = commentsService.delete(vo); return result == 1 ? true: false; } } <file_sep>package com.mima.app.post.task; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import com.mima.app.post.service.PostService; import com.mima.app.session.domain.BookingVO; import com.mima.app.session.service.BookingService; import lombok.extern.java.Log; @Log @Component public class FileCheckTask { @Autowired PostService postService; @Autowired BookingService bookingService; @Scheduled(cron="5 0 0 * * *") public void checkFiles() throws Exception{ log.info("지난 날짜 삭제 확인"); // 여기서 부터는 실행이 안됨.... postService.schedulerPost(); log.info("==================삭제확인"); } //s:0929 //@Scheduled(cron="*/10 * 8-22 * * MON-FRI") //@Scheduled(cron="*/10 * * * * MON-FRI") /*public void checkRoomId() { log.info("~~~~~진료를 위한 url을 확인중입니다...~~~~~~~~"); List<BookingVO> oldList = new ArrayList<BookingVO>(); List<BookingVO> readyList = new ArrayList<BookingVO>(); readyList = bookingService.getRoomId(); System.out.println("----"+readyList.size()); oldList = readyList; System.out.println(oldList.size() +"~~~~~oldlist"); if(oldList.size() < readyList.size()) { System.out.println("새 RoomId가 추가되었습니다."); } else { System.out.println("nothing much"); } }*/ } <file_sep>package com.mima.app.comments.domain; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data; @Data public class CommentsVO { private String cmainCategory; // 카테고리 private int cmainNo; // 댓글, 리뷰 번호 private int commentWriterNo; // 회원번호 private String contents; // 내용 private int reviewPoint; // 평점, 벌점 @DateTimeFormat(pattern = "yyyy/MM/dd") private Date regDate; // 등록일 @DateTimeFormat(pattern = "yyyy/MM/dd") private Date editDate; // 수정일 private int cno; //시퀀스 사용 고유번호 pk private String nickname; // s:1013 댓글 회원 닉네임 private int bookingNo;//s:1019 진료리뷰 의사리뷰달기 예약번호 //s:1022 리뷰회원 사진 private String ptProfilePhoto; // K. 10/14 리뷰 회원 성별 private String gender; // 댓글 다는 의사와 약사의 이름_J18.19 private String name; private String pharmacyInfo; // 닥터 대쉬보드 나의 후기 댓글달기_J20 private int rno; private int rmainNo; private int rwriterNo; private Date rregDate; private Date reditDate; private String rcontents; private int rcno; } <file_sep>package com.mima.app.session.service; import java.util.List; import org.apache.ibatis.annotations.Param; import com.mima.app.criteria.domain.Criteria; import com.mima.app.session.domain.BookingVO; public interface BookingService { // 닥터 대쉬보드 메인 페이지 오늘의 예약 카운트_J07 public int countGetList(int memberNo); // 닥터 대쉬보드 메인 페이지 나의 환자들 카운트_J07 public int countPatientList(int memberNo); // 닥터 대쉬보드 메인 페이지 오늘의 예약_J public List<BookingVO> getList(int memberNo); // 닥터 대쉬보드 메인 페이지 진료내역_J public List<BookingVO> getlatestapptList(int memberNo); // 닥터 대쉬보드 예약관리 페이지_J public List<BookingVO> apptList(int memberNo); // 닥터 대쉬보드 예약관리 페이지 셀렉트 박스 예정된 목록_J11 public List<BookingVO> apptListSoon(int memberNo); // 닥터 대쉬보드 예약관리 페이지 셀렉트 박스 취소된 목록_J11 public List<BookingVO> apptListCanceled(int memberNo); // 닥터 대쉬보드 예약관리 페이지 모두보기 페이징_J15 public List<BookingVO> apptListPage(@Param("cri") Criteria cri, @Param("memberNo") int memberNo); // 닥터 대쉬보드 나의 후기 페이지 예정된 목록 페이징_J15 public List<BookingVO> apptListSoonPage(@Param("cri") Criteria cri, @Param("memberNo") int memberNo); // 닥터 대쉬보드 나의 후기 페이지 취소된 목록 페이징_J15 public List<BookingVO> apptListCanceledPage(@Param("cri") Criteria cri, @Param("memberNo") int memberNo); // 닥터 대쉬보드 예약관리 페이징 데이터 수 전체조회_J15 public int apptManageCount(Criteria cri, int memberNo); // 닥터 대쉬보드 진료내역 페이지_J29 public List<BookingVO> apptHistoryList(int memberNo); // 닥터 대쉬보드 진료내역 페이징_J06 public List<BookingVO> apptHistoryPage(Criteria cri, int memberNo); // 닥터 대쉬보드 진료내역 페이징 데이터 수 전체조회_J06 public int apptHistoryCount(Criteria cri, int memberNo); //s:0929 s:1011 수정 예약번호 받아서 방 아이디 가져오기 public BookingVO getRoomId(int bookingNo); //s:1003 단일 예약정보 가져오기 public BookingVO getBookingInfo(BookingVO vo); //p.10/06 진료 예약 public int insertBookingDate(BookingVO vo); //p.10.07 결제 정보 public BookingVO selectBookingInfo(int memberNo); // Booking table 결제 status 업데이트 p.10/09 public int updateBookingStatus(BookingVO vo); // K. 10/21 예약번호로 환자랑 의사이름 찾기 public BookingVO findNamePtDoc(int bookingNo); // p.10/24 진료 예약 취소 시 BOOKING테이블 status 변경 public int cancelUpdate(int bookingNo); } <file_sep>package com.mima.app.session.domain; import java.util.Date; import lombok.Data; //s: 10/01 의사가 진료 볼 때 환자 정보 조회 버튼 누를 때 사용하는 보임 @Data public class PtInfoVO { private int memberNo; private String name; private String identifyNo; private String gender; private String address; private String email; private String phone; private String pastHx; private String preSelfAx; private String topic; private String medDelivery; // 닥터 진료내역 페이지 진료노트_J10 private String addr1; private String addr2; private String addr3; private int bookingNo; private Date consultDate; private String consultTime; private String ptAssessment; private String ptDiagnosis; private String subject; // 진료과목 추가_J12 private String ptSymptom; // 증상 추가_J12 } <file_sep>package com.mima.app.comments.domain; import java.util.List; import lombok.Data; @Data public class CommentsPageVO { private int replyCnt; private List<CommentsVO> list; } <file_sep>package com.mima.app.member.domain; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data; @Data public class PtDeliveryVO { private int bookingNo; // 예약번호 @DateTimeFormat(pattern = "yyyy/MM/dd") private Date consultDate; // 진료일자 private String subject; // 진료과목 private String docName; // 진료의사 private String pharmacyName; // 신청약국이름 private String deliveryStatus; // 약배달신청상태 private String deliveryDecline; // 약배달 취소이유 private int check; // 약국 후기 체크 } <file_sep>package com.mima.app.comments.service; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mima.app.comments.domain.CommentsPageVO; import com.mima.app.comments.domain.CommentsVO; import com.mima.app.comments.domain.ReplyVO; import com.mima.app.comments.mapper.CommentsMapper; import com.mima.app.criteria.domain.Criteria; import com.mima.app.meditation.mapper.MeditationMapper; import lombok.extern.java.Log; @Log @Service public class CommentsServiceImpl implements CommentsService { @Autowired CommentsMapper commentsMapper; @Autowired MeditationMapper meditationMapper; @Override public int insert(CommentsVO vo) { log.info(vo.toString()+"~~~~~~~~~~~코멘트 보입니더 코멘트서비스임플"); meditationMapper.updateCommentsCnt(vo.getCmainCategory(), vo.getCmainNo(), 1); return commentsMapper.insert(vo); } @Override public int delete(CommentsVO vo) { vo = commentsMapper.read(vo); meditationMapper.updateCommentsCnt(vo.getCmainCategory(), vo.getCmainNo(), -1); return commentsMapper.delete(vo); } @Override public int update(CommentsVO vo) { return commentsMapper.update(vo); } @Override public CommentsPageVO getList(@Param("cri") Criteria cri, @Param("cmainCategory") String cmainCategory, @Param("cmainNo") int cmainNo) { CommentsPageVO pageVo = new CommentsPageVO(); CommentsVO vo = new CommentsVO(); vo.setCmainCategory(cmainCategory); vo.setCmainNo(cmainNo); pageVo.setReplyCnt(commentsMapper.getCountByMeditNo(vo)); pageVo.setList(commentsMapper.getList(cri, cmainCategory, cmainNo)); log.info(vo.toString()+"~~~~~~~~~~~~~~~~~~~~코멘트vo"); log.info("====페이지보========getList CommentsServiceImpl"+pageVo.toString()); return pageVo; } @Override public CommentsVO read(CommentsVO vo) { return commentsMapper.read(vo); } // 닥터 대쉬보드 메인 페이지 나의 후기_J @Override public List<CommentsVO> getlatestreviewList(int memberNo) { return commentsMapper.getlatestreviewList(memberNo); } // 닥터 대쉬보드 나의 후기 페이지_J29 @Override public List<CommentsVO> docReview(int memberNo) { return commentsMapper.docReview(memberNo); } // 닥터 대쉬보드 메인 페이지 나의 후기 카운트_J07 @Override public int countDocReview(int memberNo) { return commentsMapper.countDocReview(memberNo); } @Override public String getNickname(CommentsVO vo) { return commentsMapper.getNickname(vo); } // 닥터 대쉬보드 나의 후기 페이지 최신순 페이징_J13 @Override public List<CommentsVO> docReviewPage(Criteria cri, int memberNo) { return commentsMapper.docReviewPage(cri, memberNo); } // 닥터 대쉬보드 나의 후기 페이지 페이징 카운트_J13 @Override public int docReviewCount(Criteria cri, int memberNo) { return commentsMapper.docReviewCount(cri, memberNo); } // 닥터 대쉬보드 나의 후기 페이지 오래된순 페이징_J13 @Override public List<CommentsVO> docReviewPageOldest(Criteria cri, int memberNo) { return commentsMapper.docReviewPageOldest(cri, memberNo); } // K.10/14 약국 리뷰 조회 @Override public List<CommentsVO> phaReviewList(Criteria cri,int cmainNo) { return commentsMapper.phaReviewList(cri, cmainNo); } // K. 10/14 약국 리뷰 갯수 @Override public int phaReviewCnt(int cmainNo) { return commentsMapper.phaReviewCnt(cmainNo); } // 닥터 대쉬보드 나의 후기 페이지 댓글 등록_J20 @Override public int docReplyInsert(ReplyVO vo) { return commentsMapper.docReplyInsert(vo); } // 닥터 대쉬보드 나의 후기 페이지 댓글 수정_J20 @Override public int docReplyUpdate(ReplyVO vo) { return commentsMapper.docReplyUpdate(vo); } // 닥터 대쉬보드 나의 후기 페이지 댓글 삭제_J20 @Override public int docReplyDelete(ReplyVO vo) { return commentsMapper.docReplyDelete(vo); } @Override public ReplyVO getReply(int rno) { return commentsMapper.getReply(rno); } } <file_sep>package com.mima.app.push.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mima.app.push.domain.PushVO; import com.mima.app.push.mapper.PushMapper; @Service public class PushServiceImpl implements PushService { @Autowired PushMapper pushMapper; // K. 10/16 약배달 취소시 알림 등록 @Override public int delCancelAlarm(PushVO vo) { return pushMapper.delCancelAlarm(vo); } // K. 10/17 회원별 알림건 조회 @Override public List<PushVO> selectMemberPush(int toMemberNo) { // TODO Auto-generated method stub return pushMapper.selectMemberPush(toMemberNo); } // K. 10/19 알림확인시 삭제 @Override public int pushDelete(int pushNo) { return pushMapper.pushDelete(pushNo); } } <file_sep>package com.mima.app.pharmacy.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.SQLException; import java.util.Base64; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.rowset.serial.SerialException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; 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.mvc.support.RedirectAttributes; import com.mima.app.comments.service.CommentsService; import com.mima.app.criteria.domain.Criteria; import com.mima.app.criteria.domain.PageVO; import com.mima.app.meditation.domain.MeditAttachVO; import com.mima.app.member.domain.MemberVO; import com.mima.app.member.service.MemberService; import com.mima.app.pharmacy.domain.MedDeliveryVO; import com.mima.app.pharmacy.domain.PartnerPharmacyVO; import com.mima.app.pharmacy.service.MedDeliveryService; import com.mima.app.pharmacy.service.PatnerPharmacyService; import com.mima.app.push.domain.PushVO; import com.mima.app.push.service.PushService; import com.mima.app.session.domain.BookingVO; import com.mima.app.session.service.BookingService; import lombok.extern.java.Log; @Log @Controller @RequestMapping("/pharmacy/*") public class PartnerPharmacyController { @Autowired PatnerPharmacyService partPhaService; @Autowired MedDeliveryService deliverSerive; @Autowired MemberService memberSerivce; @Autowired BCryptPasswordEncoder cryptEncoder; @Autowired CommentsService commentsService; @Autowired PushService pushService; @Autowired BookingService bookingService; @Autowired MemberService memberService; @Value("#{global['path']}") String path; // 약국 대쉬보드 [K]210929 @GetMapping("/pharmacyDash") public void pharmacyDash(Model model, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); // 약국한건 조회 model.addAttribute("profile", partPhaService.selectOne(memberNo)); // 오늘의 배달예약수 model.addAttribute("cnt", deliverSerive.deliveryCnt(memberNo)); // 복약지도수 model.addAttribute("ptEduCnt", deliverSerive.ptEducationCnt(memberNo)); // 오늘의 약배달 등록 및 취소 model.addAttribute("delivery", deliverSerive.todayDelivery(vo.getMemberNo())); // 리뷰 수 model.addAttribute("reviewCnt", commentsService.phaReviewCnt(vo.getMemberNo())); } // 약배달 전체관리페이지 [K]210929 @GetMapping("/mediDelivery") public void mediDelivery(Model model, HttpServletRequest request, @ModelAttribute("cri") Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); int total = deliverSerive.phaSelectOneCount(memberNo); // 약국 한건 조회 model.addAttribute("profile", partPhaService.selectOne(memberNo)); // 약배달 현황 model.addAttribute("phaDelivery", deliverSerive.phaSelectOne(memberNo,cri)); model.addAttribute("pageMaker", new PageVO(cri,total)); } // 약배달 완료목록 페이지 @GetMapping("/comDelivery") public void comDelivery(Model model, HttpServletRequest request, @ModelAttribute("cri") Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); int total = deliverSerive.phaCompleteDelCount(memberNo); // 약국 한건 조회 model.addAttribute("profile", partPhaService.selectOne(memberNo)); // 약배달 완료목록 model.addAttribute("phaComDelivery", deliverSerive.phaCompleteDel(memberNo,cri)); model.addAttribute("pageMaker", new PageVO(cri,total)); } // 약배달 상태 업데이트 @PostMapping("/ptEduStatusUpdate") @ResponseBody public int ptEduStatusUpdate(int bookingNo) { return deliverSerive.ptEduStatusUpdate(bookingNo); } // 약배달 상태 업데이트 @PostMapping("/deliveryStatusUpdate") @ResponseBody public int deliveryStatusUpdate(MedDeliveryVO vo) { return deliverSerive.deliveryStatusUpdate(vo); } // 약배달 취소 @PostMapping("/delCancel") @ResponseBody public int delCancel(MedDeliveryVO vo, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); int memberNo = mvo.getMemberNo(); // 약배달에서 넘기는 예약번호 환자번호 받아오기 BookingVO bvo = bookingService.getRoomId(vo.getBookingNo()); // 약배달 취소 신청시 push 알람에 내용이 저장 PushVO push = new PushVO(); push.setToMemberNo(bvo.getPtNo()); push.setUserMemberNo(memberNo); push.setType("phaCancel"); push.setContentId(vo.getBookingNo()); push.setMessage(vo.getDeliveryDecline()); int result = pushService.delCancelAlarm(push); // push에 입력 후 med_delivery에 저장 if (result > 0) { result = deliverSerive.delCancel(vo); } else { result = 0; } return result; } // 약배달 등록/취소 페이지 @GetMapping("/deliveryRegCancel") public void deliveryRegCancel(Model model, HttpServletRequest request, @ModelAttribute("cri") Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int total = deliverSerive.memDeliveryCount(vo.getMemberNo()); model.addAttribute("profile", partPhaService.selectOne(vo.getMemberNo())); model.addAttribute("delivery", deliverSerive.memDelivery(vo.getMemberNo(),cri)); model.addAttribute("pageMaker", new PageVO(cri,total)); } // 복약지도 관리페이지 [K]210929 @GetMapping("/medGuid") public void medGuid(Model model, HttpServletRequest request, @ModelAttribute("cri") Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int total = deliverSerive.ptEducationCnt(vo.getMemberNo()); model.addAttribute("profile", partPhaService.selectOne(vo.getMemberNo())); model.addAttribute("ptEducation",deliverSerive.ptEducation(vo.getMemberNo(),cri)); model.addAttribute("pageMaker", new PageVO(cri,total)); } // 프로필 페이지 [K]210929 @GetMapping("/myProfile") public void myProfile(Model model,HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); model.addAttribute("profile",partPhaService.selectOne(memberNo)); } // 프로필 수정 - ajax [K]210929 @PutMapping("/profileUpdate") @ResponseBody public int profileUpdate(@RequestBody PartnerPharmacyVO vo, Model model ) { return partPhaService.profileUpdate(vo); } // 리뷰페이지 [K]210929 @GetMapping("/review") public void review(Model model, HttpServletRequest request, @ModelAttribute("cri") Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); model.addAttribute("profile", partPhaService.selectOne(vo.getMemberNo())); model.addAttribute("review", commentsService.phaReviewList(cri,vo.getMemberNo())); model.addAttribute("reviewCnt", commentsService.phaReviewCnt(vo.getMemberNo())); model.addAttribute("pageMaker", new PageVO(cri,commentsService.phaReviewCnt(vo.getMemberNo()))); } // 문의페이지 [K]211006 @GetMapping("/phaQna") public void phaQna() {} // 비밀번호 변경페이지 [K]210929 @GetMapping("/pwUpdate") public void pwConfirmPage(Model model, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); model.addAttribute("memberId", vo.getMemberId()); model.addAttribute("profile", partPhaService.selectOne(vo.getMemberNo())); } // 현재 비밀번호 확인페이지 [K]10.12s @PostMapping("/pwConfirm") @ResponseBody public boolean pwConfirm(MemberVO vo,HttpServletRequest request) { String password = vo.getPassword(); String memberId = vo.getMemberId(); MemberVO pass = memberSerivce.findPassword1(memberId); Boolean matchPass = cryptEncoder.matches(password, pass.getPassword()); //비교 System.out.println(matchPass); return matchPass; } // 닥터 비밀번호 변경 p.10/12 @PostMapping("updatePassword") @ResponseBody public int updatePassword(MemberVO vo) { vo.setPassword(cryptEncoder.encode(vo.getPassword())); int result = memberSerivce.updatePassword(vo); return result; } //K.10/11 약국프로필등록 @PostMapping("/register") public String register(HttpServletRequest request, PartnerPharmacyVO vo, MemberVO mVo, MultipartFile[] uploadFile, RedirectAttributes rttr) { log.info("파트너 약국 컨트롤러-> 인서트// 등록할때 보 보는거임======" + vo); //K.10/11 파트너약국테이블에 저장 partPhaService.profileUpdate(vo); HttpSession session = request.getSession(); MemberVO msvo = (MemberVO) session.getAttribute("session"); log.info("**************msvo********" + msvo); //K.10/11 멤버 테이블 주소 업데이트 mVo.setAddr1(vo.getDeliveryArea()); mVo.setAddr2(vo.getDeliveryArea2()); mVo.setAddr3(vo.getDeliveryArea3()); mVo.setPostcode(vo.getPharmacyPostCode()); mVo.setMemberNo(vo.getMemberNo()); partPhaService.phaAddrUpdate(mVo); // 단건 조회후 세션에 다시 담아줌 MemberVO mvo = memberService.getUserById(msvo.getMemberId()); request.getSession().setAttribute("session", mvo); log.info("파트너 약국 컨트롤러-> 멤버테이블 주소 업뎃 보 보는거임======" + mVo); rttr.addFlashAttribute("result", vo.getMemberNo()); return "redirect:/pharmacy/pharmacyDash"; // 파라미터 전달하고 싶을 때 redirectAttr사용 } //K.10/11 첨부파일 등록 폼-- 약국 프로필사진 @PostMapping("/phaAjaxInsert") @ResponseBody // 업로드 폼에서 인풋에서 타입이 파일이기 때문에 멀티파트파일로 주고 그 네임을 찾아서 여기 업로드파일 변수에 담아줌 public MeditAttachVO docAjaxInsert(MultipartFile uploadFile, MeditAttachVO vo) throws IllegalStateException, IOException { MeditAttachVO attachVo = null; MultipartFile uFile = uploadFile; if (!uFile.isEmpty() && uFile.getSize() > 0) { String filename = uFile.getOriginalFilename(); // 사용자가 업로드한 파일명 // 파일 자체도 보안을 걸기 위해 파일이름 바꾸기도 한다. 원래 파일명과 서버에 저장된 파일이름을 따로 관리 // String saveName = System.currentTimeMillis()+""; //이거를 팀별로 상의해서 지정해 주면 된다. // File file =new File("c:/upload", saveName); UUID uuid = UUID.randomUUID(); File file = new File(path, uuid + filename); uFile.transferTo(file); attachVo = new MeditAttachVO(); // attachVO list안에 파일정보 저장하기 위해 만듦 attachVo.setPImgName(filename); attachVo.setUuid(uuid.toString()); attachVo.setUploadPath(path); System.out.println(attachVo); } return attachVo; } //제은이꺼 훔쳐옴 의사 리스트 프로필 이미지 불러오기 @RequestMapping(value = "/pharmacy/FileDown.do") public void cvplFileDownload(@RequestParam Map<String, Object> commandMap, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("파일 다운로드 커맨드맵 이미지"+commandMap.toString()); File uFile = new File(path, (String)commandMap.get("fname")); long fSize = uFile.length(); if (fSize > 0) { String mimetype = "application/x-msdownload"; response.setContentType(mimetype); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(uFile)); out = new BufferedOutputStream(response.getOutputStream()); FileCopyUtils.copy(in, out); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { in.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } } }//제은이꺼 훔쳐옴 의사 리스트 프로필 이미지 불러오기 끝 /* * @RequestMapping("/pharmacyApi") public void pharmacyApi() throws IOException * { * * String url * ="http://apis.data.go.kr/B552657/ErmctInsttInfoInqireService/getParmacyFullDown"; * String serviceKey = * "kOfUtJpoB2nNx7jaI6XEcYuKUkswBceaC1lOvwdoLaEHRjjQvgNkQwOs%2Fh3MhO%2FWHv8%2BuL0zs6LKHuXP%2Bs2qhQ%3D%3D"; * String decodeServiceKey = URLDecoder.decode(serviceKey,"UTF-8"); String * pageNo = "1"; String numbOfRows = "23414"; * * try { Document documentInfo = DocumentBuilderFactory.newInstance() * .newDocumentBuilder() .parse(url + "?serviceKey=" + serviceKey + "&pageNo="+ * pageNo + "&numOfRows=" + numbOfRows); * * documentInfo.getDocumentElement().normalize(); * * // 파싱 NodeList nList = documentInfo.getElementsByTagName("item"); for(int * temp=0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); * if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) * nNode; System.out.println("약국주소:"+getTagValue("dutyAddr",eElement)); * * System.out.println("약국주소:"+getTagValue("dutyTel1",eElement)); * System.out.println("좌표1:"+getTagValue("wgs84Lat",eElement)); * System.out.println("좌표2:"+getTagValue("wgs84Lon",eElement)); } } } catch * (Exception e) { e.printStackTrace(); } */ /*<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <response> <header> <resultCode>00</resultCode> <resultMsg>NORMAL SERVICE.</resultMsg> </header> <body> <items> <item> <dutyAddr>대전광역시 동구 계족로 362, 성남약국 1층 (성남동)</dutyAddr> <dutyName>성남약국</dutyName> <dutyTel1>042-672-2957</dutyTel1> <dutyTime1c>1900</dutyTime1c> <dutyTime1s>0900</dutyTime1s> <dutyTime2c>1900</dutyTime2c> <dutyTime2s>0900</dutyTime2s> <dutyTime3c>1900</dutyTime3c> <dutyTime3s>0900</dutyTime3s> <dutyTime4c>1900</dutyTime4c> <dutyTime4s>0900</dutyTime4s> <dutyTime5c>1900</dutyTime5c> <dutyTime5s>0900</dutyTime5s> <dutyTime6c>1300</dutyTime6c> <dutyTime6s>0900</dutyTime6s> <hpid>C1601311</hpid> <postCdn1>345</postCdn1> <postCdn2>90 </postCdn2> <rnum>1</rnum> <wgs84Lat>36.3444243564852</wgs84Lat> <wgs84Lon>127.434066050389</wgs84Lon> </item> </items> <numOfRows>3</numOfRows> <pageNo>1</pageNo> <totalCount>23413</totalCount> </body> </response> */ // } // private String getTagValue(String tag, Element eElement) { // // TODO Auto-generated method stub // NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes(); // Node nValue = (Node) nlList.item(0); // if(nValue == null) return null; // return nValue.getNodeValue(); // } } <file_sep>package com.mima.app.meditation.service; import java.util.List; import com.mima.app.criteria.domain.Criteria; import com.mima.app.meditation.domain.MeditAttachVO; import com.mima.app.meditation.domain.MeditationVO; import com.mima.app.post.domain.PostVO; public interface MeditationService { //입력 public int insert(MeditationVO vo); //수정 public int update(MeditationVO vo); //삭제 public int delete(MeditationVO vo); //한건 조회 public MeditationVO read(MeditationVO vo); //전체 조회 public List<MeditationVO> getMeditationList(Criteria cri); //전체 명상 컨텐츠 리스트 수 조회 public int getTotalMeditCount(Criteria cri); //게시글에 첨부된 파일 단건조회... public MeditAttachVO getAttach(int medtitaionNo); //첨부파일 단건조회 public MeditAttachVO attachRead(String uuid); //좋아요 숫자+1 public int updateLike(MeditationVO vo); //좋아요 숫자-1 public int updateNotLike(MeditationVO vo); //랜덤 명상 리스트 public List<MeditationVO> randomMeditList(); } <file_sep>package com.mima.app.doc.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mima.app.criteria.domain.Criteria; import com.mima.app.doc.domain.DocInfoVO; import com.mima.app.doc.domain.PartnerDoctorVO; import com.mima.app.doc.mapper.MentalSubjectMapper; import com.mima.app.doc.mapper.PartnerDoctorMapper; import com.mima.app.likes.domain.LikesVO; import com.mima.app.meditation.domain.MeditAttachVO; import com.mima.app.meditation.mapper.MeditAttachMapper; import com.mima.app.member.domain.ExperienceVO; import com.mima.app.member.domain.MemberVO; import com.mima.app.member.mapper.ExperienceMapper; @Service public class PartnerDoctorServiceImpl implements PartnerDoctorService { @Autowired PartnerDoctorMapper partnerDoctorMapper; @Autowired MeditAttachMapper attachMapper; @Autowired MentalSubjectMapper mentalSubjectMapper; @Autowired ExperienceMapper experienceMapper; // s:1006 의사프로필 인서트 + 첨부파일(프로필 사진 인서트) @Override public int docProfileInsert(PartnerDoctorVO vo) { System.out.println("니뭐고--------------------" + vo); return partnerDoctorMapper.docProfileInsert(vo); } //s:1007 프로필 등록 시 주소 멤버 테이블에 업데이트 @Override public int docAddrUpdate(MemberVO vo) { return partnerDoctorMapper.docAddrUpdate(vo); } //s:1008 의사 전체 숫자조회 @Override public int totalDocNumCount(Criteria cri) { return partnerDoctorMapper.totalDocNumCount(cri); } //s:1008 의사 전체 리스트 @Override public List<DocInfoVO> getTotalDocList(Criteria cri) { return partnerDoctorMapper.getTotalDocList(cri); } //s:1008 의사 디테일 페이지 @Override public DocInfoVO getDocDetail(DocInfoVO vo) { vo=partnerDoctorMapper.getDocDetail(vo); //의사 디테일 조회해서 담음 int docNo = vo.getMemberNo(); vo.setSubjects(mentalSubjectMapper.getPriceCategory(docNo)); //진단과목 가격 담기 ExperienceVO expVo = new ExperienceVO(); expVo.setMemberNo(docNo); vo.setExp(experienceMapper.getExpList(expVo)); System.out.println("진료과목담고 service impl "+vo.getSubjects()); return vo; } //s:1010 의사 프로필 유무 체크 @Override public DocInfoVO checkDocDetail(MemberVO vo) { return partnerDoctorMapper.checkDocDetail(vo); } //s:1020 의사 프로필 학력 조회 @Override public DocInfoVO checkEduDetail(MemberVO vo) { return partnerDoctorMapper.checkEduDetail(vo); } //s:1020 의사 프로필 학력 입력 @Override public int insertEduAjax(PartnerDoctorVO vo) { return partnerDoctorMapper.insertEduAjax(vo); } //s:1020 의사 프로필 페이지 학력수정 ajax @Override public int updateEduAjax(PartnerDoctorVO vo) { return partnerDoctorMapper.updateEduAjax(vo); } // 닥터 대쉬보드 병원 이름_J13 @Override public String clinicName(int memberNo) { return partnerDoctorMapper.clinicName(memberNo); } // p.10/14 의사 진료과목에 대한 리스트 @Override public List<DocInfoVO> subjectDoclist(String category1, String category2, String category3) { return partnerDoctorMapper.subjectDoclist(category1, category2, category3); } // e.17 환자대쉬보드 의사 좋아요 삭제 @Override public int deleteDocLike(LikesVO vo) { return partnerDoctorMapper.deleteDocLike(vo); } } <file_sep>package com.mima.app.security; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mima.app.member.domain.MemberVO; import com.mima.app.push.service.PushService; import lombok.extern.java.Log; @Log @Component("customLoginSuccess") public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler{ // 로그인 후에 Session유지를 위해 변경 p.30 @Autowired PushService pushService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException { log.info("Login Success"); List<String> roleNames = new ArrayList<>(); auth.getAuthorities().forEach(authority -> { roleNames.add(authority.getAuthority()); }); HttpSession session = request.getSession(); session.setAttribute("session", auth.getPrincipal()); log.info("!!!!!!!!"+session.getAttribute("session").toString()); log.info("ROLE NAMES: " + roleNames); MemberVO mvo = (MemberVO) auth.getPrincipal(); log.info(mvo.toString()); // K. 10/18 push 알림내역 조회 session.setAttribute("notice", pushService.selectMemberPush(mvo.getMemberNo())); //s:1004 노드에서 사용할 쿠키굽기 Cookie cookie = new Cookie("userRole", mvo.getRole()); cookie.setMaxAge(60*60*24*30); cookie.setPath("/"); response.addCookie(cookie); System.out.println(cookie.getValue()); System.out.println("++++++++++++++++++++"); String path = request.getContextPath(); if (roleNames.contains("admin")) { response.sendRedirect(path + "/admin/adMain"); } else if (roleNames.contains("doctor")) { response.sendRedirect(path + "/doctor/docMain"); } else if (roleNames.contains("pharmacy")) { response.sendRedirect(path + "/pharmacy/pharmacyDash"); } else { response.sendRedirect("/"); } } /* * // K. 10/19 알림내역 확인시 삭제 * * @DeleteMapping("pushDelete") * * @ResponseBody public int pushDelete(int pushNo) { return * pushService.pushDelete(pushNo); } */ } <file_sep>package com.mima.app.meditation.mapper; import java.util.List; import com.mima.app.meditation.domain.MeditAttachVO; public interface MeditAttachMapper { public void insert(MeditAttachVO vo); public void delete(String uuid); public MeditAttachVO findByMeditNo(int meditationNo); public void deleteAll(int meditationNo); public List<MeditAttachVO> getOldFiles(); public MeditAttachVO read(String uuid); //s:1007 프로필 사진 업로드 public void insertImg(MeditAttachVO vo); } <file_sep>package com.mima.app.doc.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.mima.app.criteria.domain.Criteria; import com.mima.app.doc.domain.DocInfoVO; import com.mima.app.doc.domain.PartnerDoctorVO; import com.mima.app.likes.domain.LikesVO; import com.mima.app.member.domain.ExperienceVO; import com.mima.app.member.domain.MemberVO; public interface PartnerDoctorMapper { // 닥터 대쉬보드 프로필 페이지 INSERT_J04 public int docProfileInsert(PartnerDoctorVO vo); // s:1007 프로필 등록 시 주소 멤버 테이블에 업데이트 public int docAddrUpdate(MemberVO vo); //s:1008 전체 의사 멤버 수 조회 public int totalDocNumCount(Criteria cri); //s:1008 댓글 수 업데이트 cmainCategory-> doc cmainNo -> 의사번호 public void updateCommentsCnt(@Param("cmainCategoty") String cmainCategory, @Param("cmainNo") int cmainNo, @Param("amount") int amount); //s:1008 의사 전체 리스트 public List<DocInfoVO> getTotalDocList(Criteria cri); //s:1008 의사 디테일 페이지 public DocInfoVO getDocDetail(DocInfoVO vo); //s:1010 의사프로필 유무 확인 public DocInfoVO checkDocDetail(MemberVO vo); //s:1020 의사 프로필 학력 조회 public DocInfoVO checkEduDetail(MemberVO vo); //s:1020 의사 프로필 페이지 학력입력 ajax public int insertEduAjax(PartnerDoctorVO vo); //s:1020 의사 프로필 페이지 학력수정 ajax public int updateEduAjax(PartnerDoctorVO vo); // 닥터 대쉬보드 병원 이름_J13 public String clinicName(int memberNo); // p.10/14 의사 진료과목에 대한 리스트 public List<DocInfoVO> subjectDoclist(@Param("category1") String category1, @Param("category2") String category2, @Param("category3") String category3); // e.17 환자대쉬보드 의사 좋아요 삭제 public int deleteDocLike(LikesVO vo); } <file_sep>package com.mima.app.pharmacy.controller; import org.springframework.stereotype.Controller; @Controller public class MedDeliveryController { } <file_sep>package com.mima.app.ptdiary.service; import org.springframework.stereotype.Service; @Service public class PtDiaryServiceImpl implements PtDiaryService { } <file_sep>package com.mima.app.admin.domain; import java.util.Date; import lombok.Data; //신고 당한사람, 신고한 사람 전체조회 //e.30 @Data public class RmemberVO { private String reportNo; //신고글 넘버 private String postNo; //신고당한 포스트 넘버 private String memberNo; //신고한 회원번호 private String reportMno; // 신고당한 회원번호 private String rmemberId; // 신고한 회원 아이디 private String reportId; // 신고 당한 회원 아이디 private Date reportDate; //신고한 날짜 private Date checkDate; //신고 확인 날짜 private String reportResult; //신고 조치 여부 //e.17 신고당한사람, 신고한 사람 private String reported;//신고당한 사람 private String reporter;//신고한 사람 } <file_sep>package com.mima.app.comments.domain; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; @Data public class ReplyVO { // 닥터 대쉬보드 나의 후기 댓글달기_J20 private int rno; private int rmainNo; private int rwriterNo; @DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-dd") private Date rregDate; private Date reditDate; private String rcontents; private int rcno; } <file_sep>package com.mima.app.medication.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mima.app.criteria.domain.Criteria; import com.mima.app.criteria.domain.PageVO; import com.mima.app.medication.domain.ApiPageVO; import com.mima.app.medication.domain.DurDangerVO; import com.mima.app.medication.domain.DurVO; import com.mima.app.medication.domain.PillSearchVO; import lombok.extern.java.Log; @Log @Controller @RequestMapping("/consultation/*") public class MedicationController { // 약검색 페이지 [K]211001 @GetMapping("/pillSearch") public void pillSearch(Model model) { } // 약 API - e약은요 [K]210929 @PostMapping("/pill") @ResponseBody public HashMap<String, Object> search(@RequestBody PillSearchVO pvo, Model model) throws IOException { Criteria cri = new Criteria(); log.info(pvo.getItemName()); log.info(pvo.getEfcyQesitm()); log.info(pvo.getIntrcQesitm()); String str = ""; cri.setPageNum(pvo.getPageNo()); StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1471000/DrbEasyDrugInfoService/getDrbEasyDrugList"); /*URL*/ urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=kOfUtJpoB2nNx7jaI6XEcYuKUkswBceaC1lOvwdoLaEHRjjQvgNkQwOs%2Fh3MhO%2FWHv8%2BuL0zs6LKHuXP%2Bs2qhQ%3D%3D"); /*Service Key*/ urlBuilder.append("&" + URLEncoder.encode("ServiceKey","UTF-8") + "=" + URLEncoder.encode("인증키(url encode)", "UTF-8")); /*공공데이터포털에서 받은 인증키*/ if(pvo.getItemName() != null) { str = pvo.getItemName(); urlBuilder.append("&" + URLEncoder.encode("itemName","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*제품명*/ } else if (pvo.getItemSeq() != 0 ) { str = String.valueOf(pvo.getItemSeq()); urlBuilder.append("&" + URLEncoder.encode("itemSeq","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*품목기준코드*/ } else if (pvo.getEfcyQesitm() != null ) { str = pvo.getEfcyQesitm(); urlBuilder.append("&" + URLEncoder.encode("efcyQesitm","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*이 약의 효능은 무엇입니까?*/ } else if (pvo.getIntrcQesitm() != null ) { str = pvo.getIntrcQesitm(); urlBuilder.append("&" + URLEncoder.encode("intrcQesitm","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*이 약을 사용하는 동안 주의해야 할 약 또는 음식은 무엇입니까?*/ } urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode(String.valueOf(cri.getPageNum()), "UTF-8")); /*페이지번호*/ urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/ urlBuilder.append("&" + URLEncoder.encode("type","UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); URL url = new URL(urlBuilder.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); log.info("Response code: " + conn.getResponseCode()); BufferedReader rd; if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } log.info(rd.toString()); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); HashMap<String, Object> hashMap = new HashMap<String, Object>(); // String -> JSON 변환 List<PillSearchVO> pList = new ArrayList<PillSearchVO>(); log.info(sb.toString()); String value = sb.toString(); JSONObject firstJson = new JSONObject(value); String bodyValue = firstJson.get("body").toString(); JSONObject twoJson = new JSONObject(bodyValue); // 페이징처리 2 PageVO pageVO = new PageVO(cri, twoJson.getInt("totalCount")); if(twoJson.getInt("totalCount") == 0) { pList = null; } else { // 결과값 JSONArray jArry = twoJson.getJSONArray("items"); // 객채에 담음 for (int i=0; i<jArry.length(); i++) { JSONObject JO = jArry.getJSONObject(i); PillSearchVO pill = new PillSearchVO(); if(!JO.isNull("entpName")) { pill.setEntpName(String.valueOf(JO.get("entpName"))); } if(!JO.isNull("itemName")) { pill.setItemName(String.valueOf(JO.get("itemName"))); } if(!JO.isNull("itemSeq")) { pill.setItemSeq(Integer.parseInt(JO.get("itemSeq").toString())); } if(!JO.isNull("efcyQesitm")) { pill.setEfcyQesitm(String.valueOf(JO.get("efcyQesitm"))); } if(!JO.isNull("useMethodQesitm")) { pill.setUseMethodQesitm(String.valueOf(JO.get("useMethodQesitm"))); } if(!JO.isNull("atpnWarnQesit")) { pill.setAtpnWarnQesitm(String.valueOf(JO.get("atpnWarnQesit"))); } if(!JO.isNull("atpnQesitm")) { pill.setAtpnQesitm(String.valueOf(JO.get("atpnQesitm"))); } if(!JO.isNull("seQesitm")) { pill.setSeQesitm(String.valueOf(JO.get("seQesitm"))); } if(!JO.isNull("depositMethodQesitm")) { pill.setDepositMethodQesitm(String.valueOf(JO.get("depositMethodQesitm"))); } if(!JO.isNull("openDe")) { pill.setOpenDe(String.valueOf(JO.get("openDe"))); } if(!JO.isNull("updateDe")) { pill.setUpdateDe(String.valueOf(JO.get("updateDe"))); } if(!JO.isNull("itemImage")) { pill.setItemImage(String.valueOf(JO.get("itemImage"))); } pList.add(pill); } } hashMap.put("list", pList); hashMap.put("pageMaker",pageVO); return hashMap; } // 약 API - DRUG 정보 조회 [K]211004 @PostMapping("/dur") @ResponseBody public HashMap<String, Object> search(@RequestBody DurVO dvo, Model model) throws IOException { Criteria cri = new Criteria(); cri.setPageNum(dvo.getPageNo()); String str = ""; StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1470000/DURPrdlstInfoService/getDurPrdlstInfoList"); /*URL*/ urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=k<KEY>kswBceaC1lOvwdoLaEHRjjQvgNkQwOs%2Fh3MhO%2FWHv8%2BuL0zs6LKHuXP%2Bs2qhQ%3D%3D"); /*Service Key*/ if(dvo.getItemName() != null) { str = dvo.getItemName(); urlBuilder.append("&" + URLEncoder.encode("itemName","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*품목명*/ } else if (dvo.getEntpName() != null ) { str = String.valueOf(dvo.getEntpName()); urlBuilder.append("&" + URLEncoder.encode("entpName","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*업체명*/ } urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode(String.valueOf(cri.getPageNum()), "UTF-8")); /*페이지 번호*/ urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과수*/ urlBuilder.append("&" + URLEncoder.encode("type","UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); URL url = new URL(urlBuilder.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); log.info("Response code: " + conn.getResponseCode()); BufferedReader rd; if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); List<DurVO> dList = new ArrayList<DurVO>(); log.info(sb.toString()); String value = sb.toString(); JSONObject firstJson = new JSONObject(value); String bodyValue = firstJson.get("body").toString(); JSONObject twoJson = new JSONObject(bodyValue); HashMap<String, Object> hashMap = new HashMap<String, Object>(); PageVO pageVO = new PageVO(cri, twoJson.getInt("totalCount")); if(twoJson.getInt("totalCount") == 0) { dList = null; } else { JSONArray jArry = twoJson.getJSONArray("items"); // 객채에 담음 for (int i=0; i<jArry.length(); i++) { JSONObject JO = jArry.getJSONObject(i); DurVO dur = new DurVO(); if(!JO.isNull("ITEM_SEQ")) { dur.setItemSeq(String.valueOf(JO.get("ITEM_SEQ")));} if(!JO.isNull("ITEM_NAME")) { dur.setItemName(String.valueOf(JO.get("ITEM_NAME")));} if(!JO.isNull("ENTP_NAME")) { dur.setEntpName(String.valueOf(JO.get("ENTP_NAME")));} if(!JO.isNull("ITEM_PERMIT_DATE")) { dur.setItemPermitDate(String.valueOf(JO.get("ITEM_PERMIT_DATE")));} if(!JO.isNull("ETC_OTC_CODE")) { dur.setEtcOtcCode(String.valueOf(JO.get("ETC_OTC_CODE")));} if(!JO.isNull("CLASS_NO")) { dur.setClassNo(String.valueOf(JO.get("CLASS_NO")));} if(!JO.isNull("CHART")) { dur.setChart(String.valueOf(JO.get("CHART")));} if(!JO.isNull("BAR_CODE")) { dur.setBarCode(String.valueOf(JO.get("BAR_CODE")));} if(!JO.isNull("MATERIAL_NAME")) { dur.setMaterialName(String.valueOf(JO.get("MATERIAL_NAME")));} if(!JO.isNull("EE_DOC_ID")) { dur.setEeDocId(String.valueOf(JO.get("EE_DOC_ID")));} if(!JO.isNull("UD_DOC_ID")) { dur.setUdDocId(String.valueOf(JO.get("UD_DOC_ID")));} if(!JO.isNull("NB_DOC_ID")) { dur.setNbDocId(String.valueOf(JO.get("NB_DOC_ID")));} if(!JO.isNull("INSERT_FILE")) { dur.setInsertFile(String.valueOf(JO.get("INSERT_FILE")));} if(!JO.isNull("STORAGE_METHOD")) { dur.setStorageMethod(String.valueOf(JO.get("STORAGE_METHOD")));} if(!JO.isNull("VALID_TERM")) { dur.setValidTerm(String.valueOf(JO.get("VALID_TERM")));} if(!JO.isNull("REEXAM_TARGET")) { dur.setReexamTarger(String.valueOf(JO.get("REEXAM_TARGET")));} if(!JO.isNull("REEXAM_DATE")) { dur.setReexamDate(String.valueOf(JO.get("REEXAM_DATE")));} if(!JO.isNull("PACK_UNIT")) { dur.setPackUnit(String.valueOf(JO.get("PACK_UNIT")));} if(!JO.isNull("CANCEL_DATE")) { dur.setCancelDate(String.valueOf(JO.get("CANCEL_DATE")));} if(!JO.isNull("CANCEL_NAME")) { dur.setCancelName(String.valueOf(JO.get("CANCEL_NAME")));} if(!JO.isNull("CHANGE_DATE")) { dur.setChangeDate(String.valueOf(JO.get("CHANGE_DATE")));} dList.add(dur); } } hashMap.put("list", dList); hashMap.put("pageMaker",pageVO); return hashMap; } // 약 병용금기 검색 페이지 [K]211004 @PostMapping("/durDanger") @ResponseBody public HashMap<String, Object> search(@RequestBody DurDangerVO ddvo, Model model) throws IOException { Criteria cri = new Criteria(); cri.setPageNum(ddvo.getPageNo()); String str = ""; StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1470000/DURPrdlstInfoService/getUsjntTabooInfoList"); /*URL*/ urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=<KEY>%2Fh3MhO%2FWHv8%2BuL0zs6LKHuXP%2Bs2qhQ%3D%3D"); /*Service Key*/ if(ddvo.getTypeName() != null) { str = ddvo.getTypeName(); urlBuilder.append("&" + URLEncoder.encode("typeName","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*DUR유형*/ } else if (ddvo.getIngrCode() != null ) { str = String.valueOf(ddvo.getIngrCode()); urlBuilder.append("&" + URLEncoder.encode("ingrCode","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*DUR성분코드*/ } else if (ddvo.getItemName() != null ) { str = ddvo.getItemName(); urlBuilder.append("&" + URLEncoder.encode("itemName","UTF-8") + "=" + URLEncoder.encode(str, "UTF-8")); /*품목명*/ } urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode(String.valueOf(cri.getPageNum()), "UTF-8")); /*페이지 번호*/ urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/ urlBuilder.append("&" + URLEncoder.encode("type","UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); URL url = new URL(urlBuilder.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); log.info("Response code: " + conn.getResponseCode()); BufferedReader rd; if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); List<DurDangerVO> ddList = new ArrayList<DurDangerVO>(); HashMap<String, Object> hashMap = new HashMap<String, Object>(); log.info(sb.toString()); String value = sb.toString(); JSONObject firstJson = new JSONObject(value); String bodyValue = firstJson.get("body").toString(); JSONObject twoJson = new JSONObject(bodyValue); PageVO pageVO = new PageVO(cri, twoJson.getInt("totalCount")); if(twoJson.getInt("totalCount") == 0) { ddList = null; } else { JSONArray jArry = twoJson.getJSONArray("items"); // 객채에 담음 for (int i=0; i<jArry.length(); i++) { JSONObject JO = jArry.getJSONObject(i); DurDangerVO dur = new DurDangerVO(); if(!JO.isNull("DUR_SEQ")) { dur.setDurSeq(String.valueOf(JO.get("DUR_SEQ"))); } if(!JO.isNull("TYPE_CODE")) { dur.setTypeCode(String.valueOf(JO.get("TYPE_CODE"))); } if(!JO.isNull("TYPE_NAME")) { dur.setTypeName(String.valueOf(JO.get("TYPE_NAME"))); } if(!JO.isNull("MIX")) { dur.setMix(String.valueOf(JO.get("MIX"))); } if(!JO.isNull("INGR_CODE")) {dur.setIngrCode(String.valueOf(JO.get("INGR_CODE"))); } if(!JO.isNull("INGR_KOR_NAME")) { dur.setIngrKorName(String.valueOf(JO.get("INGR_KOR_NAME"))); } if(!JO.isNull("INGR_ENG_NAME")) { dur.setIngrEngName(String.valueOf(JO.get("INGR_ENG_NAME"))); } if(!JO.isNull("MIX_INGR")) { dur.setMixIngr(String.valueOf(JO.get("MIX_INGR"))); } if(!JO.isNull("ITEM_SEQ")) { dur.setItemSeq(String.valueOf(JO.get("ITEM_SEQ"))); } if(!JO.isNull("ITEM_NAME")) { dur.setItemName(String.valueOf(JO.get("ITEM_NAME"))); } if(!JO.isNull("ENTP_NAME")) { dur.setEntpName(String.valueOf(JO.get("ENTP_NAME"))); } if(!JO.isNull("CHART")) { dur.setChart(String.valueOf(JO.get("CHART"))); } if(!JO.isNull("FORM_CODE")) { dur.setFormCode(String.valueOf(JO.get("FORM_CODE"))); } if(!JO.isNull("ETC_OTC_CODE")) { dur.setEtcOtcCode(String.valueOf(JO.get("ETC_OTC_CODE"))); } if(!JO.isNull("CLASS_CODE")) { dur.setClassCode(String.valueOf(JO.get("CLASS_CODE"))); } if(!JO.isNull("FORM_NAME")) { dur.setFormName(String.valueOf(JO.get("FORM_NAME"))); } if(!JO.isNull("ETC_OTC_NAME")) { dur.setEtcOtcName(String.valueOf(JO.get("ETC_OTC_NAME"))); } if(!JO.isNull("CLASS_NAME")) { dur.setClassName(String.valueOf(JO.get("CLASS_NAME"))); } if(!JO.isNull("MAIN_INGR")) { dur.setMainIngr(String.valueOf(JO.get("MAIN_INGR"))); } if(!JO.isNull("MIXTURE_DUR_SEQ")) { dur.setMixTureDurSeq(String.valueOf(JO.get("MIXTURE_DUR_SEQ"))); } if(!JO.isNull("MIXTURE_MIX")) { dur.setMixTureMix(String.valueOf(JO.get("MIXTURE_MIX"))); } if(!JO.isNull("MIXTURE_INGR_CODE")) { dur.setMixTureIngrCode(String.valueOf(JO.get("MIXTURE_INGR_CODE"))); } if(!JO.isNull("MIXTURE_INGR_KOR_NAME")) { dur.setMixTureIngrKorName(String.valueOf(JO.get("MIXTURE_INGR_KOR_NAME"))); } if(!JO.isNull("MIXTURE_INGR_ENG_NAME")) { dur.setMixTureIngrEngName(String.valueOf(JO.get("MIXTURE_INGR_ENG_NAME"))); } if(!JO.isNull("MIXTURE_ITEM_SEQ")) { dur.setMixTureItemSeq(String.valueOf(JO.get("MIXTURE_ITEM_SEQ"))); } if(!JO.isNull("MIXTURE_ITEM_NAME")) { dur.setMixTureItemName(String.valueOf(JO.get("MIXTURE_ITEM_NAME"))); } if(!JO.isNull("MIXTURE_ENTP_NAME")) { dur.setMixTureEntpName(String.valueOf(JO.get("MIXTURE_ENTP_NAME"))); } if(!JO.isNull("MIXTURE_FORM_CODE")) { dur.setMixTureFormCode(String.valueOf(JO.get("MIXTURE_FORM_CODE"))); } if(!JO.isNull("MIXTURE_ETC_OTC_CODE")) { dur.setMixTureEtcOtcCode(String.valueOf(JO.get("MIXTURE_FORM_CODE"))); } if(!JO.isNull("MIXTURE_CLASS_CODE")) { dur.setMixTureClassCode(String.valueOf(JO.get("MIXTURE_CLASS_CODE"))); } if(!JO.isNull("MIXTURE_FORM_NAME")) { dur.setMixTureFormName(String.valueOf(JO.get("MIXTURE_FORM_NAME"))); } if(!JO.isNull("MIXTURE_ETC_OTC_NAME")) { dur.setMixTureEtcOtcName(String.valueOf(JO.get("MIXTURE_ETC_OTC_NAME"))); } if(!JO.isNull("MIXTURE_CLASS_NAME")) { dur.setMixTureClassName(String.valueOf(JO.get("MIXTURE_CLASS_NAME"))); } if(!JO.isNull("MIXTURE_MAIN_INGR")) { dur.setMixTureMainIngr(String.valueOf(JO.get("MIXTURE_MAIN_INGR"))); } if(!JO.isNull("NOTIFICATION_DATE")) { dur.setNotificationDate(String.valueOf(JO.get("NOTIFICATION_DATE"))); } if(!JO.isNull("PROHBT_CONTENT")) { dur.setProhbtContent(String.valueOf(JO.get("PROHBT_CONTENT"))); } if(!JO.isNull("REMARK")) { dur.setRemart(String.valueOf(JO.get("REMARK"))); } if(!JO.isNull("ITEM_PERMIT_DATE")) { dur.setItemPermitDate(String.valueOf(JO.get("ITEM_PERMIT_DATE"))); } if(!JO.isNull("MIXTURE_ITEM_PERMIT_DATE")) { dur.setMixTureItemPermitDate(String.valueOf(JO.get("MIXTURE_ITEM_PERMIT_DATE"))); } if(!JO.isNull("MIXTURE_CHART")) { dur.setMixTureChart(String.valueOf(JO.get("MIXTURE_CHART"))); } ddList.add(dur); } } hashMap.put("list", ddList); hashMap.put("pageMaker",pageVO); return hashMap; } /* * if(!JO.isNull("DUR_SEQ")) { dur.setDurSeq(String.valueOf(JO.get("DUR_SEQ"))); * } if(!JO.isNull("TYPE_CODE")) { * dur.setTypeCode(String.valueOf(JO.get("TYPE_CODE"))); } * if(!JO.isNull("TYPE_NAME")) { * dur.setTypeName(String.valueOf(JO.get("TYPE_NAME"))); } if(!JO.isNull("MIX")) * { dur.setMix(String.valueOf(JO.get("MIX"))); } if(!JO.isNull("INGR_CODE")) { * dur.setIngrCode(String.valueOf(JO.get("INGR_CODE"))); } * if(!JO.isNull("INGR_KOR_NAME")) { * dur.setIngrKorName(String.valueOf(JO.get("INGR_CODE"))); } * if(!JO.isNull("INGR_ENG_NAME")) { * dur.setIngrEngName(String.valueOf(JO.get("INGR_ENG_NAME"))); } * if(!JO.isNull("MIX_INGR")) { * dur.setMixIngr(String.valueOf(JO.get("MIX_INGR"))); } * if(!JO.isNull("ITEM_SEQ")) { * dur.setItemSeq(String.valueOf(JO.get("ITEM_SEQ"))); } * if(!JO.isNull("ITEM_NAME")) { * dur.setItemName(String.valueOf(JO.get("ITEM_NAME"))); } * if(!JO.isNull("ENTP_NAME")) { * dur.setEntpName(String.valueOf(JO.get("ENTP_NAME"))); } * if(!JO.isNull("CHART")) { dur.setChart(String.valueOf(JO.get("CHART"))); } * if(!JO.isNull("FORM_CODE")) { * dur.setFormCode(String.valueOf(JO.get("FORM_CODE"))); } * if(!JO.isNull("ETC_OTC_CODE")) { * dur.setEtcOtcCode(String.valueOf(JO.get("ETC_OTC_CODE"))); } * if(!JO.isNull("CLASS_CODE")) { * dur.setClassCode(String.valueOf(JO.get("CLASS_CODE"))); } * if(!JO.isNull("FORM_NAME")) { * dur.setFormName(String.valueOf(JO.get("FORM_NAME"))); } * if(!JO.isNull("ETC_OTC_NAME")) { * dur.setEtcOtcName(String.valueOf(JO.get("ETC_OTC_NAME"))); } * if(!JO.isNull("CLASS_NAME")) { * dur.setClassName(String.valueOf(JO.get("CLASS_NAME"))); } * if(!JO.isNull("MAIN_INGR")) { * dur.setMainIngr(String.valueOf(JO.get("MAIN_INGR"))); } * if(!JO.isNull("MIXTURE_DUR_SEQ")) { * dur.setMixTureDurSeq(String.valueOf(JO.get("MIXTURE_DUR_SEQ"))); } * if(!JO.isNull("MIXTURE_MIX")) { * dur.setMixTureMix(String.valueOf(JO.get("MIXTURE_MIX"))); } * if(!JO.isNull("MIXTURE_INGR_CODE")) { * dur.setMixTureIngrCode(String.valueOf(JO.get("MIXTURE_INGR_CODE"))); } * if(!JO.isNull("MIXTURE_INGR_KOR_NAME")) { * dur.setMixTureIngrKorName(String.valueOf(JO.get("MIXTURE_INGR_KOR_NAME"))); } * if(!JO.isNull("MIXTURE_INGR_ENG_NAME")) { * dur.setMixTureIngrEngName(String.valueOf(JO.get("MIXTURE_INGR_ENG_NAME"))); } * if(!JO.isNull("MIXTURE_ITEM_SEQ")) { * dur.setMixTureItemSeq(String.valueOf(JO.get("MIXTURE_ITEM_SEQ"))); } * if(!JO.isNull("MIXTURE_ITEM_NAME")) { * dur.setMixTureItemName(String.valueOf(JO.get("MIXTURE_ITEM_NAME"))); } * if(!JO.isNull("MIXTURE_ENTP_NAME")) { * dur.setMixTureEntpName(String.valueOf(JO.get("MIXTURE_ENTP_NAME"))); } * if(!JO.isNull("MIXTURE_FORM_CODE")) { * dur.setMixTureFormCode(String.valueOf(JO.get("MIXTURE_FORM_CODE"))); } * if(!JO.isNull("MIXTURE_ETC_OTC_CODE")) { * dur.setMixTureEtcOtcCode(String.valueOf(JO.get("MIXTURE_FORM_CODE"))); } * if(!JO.isNull("MIXTURE_CLASS_CODE")) { * dur.setMixTureClassCode(String.valueOf(JO.get("MIXTURE_CLASS_CODE"))); } * if(!JO.isNull("MIXTURE_FORM_NAME")) { * dur.setMixTureFormName(String.valueOf(JO.get("MIXTURE_FORM_NAME"))); } * if(!JO.isNull("MIXTURE_ETC_OTC_NAME")) { * dur.setMixTureEtcOtcName(String.valueOf(JO.get("MIXTURE_ETC_OTC_NAME"))); } * if(!JO.isNull("MIXTURE_CLASS_NAME")) { * dur.setMixTureClassName(String.valueOf(JO.get("MIXTURE_CLASS_NAME"))); } * if(!JO.isNull("MIXTURE_MAIN_INGR")) { * dur.setMixTureMainIngr(String.valueOf(JO.get("MIXTURE_MAIN_INGR"))); } * if(!JO.isNull("NOTIFICATION_DATE")) { * dur.setNotificationDate(String.valueOf(JO.get("NOTIFICATION_DATE"))); } * if(!JO.isNull("PROHBT_CONTENT")) { * dur.setProhbtContent(String.valueOf(JO.get("PROHBT_CONTENT"))); } * if(!JO.isNull("REMARK")) { dur.setRemart(String.valueOf(JO.get("REMARK"))); } * if(!JO.isNull("ITEM_PERMIT_DATE")) { * dur.setItemPermitDate(String.valueOf(JO.get("ITEM_PERMIT_DATE"))); } * if(!JO.isNull("MIXTURE_ITEM_PERMIT_DATE")) { * dur.setMixTureItemPermitDate(String.valueOf(JO.get("MIXTURE_ITEM_PERMIT_DATE" * ))); } if(!JO.isNull("MIXTURE_CHART")) { * dur.setMixTureChart(String.valueOf(JO.get("MIXTURE_CHART"))); } */ } <file_sep>package com.mima.app.meditation.controller; import java.io.IOException; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.UrlResource; import org.springframework.core.io.support.ResourceRegion; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRange; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.MediaTypeFactory; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mima.app.criteria.domain.Criteria; import com.mima.app.criteria.domain.PageVO; import com.mima.app.meditation.domain.MeditationVO; import com.mima.app.meditation.service.MeditationService; import com.mima.app.member.domain.MemberVO; import lombok.extern.java.Log; @Log @Controller @RequestMapping("/meditation/*") public class MeditationController { @Autowired MeditationService meditationService; @Value("#{global['path']}") String path; //수정 처리 - 좋아요 @PutMapping("/updateLike") @ResponseBody public int updateLike(@RequestBody MeditationVO vo, Model model) { return meditationService.updateLike(vo); } //수정 처리 - 좋아요 취소 @PutMapping("/updateNotLike") @ResponseBody public int updateNotLike(@RequestBody MeditationVO vo, Model model) { return meditationService.updateNotLike(vo); } // To main 조회 @GetMapping("/meditationMain") public void meditationMain(Model model, @ModelAttribute("cri") Criteria cri) { int total = meditationService.getTotalMeditCount(cri); model.addAttribute("pageMaker", new PageVO(cri, total)); model.addAttribute("list", meditationService.randomMeditList()); } // about medit @GetMapping("/aboutMedit") public void aboutMedit(Model model,@ModelAttribute("cri") Criteria cri) { int total = meditationService.getTotalMeditCount(cri); model.addAttribute("pageMaker", new PageVO(cri, total)); model.addAttribute("list", meditationService.randomMeditList()); } // 전체 리스트 조회 @GetMapping("/totalList") public void totalList(Model model, @ModelAttribute("cri") Criteria cri) { int total = meditationService.getTotalMeditCount(cri); model.addAttribute("list", meditationService.getMeditationList(cri)); model.addAttribute("pageMaker", new PageVO(cri, total)); } // 단건조회-디테일 페이지 @GetMapping("/meditationDetail") public void meditationDetail(Model model, MeditationVO vo, @ModelAttribute("cri") Criteria cri, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); log.info("dddd"+mvo.toString()); int memberNo = mvo.getMemberNo(); log.info("before call read"+vo.toString()); vo.setMemberNo(memberNo); vo = meditationService.read(vo); System.out.println("after call read"+vo); String uuid = vo.getAttachFile().getUuid(); String name = vo.getAttachFile().getVFileName(); vo.setFileName(uuid + name); System.out.println(vo.getFileName()); model.addAttribute("item", vo); } // 디테일 페이지에서 사용 @GetMapping(value = "/video/{name}") public ResponseEntity<ResourceRegion> getVideo(@RequestHeader HttpHeaders headers, @PathVariable String name) throws IOException { //log.info("VideoController.getVideo"); UrlResource video = new UrlResource("file:"+path+ "/" + name + ".mp4"); //System.out.println(video+"명상컨트롤러 비디오"); ResourceRegion resourceRegion; final long chunkSize = 1000000L; long contentLength = video.contentLength(); Optional<HttpRange> optional = headers.getRange().stream().findFirst(); HttpRange httpRange; if (optional.isPresent()) { httpRange = optional.get(); long start = httpRange.getRangeStart(contentLength); long end = httpRange.getRangeEnd(contentLength); long rangeLength = Long.min(chunkSize, end - start + 1); resourceRegion = new ResourceRegion(video, start, rangeLength); } else { long rangeLength = Long.min(chunkSize, contentLength); resourceRegion = new ResourceRegion(video, 0, rangeLength); } return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT) .contentType(MediaTypeFactory.getMediaType(video).orElse(MediaType.APPLICATION_OCTET_STREAM)) .body(resourceRegion); } } <file_sep>package com.mima.app.ptdiary.mapper; public interface PtDiaryMapper { } <file_sep>package com.mima.app.member.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.rowset.serial.SerialException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; 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.mvc.support.RedirectAttributes; import com.mima.app.comments.domain.CommentsVO; import com.mima.app.comments.service.CommentsService; import com.mima.app.criteria.domain.Criteria; import com.mima.app.criteria.domain.PageVO; import com.mima.app.likes.domain.LikesVO; import com.mima.app.meditation.domain.MeditAttachVO; import com.mima.app.member.domain.MemberVO; import com.mima.app.member.domain.PatientsVO; import com.mima.app.member.service.MemberService; import com.mima.app.member.service.PatientsService; import com.mima.app.pharmacy.domain.MedDeliveryVO; import com.mima.app.pharmacy.domain.PartnerPharmacyVO; import com.mima.app.pharmacy.service.MedDeliveryService; import com.mima.app.pharmacy.service.PatnerPharmacyService; import com.mima.app.session.domain.BookingVO; import com.mima.app.session.domain.PaymentVO; import com.mima.app.session.service.BookingService; import com.mima.app.session.service.ConsultationService; import com.mima.app.session.service.RaymentService; import lombok.extern.java.Log; @Log @Controller public class PatientsController { // e.10/11 환자대쉬보드 @Autowired PatientsService patientsService; @Autowired CommentsService commentsService; @Autowired BookingService bookingService; // K.10/09 booking 확인 @Autowired PatnerPharmacyService phaService; // K.10/07 약국 검색 @Autowired MedDeliveryService deliveryService; // K.10/09 약배달 @Autowired MemberService memberService; // K.10/11 약배달 신청 유무 @Autowired ConsultationService consultationService; // K. 10/21 약국 후기 등록 @Autowired RaymentService paymentService; // p. 10/24 @Value("#{global['path']}") String path; //e.4 //환자대쉬보드 메인 페이지 @GetMapping("patients/ptMain") public String ptMain(Model model, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); model.addAttribute("list", patientsService.ptgetList(memberNo)); model.addAttribute("ptMainhisList", patientsService.ptMainhisList(memberNo)); model.addAttribute("ptMainreList", patientsService.ptMainreList(memberNo)); model.addAttribute("ptMyListCount", patientsService.ptMyListCount(memberNo)); model.addAttribute("ptMyHistoryCount", patientsService.ptMyHistoryCount(memberNo)); model.addAttribute("ptMyReviewCount", patientsService.ptMyReviewCount(memberNo)); // 환자 약배달 현황 model.addAttribute("ptDeliveryStatusList", patientsService.ptDeliveryStatusList(memberNo)); return "patients/ptMain"; } // K. 10/18 약 배달 현황 전체 조회 @GetMapping("patients/ptDeliveryList") public String ptDeliveryList(Model model, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); // 환자 약배달 현황 model.addAttribute("ptDeliveryStatusList", patientsService.ptDeliveryStatusAllList(memberNo)); model.addAttribute("memberNo", memberNo); return "patients/ptDeliveryList"; } // K. 10/21 약국 후기 폼 @GetMapping("patients/ptPhaReviewFrm") public String ptPhaReviewFrm(Model model, HttpServletRequest request, MedDeliveryVO mvo) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); mvo = deliveryService.phaNameSelectOne(mvo.getBookingNo()); model.addAttribute("memberNo", memberNo); model.addAttribute("pha", mvo); return "patients/ptPhaReviewFrm"; } @PostMapping("patients/ptReviewInsert") @ResponseBody public int ptReviewInsert(CommentsVO vo) { int result = consultationService.ptReviewInsert(vo); return result; } // K. 10/18 환자 약배달 수령완료시 상태 업데이트 @PostMapping("patients/delcompleteUpdate") @ResponseBody public int delcompleteUpdate(MedDeliveryVO vo) { int result = deliveryService.delcompleteUpdate(vo); return result; } // K. 10/19 환자 약배달 재신청하기 @PostMapping("patients/delReapply") @ResponseBody public int delReapply(MedDeliveryVO vo) { int result = deliveryService.delReapply(vo); return result; } // K. 10/19 환자 약배달 신청 약국 변경하기 @PostMapping("patients/delPhaUpdate") @ResponseBody public int delPhaUpdate(PatientsVO vo) { int result = patientsService.delPhaUpdate(vo); return result; } // K. 10/18 환자 약배달 취소 내역 조회 @PostMapping("patients/ptDelCancelSelect") @ResponseBody public MedDeliveryVO ptDelCancelSelect(MedDeliveryVO vo) { return deliveryService.delCancelReason(vo.getBookingNo()); } //환자대쉬보드 예약관리 페이지 e.5 @GetMapping("patients/ptBookManage") public String ptBookManage(Model model, HttpServletRequest request, @ModelAttribute("cri")Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); int total = patientsService.ptbmListCount(cri, memberNo); // model.addAttribute("ptbmList", patientsService.ptbmList(memberNo, cri)); if (cri.getKeyword() == null || cri.getKeyword().equals("all")) { model.addAttribute("ptbmListPage", patientsService.ptbmListPage(cri, memberNo)); } else if (cri.getKeyword() == null || cri.getKeyword().equals("soon")) { model.addAttribute("ptbmListPage", patientsService.ptbmListSoonPage(cri, memberNo)); } else { model.addAttribute("ptbmListPage", patientsService.ptbmListCanceledPage(cri, memberNo)); } model.addAttribute("pageMaker", new PageVO(cri,total)); return "patients/ptBookManage"; } //환자대쉬보드 진료내역 페이지 e.5 @GetMapping("patients/ptHistory") public String ptHistory(Model model, HttpServletRequest request, @ModelAttribute("cri")Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); int total = patientsService.getTotalPthCount(memberNo, cri); if (cri.getKeyword() == null || cri.getKeyword().equals("latest")) { model.addAttribute("ptHistoryList", patientsService.ptHistoryList(memberNo, cri)); } else { model.addAttribute("ptHistoryList", patientsService.ptHistoryOldestList(memberNo, cri)); } System.out.println(patientsService.ptHistoryList(memberNo, cri) + "*******"); System.out.println(patientsService.ptHistoryOldestList(memberNo, cri) + "^^^^^^^^"); model.addAttribute("pageMaker", new PageVO(cri,total)); return "patients/ptHistory"; } // 환자 대쉬보드 나의후기 페이지 e.5 @GetMapping("patients/ptReview") public String ptReview(Model model, CommentsVO commentsvo, HttpServletRequest request, @ModelAttribute("cri")Criteria cri) { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); int total = patientsService.getTotalPtrvCount(memberNo, cri); // model.addAttribute("ptReviewList", patientsService.ptReviewList(memberNo, cri)); if (cri.getKeyword() == null || cri.getKeyword().equals("latest")) { model.addAttribute("ptReviewList", patientsService.ptReviewList(memberNo, cri)); } else { model.addAttribute("ptReviewList", patientsService.ptReviewOldestList(memberNo, cri)); } model.addAttribute("pageMaker", new PageVO(cri,total)); return "patients/ptReview"; } // 환자 대쉬보드 나의 후기 댓글 조회_J20 // @GetMapping // public String ptReplySelect(Model model, CommentsVO commentsvo, HttpServletRequest request, @ModelAttribute("cri")Criteria cri) { // HttpSession session = request.getSession(); // MemberVO vo = (MemberVO) session.getAttribute("session"); // int memberNo = vo.getMemberNo(); // // return null; // // } // 환자 대쉬보드 비밀번호 변경 페이지 수정 폼 e.11 @GetMapping("patients/ptPwChangeForm") public String ptPwUpdateForm() { return "patients/ptPwChange"; } //환자 대쉬보드 비밀번호 변경 페이지 수정 처리 e.11 @PostMapping("/ptPwChange") public String ptPwUpdate(RedirectAttributes rttr, MemberVO vo) { memberService.ptPwChange(vo); rttr.addAttribute("ptPwUpdateResult", vo.getMemberId()); return "redirect:/ptPwChange"; } //환자대쉬보드 프로필페이지 e.12 @GetMapping("patients/ptProfileDetail") public void ptMyProfile(Model model, HttpServletRequest request) throws IOException { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); MemberVO membervo = patientsService.ptSelectOne(memberNo); model.addAttribute("ptMyProfile", membervo ); if(membervo.getPtProfilePhoto() != null) { File file = new File("path",membervo.getPtProfilePhoto()); if(! file.exists()) return; FileInputStream inputStream = new FileInputStream(file); ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = inputStream.read(buf))!= -1) { byteOutStream.write(buf,0,len); } byte[] fileArray = byteOutStream.toByteArray(); String s = new String (Base64.getEncoder().encodeToString(fileArray)); String changeString = "data:image/"+ "png" + ";base64," + s; membervo.setPtProfilePhotoImg(changeString); } } //e.20 환자대쉬보드 Main 프로필 이미지 @GetMapping("patients/ptProfileImg") public ResponseEntity<byte[]> ptProfileImg(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException, SerialException, SQLException { HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); int memberNo = vo.getMemberNo(); MemberVO membervo = patientsService.ptSelectOne(memberNo); String changeString = ""; String s = ""; byte[] fileArray = null; if(membervo.getPtProfilePhoto() != null) { File file = new File(path,membervo.getPtProfilePhoto()); if(! file.exists()) return new ResponseEntity<byte[]>(null, null, HttpStatus.NOT_FOUND); FileInputStream inputStream = new FileInputStream(file); ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = inputStream.read(buf))!= -1) { byteOutStream.write(buf,0,len); } fileArray = byteOutStream.toByteArray(); //s = new String (Base64.getEncoder().encodeToString(fileArray)); //changeString = "data:image/"+ "png" + ";base64," + s; final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_PNG); return new ResponseEntity<byte[]>(fileArray, headers, HttpStatus.OK); } else { return new ResponseEntity<byte[]>(null, null, HttpStatus.NOT_FOUND); } } //e.20 환자대쉬보드 Main 프로필 이미지 @RequestMapping(value = "/patients/FileDown.do") public void cvplFileDownload(@RequestParam Map<String, Object> commandMap, HttpServletRequest request, HttpServletResponse response) throws Exception { File uFile = new File(path, (String)commandMap.get("fname")); long fSize = uFile.length(); if (fSize > 0) { String mimetype = "application/x-msdownload"; response.setContentType(mimetype); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(uFile)); out = new BufferedOutputStream(response.getOutputStream()); FileCopyUtils.copy(in, out); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { in.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } } } //환자대쉬보드 프로필 수정- e.12 @PostMapping("patients/ptprofileUpdate") public String ptprofileUpdate(MemberVO vo, Model model, HttpServletRequest request) throws IllegalStateException, IOException { HttpSession session = request.getSession(); MemberVO membervo = (MemberVO) session.getAttribute("session"); int memberNo = membervo.getMemberNo(); vo.setMemberNo(memberNo); int result = patientsService.ptprofileUpdate(vo); if(result == 1) { model.addAttribute("result","수정이 완료되었습니다."); }else { model.addAttribute("result","수정에 실패하였습니다."); } return "redirect:/patients/ptProfileDetail"; } //환자대쉬보드 약배달 페이지 K.10/09 @GetMapping("patients/ptMedelivery") public String ptMedelivery(HttpServletRequest request, Model model) { String viewPage = ""; HttpSession session = request.getSession(); MemberVO vo = (MemberVO) session.getAttribute("session"); String delStatus = memberService.deliveryStatus(vo.getMemberNo()); log.info("***** 약배달 신청유무 : "+delStatus); // + 기존 약배달 신청한건 있는지부터 조회 PatientsVO pvo = new PatientsVO(); if(delStatus.equals("n") ) { viewPage = "patients/ptMedeliveryNone"; model.addAttribute("memberNo", vo.getMemberNo()); }else { log.info("예약이 존재!"); pvo = patientsService.ptDeliveryCheck(vo.getMemberNo()); if(pvo == null) { // 약배달 신청정보가 없으면 등록 model.addAttribute("memberNo", vo.getMemberNo()); model.addAttribute("messege", "insert" ); viewPage = "patients/ptMedelivery"; }else { if(pvo.getDelAddr() == null) { // 환자테이블은 있으나, 약배달 정보는 x log.info("**********************// 환자테이블은 존재, 약배달은 x "); model.addAttribute("memberNo", vo.getMemberNo()); model.addAttribute("messege", "update" ); viewPage = "patients/ptMedelivery"; } else { // 약배달 신청정보가 있으면 수정 log.info("**********************pvo : "+ pvo.toString()); model.addAttribute("pvo", pvo); model.addAttribute("memberNo", vo.getMemberNo()); model.addAttribute("messege", "updateBtn" ); viewPage = "patients/ptMedelivery"; } } } return viewPage; } //환자대쉬보드 약배달 페이지 K.10/06 @GetMapping("patients/phaSearch") public String phaSearch() { return "patients/phaSearch"; } //약국 찾기 K.10/07 @PostMapping("patients/pharmacy") @ResponseBody public List<PartnerPharmacyVO> pharmacy(@RequestBody Criteria cri){ List<PartnerPharmacyVO> list = new ArrayList<PartnerPharmacyVO>(); list = phaService.pharmacySearch(cri); return list; } //약배달 신청등록 K.10/09 @PostMapping("patients/ptDeliveryInsert") @ResponseBody public int ptDeliveryInsert(@RequestBody PatientsVO vo ){ return patientsService.ptDeliveryInsert(vo); } //약배달 정보수정 K.10/10 @PostMapping("patients/ptDeliveryUpdate") @ResponseBody public int ptDeliveryUpdate(@RequestBody PatientsVO vo ){ return patientsService.ptDeliveryUpdate(vo); } //약배달신청 유무 수정 K.10/11 @PostMapping("patients/deliberyStatusUpdate") @ResponseBody public int deliberyStatusUpdate(@RequestBody MemberVO vo){ return memberService.deliveryStatusUpdate(vo); } //약국 번호로 약국명 조회 K.10/10 @PostMapping("patients/phaNameSearch") @ResponseBody public PartnerPharmacyVO phaNameSearch(@RequestBody PartnerPharmacyVO vo){ return phaService.selectOne(vo.getMemberNo()); } //s:1007 코멘트 테이블에 입력 @PostMapping("/insert") public String insertReview(CommentsVO vo) { System.out.println("의사 리뷰 코멘트테이블입력 insert VO"+vo); commentsService.insert(vo); return "patients/ptMain"; } // p.10/12 예약 취소 @PostMapping("patients/paymentCancel") @ResponseBody public int paymentCancel(int bookingNo) throws Exception { HttpURLConnection conn = null; URL url = new URL("https://api.iamport.kr/users/getToken"); // 엑세스 토큰을 받아올 주소 입력 conn = (HttpURLConnection) url.openConnection(); // 요청 방식 : POST conn.setRequestMethod("POST"); // Header 설정 (application/json 형식으로 데이터를 전송) conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); // 서버로부터 받을 Data를 JSON형식 타입으로 요청함 // Data 설정 conn.setDoOutput(true); // OutPutStream으로 POST 데이터를 넘겨주겠다는 옵션 // 서버로 보낼 데이터 JSON 형태로 변환 (imp_apikey, imp_secret) JSONObject obj = new JSONObject(); String impkey = "8316389304848891"; String impSecrect = "d52aa0e1cd1dad310f9216ad6139ff15081c4bfef8f1e71dac9d9a7d4421d8107d488a22c205bd7a"; obj.put("imp_key", impkey); obj.put("imp_secret", impSecrect); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); bw.write(obj.toString()); bw.flush(); bw.close(); // 서버로부터 응답 데이터 받기 int result = 0; int responseCode = conn.getResponseCode(); // 응답코드 받기 System.out.println("응답코드??" + responseCode); if (responseCode == 200) { // 성공 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); System.out.println("" + sb.toString()); result = 1; // 환불 성공 시 정수값 1 반환 } else { System.out.println(conn.getResponseMessage()); // 환불 실패 시 정수값 0반환 result = 0; } if (result == 1) { bookingService.cancelUpdate(bookingNo); PaymentVO pvo = new PaymentVO(); pvo.setPayItem(bookingNo); paymentService.payStatusUpdate(pvo); } return result; } //e.18 환자대쉬보드 프로필 사진 @PostMapping("patients/phaAjaxInsert") @ResponseBody // 업로드 폼에서 인풋에서 타입이 파일이기 때문에 멀티파트파일로 주고 그 네임을 찾아서 여기 업로드파일 변수에 담아줌 public MeditAttachVO docAjaxInsert(MultipartFile uploadFile, MeditAttachVO vo) throws IllegalStateException, IOException { MeditAttachVO attachVo = null; MultipartFile uFile = uploadFile; if (!uFile.isEmpty() && uFile.getSize() > 0) { String filename = uFile.getOriginalFilename(); // 사용자가 업로드한 파일명 // 파일 자체도 보안을 걸기 위해 파일이름 바꾸기도 한다. 원래 파일명과 서버에 저장된 파일이름을 따로 관리 // String saveName = System.currentTimeMillis()+""; //이거를 팀별로 상의해서 지정해 주면 된다. // File file =new File("c:/upload", saveName); UUID uuid = UUID.randomUUID(); File file = new File(path, uuid + filename); uFile.transferTo(file); attachVo = new MeditAttachVO(); // attachVO list안에 파일정보 저장하기 위해 만듦 attachVo.setPImgName(filename); attachVo.setUuid(uuid.toString()); attachVo.setUploadPath(path); System.out.println(attachVo); } return attachVo; } // 환자 대쉬보드 환자 프로필 이름 밑_J21 } <file_sep>package com.mima.app.doc.domain; import java.util.Date; import lombok.Data; @Data public class DocAvailabilityVO { private int docNo; // 의사번호 private String mon; // 월요일 private String tue; // 화요일 private String wed; // 수요일 private String thu; // 목요일 private String fri; // 금요일 private String sat; // 토요일 private String sun; // 일요일 private String day; private Date regDate; // 등록일 private Date editDate; // 수정일 } <file_sep>package com.mima.app.doc.service; import java.util.List; import com.mima.app.criteria.domain.Criteria; import com.mima.app.doc.domain.DocInfoVO; import com.mima.app.doc.domain.PartnerDoctorVO; import com.mima.app.likes.domain.LikesVO; import com.mima.app.member.domain.ExperienceVO; import com.mima.app.member.domain.MemberVO; public interface PartnerDoctorService { // 닥터 대쉬보드 프로필 페이지 INSERT_J04 public int docProfileInsert(PartnerDoctorVO vo); // s:1007 프로필 등록 시 주소 멤버 테이블에 업데이트 public int docAddrUpdate(MemberVO vo); //s:1008 전체 의사 멤버 수 조회 public int totalDocNumCount(Criteria cri); //s:1008 의사 전체 리스트 public List<DocInfoVO> getTotalDocList(Criteria cri); //s:1008 의사 디테일 페이지 public DocInfoVO getDocDetail(DocInfoVO vo); //s:1010 의사프로필 유무 확인 public DocInfoVO checkDocDetail(MemberVO vo); //s:1020 의사 프로필 학력 조회 public DocInfoVO checkEduDetail(MemberVO vo); //s:1020 의사 프로필 페이지 학력입력 ajax public int insertEduAjax(PartnerDoctorVO vo); //s:1020 의사 프로필 페이지 학력수정 ajax public int updateEduAjax(PartnerDoctorVO vo); // 닥터 대쉬보드 병원 이름_J13 public String clinicName(int memberNo); // p.10/14 의사 진료과목에 대한 리스트 public List<DocInfoVO> subjectDoclist(String category1, String category2, String category3); // e.17 환자대쉬보드 의사 좋아요 삭제 public int deleteDocLike(LikesVO vo); }<file_sep>package com.mima.app.socket; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.mima.app.member.domain.MemberVO; import com.mima.app.session.domain.BookingVO; import com.mima.app.session.service.BookingService; import com.mima.app.session.service.ConsultationService; import lombok.extern.java.Log; //s:1009 https://stothey0804.github.io/project/WebSocketExam/ 참고 로그인중인 유저에게 알람보내기 @Log @Controller @RequestMapping("/socket/*") public class EchoHandler extends TextWebSocketHandler{ @Autowired BookingService bookingService; @Autowired ConsultationService consultationService; //로그인한 전체 유저 List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // 로그인중인 개별유저 Map<String, WebSocketSession> users = new ConcurrentHashMap<String, WebSocketSession>(); String url=""; //s:1011 진료방 링크 구하기 @GetMapping("/getRmId") @ResponseBody private BookingVO getRmId(int bookingNo) { BookingVO vo= bookingService.getRoomId(bookingNo); System.out.println(vo+"진료방아이디 확인!!"); return vo; } // 클라이언트가 서버로 연결시 @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { String senderId = getMemberId(session); // 접속한 유저의 http세션을 조회하여 id를 얻는 함수 System.out.println("senderId check "+ senderId); if(senderId!=null) { // 로그인 값이 있는 경우만 log(senderId + " 연결 됨"); users.put(senderId, session); // 로그인중 개별유저 저장 System.out.println(users+" users 보기"); sessions.add(session); //전체 유저에 저장(이거 근데 필요 없을거같은데) } System.out.println(users); } // 클라이언트가 Data 전송 시 @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String senderId = getMemberId(session); System.out.println(senderId); // 특정 유저에게 보내기 String msg = message.getPayload(); System.out.println("url 받아온 것 "+msg); // K. 10/15 <NAME> log.info(msg); if(msg.substring(0,3).equals("med")) { log.info("*****수민테스트*****"+msg); String[] strs = msg.split("="); log(strs.toString()); if(strs != null && strs.length == 4) { int bookingNo = Integer.parseInt(strs[1]); String delMessage = strs[2]; int pharmacyNo = Integer.parseInt(strs[3]); // 예약번호로 환자 NO 찾기 BookingVO vo= bookingService.getRoomId(bookingNo); // 부킹번호로 환자 ID 찾기 String ptId = consultationService.checkPtId(bookingNo); // 테스트 완료 log.info("*******취소내용:"+delMessage); log.info("*******받는사람ID: "+ptId + ", 받는사람 : "+ vo.getPtNo()); log.info("*******보내는사람Id: "+ senderId + " , 보내는사람 : "+ pharmacyNo ); TextMessage tmpMsg = new TextMessage("<p>약배달 신청이 취소되었습니다.</p><br><a href='pharmacyDash'>자세히보기</a>"); TextMessage confirmMsg = new TextMessage("<p>환자에게 알람이 전송되었습니다.</p>"); if(users.get(ptId) != null) { users.get(ptId).sendMessage(tmpMsg); } users.get(senderId).sendMessage(confirmMsg); } } // 약국 알람 end //진료시작 알람 String bknum = msg.substring(msg.lastIndexOf("=")+1); int num = Integer.parseInt(bknum); String ptId = consultationService.checkPtId(num); log.info("환자아이디======="+ptId); if(msg != null) { TextMessage tmpMsg = new TextMessage("<a target=\"_blank\" href="+msg+">진료실이 준비되었습니다. 이동하기</a>"); TextMessage confirmMsg = new TextMessage("<p>환자께 알림을 보냈습니다.</p>"); System.out.println("보내진 메세지 확인"+ tmpMsg.toString()); if(users.get(ptId) != null) { users.get(ptId).sendMessage(tmpMsg); } users.get(senderId).sendMessage(confirmMsg); System.out.println("msg sent"); } } // 연결 해제될 때 @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { String senderId = getMemberId(session); if(senderId!=null) { // 로그인 값이 있는 경우만 log(senderId + " 연결 종료됨"); //메세지 보낸 유저 연결해제 users.remove(senderId); //전체 유저중에서 연결해제 sessions.remove(session); } } // 에러 발생시 @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { log(session.getId() + " 익셉션 발생: " + exception.getMessage()); } // 로그 메시지 private void log(String logmsg) { System.out.println(new Date() + " : " + logmsg); } // 웹소켓에 id 가져오기 // 접속한 유저의 http세션을 조회하여 id를 얻는 함수 private String getMemberId(WebSocketSession session) { Map<String, Object> httpSession = session.getAttributes(); MemberVO mVo = (MemberVO) httpSession.get("session"); log.info("세션 저장된 멤버 아이디 "+mVo.toString()); String m_id = mVo.getMemberId(); // 세션에 저장된 m_id 기준 조회 return m_id==null? null: m_id; } } <file_sep>package com.mima.app.session.domain; import java.util.Date; import lombok.Data; @Data public class PaymentVO { private String payMethod; // 결제 수단 private Date payDate; // 결제 일 private String payStatus; // 결제 상태 private String payResult; // 결제 완료 후 결과 값 private int payItem; // 예약 번호 private int payAmount; // 금액 private String payConfirmnum; // 카드 승인 번호 } <file_sep>package com.mima.app.admin.controller; import java.io.File; import java.io.IOException; import java.util.Optional; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.UrlResource; import org.springframework.core.io.support.ResourceRegion; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRange; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.MediaTypeFactory; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; 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.mvc.support.RedirectAttributes; import com.mima.app.admin.domain.ReportVO; import com.mima.app.admin.domain.RmemberVO; import com.mima.app.admin.service.ReportService; import com.mima.app.criteria.domain.Criteria; import com.mima.app.criteria.domain.PageVO; import com.mima.app.meditation.domain.MeditAttachVO; import com.mima.app.meditation.domain.MeditationVO; import com.mima.app.meditation.service.MeditationService; import com.mima.app.member.domain.MemberVO; import com.mima.app.member.service.MemberService; import com.mima.app.member.service.PatientsService; import lombok.extern.java.Log; @Log @Controller @RequestMapping("/admin/*") public class AdminController { @Autowired MemberService memberService; @Autowired PatientsService patientsService; // 시큐리티 때문에 추가 p.10/11 @Autowired ReportService reportService; @Autowired MeditationService meditationService; @Value("#{global['path']}") String path = "c:/upload"; //e.29 //K 10/06 수정 //관리자 회원정보조회(환자,의사,약국) @GetMapping("/adlist") public String list(Model model, @ModelAttribute("cri") Criteria cri) { int total = patientsService.getTotalPatientsCount(cri); int totalDoc = patientsService.getTotaldoctorCount(cri); int totalPhar = patientsService.getTotalpharCount(cri); model.addAttribute("getptList", patientsService.getptList()); model.addAttribute("getdocList", patientsService.getdocList()); model.addAttribute("getpmList", patientsService.getpmList()); model.addAttribute("getPatientsList",patientsService.getPatientsList(cri)); model.addAttribute("getdoctorList", patientsService.getdoctorList(cri)); model.addAttribute("getpharList", patientsService.getpharList(cri)); model.addAttribute("pageMaker", new PageVO(cri,total)); model.addAttribute("pageMakerDoc", new PageVO(cri,totalDoc)); model.addAttribute("pageMakerPhar", new PageVO(cri,totalPhar)); return "admin/adlist"; } //e.29 //관리자 메인페이지 @GetMapping("/adMain") public String adMain(Model model) { //관리자 회원정보조회 토탈카운트 e.13 model.addAttribute("getTotalCount",patientsService.getTotalCount()); return "admin/adMain"; } //e.29 // 파트너 의사 / 약국 승인 유무 검색 @GetMapping("/patnerStatusSelect") public String patnerStatusSelect(Model model) { model.addAttribute("patnerStatusSelect",memberService.patnerStatusSelect()); return "admin/patnerStatusSelect"; } //e.29 // 파트너 의사 / 약국 승인 등록 @PostMapping("/patnerStatusUpdate") @ResponseBody public int patnerStatusUpdate(MemberVO vo) { System.out.println(vo.getLicense()); int result = memberService.patnerStatusUpdate(vo); return result; } //e.30 //관리자 신고당한사람 전체조회 @GetMapping("/rplist") public void rplist(Model model, @ModelAttribute("cri") Criteria cri) { int total = reportService.getTotalCount(cri); model.addAttribute("list", reportService.getList(cri)); model.addAttribute("pageMaker", new PageVO(cri,total)); } //e.29 //관라자 신고당한사람 단건조회 @GetMapping("/rpget") public void rpget(Model model, RmemberVO vo, @ModelAttribute("cri") Criteria cri) { int total = reportService.getTotalCount(cri); model.addAttribute("report",reportService.rmemberReportSelect(vo)); model.addAttribute("list", reportService.getList(cri)); model.addAttribute("pageMaker", new PageVO(cri,total)); } //e.29 //관리자 신고당한사람 삭제 @GetMapping("/rpdelete") public String rpdelete(RedirectAttributes rttr, @RequestParam int reportNo, @ModelAttribute("cri") Criteria cri) { ReportVO vo = new ReportVO(); vo.setReportNo(reportNo); int result = reportService.adminDelete(vo); //알림전송 "신고글이 접수되었습니다." if(result == 1) { rttr.addFlashAttribute("result","success"); } //rttr.addAttribute("list", reportService.rmemberReportSelect()); rttr.addAttribute("pageNum",cri.getPageNum()); rttr.addAttribute("amount",cri.getAmount()); return "redirect:/admin/rplist"; } // 명상 등록 페이지로 시큐리티를 위해 컨트롤러 수정 p.10/11 @GetMapping("/meditationInsertForm") public void meditationInsertForm() { } // 등록 @PostMapping("/register") public String register(MeditationVO vo, MultipartFile[] uploadFile, RedirectAttributes rttr) { System.out.println("명상컨트롤 등록할때 보 보는거임======" + vo); meditationService.insert(vo); rttr.addFlashAttribute("result", vo.getMeditationNo()); return "redirect:/meditation/meditationMain"; // 파라미터 전달하고 싶을 때 redirectAttr사용 } @GetMapping("/delete") public String delete(MeditationVO vo, RedirectAttributes rttr) { int result = meditationService.delete(vo); if (result == 1) { rttr.addFlashAttribute("result", "success"); } return "redirect:/meditation/meditationMain"; } // 첨부파일 등록 폼---명상동영상 @PostMapping("/meditAjaxInsert") @ResponseBody // 업로드 폼에서 인풋에서 타입이 파일이기 때문에 멀티파트파일로 주고 그 네임을 찾아서 여기 업로드파일 변수에 담아줌 public MeditAttachVO meditAjaxInsert(MultipartFile uploadFile, MeditAttachVO vo, HttpServletRequest request) throws IllegalStateException, IOException { MeditAttachVO attachVo = null; //String path = request.getSession().getServletContext().getRealPath("/WEB-INF/resources/meditVideo");; MultipartFile uFile = uploadFile; if (!uFile.isEmpty() && uFile.getSize() > 0) { String filename = uFile.getOriginalFilename(); // 사용자가 업로드한 파일명 // 파일 자체도 보안을 걸기 위해 파일이름 바꾸기도 한다. 원래 파일명과 서버에 저장된 파일이름을 따로 관리 // String saveName = System.currentTimeMillis()+""; //이거를 팀별로 상의해서 지정해 주면 된다. // File file =new File("c:/upload", saveName); UUID uuid = UUID.randomUUID(); File file = new File(path, uuid + filename); uFile.transferTo(file); attachVo = new MeditAttachVO(); // attachVO list안에 파일정보 저장하기 위해 만듦 attachVo.setVFileName(filename); attachVo.setUuid(uuid.toString()); attachVo.setUploadPath(path); System.out.println(attachVo); } return attachVo; } } <file_sep>package com.mima.app.doc.mapper; import org.apache.ibatis.annotations.Param; import com.mima.app.doc.domain.DocAvailabilityVO; import com.mima.app.member.domain.MemberVO; public interface DocAvailabilityMapper { // 의사 진료 시간 조회 p.10/04 public String selectDocTime(@Param("day") String day, @Param("docNo") int docNo); //의사 진료 시간 전체조회 s:1017 public DocAvailabilityVO checkAvail(MemberVO vo); //S: 1005 의사 진료 가능 시간 요일 입력 public int insert(DocAvailabilityVO vo); //S: 1017 의사 진료 가능 시간 요일 update public int update(DocAvailabilityVO vo); } <file_sep>package com.mima.app.doc.service; import com.mima.app.doc.domain.MentalSubjectVO; public interface MentalSubjectService { //S: 1005 의사 진료 과목과 가격 입력 public int insert(MentalSubjectVO vo); //S: 1017 의사 진료 과목과 가격 update public int update(MentalSubjectVO vo); // p.10/07 의사 카테고리 금액 가져오기 public MentalSubjectVO getPriceCategory(int docNo); // p.10/07 의사 카테고리만 가져오기 public MentalSubjectVO categorySelect(int docNo); }<file_sep>package com.mima.app.doc.controller; import org.springframework.stereotype.Controller; @Controller public class ClinicHoursController { } <file_sep>package com.mima.app.member.service; import java.util.List; import org.apache.ibatis.annotations.Param; import com.mima.app.admin.domain.CscVO; import com.mima.app.admin.domain.QnaVO; import com.mima.app.comments.domain.CommentsVO; import com.mima.app.comments.domain.ReplyVO; import com.mima.app.criteria.domain.Criteria; import com.mima.app.doc.domain.DocInfoVO; import com.mima.app.doc.domain.PartnerDoctorVO; import com.mima.app.likes.domain.LikesVO; import com.mima.app.member.domain.MemberVO; import com.mima.app.member.domain.PatientsVO; import com.mima.app.member.domain.PtDeliveryVO; import com.mima.app.pharmacy.domain.PartnerPharmacyVO; import com.mima.app.session.domain.BookingVO; public interface PatientsService { //s:1004 자가정보 입력 public int update(PatientsVO vo); //s:1004 자가진단표 public int updateAx(PatientsVO vo); //관리자 회원정보조회 토탈카운트 e.13 public int getTotalCount(); //관리자 회원정보조회(환자) e.29 public List<PatientsVO> getptList(); //관리자 회원정보조회(의사) e.7 public List<PartnerDoctorVO> getdocList(); //관리자 회원정보조회(약국) e.7 public List<PartnerPharmacyVO> getpmList(); //관리자 회원정보조회(환자) 페이징 e.4 public List<PatientsVO> getPatientsList(Criteria cri); //관리자 회원정보조회(환자) 페이징 e.4 public int getTotalPatientsCount(Criteria cri); //관리자 회원정보조회(의사) 전체조회 페이징 e.7 public List<PartnerDoctorVO> getdoctorList(Criteria cri); //관리자 회원정보조회(의사) 전체 데이터 수 조회 페이징 e.7 public int getTotaldoctorCount(Criteria cri); //관리자 회원정보조회(약국) 전체조회 페이징 e.8 public List<PartnerPharmacyVO> getpharList(Criteria cri); //관리자 회원정보조회(약국) 전체 데이터 수 조회 페이징 e.8 public int getTotalpharCount(Criteria cri); //환자대쉬보드 Main 오늘의예약 e.4 public List<BookingVO> ptgetList(int memberNo); //환자대쉬보드 예약관리 페이지,페이징 e.5 public List<BookingVO> ptbmList(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); //전체 데이터 수 조회 예약관리 페이징 e.5 public int getTotalPtbmCount(Criteria cri); // 환자 대쉬보드 예약관리 페이징 카운트_J18 public int ptbmListCount(@Param("cri") Criteria cri, @Param("memberNo") int memberNo); // 환자 대쉬보드 예약관리 페이지 모두보기 페이징_J18 public List<BookingVO> ptbmListPage(@Param("cri") Criteria cri, @Param("memberNo") int memberNo); // 닥터 대쉬보드 나의 후기 페이지 예정된 목록 페이징_J15 public List<BookingVO> ptbmListSoonPage(@Param("cri") Criteria cri, @Param("memberNo") int memberNo); // 닥터 대쉬보드 나의 후기 페이지 취소된 목록 페이징_J15 public List<BookingVO> ptbmListCanceledPage(@Param("cri") Criteria cri, @Param("memberNo") int memberNo); //환자대쉬보드 Main 진료내역 e.5 public List<BookingVO> ptMainhisList(int memberNo); //환자대쉬보드 진료내역 페이지,페이징 e.5 public List<BookingVO> ptHistoryList(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); // 환자 대쉬보드 진료내역 페이지 오래된순_J18 public List<BookingVO> ptHistoryOldestList(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); //전체 데이터 수 조회 진료내역 페이징 e.6 public int getTotalPthCount(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); //환자대쉬보드 Main 나의후기 e.5 public List<CommentsVO> ptMainreList(int memberNo); //환자대쉬보드 나의후기 페이지,페이징 e.5 // public List<CommentsVO> ptReviewList(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); //전체 데이터 수 조회 나의후기 페이징 e.6 public int getTotalPtrvCount(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); // 환자 대쉬보드 나의 후기 페이지 최신순 페이징_J18 public List<CommentsVO> ptReviewList(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); // 환자 대쉬보드 나의 후기 페이지 오래된순 페이징_J18 public List<CommentsVO> ptReviewOldestList(@Param("memberNo") int memberNo, @Param("cri") Criteria cri); //환자 대쉬보드 프로필 관리 한건조회 e.12 public MemberVO ptSelectOne(int memberNo); //환자 대쉬보드 프로필 수정 e.12 public int ptprofileUpdate(MemberVO vo); // 약배달 신청내역 조회 K.10/10 public PatientsVO ptDeliveryCheck(int memberNo); // 약배달 정보 등록 K.10/10 public int ptDeliveryInsert(PatientsVO vo); // 약배달 정보 수정 K.10/10 public int ptDeliveryUpdate(PatientsVO vo); // 환자 대쉬보드 메인 나의 예약수 카운트_J17 public int ptMyListCount (int memberNo); // 환자 대쉬보드 메인 진료내역 수 카운트_J17 public int ptMyHistoryCount (int memberNo); // 환자 대쉬보드 메인 나의 후기수 카운트_J17 public int ptMyReviewCount (int memberNo); // 환자 5건 약배달현황 조회 K. 10/17 public List<PtDeliveryVO>ptDeliveryStatusList(int memberNo); // 환자 약배달현황 전체 조회 K. 10/18 public List<PtDeliveryVO>ptDeliveryStatusAllList(int memberNo); // 환자 약배달 신청 약국 변경 K. 10/19 public int delPhaUpdate(PatientsVO vo); } <file_sep>/*WebApp/resources/assets/js/comments.js*/ var csrfHeaderName = "${_csrf.headerName}"; var csrfTokenValue = "${_csrf.token}"; let replyService =(function(){ //댓글 등록 function add(callback, err){ $.ajax({ url:"../replies/", data:$("#replyForm").serialize(), beforeSend : function(xhr) { xhr.setRequestHeader(csrfHeaderName, csrfTokenValue); }, method:"post", dataType:"json", success:function(data){ if(callback) callback(data) }, error: function(err){ console.error(err); } }); } //댓글 조회 function getList(param, callback, err){ var cmainCategory=param.cmainCategory; var cmainNo = param.cmainNo; var page = param.page ||1; $.ajax({ url:"../replies/", method:"get", data:{ cmainCategory: cmainCategory, cmainNo: cmainNo, page:page }, beforeSend : function(xhr) { xhr.setRequestHeader(csrfHeaderName, csrfTokenValue); }, dataType:"json", success: function(data){ console.log(data); if(callback){ callback(data.replyCnt, data.list); } }, error: function(error){ if(error) error(error) } }); } //댓글 삭제 function deleteReply(cno, callback, err){ $.ajax({ url:"../replies/"+cno, method:"delete", dataType:"json", beforeSend : function(xhr) { xhr.setRequestHeader(csrfHeaderName, csrfTokenValue); }, success: function(data){ if(callback){ callback(data) } }, error: function(error){ console.error(error); } }); } //한건댓글 읽기 function read(param, callback, err){ var cno = param.cno; $.ajax({ url:"../replies/"+cno, method:"get", dataType:"json", beforeSend : function(xhr) { xhr.setRequestHeader(csrfHeaderName, csrfTokenValue); }, success: function(data){ if(callback){ callback(data) } }, error: function(error){ console.error(error); } }); } //댓글 수정 function update(editedReply, callback, err){ $.ajax({ url:"../replies/"+editedReply.cno, method:"put", data: JSON.stringify(editedReply), beforeSend : function(xhr) { xhr.setRequestHeader(csrfHeaderName, csrfTokenValue); }, contentType:"application/json; charset=utf-8", success: function(data){ if(callback){ callback(data) } }, error: function(error){ console.error(error); } }); } return {add:add, getList: getList, deleteReply:deleteReply, read:read, update:update}; })();<file_sep>package com.mima.app.doc.service; import org.springframework.stereotype.Service; @Service public class ClinicHoursServiceImpl implements ClinicHoursService { } <file_sep>package com.mima.app.doc.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mima.app.doc.domain.DocAvailabilityVO; import com.mima.app.doc.mapper.DocAvailabilityMapper; import com.mima.app.member.domain.MemberVO; @Service public class DocAvailabilityServiceImpl implements DocAvailabilityService { @Autowired DocAvailabilityMapper docAvailabilityMapper; @Override public String selectDocTime(String day, int docNo) { return docAvailabilityMapper.selectDocTime(day, docNo); } //S: 1005 의사 진료 가능 시간 요일 입력 @Override public int insert(DocAvailabilityVO vo) { return docAvailabilityMapper.insert(vo); } @Override public DocAvailabilityVO checkAvail(MemberVO vo) { return docAvailabilityMapper.checkAvail(vo); } @Override public int update(DocAvailabilityVO vo) { return docAvailabilityMapper.update(vo); } } <file_sep>package com.mima.app.admin.service; public interface NoticeService { } <file_sep>package com.mima.app.likes.domain; import java.util.Date; import lombok.Data; @Data public class LikesVO { private int memberNo; // 회원번호 private Date likeDate; // 좋아요 누른 날짜 private String category; // 카테고리 private int likeMainNo; // 좋아요 번호 } <file_sep>/*WebApp/resources/assets/js/like.js*/ let likeService =(function(){ //좋아요 등록 // 좋아요 클릭 이벤트 $(document).on("click", "#likeBtn", function() { var heart = $(this); var category=cmainCategory; var postNo = cmainNo; /* 멤버번호는 로그인 세션에서 가져올거임 */ var memberNo = 1; var likeAjaxUrl; if (heart.css("background-color") == "rgb(6, 26, 58)") { likeAjaxUrl = "updateNotLike"; $.ajax({ url : "likesDelete", method : "delete", dataType : "json", data : JSON.stringify({ likeMainNo : postNo, memberNo : CurrentNo }), contentType : 'application/json', success : function(data) { console.log("Likes_기록취소_성공"); }// success end }); // ajax end } else { urlJuso = "updateLike"; $.ajax({ url : "likesInsert", method : "post", dataType : "json", data : JSON.stringify({ likeMainNo : postNo, memberNo : CurrentNo }), contentType : 'application/json', success : function() { console.log("Likes 기록입력 성공!!"); }// success end }); // ajax end } console.log(urlJuso); console.log("===========좋아요 수=========="); $.ajax({ url : urlJuso, method : "put", dataType : "json", data : JSON.stringify({ postNo : postNo }), contentType : 'application/json', success : function() { if (urlJuso == "updateLike") { console.log("좋아요_성공") alert("좋아요 성공!!"); heart.css("background-color", "#061a3a"); } else { console.log("좋아요_취소_성공") alert("좋아요 취소!!"); heart.css("background-color", "#eaf8f6"); } }// success end }) // ajax end })// heartIcon end function add(callback, err){ $.ajax({ url:"../replies/", data:$("#replyForm").serialize(), method:"post", dataType:"json", success:function(data){ if(callback) callback(data) }, error: function(err){ console.error(err); } }); } //댓글 조회 function getList(param, callback, err){ var cmainCategory=param.cmainCategory; var cmainNo = param.cmainNo; var page = param.page ||1; $.ajax({ url:"../replies/", method:"get", data:{ cmainCategory: cmainCategory, cmainNo: cmainNo, page:page }, dataType:"json", success: function(data){ console.log(data); if(callback){ callback(data.replyCnt, data.list); } }, error: function(error){ if(error) error(error) } }); } //댓글 삭제 function deleteReply(cno, callback, err){ $.ajax({ url:"../replies/"+cno, method:"delete", dataType:"json", success: function(data){ if(callback){ callback(data) } }, error: function(error){ console.error(error); } }); } //한건댓글 읽기 function read(param, callback, err){ var cno = param.cno; $.ajax({ url:"../replies/"+cno, method:"get", dataType:"json", success: function(data){ if(callback){ callback(data) } }, error: function(error){ console.error(error); } }); } //댓글 수정 function update(editedReply, callback, err){ $.ajax({ url:"../replies/"+editedReply.cno, method:"put", data: JSON.stringify(editedReply), contentType:"application/json; charset=utf-8", success: function(data){ if(callback){ callback(data) } }, error: function(error){ console.error(error); } }); } return {add:add, getList: getList, deleteReply:deleteReply, read:read, update:update}; })();<file_sep>package com.mima.app.member.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.mima.app.member.domain.MemberVO; //로그인 후에 Session에 vo객체를 가져오기 위해 추가한 클래스 p.30 public class CustomUserDetailsService implements UserDetailsService{ @Autowired private MemberService memberService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { MemberVO mvo = memberService.getUserById(username); if (mvo == null) { throw new UsernameNotFoundException("username" + username + "not found"); } System.out.println("==================== Found user ===================="); System.out.println("id : " + mvo.getUsername()); return mvo; } } <file_sep>package com.mima.app.doc.domain; import java.util.Date; import lombok.Data; @Data public class ClinicHoursVO { private int docNo; // 의사번호 private Date closedDate; // 예약 불가 일 private String closedTime; // 예약 불가 시간 private Date regDate; // 등록일 private Date editDate; // 수정일 } <file_sep>package com.mima.app.member.controller; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class LoginController { // 로그인 폼으로 이동 @GetMapping("/login") public String loginForm(String error, String logout, Model model, HttpServletResponse response) { if (error != null) { model.addAttribute("error", "아이디 또는 비밀번호가 틀렸거나 아직 승인되지 않았습니다."); } if (logout != null) { model.addAttribute("logout", "로그아웃 하셨습니다."); } return "member/loginForm"; } } <file_sep>package com.mima.app.admin.domain; import lombok.Data; @Data public class QnaVO { private int qnaNo; // 문의글 번호 private String qnaTitle; // 문의글 제목 private String qnaDate; // 답변 등록일 private String qnaName; // 문의자 이름 } <file_sep>package com.mima.app.admin.mapper; import java.util.List; import com.mima.app.admin.domain.CscVO; public interface CscMapper { // 닥터 대쉬보드 나의 문의 페이지_J29 public List<CscVO> docQna(); } <file_sep>package com.mima.app.likes.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mima.app.likes.domain.LikesVO; import com.mima.app.likes.mapper.LikesMapper; @Service public class LikesServiceImpl implements LikesService { @Autowired LikesMapper likesMapper; // post 좋아요 기록 추가 @Override public int postLikeinsert(LikesVO vo) { return likesMapper.postLikeinsert(vo); } // post 좋아요 기록 확인 @Override public LikesVO postLikesRead(LikesVO vo) { return likesMapper.postLikesRead(vo); } // post 좋아요 기록 삭제 @Override public int postLikedelete(LikesVO vo) { return likesMapper.postLikedelete(vo); } //공용으로 사용 @Override public int likeInsert(LikesVO vo) { return likesMapper.likeInsert(vo); } @Override public int likeDelete(LikesVO vo) { return likesMapper.likeDelete(vo); } } <file_sep>package com.mima.app.comments.service; import java.util.List; import org.apache.ibatis.annotations.Param; import com.mima.app.comments.domain.CommentsPageVO; import com.mima.app.comments.domain.CommentsVO; import com.mima.app.comments.domain.ReplyVO; import com.mima.app.criteria.domain.Criteria; import com.mima.app.session.domain.BookingVO; public interface CommentsService { //CURD public int insert(CommentsVO vo); public int delete(CommentsVO vo); public int update(CommentsVO vo); public CommentsVO read(CommentsVO vo); //게시글번호에 해당하는 댓글 조회 public CommentsPageVO getList(@Param("cri") Criteria cri, @Param("cmainCategory") String cmainCategory, @Param("cmainNo") int cmainNo); // 닥터 대쉬보드 메인 페이지 나의 후기_J public List<CommentsVO> getlatestreviewList(int memberNo); // 닥터 대쉬보드 메인 페이지 나의 후기_J29 public List<CommentsVO> docReview(int memberNo); // 닥터 대쉬보드 메인 페이지 나의 후기 카운트_J07 public int countDocReview(int memberNo); //s:1013 게시글 댓글 닉네임 가져오기 public String getNickname(CommentsVO vo); // 닥터 대쉬보드 나의 후기 페이지 최신순 페이징_J13 public List<CommentsVO> docReviewPage(Criteria cri, int memberNo); // 닥터 대쉬보드 나의 후기 페이지 오래된순 페이징_J13 public List<CommentsVO> docReviewPageOldest(Criteria cri, int memberNo); // 닥터 대쉬보드 나의 후기 페이지 페이징_J13 public int docReviewCount(Criteria cri, int memberNo); // K.10/14 약국 리뷰 조회 public List<CommentsVO> phaReviewList(@Param("cri") Criteria cri, @Param("cmainNo") int cmainNo); // K. 10/14 약국 리뷰 갯수 public int phaReviewCnt(int cmainNo); // 닥터 대쉬보드 나의 후기 페이지 댓글 등록_J20 public int docReplyInsert(ReplyVO vo); // 닥터 대쉬보드 나의 후기 페이지 댓글 수정_J20 public int docReplyUpdate(ReplyVO vo); // 닥터 대쉬보드 나의 후기 페이지 댓글 삭제_J20 public int docReplyDelete(ReplyVO vo); public ReplyVO getReply(int rno); } <file_sep>package com.mima.app.admin.mapper; public interface NoticeMapper { } <file_sep>package com.mima.app.medication.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.mima.app.medication.domain.PillSearchVO; import lombok.extern.java.Log; @Log @Controller public class ApiExplorer { // (K)210929 - 약검색 TEST 페이지 @RequestMapping("/pillsearch") public void search(PillSearchVO vo) throws IOException { StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1471000/DrbEasyDrugInfoService/getDrbEasyDrugList"); /*URL*/ urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=k<KEY>kswBceaC1lOvwdoLaEHRjjQvgNkQwOs%2Fh3MhO%2FWHv8%2BuL0zs6LKHuXP%2Bs2qhQ%3D%3D"); /*Service Key*/ urlBuilder.append("&" + URLEncoder.encode("ServiceKey","UTF-8") + "=" + URLEncoder.encode("인증키(url encode)", "UTF-8")); /*공공데이터포털에서 받은 인증키*/ urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/ urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("3", "UTF-8")); /*한 페이지 결과 수*/ urlBuilder.append("&" + URLEncoder.encode("entpName","UTF-8") + "=" + URLEncoder.encode("한미약품(주)", "UTF-8")); /*업체명*/ urlBuilder.append("&" + URLEncoder.encode("type","UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); /*응답데이터 형식(xml/json) Default:xml*/ URL url = new URL(urlBuilder.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); System.out.println("Response code: " + conn.getResponseCode()); BufferedReader rd; if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); // 전체 조회 //System.out.println(sb.toString()); //System.out.println("============================================"); JSONArray jArry = new JSONObject(new JSONObject(sb.toString()).get("body").toString()).getJSONArray("items"); /* * String value = sb.toString(); * JSONObject firstJson = new JSONObject(value); * String bodyValue = firstJson.get("body").toString(); * JSONObject twoJson = new JSONObject(bodyValue); * JSONArray jArry = twoJson.getJSONArray("items"); * System.out.println(jArry.getJSONObject(0)); * System.out.println("******************배열안에******************"); * System.out.println(jArry.getJSONObject(0).get("entpName")); */ System.out.println(jArry); List<PillSearchVO> pList = new ArrayList<PillSearchVO>(); for (int i=0; i<jArry.length(); i++) { JSONObject JO = jArry.getJSONObject(i); PillSearchVO pill = new PillSearchVO(); if(!JO.isNull("entpName")) { pill.setEntpName(String.valueOf(JO.get("entpName"))); } if(!JO.isNull("itemName")) { pill.setItemName(String.valueOf(JO.get("itemName"))); } if(!JO.isNull("itemSeq")) { pill.setItemSeq(Integer.parseInt(JO.get("itemSeq").toString())); } if(!JO.isNull("efcyQesitm")) { pill.setEfcyQesitm(String.valueOf(JO.get("efcyQesitm"))); } if(!JO.isNull("useMethodQesitm")) { pill.setUseMethodQesitm(String.valueOf(JO.get("useMethodQesitm"))); } if(!JO.isNull("atpnWarnQesit")) { pill.setAtpnWarnQesitm(String.valueOf(JO.get("atpnWarnQesit"))); } if(!JO.isNull("atpnQesitm")) { pill.setAtpnQesitm(String.valueOf(JO.get("atpnQesitm"))); } if(!JO.isNull("seQesitm")) { pill.setSeQesitm(String.valueOf(JO.get("seQesitm"))); } if(!JO.isNull("depositMethodQesitm")) { pill.setDepositMethodQesitm(String.valueOf(JO.get("depositMethodQesitm"))); } if(!JO.isNull("openDe")) { pill.setOpenDe(String.valueOf(JO.get("openDe"))); } if(!JO.isNull("updateDe")) { pill.setUpdateDe(String.valueOf(JO.get("updateDe"))); } if(!JO.isNull("itemImage")) { pill.setItemImage(String.valueOf(JO.get("itemImage"))); } pList.add(pill); } System.out.println("!!!!!!!!!!!!!최종 리스트!!!!!!!!!!!!!!!!!"); System.out.println(pList); // vo에 결과값 담기 /* //Response code: 200 {"header": {"resultCode":"00","resultMsg":"NORMAL SERVICE."}, "body": {"pageNo":1,"totalCount":69,"numOfRows":3,"items": [ { "entpName":"한미약품(주)", "itemName":"티어드롭점안액(포비돈)", "itemSeq":"200301820", "efcyQesitm":"<p>이 약은 건조한 눈, 하드콘택트렌즈 착용시에 사용합니다.<\/p>", "useMethodQesitm":"<p>1회 1~2방울 1일 4~5회 점안합니다.<\/p><p>증상에 따라 적절히 증감합니다.<\/p>", "atpnWarnQesitm":null, "atpnQesitm":"<p>치료 중에는 소프트콘택트렌즈의 착용을 피하십시오.<\/p><p>점안용으로만 사용하십시오.<\/p><p>오염을 방지하기 위해 될 수 있는 한 공동으로 사용하지 마십시오.<\/p>", "intrcQesitm":null, "seQesitm":"<p>매우 드물게 과민반응이 나타날 수 있습니다.<\/p>", "depositMethodQesitm":"<p>습기와 빛을 피해 실온에서 보관하십시오.<\/p><p>어린이의 손이 닿지 않는 곳에 보관하십시오.<\/p>", "openDe":"2021-01-29 00:00:00", "updateDe":"20210129", "itemImage":null }, { "entpName":"한미약품(주)", "itemName":"스파부틴정100밀리그램(트리메부틴말레산염)", "itemSeq":"198100428", "efcyQesitm":"<p>이 약은 식도역류 및 열공헤르니아, 위 십이지장염, 위ㆍ십이지장궤양에 있어서의 소화기능이상 (복통, 소화불량,구역, 구토)과 과민성대장증후군 및 경련성 결장과 소아 질환(습관성 구토, 비감염성 장관 통과 장애(변비, 설사))에 사용합니다.<\/p>", "useMethodQesitm":"<p>성인은 1회 1~2정(100~200 mg) 1일 3회 식전에 복용합니다.<\/p><p>연령, 증상에 따라 적절히 증감합니다.<\/p>", "atpnWarnQesitm":null, "atpnQesitm":"<p>갈락토오스 불내성, Lapp 유당분해효소 결핍증 또는 포도당-갈락토오스 흡수장애 등의 유전적인 문제가 있는 환자는 이 약을 복용하지 마십시오.<\/p><p>이 약을 복용하기 전에 황색4호에 과민증 환자 또는 경험자, 임부 또는 임신하고 있을 가능성이 있는 여성 및 수유부는 의사 또는 약사와 상의하십시오.<\/p>", "intrcQesitm":null, "seQesitm":"<p>드물게 변비, 설사, 복명, 구역, 구토, 소화장애, 구갈, 구내마비감, 심계항진, 피로감, 졸음, 현기, 권태감, 두통, GOT, GPT상승이 나타날 수 있습니다.<\/p><p>드물게 발진 등이 나타나는 경우 복용을 즉각 중지하고 의사 또는 약사와 상의하십시오.<\/p>", "depositMethodQesitm":"<p>실온에서 보관하십시오.<\/p>", "openDe":"2021-01-29 00:00:00", "updateDe":"20210129", "itemImage":"https://nedrug.mfds.go.kr/pbp/cmn/itemImageDownload/1MucEwTxVj2" }, { "entpName":"한미약품(주)", "itemName":"제텐씨정", "itemSeq":"198501220", "efcyQesitm":"<p>이 약은 육체피로, 임신ㆍ수유기, 병중ㆍ병후(병을 앓는 동안이나 회복 후)의 체력 저하 시, 노년기의 비타민 B1, B2, B6, C, E의 보급과 구각염, 구순염, 구내염, 설염, 습진, 피부염 증상의 완화, 햇빛,피부병 등에 의한 색소침착(기미, 주근깨)의 완화, 잇몸출혈·비출혈(코피) 예방과 아연의 보급에 사용합니다.<\/p>", "useMethodQesitm":"<p>만 12세 이상 및 성인은 1회 1정씩, 1일 1회 식후에 복용합니다.<\/p>", "atpnWarnQesitm":null, "atpnQesitm":"<p>이 약에 과민증 환자, 만 12개월 미만의 젖먹이는 이 약을 복용하지 마십시오.<\/p><p>이 약을 복용하기 전에 임부 또는 임신하고 있을 가능성이 있는 여성 및 수유부, 미숙아, 유아, 고옥살산뇨증(뇨중에 과량의 수산염이 배설되는 상태), 심장ㆍ순환기계기능 장애, 신장장애, 저단백혈증, 통풍, 신장결석, 혈전성 소인이 있는 환자, 폴산이 부족한 환자, 황색4호에 과민증 환자 또는 경험자는 의사 또는 약사와 상의하십시오.<\/p><p>정해진 용법과 용량을 잘 지키십시오.<\/p><p>각종 요검사 시에 혈당의 검출을 방해할 수 있으며, 요를 황색으로 변하게 하여 임상검사치에 영향을 줄 수 있습니다.<\/p>", "intrcQesitm":"<p>인산염, 칼슘염, 경구용 테트라사이클린계 제제, 제산제, 레보도파와 함께 복용하지 마십시오.<\/p><p>에스트로겐을 포함한 경구용 피임제, 항알도스테론제, 트리암테렌과 함께 복용 시 의사 또는 약사와 상의하십시오.<\/p><p>녹차, 홍차 등 탄닌을 함유하는 차는 복용중, 복용전후에는 피하십시오.<\/p>","seQesitm":"<p>위부불쾌감, 설사, 변비, 발진, 발적, 구역, 구토, 묽은 변, 위장관장애, 소화장애, 상복부통증, 저혈압, 폐부종, 생리가 예정보다 빨라지거나 양이 점점 많아지고, 출혈이 오래 지속 되는 경우 복용을 즉각 중지하고 의사 또는 약사와 상의하십시오.<\/p>", "depositMethodQesitm":"<p>습기와 빛을 피해 실온에서 보관하십시오.<\/p><p>어린이의 손이 닿지 않는 곳에 보관하십시오.<\/p>", "openDe":"2021-01-29 00:00:00", "updateDe":"20210129", "itemImage":"https://nedrug.mfds.go.kr/pbp/cmn/itemImageDownload/151732685268700094" }] } } // 데이터 끝 */ } } <file_sep>package com.mima.app.medication.domain; import lombok.Data; @Data public class DurDangerVO { // 병용금기 요청 변수 private String typeName; // Drug 유형 private String ingrCode; // Drug 성분코드 private String itemName; // 품목명 private int resultCode; // 결과코드 private String resultMsg; // 결과메세지 private int numOfRows; // 한 페이지 결과 수 private int pageNo; // 페이지 번호 private int totalCount; // 전체 결과 수 private String DurSeq; // 약 일련번호 private String typeCode; // 유형코드 private String mix; // 단일,복합 private String ingrKorName; // 약 성분 private String ingrEngName; // 약 성분(영문) private String mixIngr; // 복합제 private String itemSeq; // 품목기준코드 private String entpName; // 업체명 private String chart; // 성상 private String formCode; // 제형구분코드 private String etcOtcCode; // 전문일반 구분코드 private String classCode; // 약효분류코드 private String formName; // 제형 private String etcOtcName; // 전문/일반 private String className; // 약효분류 private String mainIngr; // 주성분 private String mixTureDurSeq; // 병용금기 약번호 private String mixTureMix; // 병용금기 복합제 private String mixTureIngrCode; // 병용금기 DUR 성분코드 private String mixTureIngrKorName; // 병용금기 약 성분 private String mixTureIngrEngName; // 병용금기 약 성분(영문) private String mixTureItemSeq; // 병용금기품목기준코드 private String mixTureItemName; // 병용금기품목명 private String mixTureEntpName; // 병용금기 업체명 private String mixTureFormCode; //병용금기 제형구분코드 private String mixTureEtcOtcCode; // 병용금기 전문일반구분코드 private String mixTureClassCode; // 병용금기 약효분류 코드 private String mixTureFormName; // 병용금기 제형 private String mixTureEtcOtcName; // 병용금기 전문/일반 private String mixTureClassName; // 병용금기 약효분류 private String mixTureMainIngr; // 병용금기 주성분 private String notificationDate; // 고시일자 private String prohbtContent; // 금기내용 private String remart; // 비고 private String itemPermitDate; // 품목허가일자 private String mixTureItemPermitDate; // 병용금기 품목 허가일자 private String mixTureChart; // 병용금기성상 } <file_sep>package com.mima.app.medication.mapper; public interface MedicationMapper { } <file_sep>package com.mima.app.meditation.domain; import java.util.Date; import lombok.Data; @Data public class MeditationVO { private int meditationNo; // 명상번호 private String title; // 제목 private String contents; // 내용 private String meditationFile; // 파일 private int meditationLike; // 명상 좋아요 수 private int hit; // 조회수 private String category; // 카테고리 private Date regDate; // 등록일 private Date editDate; // 수정일 private String teacherName; // 명상가 이름 private String teacherInfo; // 명상가 정보 private String teacherPhoto; // 명상가 사진 private String meditationThumb; // 토탈리스트에 들어갈 썸넬사진 private String vFileUuid; // 명상비디오 uuid private int commentsCnt; // 명상에 달린 댓글 수 private String fileName; //게시글 하나에 들어가있는 첨부파일 private MeditAttachVO attachFile; //s:1013 로그인세션멤버번호담기 private int memberNo; //s:1013 좋아요 1 또는 널!!!! private int likesNo; } <file_sep>package com.mima.app.doc.controller; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.log; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.text.DecimalFormat; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.rowset.serial.SerialException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; 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.mvc.support.RedirectAttributes; import com.mima.app.admin.domain.CscVO; import com.mima.app.admin.service.CscService; import com.mima.app.comments.domain.CommentsVO; import com.mima.app.comments.domain.ReplyVO; import com.mima.app.comments.service.CommentsService; import com.mima.app.criteria.domain.Criteria; import com.mima.app.criteria.domain.PageVO; import com.mima.app.doc.domain.DocAvailabilityVO; import com.mima.app.doc.domain.DocInfoVO; import com.mima.app.doc.domain.MentalSubjectVO; import com.mima.app.doc.domain.PartnerDoctorVO; import com.mima.app.doc.service.DocAvailabilityService; import com.mima.app.doc.service.MentalSubjectService; import com.mima.app.doc.service.PartnerDoctorService; import com.mima.app.meditation.domain.MeditAttachVO; import com.mima.app.member.domain.ExperienceVO; import com.mima.app.member.domain.MemberBookingVO; import com.mima.app.member.domain.MemberVO; import com.mima.app.member.service.ExperienceService; import com.mima.app.member.service.MemberService; import com.mima.app.session.domain.BookingVO; import com.mima.app.session.domain.PtInfoVO; import com.mima.app.session.service.BookingService; import lombok.extern.java.Log; // 타일스 때문에 RequestMapping제거 p.10/06 // 타일스로 인해 아래 맵핑 해주는 클래스 String으로 수정 return으로 페이지 이동 p.10/06 // 시큐리티 권한 부여 때문에 전체적인 Mapping 수정 p.10/11 @Log @Controller public class PatnerDoctorController { @Autowired BookingService bookingService; @Autowired CommentsService commentsService; @Autowired CscService cscService; @Autowired PartnerDoctorService doctorService; @Autowired MemberService memberService; @Autowired ExperienceService experienceService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired DocAvailabilityService docAvailabilityService; @Autowired MentalSubjectService mentalSubjectService; @Value("#{global['path']}") String path; // 닥터 대쉬보드 메인 페이지_J @GetMapping("doctor/docMain") public String docMain(Model model, BookingVO bookingvo, CommentsVO commentsvo, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); int memberNo = mvo.getMemberNo(); model.addAttribute("member", mvo); model.addAttribute("clinicName", clinicName(request)); model.addAttribute("countGetList", bookingService.countGetList(memberNo)); model.addAttribute("countPatientList", bookingService.countPatientList(memberNo)); model.addAttribute("countDocReview", commentsService.countDocReview(memberNo)); model.addAttribute("bookingList", bookingService.getList(memberNo)); model.addAttribute("getlatestapptList", bookingService.getlatestapptList(memberNo)); model.addAttribute("getlatestreviewList", commentsService.getlatestreviewList(memberNo)); return "docDash/docMain"; } // 닥터 대쉬보드 예약관리 페이지_J @GetMapping("doctor/apptManage") public String apptManage(Model model, BookingVO bookingvo, @ModelAttribute("cri") Criteria cri, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); int memberNo = mvo.getMemberNo(); int total = bookingService.apptManageCount(cri, memberNo); model.addAttribute("member", mvo); model.addAttribute("clinicName", clinicName(request)); model.addAttribute("apptListPage", bookingService.apptListPage(cri, memberNo)); model.addAttribute("apptListSoonPage", bookingService.apptListSoonPage(cri, memberNo)); model.addAttribute("apptListCanceledPage", bookingService.apptListCanceledPage(cri, memberNo)); model.addAttribute("pageMaker", new PageVO(cri, total)); return "docDash/apptManage"; } // 닥터 대쉬보드 진료내역 페이지_J29 @GetMapping("doctor/apptHistory") public String apptHistory(Model model, BookingVO bookingvo, @ModelAttribute("cri") Criteria cri, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); int memberNo = mvo.getMemberNo(); int total = bookingService.apptHistoryCount(cri, memberNo); model.addAttribute("clinicName", clinicName(request)); model.addAttribute("apptHistoryPage", bookingService.apptHistoryPage(cri, memberNo)); model.addAttribute("pageMaker", new PageVO(cri, total)); return "docDash/apptHistory"; } // 닥터 대쉬보드 나의 환자들 페이지_J29. J06 @GetMapping("doctor/patientList") public String patientList(Model model, MemberBookingVO memberbookingvo, @ModelAttribute("cri") Criteria cri, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); int memberNo = mvo.getMemberNo(); int total = memberService.patientListCount(cri, memberNo); model.addAttribute("member", mvo); model.addAttribute("clinicName", clinicName(request)); model.addAttribute("patientListPage", memberService.patientListPage(cri, memberNo)); model.addAttribute("pageMaker", new PageVO(cri, total)); return "docDash/patientList"; } // 닥터 대쉬보드 나의 후기 페이지_J29 @GetMapping("doctor/docReview") public String docReview(Model model, CommentsVO commentsvo, ReplyVO vo, HttpServletRequest request, @ModelAttribute("cri")Criteria cri) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); int memberNo = mvo.getMemberNo(); int total = commentsService.docReviewCount(cri, memberNo); model.addAttribute("clinicName", clinicName(request)); /* model.addAttribute("docReview", commentsService.docReview(memberNo)); */ if (cri.getKeyword() == null || cri.getKeyword().equals("latest")) { model.addAttribute("docReviewPage", commentsService.docReviewPage(cri, memberNo)); } else { model.addAttribute("docReviewPage", commentsService.docReviewPageOldest(cri, memberNo)); } model.addAttribute("pageMaker", new PageVO(cri,total)); return "docDash/docReview"; } // 닥터 대쉬보드 나의 후기 페이지 댓글 등록_J20 @PostMapping("doctor/docReplyInsert") @ResponseBody public ReplyVO docReplyInsert(ReplyVO replyvo) { int result = commentsService.docReplyInsert(replyvo); ReplyVO vo = new ReplyVO(); if ( result > 0 ) { vo = commentsService.getReply(replyvo.getRno()); } return vo; } // 닥터 대쉬보드 나의 후기 페이지 댓글 수정_J20 @PostMapping("doctor/docReplyUpdate") @ResponseBody public ReplyVO docReplyUpdate(ReplyVO replyvo) { int result = commentsService.docReplyUpdate(replyvo); ReplyVO vo = new ReplyVO(); if ( result > 0 ) { vo = commentsService.getReply(replyvo.getRno()); } return vo; } // 닥터 대쉬보드 나의 후기 페이지 댓글 삭제_J20 @PostMapping("doctor/replyDelete") @ResponseBody public int replyDelete(ReplyVO replyvo) { return commentsService.docReplyDelete(replyvo); } @GetMapping("doctor/docQna") public String docQna(Model model, CscVO cscvo) { model.addAttribute("docQna", cscService.docQna()); return "docDash/docQna"; } // 닥터 대쉬보드 프로필 페이지 수정폼_J04 /* * @GetMapping("docProfileFrom") public String docProfile() { * return"docDash/docProfile"; } */ // 닥터 대쉬보드 패스워드 변경 페이지 수정 폼_J04 @GetMapping("doctor/docPwChangeForm") public String pwUpdateForm(Model model, HttpServletRequest request) { // 닥터 프로필 병원 이름 호출_J17 model.addAttribute("clinicName", clinicName(request)); return "docDash/docPwChange"; } // 닥터 대쉬보드 패스워드 변경 페이지 수정 처리_J04 @PostMapping("doctor/docPwChange") @ResponseBody public boolean pwUpdate(MemberVO vo, HttpServletRequest request) { String password = vo.getPassword(); String memberId = vo.getMemberId(); MemberVO pass = memberService.findPassword1(memberId); Boolean matchPass = bCryptPasswordEncoder.matches(password, pass.getPassword()); //비교 System.out.println(matchPass); return matchPass; } // 닥터 비밀번호 변경 p.10/11 @PostMapping("doctor/updatePassword") @ResponseBody public int updatePassword(MemberVO vo) { vo.setPassword(<PASSWORD>.encode(vo.getPassword())); int result = memberService.updatePassword(vo); return result; } // 닥터 진료노트_J06. J10 @GetMapping("doctor/cnote") public String getCnote(Model model,int bookingNo, PtInfoVO vo) { vo.setBookingNo(bookingNo); model.addAttribute("cnote", memberService.getCnote(vo)); return "docDash/cnote"; } // 닥터 처방전 새창_J06. J12 @GetMapping("doctor/prescription") public String prescription(Model model,int bookingNo, PtInfoVO vo) { vo.setBookingNo(bookingNo); return "docDash/prescription"; } // 닥터 대쉬보드 병원 이름_J13 public String clinicName(HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO mvo = (MemberVO) session.getAttribute("session"); int memberNo = mvo.getMemberNo(); String clinicName = doctorService.clinicName(memberNo); return clinicName; } //s:1005 docProfileInsertFrm @GetMapping("doctor/docProfileInsertForm") public String docProfileInsertForm(Model model, MemberVO mVo, ExperienceVO expVo, DocInfoVO docVo, HttpServletRequest request ) throws IOException { // 닥터 프로필 병원 이름 호출_J17 model.addAttribute("clinicName", clinicName(request)); //s:1010 세션에서 의사번호 가져와서 파트너의사 테이블 검색 후 널이면 인서트 널이 아니면 수정 HttpSession session = request.getSession(); mVo = (MemberVO) session.getAttribute("session"); docVo = doctorService.checkDocDetail(mVo); System.out.println("파트너닥터컨트롤러 값이 있나 확인"+docVo); if(docVo != null) { expVo.setMemberNo(docVo.getMemberNo()); model.addAttribute("doc", doctorService.getDocDetail(docVo)); model.addAttribute("expList", experienceService.getExpList(expVo)); } //프로필 사진 가져오기 시작 if(docVo.getProfilePhoto() != null) { File file = new File("c:/upload",docVo.getProfilePhoto()); if(! file.exists()) { return "docDash/docProfileInsertForm"; } FileInputStream inputStream = new FileInputStream(file); ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = inputStream.read(buf))!= -1) { byteOutStream.write(buf,0,len); } byte[] fileArray = byteOutStream.toByteArray(); String s = new String (Base64.getEncoder().encodeToString(fileArray)); String changeString = "data:image/"+ "png" + ";base64," + s; docVo.setProfilePhoto(changeString); }//프로필 사진 가져오기 끝 return "docDash/docProfileInsertForm"; } //s:1020 의사 프로필 페이지 학력조회 ajax @GetMapping("doctor/getEduAjax") @ResponseBody public DocInfoVO getEduAjax(MemberVO mVo, DocInfoVO docVo, HttpServletRequest request ) { //s:1010 세션에서 의사번호 가져와서 파트너의사 테이블 검색 후 널이면 인서트 널이 아니면 수정 HttpSession session = request.getSession(); mVo = (MemberVO) session.getAttribute("session"); System.out.println("세션확인..."+mVo); docVo = doctorService.checkEduDetail(mVo); System.out.println("확인중..."+docVo); return docVo; } //s:1020 의사 프로필 페이지 학력입력 ajax @PostMapping("doctor/insertEduAjax") @ResponseBody public int insertEduAjax(MemberVO mVo, PartnerDoctorVO docVo, HttpServletRequest request ) { //s:1010 세션에서 의사번호 가져와서 파트너의사 테이블 검색 후 널이면 인서트 널이 아니면 수정 HttpSession session = request.getSession(); mVo = (MemberVO) session.getAttribute("session"); docVo.setMemberNo(mVo.getMemberNo()); System.out.println("입력할 학력 조회" +docVo); int result = doctorService.insertEduAjax(docVo); return result; } //s:1020 의사 프로필 페이지 학력수정 ajax @PostMapping("doctor/updateEduAjax") @ResponseBody public int updateEduAjax(MemberVO mVo, PartnerDoctorVO docVo, HttpServletRequest request ) { //s:1010 세션에서 의사번호 가져와서 파트너의사 테이블 검색 후 널이면 인서트 널이 아니면 수정 HttpSession session = request.getSession(); mVo = (MemberVO) session.getAttribute("session"); docVo.setMemberNo(mVo.getMemberNo()); System.out.println("입력할 학력 조회" +docVo); int result = doctorService.updateEduAjax(docVo); return result; } //s:1020 의사 프로필 페이지 경력조회 ajax @GetMapping("doctor/getExpAjax") @ResponseBody public List<ExperienceVO> getExpAjax(MemberVO mVo, ExperienceVO expVo, HttpServletRequest request) { //s:1010 세션에서 의사번호 가져와서 파트너의사 테이블 검색 후 널이면 인서트 널이 아니면 수정 HttpSession session = request.getSession(); mVo = (MemberVO) session.getAttribute("session"); expVo.setMemberNo(mVo.getMemberNo()); System.out.println("경력확인중.."+expVo); return experienceService.getExpList(expVo); } //s:1020 의사 프로필 페이지 경력 입력 ajax @PostMapping("doctor/insertExpAjax") @ResponseBody public List<ExperienceVO> insertExpAjax(@RequestBody ExperienceVO expVo, HttpServletRequest request ) { System.out.println("입력할 경력 조회" +expVo); int result = experienceService.insertExpAjax(expVo); return experienceService.getExpList(expVo); } //s:1020 의사 프로필 페이지 경력 입력 ajax @PostMapping("doctor/delExpAjax") @ResponseBody public int delExpAjax(@RequestBody ExperienceVO expVo, HttpServletRequest request ) { System.out.println("경력삭제" +expVo); int result = experienceService.deleteExp(expVo); return result; } //s:1020 의사 프로필 페이지 경력수정 ajax @PostMapping("doctor/updateExpAjax") @ResponseBody public int updateExpAjax(ExperienceVO expVo, HttpServletRequest request ) { System.out.println("수정할 경력 조회" +expVo); int result = experienceService.updateExpAjax(expVo); return result; } // S:1005 닥터 진료가능 요일 시간 등록 폼 페이지 @GetMapping("doctor/docProfileForm") public String docProfileFrom(Model model, MemberVO mVo, DocAvailabilityVO availVo, MentalSubjectVO subVo, HttpServletRequest request ) { //s:1017 added. HttpSession session = request.getSession(); mVo = (MemberVO) session.getAttribute("session"); String clinicName=doctorService.clinicName(mVo.getMemberNo()); availVo = docAvailabilityService.checkAvail(mVo); System.out.println("checking 진료가능시간 전체"+ availVo); subVo = mentalSubjectService.getPriceCategory(mVo.getMemberNo()); System.out.println("checking 진료과목 전체"+ subVo); model.addAttribute("cName", clinicName); model.addAttribute("time", availVo); model.addAttribute("sub", subVo); // 닥터 프로필 병원 이름 호출_J17 model.addAttribute("clinicName", clinicName(request)); return "docDash/docProfileForm"; } //s:1006 의사프로필등록 @PostMapping("doctor/register") public String register(PartnerDoctorVO vo, MemberVO mVo, ExperienceVO expVo, MultipartFile[] uploadFile, RedirectAttributes rttr, HttpServletRequest request) { HttpSession session = request.getSession(); MemberVO membervo = (MemberVO) session.getAttribute("session"); int memberNo = membervo.getMemberNo(); vo.setMemberNo(memberNo); System.out.println("파트너 의사 컨트롤러-> 인서트// 등록할때 보 보는거임======" + vo.getProfileEducation()); //s:1006 파트너의사테이블에 저장 doctorService.docProfileInsert(vo); //s:1007 멤버 테이블 주소 업데이트 doctorService.docAddrUpdate(mVo); System.out.println("파트너 의사 컨트롤러-> 멤버테이블 주소 업뎃 보 보는거임======" + mVo); return "redirect:/doctor/docProfileInsertForm"; } //s:1006 첨부파일 등록 폼---의사 프로필사진 @PostMapping("doctor/docAjaxInsert") @ResponseBody // 업로드 폼에서 인풋에서 타입이 파일이기 때문에 멀티파트파일로 주고 그 네임을 찾아서 여기 업로드파일 변수에 담아줌 public MeditAttachVO docAjaxInsert(MultipartFile uploadFile, MeditAttachVO vo) throws IllegalStateException, IOException { MeditAttachVO attachVo = null; String imgPath = path; MultipartFile uFile = uploadFile; if (!uFile.isEmpty() && uFile.getSize() > 0) { String filename = uFile.getOriginalFilename(); // 사용자가 업로드한 파일명 // 파일 자체도 보안을 걸기 위해 파일이름 바꾸기도 한다. 원래 파일명과 서버에 저장된 파일이름을 따로 관리 // String saveName = System.currentTimeMillis()+""; //이거를 팀별로 상의해서 지정해 주면 된다. // File file =new File("c:/upload", saveName); UUID uuid = UUID.randomUUID(); File file = new File(imgPath, uuid + filename); System.out.println("이미지패스랑 유유아디파일"+file); uFile.transferTo(file); attachVo = new MeditAttachVO(); // attachVO list안에 파일정보 저장하기 위해 만듦 attachVo.setPImgName(filename); attachVo.setUuid(uuid.toString()); attachVo.setUploadPath(imgPath); System.out.println("어태치보 확인"+attachVo); } return attachVo; } //s:1008 전체 의사 리스트 페이지로 이동 @GetMapping("/getTotalDocList") public String getTotalDocList(Model model, @ModelAttribute("cri") Criteria cri) { int total = doctorService.totalDocNumCount(cri); model.addAttribute("list", doctorService.getTotalDocList(cri) ); model.addAttribute("pageMaker", new PageVO(cri, total)); return "/docList/getTotalDocList"; } //s:1007 의사 프로필 디테일 페이지로 이동하는거 s:1012 @GetMapping("/docProfileDetail") public String docProfileDetail(DocInfoVO docVo, Model model, MemberVO mVo, CommentsVO comVo, ExperienceVO expVo, @ModelAttribute("cri")Criteria cri, HttpServletRequest request) { System.out.println("넘겨받은 멤버보"+mVo); docVo = doctorService.checkDocDetail(mVo); expVo.setMemberNo(mVo.getMemberNo()); //s:1019 의사 리뷰 가져오기 int mNo = mVo.getMemberNo(); //토탈리뷰수 int reviewTotal = commentsService.docReviewCount(cri, mNo); System.out.println("총 리뷰 숫자"+ reviewTotal); if(docVo !=null) { docVo = doctorService.getDocDetail(docVo); System.out.println(docVo+"보 값 확인"); System.out.print("테이블에 값 잇음"); List<ExperienceVO> expList = experienceService.getExpList(expVo); model.addAttribute("item", docVo); model.addAttribute("expList", expList); //의사리뷰리스트 model.addAttribute("docReviewPage", commentsService.docReviewPage(cri, mNo)); model.addAttribute("reviewTotalNum", reviewTotal); model.addAttribute("pageMaker", new PageVO(cri,reviewTotal)); return "/docList/docProfileDetail"; }else { System.out.print("테이블에 값 없음 노노 "); model.addAttribute("message", "No details saved for this doctor!"); return "/tiles/errorPage"; } } //p.10.13 의사 경력 등록 @PostMapping("docExperienceInsert") public int docExperienceInsert() { return 1; } // p.10/14 의사 진료과목에 따른 리스트 페이지 @PostMapping("/subjectDoclist") public String subjectDoclist(String category1, String category2, String category3, Model model) { model.addAttribute("list", doctorService.subjectDoclist(category1, category2, category3)); System.out.println("==========================" + category1); model.addAttribute("category", category1); return "/docList/getSubjectDocList"; } //s:1021 제은이꺼 훔쳐옴 의사 dash 프로필 이미지 불러오기 @RequestMapping(value = "/doctor/FileDown.do") public void cvplFileDownload(@RequestParam Map<String, Object> commandMap, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("파일 다운로드 커맨드맵 이미지"+commandMap.toString()); File uFile = new File(path, (String)commandMap.get("fname")); long fSize = uFile.length(); if (fSize > 0) { String mimetype = "application/x-msdownload"; response.setContentType(mimetype); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(uFile)); out = new BufferedOutputStream(response.getOutputStream()); FileCopyUtils.copy(in, out); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { in.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } } }//s:1021 제은이꺼 훔쳐옴 의사 dash 프로필 이미지 불러오기 끝 //s:1021 제은이꺼 훔쳐옴 의사 totaList 프로필 이미지 불러오기 @RequestMapping(value = "/FileDown.do") public void cvplFileDownloadDocList(@RequestParam Map<String, Object> commandMap, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("파일 다운로드 커맨드맵 이미지"+commandMap.toString()); File uFile = new File(path, (String)commandMap.get("fname")); long fSize = uFile.length(); if (fSize > 0) { String mimetype = "application/x-msdownload"; response.setContentType(mimetype); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(uFile)); out = new BufferedOutputStream(response.getOutputStream()); FileCopyUtils.copy(in, out); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { in.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } } }//s:1021 제은이꺼 훔쳐옴 의사 리스트 프로필 이미지 불러오기 끝 } <file_sep>package com.mima.app.admin.service; import java.util.List; import com.mima.app.admin.domain.CscVO; public interface CscService { // 닥터 대쉬보드 나의 문의 페이지_J29 public List<CscVO> docQna(); } <file_sep>package com.mima.app.member.service; import java.util.List; import com.mima.app.criteria.domain.Criteria; import com.mima.app.member.domain.MemberBookingVO; import com.mima.app.member.domain.MemberVO; import com.mima.app.session.domain.BookingVO; import com.mima.app.session.domain.PtInfoVO; public interface MemberService { // 한건 조회 및 아이디 중복 체크 public int idCheck(MemberVO vo); // 닉네임 중복 체크 public int nickNameCheck(MemberVO vo); // 의사 약사 면허 체크 public int licenseCheck(MemberVO vo); // 아이디 찾기 p-29 public String findMemberId(MemberVO vo); // 아이디 이메일로 초기화 유무 묻기 p-29 public int findPassword(MemberVO vo); // 로그인 public MemberVO memberLogin(MemberVO vo); // 회원가입 public int memberInsert(MemberVO vo); // 파트너 회원가입 (의사/약사) public int partnerMemberInsert(MemberVO vo); // status가 y인 의사 조회 p.10/04 public List<MemberVO> selectDoctorY(); //e.29 // 파트너 의사 / 약국 승인 유무 검색 public List<MemberVO> patnerStatusSelect(); //e.29 // 파트너 의사 / 약국 승인 등록 public int patnerStatusUpdate(MemberVO vo); // 비밀번호 초기화 시 멤버 테이블 비밀번호 업데이트 p.30 public int passwordResetUpdate(MemberVO vo); // 유저 세션 유지 위한 p.30 public MemberVO getUserById(String memberId); // 닥터 비밀번호 변경_J04 public int docPwChange(MemberVO vo); // 환자 대쉬보드 비밀번호 변경 e.11 public int ptPwChange(MemberVO vo); // 닥터 나의 환자들 조회_J06 public List<MemberBookingVO> patientList(int memberNo); // 닥터 대쉬보드 나의 환자들 페이징_J13 public List<MemberBookingVO> patientListPage(Criteria cri, int memberNo); // 닥터 대쉬보드 나의 환자들 페이징 데이터 수 전체조회_J13 public int patientListCount(Criteria cri, int memberNo); // 닥터 진료내역 페이지 선택한 환자의 진료노트 조회_J10 public PtInfoVO getCnote(PtInfoVO vo); // 약배달 신청유무 변경 K.10/11 public int deliveryStatusUpdate(MemberVO vo); // 약배달 신청 유무 확인 K.10/11 public String deliveryStatus(int memberNo); // 현재 비밀번호 확인을 위해 DB에 저장된 비밀번호 가져오기 p.10/11 public MemberVO findPassword1(String memberId); // 의사 비밀번호 변경 p.10/11 public int updatePassword(MemberVO vo); } <file_sep>package com.mima.app.likes.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.mima.app.likes.domain.LikesVO; import com.mima.app.likes.service.LikesService; @Controller @RequestMapping("/likes/*") public class LikesController { @Autowired LikesService likeService; // like 기록 등록 @PostMapping("/likesInsert") @ResponseBody public int likeInsert(@RequestBody LikesVO vo, Model model, RedirectAttributes rttr) { System.out.println("LikesVO test=== like insert" + vo); return likeService.likeInsert(vo); } // like 기록 등록 취소 @DeleteMapping("likesDelete") @ResponseBody public int likesDelete(@RequestBody LikesVO vo, Model model) { System.out.println("LikesVO test=== like delete" + vo); return likeService.likeDelete(vo); } } <file_sep>package com.mima.app.member.domain; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data; //약국 의사 경력 테이블에 사용하는 보입니다. s:1007 @Data public class ExperienceVO { private int expNo; private String title; private String detail; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date fromDate; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date toDate; private int memberNo; private Date regDate; private Date editDate; }
91b0c274a2cab968820e4972759f8396e574bbff
[ "JavaScript", "Java" ]
55
Java
Cbear1234/MIMA
e2b94069dfdcce4a51ad34ba4eac588128740846
7bda0835a7252caa0f77a49007d5d693375246c4
refs/heads/master
<repo_name>JingweiZuo/MultivariateTimeSeriesMining<file_sep>/venv/use/shapelet.py import use.similarity_measures as sm import numpy as np class Shapelet(object): def __init__(self): self.id = id(self) self.name = '' # self.time = None self.subsequence = None self.class_shapelet = '' self.differ_distance = 0.0 self.normal_distance = 0.0 self.dist_threshold = 0.0 self.dimension_name = '' # [ts_target_name1, ts_target_name2, ...], Array[string] self.matching_ts = [] # {ts_target_name:[idx1,idx2,...]}, dict{String:Array[]} self.matching_indices = {}
089f5543f83d38352f9e2493b00e77c3b1fa516f
[ "Python" ]
1
Python
JingweiZuo/MultivariateTimeSeriesMining
3203c7ad74615b7a169799f978085e7a0e426de5
878312d09074efe385a70abf438401b2030d468d
refs/heads/main
<file_sep># user-behavioral-data-processing-pipeline - The main purpose of this pipeline is to collect user behavior data for the BI team for further analytics. - The data will be consumed from Kafka by Spark Streaming and will be stored in the HDFS as Parquet files. - The data will be stored in HDFS on a daily basis. #### Kafka message format! ```json { "os":"mac", "src":"amazon.com", "browser":"chrome", "clicks":{ "clickCount":2, "clickDetails":[ { "x":"345", "y":"783", "timestamp":1608964744561 }, { "x":"215", "y":"976", "timestamp":1608964744563 } ] }, "id":"05h0300", "userId":90700, "timestamp":1609064744560 } ``` #### Configuration! Before submitting the job you have to configure *start.sh* script. Please define following configurations. > "bootstrapServers" > "sourceTopic" > "outputPath" > "groupId" > "spark.hadoop.fs.defaultFS" > "spark.hadoop.yarn.resourcemanager.address" > "spark.yarn.jars" ##### Java Version! - 1.8.* #### To compile use: ```sh $ mvn package ``` #### For subbmiting the job: ```sh $ ./start.sh ``` <file_sep>#!/usr/bin/env bash bootstrapServers="*****" sourceTopic="*****" outputPath="*****" groupId="*****" spark-submit \ --class com.agaspary.driver.Driver \ --packages org.apache.spark:spark-streaming-kafka-0-10_2.12:2.4.5 \ --master yarn \ --deploy-mode cluster \ --conf spark.hadoop.fs.defaultFS=***** \ --conf spark.hadoop.yarn.resourcemanager.address=***** \ --conf spark.yarn.jars=***** \ --conf spark.sql.shuffle.partitions=20 \ --name user-behavioral-data-processing-pipeline ../target/kafka-spark-hdfs-pipeline-jar-with-dependencies.jar \ "$bootstrapServers" "$sourceTopic" "$outputPath" "$groupId"
39bde8e6c606a4bb4126fe96aa5e84b756e7f31a
[ "Markdown", "Shell" ]
2
Markdown
agaspary/user-behavioral-data-processing-pipeline
f0d72633ba8f77b862906f2f052a5c2951347454
39aa09876e5735b22b529f8a3037d97db1f803c5
refs/heads/main
<file_sep>import React from 'react' export default function Imagen({urlImagen}) { return ( <img src={urlImagen} alt="Imagen aleatoria" className="mr-3" /> ) } <file_sep>import React from 'react' import Comentario from './components/Comentario' import Saludo from './components/Saludo' function App() { return ( <div className="container mt-5"> <h1>Proyecto desde cero</h1> <Saludo persona='Ignacio' edad={30} /> <Saludo persona='Pedro' edad={28} /> <Saludo persona='Juan' edad={33} /> <hr /> <h3>Cajita de comentarios</h3> <Comentario urlImagen="https://picsum.photos/64" persona="Ignacio" texto="wwwwwwwwwwwwwwwwwwwwwww" /> <Comentario urlImagen="https://picsum.photos/64" persona="Pedro" texto="nnnnnnnnnnnnnnnnnnnnnnnnnn" /> <Comentario urlImagen="https://picsum.photos/64" persona="Juan" texto="yyyyyyyyyyyyyyyyyyyyyyyyyyy" /> </div> ); } export default App;
1fcda5053f2b2eda406669f13456511004fac382
[ "JavaScript" ]
2
JavaScript
GonzaloMonteodorisio/react-comunicacion-entre-componentes-practica
70a516866cdc3158cfbe92d384d7353900ca51d1
d59d26b6e85324fddc094a0940fbe17f0975eaa7
refs/heads/master
<file_sep>import {FormGroup} from "@angular/forms"; import {FormControlFactory} from "./form-control-factory"; export class FormGroupFactory { public static createQuestionForm(): FormGroup { return new FormGroup({ userIdentifiers: this.createUserIdentifiersForm(), questionData: this.createQuestionDataForm() }); } public static createUserIdentifiersForm(): FormGroup { return new FormGroup({ nameField: FormControlFactory.createNameField(), emailField: FormControlFactory.createEmailField() }); } public static createQuestionDataForm(): FormGroup { return new FormGroup({ topicsField: FormControlFactory.createTopicsField(), titleField: FormControlFactory.createTitleField(), questionTextArea: FormControlFactory.createQuestionTextArea() }); } } <file_sep>import {Component, Input, OnInit} from '@angular/core'; import {FormGroup} from "@angular/forms"; @Component({ selector: 'question-data', templateUrl: './question-data.component.html' }) export class QuestionDataComponent implements OnInit { @Input() questionData: FormGroup; constructor() { } ngOnInit() { } } <file_sep>package com.zihler.fish.questions.applicationservices; import com.zihler.fish.questions.dataaccess.QuestionEntity; import com.zihler.fish.questions.dataaccess.QuestionRepository; import com.zihler.fish.questions.resources.input.QuestionInputData; import com.zihler.fish.questions.resources.output.QuestionOutputResource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static java.util.stream.Collectors.toList; @Service @Transactional public class QuestionService { private QuestionRepository questionRepository; public QuestionService(QuestionRepository questionRepository) { this.questionRepository = questionRepository; } public List<QuestionOutputResource> getAll() { return this.questionRepository.findAll() .stream() .map(QuestionOutputResource::create) .collect(toList()); } public QuestionOutputResource save(QuestionInputData questionInputData) { QuestionEntity questionEntity = QuestionInputToEntityConverter.convert(questionInputData); QuestionEntity savedQuestionEntity = this.questionRepository.save(questionEntity); return QuestionOutputResource.create(savedQuestionEntity); } } <file_sep>export class QuestionData { constructor(public topics: string, public title: string, public questionText: string) { } static create(topics: string, title: string, questionText: string): QuestionData { return new QuestionData(topics, title, questionText); } } <file_sep>export class UserIdentifiers { constructor(public name: string, public emailAddress: string) { } public static create(name: string, emailAddress: string): UserIdentifiers { return new UserIdentifiers(name, emailAddress); } } <file_sep>package com.zihler.fish.questions.dataaccess; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class QuestionEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; private String name; private String emailAddress; private String topics; private String title; private String questionText; public QuestionEntity() { } public QuestionEntity(String name, String emailAddress, String topics, String title, String questionText) { this.name = name; this.emailAddress = emailAddress; this.topics = topics; this.title = title; this.questionText = questionText; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getTopics() { return topics; } public void setTopics(String topics) { this.topics = topics; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getQuestionText() { return questionText; } public void setQuestionText(String questionText) { this.questionText = questionText; } } <file_sep>import {FormControl, Validators} from "@angular/forms"; export class FormControlFactory { public static createEmailField(): FormControl { let emailField = new FormControl(); emailField.setValidators([ Validators.required, Validators.pattern('[a-zA-z0-9_\.]+@[a-zA-Z]+\.[a-zA-Z]+') ]); return emailField; } public static createNameField(): FormControl { return new FormControl(); } public static createTopicsField(): FormControl { return new FormControl(); } public static createTitleField(): FormControl { return new FormControl(); } static createQuestionTextArea(): FormControl { return new FormControl(); } } <file_sep>package com.zihler.fish.questions.applicationservices; import com.zihler.fish.questions.dataaccess.QuestionEntity; import com.zihler.fish.questions.resources.input.QuestionDataInputData; import com.zihler.fish.questions.resources.input.QuestionInputData; import com.zihler.fish.questions.resources.input.UserIdentifiersInputData; class QuestionInputToEntityConverter { static QuestionEntity convert(QuestionInputData questionInputData) { QuestionEntity questionEntity = new QuestionEntity(); addUserIdentifiers(questionEntity, questionInputData.getUserIdentifiers()); addQuestionData(questionEntity, questionInputData.getQuestionData()); return questionEntity; } private static void addUserIdentifiers(QuestionEntity questionEntity, UserIdentifiersInputData userIdentifiersInputData) { questionEntity.setName(userIdentifiersInputData.getName()); questionEntity.setEmailAddress(userIdentifiersInputData.getEmailAddress()); } private static void addQuestionData(QuestionEntity questionEntity, QuestionDataInputData userIdentifiersInputData) { questionEntity.setTopics(userIdentifiersInputData.getTopics()); questionEntity.setTitle(userIdentifiersInputData.getTitle()); questionEntity.setQuestionText(userIdentifiersInputData.getQuestionText()); } } <file_sep>import {Routes} from "@angular/router"; import {QuestionFormComponent} from "./question-form/question-form.component"; import {BlogComponent} from "./blog/blog.component"; export const routes: Routes = [ {path: 'blog', component: BlogComponent}, {path: 'question-form', component: QuestionFormComponent}, {path: '', redirectTo: '/blog', pathMatch: 'full'} ]; <file_sep>import {Component, Input, OnInit} from '@angular/core'; import {AbstractControl, FormGroup, ValidationErrors} from "@angular/forms"; @Component({ selector: 'user-identifiers', templateUrl: './user-identifiers-field.component.html' }) export class UserIdentifiersFieldComponent implements OnInit { @Input() userIdentifiers: FormGroup; constructor() { } get emailField(): AbstractControl { return this.userIdentifiers.get('emailField'); } get emailFieldErrors(): ValidationErrors { return this.userIdentifiers.get('emailField')['errors']; } get hasEmailFieldErrors() { return this.userIdentifiers.get('emailField')['errors']; } ngOnInit() { } } <file_sep>import {Component, OnInit} from "@angular/core"; import {Question} from "./dtos/question"; import {FormGroup} from "@angular/forms"; import {QuestionService} from "./question.service"; import {FormGroupFactory} from "../utils/form-factories/form-group-factory"; @Component({ selector: 'app-question-form', templateUrl: './question-form.component.html' }) export class QuestionFormComponent implements OnInit { questions: Question[] = []; questionForm: FormGroup; constructor(private questionFormService: QuestionService) { this.questionForm = FormGroupFactory.createQuestionForm(); } ngOnInit() { this.questionFormService.getAll() .subscribe(halResponse => { this.questions = QuestionService.questionResourcesFrom(halResponse); }); } public submitQuestion() { this.questionFormService.post(this.questionFormData()) .subscribe(question => { this.questions.push(question); this.questionForm.reset(); }); } private questionFormData() { return this.questionForm.value; } get email() { return this.questionForm.get("email"); } get userIdentifiers() { return this.questionForm.get('userIdentifiers'); } get questionData() { return this.questionForm.get('questionData'); } } <file_sep>package com.zihler.fish.questions.resources; import com.zihler.fish.questions.applicationservices.QuestionService; import com.zihler.fish.questions.resources.input.QuestionInputData; import com.zihler.fish.questions.resources.output.QuestionOutputResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.Resources; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin(origins = "*") @RestController @RequestMapping(value = "/questions", produces = "application/hal+json") public class QuestionsController { private static final Logger logger = LoggerFactory.getLogger(QuestionsController.class); private QuestionService questionService; public QuestionsController(QuestionService questionService) { this.questionService = questionService; } @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Resources<QuestionOutputResource>> all() { List<QuestionOutputResource> allQuestions = questionService.getAll(); Resources<QuestionOutputResource> questionResources = new Resources<>(allQuestions); return ResponseEntity.ok(questionResources); } @RequestMapping(method = RequestMethod.POST) public ResponseEntity<QuestionOutputResource> post(@RequestBody QuestionInputData questionInputData) { logger.info("Received question: {}", questionInputData); QuestionOutputResource questionOutputResource = questionService.save(questionInputData); return ResponseEntity.ok(questionOutputResource); } // // @RequestMapping(path = "/{id}", method = RequestMethod.PUT) // public ResponseEntity<CourseResource> put(@PathParam("id") long id, @RequestBody Course course) { // return null; // } // // @RequestMapping(path = "/{id}", method = RequestMethod.DELETE) // public ResponseEntity<CourseResource> delete(@PathParam("id") long id) { // return null; // } }<file_sep>rootProject.name = 'fish' <file_sep>package com.zihler.fish.questions.resources.input; public class UserIdentifiersInputData { private String name; private String emailAddress; public UserIdentifiersInputData() { } UserIdentifiersInputData(String name, String emailAddress) { this.name = name; this.emailAddress = emailAddress; } public String getName() { return name; } public String getEmailAddress() { return emailAddress; } @Override public String toString() { return "UserIdentifiers{" + "name='" + name + '\'' + ", emailAddress='" + emailAddress + '\'' + '}'; } } <file_sep>import {UserIdentifiers} from "./user-identifiers"; import {QuestionData} from "./question-data"; export class Question { constructor(public userIdentifiers: UserIdentifiers, public questionData: QuestionData) { } public static createFrom(questionData): Question { return new Question( UserIdentifiers.create(questionData.userIdentifiers.nameField, questionData.userIdentifiers.emailField), QuestionData.create(questionData.questionData.topicsField, questionData.questionData.titleField, questionData.questionData.questionTextArea) ); } } <file_sep>import { QuestionFormPage } from './users/pages/questionform.po'; import {QuestionFormUser} from "./users/QuestionFormUser"; describe('Question page', () => { let questionFormUser: QuestionFormUser; beforeEach(() => { questionFormUser = new QuestionFormUser(); }); it('should display a form to enter a question', () => { questionFormUser.visitsQuestionFormPage(); questionFormUser.seesQuestionForm(); }); }); <file_sep>import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {RouterModule} from '@angular/router'; import {ReactiveFormsModule} from "@angular/forms"; import {QuestionFormComponent} from "./question-form/question-form.component"; import {UserIdentifiersFieldComponent} from './question-form/username-field/user-identifiers-field.component'; import {QuestionDataComponent} from './question-form/question-data/question-data.component'; import {HttpClient, HttpClientModule} from "@angular/common/http"; import {BlogComponent} from "./blog/blog.component"; import {routes} from "./routes"; import {BrowserAnimationsModule} from "@angular/platform-browser/animations"; @NgModule({ declarations: [ AppComponent, QuestionFormComponent, UserIdentifiersFieldComponent, QuestionDataComponent, BlogComponent ], imports: [ BrowserModule, ReactiveFormsModule, RouterModule.forRoot(routes), HttpClientModule, BrowserAnimationsModule, ], providers: [HttpClient], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import {Injectable} from '@angular/core'; import {Question} from "./dtos/question"; import {Observable} from "rxjs"; import {HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class QuestionService { private questionUrl: string = "http://localhost:8080/questions"; constructor(private http: HttpClient) { } public getAll(): Observable<any> { return this.http.get(this.questionUrl); } public post(questionData: FormData): Observable<Question> { let question = Question.createFrom(questionData); return this.http.post<Question>(this.questionUrl, question); } public static questionResourcesFrom(halResponse): Question[] { if (!halResponse || !halResponse._embedded ) { return []; } return halResponse._embedded.questionOutputResources as Question[]; } }
fa1fcf94468934cd38b072605755780f0f125914
[ "Java", "TypeScript", "Gradle" ]
18
TypeScript
ozihler/qa
95e78ad9c74d9d5f4c891bb10947e30ce5dcb49f
a1324e15e3e3f639d0321d732d9d89769b2d163d
refs/heads/master
<repo_name>anshckr/react-ssr-next-boilerplate<file_sep>/pages/index.js import React from 'react'; import fetch from 'isomorphic-unfetch'; import PropTypes from 'prop-types'; import Layout from '../src/components/Layout'; import ErrorBoundary from '../src/components/ErrorBoundary'; const App = ({ posts }) => { return ( <ErrorBoundary> <Layout posts={posts} /> </ErrorBoundary> ); }; App.propTypes = { posts: PropTypes.array.isRequired, }; App.getInitialProps = async () => { const postsResponse = await fetch('https://jsonplaceholder.typicode.com/posts'); const posts = await postsResponse.json(); return { posts, }; }; export default App; <file_sep>/src/components/Layout.jsx import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './Layout.scss'; class Layout extends Component { render() { const { posts } = this.props; return ( <div className="layout"> {posts.map((post) => { return ( <div className="post" key={post.id}> <h2>{post.title}</h2> </div> ); })} </div> ); } } Layout.propTypes = { posts: PropTypes.array.isRequired, }; export default Layout; <file_sep>/README.md Install local project dependencies ```sh npm install ``` To start next dev-server, run the following command - ```sh npm run dev ``` To build the project, run the following command - ```sh npm run build ``` To serve the build project, run the following command - ```sh npm run start ``` To check the linting errors, run the following command - ```sh npm run lint:check ``` To autofix the linting errors, run the following command - ```sh npm run lint:fix ```
ec277bbd921f98c5777ee9f4b00ac59bd0e2afbc
[ "JavaScript", "Markdown" ]
3
JavaScript
anshckr/react-ssr-next-boilerplate
dada15912604c41296688d2ad4dc375925236142
2401babe043bda1c798177d186057f587c4d1c96
refs/heads/master
<file_sep># data-uri-stream-decode Decodes streaming data-uris (`data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....`) for example from file uploads, stripping the header from the stream. ## Example ``` var fs = require('fs'); var base64 = require('base64-stream'); //to decode base64 streaming data var decodeDataUri = require('data-uri-stream-decode'); var stream;// = some stream containing a data uri like: `data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....` stream.pipe(decodeDataUri()) .on('header', function (header, dataStream) { // header will be: // - mimetype: image/png // - mediatype: image/png;charset... (if relevant) // - base64: true // dataStream will be a byte stream of the remaining bytes // it's the same as the result of `stream.pipe(decodeDataUri())` // but using this callback allows you to get header information var ext = header.mimetype.split('/')[1]; var outputFile = fs.createWriteStream(__dirname + '/outputfile.' + ext); dataStream.pipe(base64.decode()).pipe(outputFile); }) ``` <file_sep>var stream = require('stream'); var stringToStream = function (string, bytesPerChunk) { bytesPerChunk = bytesPerChunk || 1; var s = new stream.Readable(); s._read = function noop() {}; // redundant? see update below var toPush = string; function doLoop() { if (toPush.length === 0) { return s.push(null); } s.push(toPush.slice(0, bytesPerChunk)); toPush = toPush.slice(bytesPerChunk); setTimeout(doLoop, 0); } setTimeout(doLoop, 0); return s; }; module.exports = stringToStream;
4402d1aa3ca06e2ca08e85de20802a7658cc4b72
[ "Markdown", "JavaScript" ]
2
Markdown
latentflip/data-uri-stream-decode
f2d0e51484a505959f091c1ff68a624c61626daa
73b2720552b19b3352ddc7066be6369328e13edd
refs/heads/master
<file_sep>Flask weather app using openweathermap API <file_sep>import json, requests API_KEY = "" BASE_URL = "http://api.openweathermap.org/data/2.5/weather?" def weather_report(city_name): complete_url = BASE_URL + "appid=" + API_KEY + "&q=" + city_name response = requests.get(complete_url) # convert json format data into # python format data weather_report = response.json() if weather_report["cod"] != "404": temperature = weather_report["main"]["temp"] - 273.15 humidity = weather_report["main"]["humidity"] description = weather_report["weather"][0]["main"] pressure = weather_report["main"]["pressure"] elaborate = weather_report["weather"][0]["description"] name = weather_report["name"] error_code = weather_report["cod"] weather_dict = {"name":name, "temp":round(temperature,1), "humidity":humidity, "desc":description, "pressure":pressure, "elaborate": elaborate, "code": error_code} return weather_dict else: pass # city not found <file_sep>from flask import Flask, render_template, url_for from flask import request, flash import time # weather_report() returns a dictionary with weather data from weather_details import weather_report app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def main_page(): if request.method == "POST": city = request.form.get("city") if city == "": return "<h2>Please enter a city</h2>" secs = time.time() current_time = time.ctime(secs) # extracting only the day of the week, month and year from current_time ctime = {"date":current_time[:11],"year":current_time[-4:]} weather_data = weather_report(city) try: if weather_data["code"] != "404": weather_description = weather_data["desc"] else: weather_description = None except: return "<h2>Unable to find city. Please enter a valid city name.</h2>" return render_template("weather.html", ctime = ctime, weather_data = weather_data, weather_description=weather_description) return render_template("homepage.html") if __name__ == "__main__": app.run(debug = True, port = 8080)
69cd0f229d8f8e3dbcf42a9fa9960bfcf59e5c32
[ "Markdown", "Python" ]
3
Markdown
crimsonfngrs/weather-report
d0d3de9a15b73d8717b2d20aa4f9f0bca008999b
68391b0a2f71c853c7225cfa5027da28f7d58147
refs/heads/master
<repo_name>codacy-badger/pizzafriday<file_sep>/src/components/nav.js import React, {Component} from 'react' import {Router, Route, Link, IndexRoute} from 'react-router' class Nav extends Component { render() { return ( <nav className="navbar navbar-inverse"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="#"> Pizza Day </a> </div> <div className="collapse navbar-collapse"> <ul className="nav navbar-nav navbar-right"> <li> <Link to="/group">Grouped list</Link> </li> <li> <Link to="/orders">List</Link> </li> <li> <Link to="/order">Order</Link> </li> </ul> </div> </div> </nav> ) } } export default Nav<file_sep>/README.md # Pizza friday Allow to select food from restaurants on pizza day. ### Requirements - mongodb - node ### Instalation ```npm install``` ### Start ```npm run start``` ### Todo - ~~move restaurants list to db~~ - move menu to db - create menu editor for admin - levels of auth - users list for admin - change ```monk``` to something smarter [![Build Status](https://travis-ci.org/bonanzakrak/pizzafriday.svg?branch=master)](https://travis-ci.org/bonanzakrak/pizzafriday) [![CodeFactor](https://www.codefactor.io/repository/github/bonanzakrak/pizzafriday/badge/master)](https://www.codefactor.io/repository/github/bonanzakrak/pizzafriday/overview/master)
4979eea5721eb3e84ea447a3f973441caf47af0a
[ "JavaScript", "Markdown" ]
2
JavaScript
codacy-badger/pizzafriday
5f569dc1fb9de36d0d952b9c2601c74f9dc4f498
69e3a3415421829999873c9daad448994da7a512
refs/heads/master
<file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] print('Smallest number: ', min(nums)) <file_sep>name = "<NAME>" nameUpper = name.upper() print(nameUpper) <file_sep>wordsDict = {} sentence = input('Word Histogram, Please input a sentence: ') splitSentence = sentence.split() for i in splitSentence: wordsDict[i] = 0 for i in splitSentence: wordsDict[i] = wordsDict[i] + 1 print(sentence) print(wordsDict) <file_sep>import React, { Component } from 'react'; class Hello extends Component { render() { return <h1>Hello! There! What! You! Me! Who! { this.props.name }</h1> } } export default Hello; <file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] print('Even numbers: ') for i in nums: if i % 2 == 0: print(i) <file_sep>day_of_week = ["Sleep in", "Go to work", "Go to work", "Go to work", "Go to work", "Go to work", "Sleep in"] day = int(input("Day (0-6)? ")) print(day_of_week[day]) <file_sep>user_N = int(input('How big is the square? ')) for i in range(0, user_N): user_line = '*' * user_N print(user_line) <file_sep>import random my_random_number = random.randint(1, 10) print('Random', my_random_number) count = 5 print('I am thinking of a number from 1 to 10.') print('You have', count, 'guesses left.') while True: prompt = int(input("What's the number? ")) if prompt < my_random_number: print(prompt, 'is too low.') elif prompt > my_random_number: print(prompt, 'is too high.') elif prompt == my_random_number: print('Yes! You Win!') break print('You have', count, 'guesses left.') count -= 1 if count == 0: print('You ran out of guesses!') break <file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] print('Positive numbers I: ') for i in nums: if i > 0: print(i) <file_sep>var readline = require('readline'); var fs = require('fs'); var dns = require('dns'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Domain name: ", function(doname) { dns.lookup(doname, 4, function (err, addr, family) { if (err) { console.log('Invalid IP address\n' + err.message); return; } console.log('IP address: ' + addr); }); rl.close(); }); <file_sep>var readline = require('readline'); var fs = require('fs'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Filename: ", function(file) { fs.readFile(file, 'utf-8', function (error, buffer) { if (error) { console.log(error.message); return; } console.log(buffer.toString().toUpperCase()); }); rl.close(); }); <file_sep>function madlib (name, subject) { var output = name + "'s favorite subject in school is " + subject + "."; return output; } var favSubject = madlib('Chris', 'math'); console.log(favSubject) <file_sep>var fs = require('fs-promise'); var rp = require('request-promise'); var myUrl = "http://www.github.com" var myFilename = "fileHtml4.txt" function saveWebPage(url, filename) { rp(url) .then(function(resultsOfFS){ console.log(resultsOfFS); return fs.writeFile(filename, resultsOfFS); }) .then(function () { console.log('File written successfully'); }) .catch(error=> { console.error(error.message); }) }; saveWebPage(myUrl, myFilename) <file_sep>// Prints a banner, wraps stars around a text that was input into the function. function printSquare (string) { var word = string.length; console.log('*'.repeat(word + 4)); console.log('* ' + string + ' *'); console.log('*'.repeat(word + 4)); } printSquare('Welcome to Digital Crafts') <file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] nums2 = [] for i in nums: if i > 0: nums2.append(i) print('nums2 = ', nums2) <file_sep>"""Week 2 Friday's Challenge 1: Collatz Conjecture""" stringNum = "" newNum = 0 num = int(input("Enter a number for Collatz Conjecture: ")) while True: oddOrEven = num % 2 if oddOrEven == 0: newNum = num / 2 stringNum = stringNum + (str(newNum) + " ") num = newNum elif oddOrEven != 0: newNum = (3 * num) + 1 stringNum = stringNum + (str(newNum) + " ") num = newNum else: stringNum = stringNum + (str(newNum) + " ") if num <= 1: break print(stringNum) <file_sep># A program that takes a JSON file name as input and plots the X,Y data. import json data = {} data.append({ [1, 1], [2, 2], [3, 3], [4, 4] }) with open('data.json', 'w') as outfile: json.dump(data, outfile) # { # "data": [ # [1, 1], # [2, 2], # [3, 3], # [4, 4] # ] # } <file_sep>totalBillAmount = int(input('Total bill amount? ')) levelOfService = input('Level of service? ') tip = 0 if levelOfService == 'good': tip = .2 totalAmount = (totalBillAmount * tip) + totalBillAmount elif levelOfService == 'fair': tip = .15 totalAmount = (totalBillAmount * tip) + totalBillAmount elif levelOfService == 'bad': tip = .1 totalAmount = (totalBillAmount * tip) + totalBillAmount else: print("Please select good, bad, or fair for service and try again.") totalAmount = 0 print("${:.2f}".format(totalAmount)) <file_sep>cipher = input("Cipher? ") new_cipher = '' for char in cipher: new_char = char letter_number = ord(new_char) new_number = int(letter_number) + 13 if new_number >= 122: new_number = new_number - 26 newer_char = chr(new_number) new_cipher = new_cipher + newer_char print(new_cipher) <file_sep>good = 'Good' new_good = good.replace('oo', 'ooooo') print(new_good) cheese = 'Cheese' new_cheese = cheese.replace('ee', 'eeeee') print(new_cheese) man = 'Man' new_man = man.replace('a', 'aaaaa') print(new_man) spoon = 'Spoon' new_spoon = spoon.replace('oo', 'ooooo') print(new_spoon) <file_sep> # print('1.1-10') # for i in range(0, 10): # print(i + 1) # print('2.n-m') # m = int(input('Start from: ')) # n = int(input('End on: ')) + 1 # for i in range(m, n): # print(i) # print('3.Odd Numbers') # for i in range(0, 10): # if i % 2 != 0: # print(i) # print('4.Print a Square') # line = '*****' # for i in range(0, 5): # print(line) # print('5.Print a Square II') # user_N = int(input('How big is the square? ')) # for i in range(0, user_N): # user_line = '*' * user_N # print(user_line) print('6. Print a Box') width = int(input('Width? ')) height = int(input('Height? ')) space = ' ' remove_star = height - 2 linesSpaces = width - 2 print('*' * width) for i in range(0, remove_star): print('*', space * linesSpaces, '*', sep='') print('*' * width) print('7. Print a Triangle') counter = 1 sec_counter = 4 for i in range(0, 4): print(' ' * sec_counter, '*' * counter, sep='') counter += 2 sec_counter -= 1 print('8. Print a Triangle II') sec_height = int(input('Height? ')) counter = 1 sec_counter = sec_height for i in range(0, sec_height): print(' ' * sec_counter, '*' * counter, sep='') counter += 2 sec_counter -= 1 print('9.Multiplication Table') for i in range(1, 11): for j in range(1, 11): multiply = i * j print(i, 'X', j, '=', multiply) <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <link href="path/to/lightbox.css" rel="stylesheet"> <script src="path/to/lightbox.js"></script> <script> /* When the button is clicked, change the text of the paragraph #the-message to "You clicked me!", and the text of the button #the-button to "Click again?". */ (function ( $ ) { $.fn.reverse = function () { $.fn.greenify = function() { this.css( "color", "green"); return this; }; }; }( jQuery )); </script> <script> $(document).ready( function () { // $('#the-button').click (function () { // $(this).text('Click Again?'); // $('#the-message').text('You clicked me!'); // }); $('#the-button').reverse(); }); </script> </head> <body> <p id="the-message">Pardon me, would you please</p> <button id="the-button">Click me?</button> </body> </html> <file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] print('Largest number: ', max(nums)) <file_sep>// A function that takes and array and outputs a new array with the positive // numbers of the previous arrray only. var array = [1, 5, 4, 6, 13, 64, 20, 34, 99, 12, 53, 33]; function evenNumbers (nums) { var arrayEven = []; nums.forEach(function (num) { if (num % 2 === 0) { arrayEven.push(num); } }); return arrayEven } console.log(evenNumbers(array)); <file_sep>ramit = {'name': 'Ramit', 'email': '<EMAIL>', 'interests': ['movies', 'tennis'], 'friends':[ { 'name': 'Jasmine', 'email': '<EMAIL>', 'interests': ['photography', 'tennis'] }, { 'name': 'Jan', 'email': '<EMAIL>', 'interests': ['movies', 'tv'] } ] } ramitEmail = ramit.get('email') #1 print(ramitEmail) ramitInterest1 = ramit.get('interests')[0] #2 print(ramitInterest1) jasmineEmail = ramit.get('friends')[0]['email'] #3 print(jasmineEmail) jasmineInterests2 = ramit.get('friends')[0]['interests'][1] #4 print(jasmineInterests2) <file_sep>m = int(input('Start from: ')) n = int(input('End on: ')) + 1 for i in range(m, n): print(i) <file_sep>var rp = require('request-promise'); var urls = [ 'https://en.wikipedia.org/wiki/Futures_and_promises', 'https://en.wikipedia.org/wiki/Continuation-passing_style', 'https://en.wikipedia.org/wiki/JavaScript', 'https://en.wikipedia.org/wiki/Node.js', 'https://en.wikipedia.org/wiki/Google_Chrome' ]; var promise_array = [] urls.forEach((url)=>{ var p = rp(url) promise_array.push(p) }) Promise.all(promise_array) .then(values=> { console.log(values[0]); }); <file_sep>secret_number = 5 print('I am thinking of a number from 1 to 10.') prompt = int(input("What's the number? ")) while prompt != secret_number: print('Nope, try again.') prompt = int(input("What's the number? ")) print('Yes! You Win!') <file_sep>// A function that tally's up all the letters in the string and prints // and object with the info in it. function letterHistogram (str) { var letters = []; var strObject = {}; for (var i = 0; i < str.length; i++) { var letter = str.charAt(i); letters.push(letter); // console.log(letters); // } // for () { strObject.letters = strObject.letters + 1 || 1; // console.log(strObject); } return strObject; } letterHistogram('banana'); // console.log(a); console.log(letterHistogram('banana')); <file_sep>// A function that takes an array of numbers, squares all the numbers, and // returns a new array with the new squared numbers. function squareTheNumbers (nums) { var squaredArray = []; nums.forEach(function (num) { var sqNum = num * num squaredArray.push(sqNum); }); return squaredArray; } console.log(squareTheNumbers([1, 2, 3, 4, 5, 6])); <file_sep>count = 0 class Person: """Saves an object with persons name, email, and phone""" def __init__(self, name, email, phone): friends = [] self.name = name self.email = email self.phone = phone self.friends = friends def print_contact_info(self): print("Sonny's email: {}, Sonny's phone number: {}" .format(sonny.email, sonny.phone, sep='')) def greeting_count(self): global count self.count += 1 # A function that prints a greeting from one person to another. def greet(self, other_person): print('Hello {}, I am {}!'.format(other_person.name, self.name)) self.greeting_count() print(' ') # Instantiates an object for a person and stores name, email, and phone into # local fariables. sonny = Person('Sonny', '<EMAIL>', '483-485-4948') jordan = Person('Jordan', '<EMAIL>', '495-586-3456') # prints a string, jordan says hello to sonny and vice versa. sonny.greet(jordan) print(count) sonny.greet(jordan) print(count) sonny.greet(jordan) print(count) # jordan.greet(sonny) # prints name, email and phone of Sonny and Jordan # print(sonny.name, sonny.email, sonny.phone) # print(jordan.name, jordan.email, jordan.phone) sonny.print_contact_info() jordan.friends.append(sonny) sonny.friends.append(jordan) print(len(jordan.friends)) # Count number of greetings # # We want to count the number of times a person has greeted someone. To do this # , we'll add another attribute, call it say greeting_count, and initialize it # to 0. # Then each time the greet method is called, we'll increment greeting_count by # 1. # # >>> sonny.greeting_count # 0 # >>> sonny.greet(jordan) # >>> sonny.greeting_count # 1 # >>> sonny.greet(jordan) # >>> sonny.greeting_count # 2 print(' ') class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def print_info(self): print(car.year, car.make, car.model) car = Vehicle('Nissan', 'Leaf', '2015') car.print_info() print(' ') <file_sep>import random que = 'n' while True: my_random_number = random.randint(1, 10) print('Random', my_random_number) count = 5 print('I am thinking of a number from 1 to 10.') print('You have', count, 'guesses left.') while True: prompt = int(input("What's the number? ")) if prompt < my_random_number: print(prompt, 'is too low.') elif prompt > my_random_number: print(prompt, 'is too high.') elif prompt == my_random_number: print('Yes! You Win!') que = input('Do you want to play again? (Y or N) ') break print('You have', count, 'guesses left.') count -= 1 if count == 0: print('You ran out of guesses!') que = input('Do you want to play again? (Y or N) ') if que != 'y': break <file_sep>class Person { constructor(name) { this.name = name; this.friends = []; } addFriend (friend) { this.friends.push(friend); } createGreeting (other) { return 'Yo ' + other.name + '! from ' + this.name + '.'; } greet (other) { console.log(this.createGreeting(other)); } lazyGreet (other) { setTimeout(()=> { console.log(this.createGreeting(other)); }, 2000); } createGreetingsForFriends () { let greetings = this.friends.map((friend)=>{ return this.createGreeting(friend); }) return greetings; } } var alfie = new Person('Alfie'); var anushka = new Person('Anushka'); var henrique = new Person('Henrique'); alfie.addFriend(anushka); alfie.addFriend(henrique); console.log(alfie.createGreetingsForFriends()); <file_sep># import matplotlib.pyplot as plot # import math # print('1.Hello') # def hello (name): # print('Hello {}'.format(name)) # hello('Igor') # print('2.y=x+1') # def f(x): # return x + 1 # xs = list(range(-3, 4)) # ys = [] # for x in xs: # ys.append(f(x)) # plot.plot(xs, ys) # plot.show() # print('3.Square of X') # def f(x): # return x * x # # xs = list(range(-100, 100)) # ys = [] # # for x in xs: # ys.append(f(x)) # # plot.plot(xs, ys) # plot.show() # print('4.Odd or Even') # def f(x): # return x # xs = list(range(-5, 5)) # ys = [] # for x in xs: # if (x % 2) == 0: # x = 1 # ys.append(f(x)) # elif (x % 2) != 0: # x = -1 # ys.append(f(x)) # plot.bar(xs, ys) # plot.show() # print('5.Sine') # import matplotlib.pyplot as plot # # def f(x): # return math.sin(x) # # xs = list(range(-5, 5)) # ys = [] # for x in xs: # ys.append(f(x)) # # plot.plot(xs, ys) # plot.show() # print('6.sine 2') # # import matplotlib.pyplot as plot # from numpy import arange # # def f(x): # return math.sin(x) # # xs = list(arange(-5, 5, .1)) # ys = [] # for x in xs: # ys.append(f(x)) # # plot.plot(xs, ys) # plot.show() # print('7.Degree Conversion') # import matplotlib.pyplot as plot # # from numpy import arange # # def f(x): # return ((x * 1.8) + 32) # # xs = list(range(0, 20)) # ys = [] # for x in xs: # ys.append(f(x)) # # plot.plot(xs, ys) # plot.show() # print('8.Play Again') # def playAgain(): # answer = input('Do you want to play again? (Y or N)') # if answer == 'Y': # return True # elif answer == 'N': # return False # print(playAgain()) print('9.Play again? Again.') def playAgain(): answer = str(input('Do you want to play again? (Y or N): ')) while True: if answer in ['Y', 'y', 'N', 'n']: break else: print('Invalid Input.') answer = str(input('Do you want to play again? (Y or N): ')) if answer == 'Y': return True elif answer == 'y': return True elif answer == 'N': return False elif answer == 'n': return False print(playAgain()) <file_sep>phonebook_dict = {'Alice': '703-493-1834', 'Bob': '857-384-1234', 'Elizabeth': '484-584-2923'} print(phonebook_dict.get('Elizabeth')) #1 phonebook_dict['Kareem'] = ('938-345-2345') #2 del phonebook_dict['Alice'] #3 phonebook_dict['Bob'] = ('968-345-1234') #4 print(phonebook_dict) #5 <file_sep>line = '*****' for i in range(0, 5): print(line) <file_sep>from pycipher import Caesar Caesar(key=1).encipher('lbh zhfg hayrnea jung lbh unir yrnearq') 'EF<KEY>' Caesar(key=1).decipher('<KEY>') 'DEFENDTHEEASTWALLOFTHECASTLE' <file_sep>width = int(input('Width? ')) height = int(input('Height? ')) space = ' ' remove_star = height - 2 linesSpaces = width - 2 print('*' * width) for i in range(0, remove_star): print('*', space * linesSpaces, '*', sep='') print('*' * width) <file_sep># This a program that prompts the user to enter a file name, then prompts the # user to enter the contents of the file, and then saves the content to the # file. fileName = input('Enter file name: ') file_handle = open(fileName,'w') content = str(input('Enter contents of file: ')) file_handle.write(content) file_handle.close() <file_sep>counter = 1 sec_counter = 4 for i in range(0, 4): print(' ' * sec_counter, '*' * counter, sep='') counter += 2 sec_counter -= 1 <file_sep>count = 0 print('You have ', count, ' coins.', sep='') prompt = input('Do you want another? ') while prompt == 'yes': count += 1 print('You have ', count, ' coins.', sep='') prompt = input('Do you want another? ') print('Bye') <file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] nums3 = [] singleFactor = 2 for i in nums: nums3.append(i * singleFactor) print(nums3) <file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] nums2 = [] nums3 = [] nums4 = [] singleFactor = 2 j = 0 m1 = [[1, 3, 5], [2, 8, -1]] m2 = [[8, 4, 3], [4, 1, -4]] m3 = [] print(nums) print('Sum: ', sum(nums)) print('Largest number: ', max(nums)) print('Smallest number: ', min(nums)) print('Even numbers: ') for i in nums: if i % 2 == 0: print(i) print('Positive numbers I: ') for i in nums: if i > 0: print(i) print("Positive Numbers II: ") for i in nums: if i > 0: nums2.append(i) print('nums2 = ', nums2) print('Multiply a list: ') for i in nums: nums3.append(i * singleFactor) print(nums3) print('Multiply Vectors: ') for i in range(0, len(nums)): nums4.append(nums[i] * nums3[i]) print(nums4) # print('m1 = ', m1) # print('m2 = ', m2 ) # print('9.Matrix Addition: ') # for i in range(0, len(m1)): # m3.append(m1 + m2) # print(m3) <file_sep>class Person: """ Person class saves names, emails, phone numbers, and friends to an object. Method greet() greets one person from another. Method print_contact_info prints objects email & phone number. """ def __init__(self, name, email, phone): friends = [] count = 0 self.name = name self.email = email self.phone = phone self.friends = friends self.count = count def greeting_count(self): self.count += 1 def greet(self, other_person): print('Hello {}, I am {}!'.format(other_person.name, self.name)) self.greeting_count() def print_contact_info(self): print(self.name, "'s email: ", self.email, ' ', self.name, "'s phone: ", self.phone, sep='') def add_friends(self, addFriend): self.friends.append(addFriend) def __str__(self): return 'Person: {} {} {}'.format(self.name, self.email, self.phone) sonny = Person('Sonny', '<EMAIL>', '222-333-4455') jordan = Person('Jordan', '<EMAIL>', '999-444-6677') sonny.print_contact_info() jordan.print_contact_info() jordan.add_friends(sonny) sonny.add_friends(jordan) print(len(jordan.friends)) print(len(sonny.friends)) sonny.greet(jordan) jordan.greet(sonny) sonny.greet(jordan) print(sonny.count) sonny.greet(jordan) print(sonny.count) jordan.greet(sonny) print(jordan.count) print(jordan) print(str(jordan)) class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def print_info(self): print(self.year, self.make, self.model) car = Vehicle('Nissan', 'Leaf', '2015') car.print_info() <file_sep>var express = require('express'); var app = express(); var animals = [ { name: 'cats', favorite: true }, { name: 'dogs', favorite: true }, { name: 'tree frogs', favorite: true }, { name: 'earth worms', favorite: false }, { name: 'guinea pigs', favorite: true }, ]; // view engine setup app.set('views', './views'); app.set('view engine', 'hbs'); app.use(express.static('public')); app.get('/', function (request, response) { let name = 'Chris'; response.render('chris', {name: name}); }); // Make an express program that will display "Hello, world!" at the root URL: / app.get('/hello_world', function (request, response) { response.send('Hello World'); }); // Routes: Add to your program the following pages: app.get('/cats', function (request, response) { response.send('Meow'); }); app.get('/dogs', function (request, response) { response.send('Woof'); }); app.get('/cats_and_dogs', function (request, response) { response.send('Living together'); }); // Route Parameters:Adding to the same program, say a greeting to the user, given that the user's name is encoded inside the URL. For example, if you go to the URL app.get('/greet/:slug', function (request, response) { var slug = request.params.slug; response.send('Hello, ' + slug + '!'); }); // Query Parameters: Tell the year you were born app.get('/year', function (request, response) { let year = request.query.age || 'age'; let age = Number(2017) - Number(year); response.send('You were born in ' + age + '.'); }); // Templates: Make the greet page say hello to visitor and tell the year they were born. This time you will use a .hbs file in the views folder to render the message using HTML. For example, if you go to the URL: /greet/Manoush?age=32 app.get('/greet/:slug', function (request, response) { let slug = request.params.slug; let year = request.query.age || 2017; let age = Number(2017) - Number(year); response.render( 'home', {slug: slug, age: age}); }); app.get('/fav_animals', function (request, response) { let animals = [ { name: 'cats', favorite: true }, { name: 'dogs', favorite: true }, { name: 'tree frogs', favorite: true }, { name: 'earth worms', favorite: false }, { name: 'guinea pigs', favorite: true }, ]; response.render('animals', {animals: animals}); }); app.listen(8000, function () { console.log('Listening on port 8000'); }); <file_sep>// A function that sorts an array by how long each name is, shortest name first. var people = [ 'Dom', 'Lyn', 'Kirk', 'Autumn', 'Trista', 'Jesslyn', 'Kevin', 'John', 'Eli', 'Juan', 'Robert', 'Keyur', 'Jason', 'Che', 'Ben' ]; people.sort(function(a, b) { console.log(a); console.log(b); console.log(a.length - b.length); return a.length - b.length; }); console.log(people); <file_sep>var express = require('express'); var app = express(); var pgp = require('pg-promise')({}); var db = pgp({database: 'restaurant'}); const body_parser = require('body-parser'); app.use(body_parser.urlencoded({extended: false})); app.set('views', './views'); app.set('view engine', 'hbs'); <file_sep>import React, { Component } from 'react'; import HelloMessage from './Hello'; class HelloList extends Component { constructor (props) { super (props); this.state = { date: new Date(), people: [ {age: 19, name: 'John'}, {age: 32, name: 'Mark'}, {age: 21, name: 'Mary'}, {age: 20, name: 'Tim'}, {age: 26, name: 'Melanie'}, {age: 18, name: 'Samantha'}, {age: 30, name: 'Don'}, {age: 19, name: 'Eric'} ] } } handleClick (event, person, selected) { console.log('Parent', person, selected); } render () { return <ul> {this.state.people.map((person) => <li key={person.id}> <HelloMessage name={person.name} callback={this.handleClick} /> </li> )} </ul> } } export default HelloList; <file_sep># DC-Class-Sept-17 <file_sep>// A function that takes an array of words as an argument and returns the // acronym of the words. var arrrayOfWords1 = ['very', 'important', 'person']; var arrrayOfWords2 = ['national', 'aeronautics', 'space', 'administration']; var newArray = []; function acronym (arrrayOfWords) { arrrayOfWords.forEach(function(word) { var y = word.charAt(0) newArray.push(y); }); var acron = newArray.reduce(function (a, b) { return a + b; }); return acron; } console.log(acronym(arrrayOfWords1)); <file_sep># Phonebook app # Ask them for the person's name, and then look up the person's phone number by # the given name and print it to the screen. def lookUp(): name = input('Name: ') print('Found entry for ' + name + ': ' + phoneBook[name]) # Set an entry, prompt user for the person's name and the person's phone number. def setNameNumber(): name = input('Name: ') phoneNumber = input('Phone number: ') phoneBook[name] = phoneNumber print('Entry stored for ' + name +'.') # Delete an entry, you will prompt user for person's name and delete the given # person's entry. def delete(): name = input('Name: ') phoneBook.pop(name) print('Deleted entry for ' + name +'.') # List all entries, go through all entries in the dictionary and print each out # to the terminal. def listAll(): for key in phoneBook: print('Found entry for ' + key + ': ' + phoneBook[key]) # Quit, end the program. def quit(): a = 1 phoneBook = {} while True: print('Electronic Phone Book') print('=====================') print('1. Look up an entry') print('2. Set an entry') print('3. Delete an entry') print('4. List all entries') print('5. Quit') selection = int(input('What do you want to do (1-5)?: ')) if selection == 1: lookUp() elif selection == 2: setNameNumber() elif selection == 3: delete() elif selection == 4: listAll() elif selection == 5: print('Bye') break <file_sep>name = "<NAME>" nameCapital = name.title() print(nameCapital) <file_sep>function add(x, y, callback) { setTimeout(function () { var result = x + y; callback(result); }, 1000); } function subtract(x, y, callback) { setTimeout(function () { callback(x - y); }, 1500); } function greeting(person, callback) { setTimeout(function () { callback('Hola, ' + person + '!'); }, 2000); } function product(numbers, callback) { setTimeout(function () { var x = numbers.reduce(function(a, b) { return a * b; }, 1); callback(x); }, 2500); } add(1, 2, function (result) { console.log(result); }); subtract(10, 3, function (result) { console.log(result); }); greeting('Chris', function (result) { console.log(result); }); var nums = [5, 6]; product(nums, function (result) { console.log(result); }); <file_sep>var readline = require('readline'); var request = require('request'); var fs = require('fs'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("URL: ", function(inputURL) { rl.question("Output file: ", function (outputURL) { request.get(inputURL, function (error, response, html) { if (error) { console.error(error.message); return; }; rl.close(); fs.writeFile(outputURL, html, function (err) { if (error) { console.log(error.message); return; }; }); }); }); }); <file_sep>var array = [1]; for (var x = 2; x < 20; x++) { for (var i = 2; i < x; i++) { if (x % i !== 0) { array.push(x); } } } console.log(array); <file_sep>// A function which takes an array of city objects as input and returns a new // array containing the cities whose temperature is cooler than 70 degrees. var cities = [ { name: 'Los Angeles', temperature: 60.0}, { name: 'Atlanta', temperature: 52.0 }, { name: 'Orland Hills', temperature: 70.0 }, { name: 'Detroit', temperature: 48.0 }, { name: 'New York', temperature: 80.0 }, { name: 'Chicago', temperature: 90.0 } ]; function citiesTemp (cities) { var seventyDegCities = []; cities.forEach(function (city) { if (city.temperature < 70.0) { seventyDegCities.push(city); } }); return seventyDegCities } console.log(citiesTemp(cities)); <file_sep>name = "<NAME>" nameReverse = name[::-1] print(nameReverse) <file_sep>var express = require('express'); var app = express(); var body_parser = require('body_parser'); var pgp = var db = app.set('view engine', 'hbs'); app.use(express.static('public')); app.get('/', function (request, response) { response.send('Hello World!'); }); app.get('/about', function (request, response) { response.send('About Me'); }); app.get('/hello', function (request, response) { var name = request.query.name || 'World'; response.send('Hello ' + name); }); app.get('/hello', function (request, response) { var name = request.query.name || 'World'; var context = {title: 'Hello', name: name}; response.render('hello.hbs', context); }); app.get('/post/:slug', function (request, response) { var slug = request.params.slug; response.send('Post About: ' + slug); }); app.get('/projects', function (request, response) { response.send('Projects'); }); app.post('/submit', function (request, response) { console.log(request.body); response.send('OK'); response.redirect('/some-where-else'); }); app.get('/search', function(req, resp, next) { let term = req.query.searchTerm; let query = "SELECT * FROM restaurant WHERE \ restaurant.name ILIKE '%$1#%'"; /*SQL Injection. Casing sensitive structure.*/ db.any(query, term) .then(function(resultsArray) { resp.render('search_results.hbs', { results: resultsArray }); }) .catch(next); }); app.listen(8000, function () { console.log('Listening on port 8000'); }); /*Go through the slides. Erased some code, not sure if it matches Paul's. Make Directory views and put the template in there for Handlebars. Ex.: views/hello.hbs use {{title}} and {{name}} Handlebars template is an layout.hbs file. Ex.: <html> <head> <title>{{title}}</title> </head> <body> {{{body}}} </body> </html> Always send in your HTML Escaping Sometimes you might want to turn off escaping, but be careful because that gives access to your code. var html_content = '<strong>hello</strong>'; {{html_content}} vs {{{html_content}}} */ <file_sep>// video 1 LearnCode.acaedemy What makes javascropt weird function add(first, second, callback) { console.log(first + second); callback(); } // add(2, 3, function() { // console.log('done'); // }); // // add(4, 5, function () { // console.log('done again'); // }); // // OR function logDone () { console.log('done'); } add(2, 3, logDone); // add(4, 5); function handleClick() { // something } $('myDiv').click(handleClick) // video 2 $(document).ready(function() { $('button').on('click', function() { alert('yay!'); }); }); <file_sep>function printSquare (length) { for (var i = 0; i < length; i++) { console.log('*'.repeat(length)); } } printSquare(3) <file_sep># wk_dy = [] # # for i in range(45018): # sat = wk_dy.append('w') # # print(wk_dy) # # for i in range(0, 45018, 6): # sats = sat.append('w') # # print(sat) print(__name__) <file_sep>// console.log('What's my name Bitch?') // <file_sep>class Card { constructor (point, suit) { this.point = point; this.suit = suit; } } class Hand { constructor(){ this.cards = []; } addCard(cards) { this.cards.push(cards); return this.cards; } points(card, point) { var totalPoints = Number(''); this.cards.forEach(function (card) { totalPoints = totalPoints + Number(card['point']); console.log(totalPoints); }); } } var myHand = new Hand(); myHand.addCard(new Card(5, 'diamonds')); myHand.addCard(new Card(13, 'spades')); console.log(myHand.cards); myHand.points(); <file_sep>function longLongVowels (str) { 'aa' 'ee' 'ii' 'oo' 'uu' } <file_sep>print('Guess Game 2') count =50 print('Is your number', count, '?') response = input('high, low, yes? ') for i in range(0, 100): if response == 'high': count -= 1 print('Is this your number', count, "?") response = input('high, low, yes? ') if response == 'low': count += 1 print('Is this your number', count, "?") response = input('high, low, yes? ') if response == 'yes': print('Got it') break <file_sep>// Phonebook app: get and insert data into a map. var phonebookMap = new Map (); phonebookMap.set('Alice', '703-493-1834'); phonebookMap.set('Bob', '857-384-1234'); phonebookMap.set('Elizabeth', '484-584-2923'); // Print Elizabeth's phone number. console.log(phonebookMap.get('Elizabeth')); // Add Kareem's number. phonebookMap.set('Kareem', '938-489-1234'); // Delete Alice phonebookMap.delete('Alice'); // Change Bob's number phonebookMap.set('Bob', '968-345-2345'); // Access map with variable. List all phonenumbers with for...in loop. var personName = 'Elizabeth' phonebookMap.get(personName); for (var key of phonebookMap.keys()) { console.log(phonebookMap.get(key)); } <file_sep>class Card { constructor (point, suit) { this.point = point; this.suit = suit; } } var myCard = new Card(5, 'diamonds'); console.log(myCard.point); console.log(myCard.suit); <file_sep># Prompts user to enter file, reads file, and prints the file to the screen. fileName = input('Enter file name to be printed to screen: ') file_handle = open(fileName,'r') text = file_handle.read() print(text) file_handle.close() <file_sep># A => 4 # E => 3 # G => 6 # I => 1 # O => 0 # S => 5 # T => 7 print('Goats in Leetspeak') word = 'Goats'.upper() # word = word.upper() # new_letters = word[:len(word)] new_word = '' # print('test', new_letters) for x in word: i = x if i == 'E': i = '3' if i == 'G': i = '6' if i == 'I': i = '1' if i == 'O': i = '0' if i == 'S': i = '5' if i == 'T': i = '7' if i == 'A': i = '4' new_word = new_word + i print(new_word) <file_sep># Write a program that prompts the user to enter a file name, then prints the # letter histogram and the word histogram of the contents of the file. # Function that makes a list of all the different letters and counts how many of # each letter. It inputs the data into a dictionary variable lettersDict. def letterHistogram(letters): lettersDict = {} lowerWord = letters.lower() for i in lowerWord: lettersDict[i] = 0 for i in lowerWord: lettersDict[i] = lettersDict[i] + 1 return lettersDict # Function that makes a list of all the different words and counts how many of # each word. It inputs the data into a dictionary variable wordsDict. def wordHistogram(words): wordsDict = {} lowerWords = words.lower() splitSentence = lowerWords.split() for i in splitSentence: wordsDict[i] = 0 for i in splitSentence: wordsDict[i] = wordsDict[i] + 1 return wordsDict fileName = input('Enter file name: ') file_handle = open(fileName,'r') content = file_handle.read() file_handle.close() lettersHist = letterHistogram(content) wordsHist = wordHistogram(content) print(lettersHist) print(wordsHist) <file_sep>name = "<NAME>" word_letters = [] new_letters = [] count = 0 print('\n', 'name = ', name, '\n', sep='') print('1.Uppercase a String: ') nameUpper = name.upper() print(nameUpper) print('2.Capitalize a String: ') nameCapital = name.title() print(nameCapital) print('3.Reverse a String: ') nameReverse = name[::-1] print(nameReverse) print('4.Leetspeak: ') # A => 4 # E => 3 # G => 6 # I => 1 # O => 0 # S => 5 # T => 7 print('Goats in Leetspeak') word = 'Goats'.upper() # word = word.upper() # new_letters = word[:len(word)] new_word = '' # print('test', new_letters) for x in word: i = x if i == 'E': i = '3' if i == 'G': i = '6' if i == 'I': i = '1' if i == 'O': i = '0' if i == 'S': i = '5' if i == 'T': i = '7' if i == 'A': i = '4' new_word = new_word + i print(new_word) print('5.Long Vowels') good = 'Good' new_good = good.replace('oo', 'ooooo') print(new_good) cheese = 'Cheese' new_cheese = cheese.replace('ee', 'eeeee') print(new_cheese) man = 'Man' new_man = man.replace('a', 'aaaaa') print(new_man) spoon = 'Spoon' new_spoon = spoon.replace('oo', 'ooooo') print(new_spoon) print('6.Caesar Cipher') cipher = input("Cipher? ") new_cipher = '' for char in cipher: new_char = char letter_number = ord(new_char) new_number = int(letter_number) + 13 if new_number >= 122: new_number = new_number - 26 newer_char = chr(new_number) new_cipher = new_cipher + newer_char print(new_cipher) <file_sep>nums = [1, 30, -3, 5, 49, 2, 0, 9, 299, -30] nums3 = [2, 60, -6, 10, 98, 4, 0, 18, 598, -60] nums4 = [] for i in range(0, len(nums)): nums4.append(nums[i] * nums3[i]) print(nums4) <file_sep>totalBillAmount = int(input('Total bill amount? ')) levelOfService = input('Level of service? ') splitHowMany = input('Split how many ways? ') if levelOfService == 'good': tip = .2 totalAmount = (totalBillAmount * tip) + totalBillAmount print("$", "{:.2f}".format(totalAmount)) elif levelOfService == 'fair': tip = .15 totalAmount = (totalBillAmount * tip) + totalBillAmount print("$", "{:.2f}".format(totalAmount)) elif levelOfService == 'bad': tip = .1 totalAmount = (totalBillAmount * tip) + totalBillAmount print("$", "{:.2f}".format(totalAmount)) else: print("Please select good, bad, or fair for service and try again.") <file_sep>lettersDict = {} word = input('Letter Histogram, Please input a word: ') lowerWord = word.lower() # # for i in lowerWord: # lettersDict[i] = 0 for i in lowerWord: lettersDict[i] = lettersDict[i] + 1 # print(word) print(lettersDict) <file_sep>celsius = float(input("Temperature in C? ")) farenh = (celsius * 1.8) + 32 print(farenh, "F") <file_sep>sec_height = int(input('Height? ')) counter = 1 sec_counter = sec_height for i in range(0, sec_height): print(' ' * sec_counter, '*' * counter, sep='') counter += 2 sec_counter -= 1 <file_sep>var readline = require('readline'); var fs = require('fs'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Input file: ", function(inputFile) { fs.readFile(inputFile, 'utf-8', function (error, buffer) { if (error) { console.log(error.message); return; } rl.question("Output file: ", function (outputFile) { var text = buffer.toString().toUpperCase(); rl.close(); fs.writeFile(outputFile, text, function (err) { if (error) { console.log(error.message); return; }; }); }); }); }); <file_sep>import random my_random_number = random.randint(1, 10) print('I am thinking of a number from 1 to 10.') prompt = int(input("What's the number? ")) while prompt != my_random_number: if prompt < my_random_number: print(prompt, 'is too low.') prompt = int(input("What's the number? ")) elif prompt > my_random_number: print(prompt, 'is too high.') prompt = int(input("What's the number? ")) print('Yes! You Win!') <file_sep> var prompt = require('prompt-promise'); var pgp = require('pg-promise')({}); var db = pgp({database: 'music'}); var result = []; prompt('Album name? ') .then(function albumName(val) { result.push(val); return prompt('albumYear: '); }) .then(function albumYear(val){ result.push(val); return prompt('Artist ID? '); }) .then(function artistId(val) { result.push(val); var q = "INSERT INTO album VALUES (default, $1, $2, $3)"; db.result(q, result); console.log(result); prompt.done(); pgp.end(); result = []; }) .catch(function rejected(err) { console.log('error:', err.stack); prompt.finish(); }); <file_sep>function counter (x) { var count = x; return { increment: function() { count++; return count; }, decrement: function() { count--; return count; } }; } <file_sep>import React, { Component } from 'react'; class HelloList extends Component { constructor(props) { super(props); this.state = { friends : [ {id: 1, name: 'John', age: 22}, {id: 2, name: 'Dan', age: 32}, {id: 3, name: 'Mark', age: 20}, {id: 4, name: 'Ryan', age: 19}, {id: 5, name: 'Melissa', age: 16}, {id: 6, name: 'Sam', age: 54}, {id: 7, name: 'Rob', age: 12}, {id: 8, name: 'George', age: 65}, {id: 9, name: 'Laura', age: 90}, {id: 10, name: 'Steve', age: 31}, {id: 11, name: 'Samantha', age: 21} ] }; } can_party(friend) { if (friend.age >= 21) { return <span>- Can Party! </span> } else { return <span>- Can't Party Legally! </span> } } render() { return <ul> {this.state.friends.map((friend) => <li key={friend.id}> {friend.name} {friend.age} {this.can_party(friend)} {friend.age >= 21 ? <span>- Of age </span> : <span>- Under age </span>} </li> )} </ul> } } export default HelloList; <file_sep>count = 0 while count < 10: count += 1 print(count) for i in range(0, 10): print(i + 1)
d129518f03890015c48ab489dcccf9322cec9ef9
[ "JavaScript", "Python", "Markdown" ]
82
Python
cfudala82/DC-Class-Sept-17
fe33dd26af56dff7e0ff8a3b95b0cf9f9738fd6f
4918d3cb7b23567176b80811a20c278a3b7ccbf4
refs/heads/master
<file_sep>var loginForm = document.getElementById('loginForm'); loginForm.onsubmit = validateForm;
da3c00f39edbe0454c24c5e53b0bcd5bbedcbce6
[ "JavaScript" ]
1
JavaScript
TheInsideMan/learningJS
8b3fd4ae3f16e8d8cb4de6f376714ace117cd1bd
04dc97db4cb90749af1a9a53c6662be0313287b0
refs/heads/master
<repo_name>Apple-yong/Practice<file_sep>/mini_project/js轮播/改进轮播/main.js let $buttons = $('#buttonWrapper>button') let $images = $('#slides>img') let current = 0 makeSlides() $("#slides").css({transform:'translateX(-300px)'}) bindEvents() $(next).on('click', function(){ goToSlide(current+1) }) $(previous).on('click', function(){ goToSlide(current-1) }) let timer = setInterval(function(){ goToSlide(current+1) },3000) $('.container').on('mouseenter', function(){ window.clearInterval(timer) }).on('mouseleave', function(){ timer = setInterval(function(){ goToSlide(current+1) },3000) }) function bindEvents() { $buttons.click(function(){ let index = $(this).index() goToSlide(index) }) } function goToSlide(index) { if(index > $buttons.length-1){ index = 0 }else if(index <0){ index = $buttons.length - 1 } if(current === $buttons.length -1 && index === 0){ //最后一张到第一张 $("#slides").css({transform:`translateX(${-($buttons.length + 1) * 300}px)`})//假的 .one('transitionend', function () { $("#slides").hide().offset() $("#slides").css({transform:`translateX(${-(index+1)*300}px)`}).show() }) }else if(current === 0 && index === $buttons.length - 1){ // 第一张到最后一张 $("#slides").css({transform:`translateX(0px)`}) .one('transitionend', function(){ $("#slides").hide().offset() $("#slides").css({transform:`translateX(${-(index+1)*300}px)`}).show() }) }else{ $("#slides").css({transform:`translateX(${- (index + 1) * 300}px)`}) } current = index } function makeSlides() { let $firstCopy = $images.eq(0).clone(true) let $lastCopy = $images.eq($images.length-1).clone(true) $("#slides").append($firstCopy) $("#slides").prepend($lastCopy) }<file_sep>/mini_project/js轮播/苹果轮播/script.js $(document).ready(function(){ /* 自动计算轮播视图宽度 */ var totWidth=0 var positions = new Array() $('#slides .slide').each(function(i){ positions[i]= totWidth totWidth = $(this).width() + totWidth }) $('#slides').width(totWidth) $('#menu ul li a').click(function(e,keepScroll){ $('li.menuItem').removeClass('act').addClass('inact') $(this).parent().addClass('act') var pos = $(this).parent().prevAll('.menuItem').length//获取第几个轮播按钮 $('#slides').animate({marginLeft:-positions[pos]+'px'},450)//切换及切换速度 e.preventDefault() // 点击图标,停止自动滚动 if(!keepScroll) clearInterval(itvl) }) //一开始第一项hover $('#menu ul li.menuItem:first').addClass('act').siblings().addClass('inact') //自动轮播 var current=1 function autoAdvance(){ if(current==-1) return false $('#menu ul li a').eq(current%$('#menu ul li a').length).trigger('click',[true]) current++ } //自动轮播秒数 var changeEvery = 5 var itvl = setInterval(() => { autoAdvance() }, changeEvery*1000); })<file_sep>/gulp/dist/js/a.js var a;console.log(a);<file_sep>/README.md # demo.sh 测试<file_sep>/vue/vuex/examples/counter-hot/store/actions.js // 异步操作,作为所有同步事件的统一出口 const actions = { increment: ({commit}) => commit('increment'), decrement: ({commit}) => commit('decrement'), incrementIfOdd({commit,state}){ if((state.count + 1)%2 == 0){ commit('increment') } }, incrementAsync({commit}){ setTimeout(() => { commit('increment') }, 1000); } } export default actions<file_sep>/mini_project/js轮播/jquery/main.js // $(p1).click(function(){ // $(images).css({ // transform: 'translateX(0)' // }) // }); // $(p2).click(function(){ // $(images).css({ // transform: 'translateX(-300px)' // }) // }); // $(p3).click(function(){ // $(images).css({ // transform: 'translateX(-600px)' // }) // }); (function(){//立即执行函数,避免污染全局变量 var allButtons = $('#button > span') for(var i=0; i<allButtons.length; i++){ $(allButtons[i]).click(function (x) { var index = $(this).index()//jquery直接获取第几张 var p = index * -300 $(images).css({ transform: 'translateX(' + p + 'px)' }) activeButton($(this)) }) } //自动轮播 var n=0 var size = allButtons.length allButtons.eq(n%size).trigger('click') activeButton(allButtons.eq(n%size)) var timeId = setTimer() //鼠标hover停止播放 $('.carousel').mouseenter(function(){ window.clearInterval(timeId) }); $('.carousel').mouseleave(function(){ timeId = setTimer() }); function setTimer() { return setInterval(() => { n+=1 playSlide(n%size)//模仿点击,触发被选元素的指定事件类型 }, 3000); } //播放列表 function playSlide(index) { allButtons.eq(index).trigger('click') activeButton(allButtons.eq(index)) } //高亮红色,其余不变 function activeButton($button) { $button .addClass('red') .siblings('.red').removeClass('red') } //原生js实现当前点击的第几个span function numberSpan(s) { var n for(let i=0;i<allButtons.length;i++){ if(allButtons[i] === s){ n=i break; } } return n } // 原生JS获取this之外的其他元素,等价于jquery的siblings function getSiblings(n) { return getChildren(n.parentNode.firstChild, n); function getChildren(n, skipMe){ var r = []; for ( ; n; n = n.nextSibling ) if ( n.nodeType == 1 && n != skipMe) r.push( n ); return r; } } })()<file_sep>/test/src/js/app.js import x from './module1' import y from './module2' import '../css/index.scss' x() y()<file_sep>/vue/vuex/examples/counter-hot/store/getters.js const limit = 5 // 相当于计算属性computed const getters = { recentHistory: state => { const end = state.history.length const begin = end - limit > 0 ? end - limit : 0 return state.history.slice(begin, end).toString().replace(/,/g, ', ') }, count: state => state.count } export default getters<file_sep>/js_practice/deepCopy/deepCopy.js const obj1 = { age: 20, name: "Lee", address: { city: '北京' }, arr: ['a', 'b', 'c'] } /** * 深拷贝 */ function deepClone(obj) { //obj为null,不是对象数组,直接返回 if(typeof obj !== 'object' || obj == null){ return obj } //初始化返回结果 let result //是不是数组,否则为对象 (obj instanceof Array) ? result = [] : result = {} //遍历obj的key for(let key in obj){ //保证key不是原型的属性 if(obj.hasOwnProperty(key)){ //递归调用 result[key] = deepClone(obj[key]) } } return result } const obj2 = deepClone(obj1) obj2.address.city = "广州" console.log(obj1.address.city) console.log(obj1) console.log(obj2) //相互独立不影响 <file_sep>/vue/vuex/examples/counter/store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ // 相当于data state: { count: 0 }, // 相当于计算属性computed getters: { evenOrOdd: state => state.count % 2 == 0 ? 'even' : 'odd' }, // 相当于methods,只允许同步操作,不允许异步操作,对state修改只能在这进行 mutations: { increment(state){ state.count++ }, decrement(state){ state.count-- }, incrementIfOdd(state){ if((state.count + 1)%2 == 0){ state.count++ } } }, // 异步操作,作为所有同步事件的统一出口 actions: { incrementAsync({commit}){ setTimeout(() => { commit.increment() }, 1000); } } }) export default store<file_sep>/webpack/webpack_vue/src/js/index.js var info = { name: '21', age: '23' } export var title = "历史" export var book = "语文" export default info<file_sep>/gulp/gulpfile.js const plugins = require('gulp-load-plugins')() const gulp = require('gulp'); // const args = require('yargs').argv; //用于获取启动参数,针对不同参数,切换任务执行过程时需要 const uglify = require('gulp-uglify') //js压缩 const sass = require('gulp-sass'); //将sass预处理为css const cssMinify = require("gulp-minify-css"); //压缩css const autoprefixer = require('gulp-autoprefixer'); //解决内核前缀 const imagemin = require('gulp-imagemin'); //压缩图片 const pngquant = require('imagemin-pngquant'); //深度压缩 const cache = require('gulp-cache'); //只压缩没压缩过的,压缩过的从缓存中获取 // const rename = require('gulp-rename'); //重命名 const browserSync = require('browser-sync'); //监听文件的更改并且自动刷新页面 // const reload = browserSync.reload; //静态文件服务器,同时也支持浏览器自动刷新 // const ngConstant = require('gulp-ng-constant'); // const del = require('del'); //删除build文件(当css,img,js出现删除操作的时候,虽然watch会监听,但是并不会删除相应文件。) const paths = { appDir: "./app/", outputDir: "./dist/", sassSrc: { input: './app/css/*.scss', output: './dist/css/', }, imgSrc: { input: ['./app/img/*.png', './app/img/*.jpg'], output: './dist/img/' }, jsSrc: { input: ['./app/js/*.js'], output: './dist/js/' }, watch: { sass: ['./app/**/*.scss'], css: ['./app/app.css'], html: ['app/**/*.html', '!app/lib/**/*.js'], js: ['app/**/*.js', '!app/**/*.js'] } }; //转换成css,加css前缀,压缩 gulp.task('sass', function() { return gulp.src(paths.sassSrc.input) .pipe(sass()) .pipe(autoprefixer({ browsers: ['last 2 versions', 'Android >= 4.0'], cascade: false, //是否美化属性值(对齐) 默认:true })) .pipe(cssMinify()) //gulp-minify-css压缩比gulp-sass自带压缩效率好 .pipe(gulp.dest(paths.sassSrc.output)) }); // 压缩图片 gulp.task('images', function() { return gulp.src(paths.imgSrc.input) .pipe(cache(imagemin({ progressive: true, use: [pngquant()] }))) .pipe(gulp.dest(paths.imgSrc.output)) }); //js压缩 gulp.task('script', function() { return gulp.src(paths.jsSrc.input) // 2\. 压缩文件 .pipe(uglify()) .pipe(gulp.dest(paths.jsSrc.output)) }); //浏览器同步 // gulp.task('browser-sync', function() { //默认地址localhost:3000,默认打开 // browserSync({ // server: { // baseDir: [paths.appDir, paths.publishDir] // 设置服务器的根目录 // } // }); // }); gulp.task('default', ['sass', 'images', 'script']); gulp.task('build', ['sass', 'images', 'script']);<file_sep>/js_practice/手写jquery/jquery_demo.js class jQuery { constructor(selector){ const result = document.querySelectorAll(selector) const length = result.length for(let i=0; i < length; i++){ this[i] = result[i] } this.length = length this.selector = selector } get(index){ return this[index] } each(fn) { for(let i=0; i<this.length; i++){ const elem = this[i] fn(elem) } } on(type, fn){ return this.each(elem => { elem.addEventListener(type, fn, false) }) } } // 弹窗插件 jQuery.prototype.dialog = function (info) { alert(info) } // promise加载图片 function loadImg(src) { return new Promise((resolve, reject) => { const img = document.createElement('img') img.onload = () => { resolve(img) } img.onerror = () => { const err = new Error(`图片加载失败 ${src}`) reject(err) } img.src = src }); } const url = "https://upload.jianshu.io/users/upload_avatars/4820992/9165dbb8-9df8-467a-af97-773c0e0a2d05.jpeg?imageMogr2/auto-orient/strip|imageView2/1/w/240/h/240" loadImg(url).then(img =>{ console.log(img.width) return img }).then(img =>{ console.log(img.height) }).catch(ex => console.log(ex)) // 手写bind函数 Function.prototype.bind1 = function () { // 将参数解析为数组 const args = Array.prototype.slice.call(arguments) // 获取this(去除数组第一项,数组剩余的就是传递的参数) const t = args.shift() const self = this // 当前函数 // 返回一个函数 return function () { // 执行原函数,并返回结果 return self.apply(t, args) } } // 执行例子 function fn1(a,b,c) { console.log('this', this); console.log(a,b,c) return 'this is fn1' } const fn2 = fn1.bind1({x:100}, 10, 20, 30) const res = fn2() console.log(res); // Promise执行案例 Promise.resolve().then(() =>{ console.log('1'); }).catch(() => { console.log('2'); }).then(() => { console.log('3'); }) Promise.resolve().then(() =>{ console.log('1'); throw new Error("error1") }).catch(() => { console.log('2'); }).then(() => { console.log('3'); }) Promise.resolve().then(() =>{ console.log('1'); throw new Error("error1") }).catch(() => { console.log('2'); }).catch(() => { console.log('3'); }) // 执行async函数,返回的是Promise对象 async function fn1() { return 100 } const res1 = fn1() console.log(res1); // await相当于Promise的then (async function () { const p1 = Promise.resolve(300) const data = await p1 // await相当于Promise的then,resolved才会执行 console.log(data); })() (async function () { const data = await 200 // await相当于Promise的then,resolved才会执行 console.log(data); })() async function fn1() { return Promise.resolve(200) } (async function () { const data = await fn1() console.log(data); })() // try...catch可捕获异常,代替了Promise的catch (async function () { const p1 = Promise.reject("err1") try { const res = await p4 console.log(res); } catch (error) { console.log(error); } })() // async/await执行顺序案例 // 案例1 async function async1() { console.log('async start');// 2.1 打印 await async2() //3、执行 console.log('async1 end'); // 5、打印 } async function async2() { console.log('async2');// 3.1 打印 } console.log('script start'); // 1、执行并打印 async1() // 2、执行 console.log('script end'); //4、打印 // 案例2 async function async1() { console.log('async1 start'); await async2() console.log('async1 end'); await async3() console.log('async1 end 2'); } async function async2() { console.log('async2'); } async function async3() { console.log('async3'); } console.log('script start'); async1() console.log('script end'); //script start //async1 start //async2 //script end //async1 end //async3 //async1 end 2 // for of异步遍历 function muti(num) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(num * num) }, 1000); }); } const nums = [1, 2, 3]; // forEach遍历,没有延迟 nums.forEach(async (i) => { const result = await muti(i) console.log(result); }); // for of异步遍历,有延迟 (async function () { for (const i of nums) { const result = await muti(i) console.log(result); } })() // 宏任务与微任务 console.log(100) setTimeout(() => { console.log(200); }); // 宏任务 Promise.resolve().then(() =>{ console.log(300); }) // 微任务 console.log(400); // 综合题目 async function async1() { console.log('async1 start');// 3.1 输出 await async2() // 4 执行 console.log('async1 end');// 5 异步 微任务1 } async function async2() { console.log('async2'); // 4.1 输出 } console.log('script start'); // 1、输出 setTimeout(() => { // 2、执行,异步,宏任务1 console.log('setTimeout'); }, 0); async1() // 3、执行 // 初始化Promise,传入的函数会立刻执行 new Promise((resolve, reject) => { console.log('promise1'); // 6、输出 resolve() // 异步 微任务2 }).then(() =>{ console.log('promise2'); }) console.log('script end');// 7、输出,同步执行完毕,异步先执行微任务,再执行宏任务 //script start //async1 start //async2 //promise1 //script end //async1 end //promise2 //setTimeout // DOM插入性能优化 const listNode = document.getElementById('list') // 插入一个文档片段,此时还没有插入到DOM书中 const frag = document.createDocumentFragment() // 执行插入 for (let x = 0; x < 10; x++) { const li = document.createElement("li") li.innerHTML = "List item" + x frag.appendChild(li) } // 都完成后,最后插入到DOM树中 listNode.appendChild(frag) // 对DOM查询做缓存 const pList = document.getElementsByTagName("p") const pLength = pList.length for (let i = 0; i < pLength; i++) { // 缓存length ,只进行一次DOM查询 } // 通用事件监听事件 function bindEvent(elem, type, selector, fn) { // 如果传了三个参数 if(fn == null){ fn = selector selector = null } elem.addEventListener(type, event => { const target = event.target if (selector) { // 代理绑定,绑定无限个 if (target.matches(selector)) { fn.call(target, event) } } else { // 普通绑定 fn.call(target, event) } }) }<file_sep>/vue/vuex_demo/src/vuex/dialog_store.js export default { state:{ show:false, name:'你爸爸吧' }, // 类似于computed计算属性 getters:{ not_show(state){//这里的state对应着上面这个state return !state.show; } }, // 类似于methods, mutations:{ switch_dialogg(state){//这里的state对应着上面这个state state.show = state.show?false:true; //你还可以在这里执行其他的操作改变state } }, // 执行多个 mutations 就需要用 action ,异步 actions:{ switch_dialog(context){//这里的context和我们使用的$store拥有相同的对象和方法 context.commit('switch_dialogg'); //你还可以在这里触发其他的mutations方法 }, } }<file_sep>/mini_project/js轮播/无缝轮播/main.js // setTimeout(() => { // $('.images>img:nth-child(1)').css({ // transform: 'translateX(-100%)' // }) // $('.images>img:nth-child(2)').css({ // transform: 'translateX(-100%)' // }) // $('.images>img:nth-child(1)').one('transitionend', function name() { //动画执行完后 // $(this).addClass('right').css({transform: 'none'}) // }) // }, 3000); // setTimeout(() => { // $('.images>img:nth-child(2)').css({ // transform: 'translateX(-200%)' // }) // $('.images>img:nth-child(3)').css({ // transform: 'translateX(-100%)' // }) // $('.images>img:nth-child(2)').one('transitionend', function name() { //动画执行完后执行1次 // $(this).addClass('right').css({transform: 'none'}) // }) // }, 6000); // setTimeout(() => { // $('.images>img:nth-child(3)').css({ // transform: 'translateX(-300%)' // }) // $('.images>img:nth-child(1)').css({ // transform: 'translateX(-100%)' // }) // $('.images>img:nth-child(3)').one('transitionend', function name() { //动画执行完后,执行1次 // $(this).addClass('right').css({transform: 'none'}) // }) // }, 9000); let n initialize()//初始化 let timer = setInterval(() => { Leave(getImage(n)) .one('transitionend', function name() { Enter($(this)) }) Current(getImage(n+1)) n+=1 }, 3000); //用户切换到其他页面停止播放 document.addEventListener('visibilitychange',function(){ if(document.hidden){ window.clearInterval(timer) }else{ timer = setInterval(() => { Leave(getImage(n)) .one('transitionend', function name() { Enter($(this)) }) Current(getImage(n+1)) n+=1 }, 3000); } }) //初始化 function initialize() { n=1 $(`.images>img:nth-child(${n})`).addClass('current') .siblings().addClass('enter') } function x(n){ if(n>3){ n=n%3 if(n===0){ n=3 } } return n } function getImage(n){ return $(`.images > img:nth-child(${x(n)})`) } function Current($node) { return $node.removeClass('enter').addClass('current') } function Leave($node) { return $node.removeClass('current').addClass('leave') } function Enter($node) { return $node.removeClass('leave').addClass('enter') }<file_sep>/部分素材/悬浮导航条/游戏网站左侧抽屉式分享浮动导航代码/js/lrtk.js function sideFixed(){ var scrolltop = document.body.scrollTop || document.documentElement.scrollTop; var a1 = 650; var ww = $(window).width(); if(ww>540){ if(a1<=scrolltop){ $('.appgame-app-dl,#appgame-leftside-share').slideDown(); } else{ $('.appgame-app-dl,#appgame-leftside-share').slideUp(); } } } $(function(){ sideFixed(); $(window).scroll(function(e) { sideFixed(); }); $(".appgame-sidebar-glist li").mouseenter(function(e) { if($(this).hasClass('current')){ } else{ $(this).parent('ul').find('li').removeClass('current'); $(this).addClass('current'); } }); $('.appgame-comments').click(function(e) { $('html,body').animate({scrollTop:$('#appgame-comments').offset().top},400); }); }); /*$(window).load(function(e) { ykplayer=document.getElementById('youku-player'); wmode=document.createElement('param'); wmode.name='wmode'; wmode.value='Opaque'; ykplayer.appendChild(wmode); });*/ /*左侧滚动导航*/ function gotoTPoint(obj, speed) { var objTop; var objId = '#' + obj; if (obj != 'top') { objTop = $(objId).offset().top-70; } else { objTop = 0; } $('html,body').animate({ scrollTop: objTop }, speed); }<file_sep>/vue/vuex_test/src/store/Hello_store.js export default{ state: { name:'你好', count: 0 }, mutations: { add(state) { state.count++ }, addN(state, step) { state.count += step } }, actions: { addAsync(context, step) { setTimeout(() => { context.commit('addN', step) }, 1000); } }, getters: { showNum(state) { return `当前数字为` + state.count } } }<file_sep>/mini_project/jianli/src/js/module-1.js function fn(){ setTimeout(() => { siteWelcome.classList.remove('active') }, 300); // portfolio1.onclick = function () { // portfolioBar.className = "bar state-1" // } // portfolio2.onclick = function () { // portfolioBar.className = "bar state-2" // } // portfolio3.onclick = function () { // portfolioBar.className = "bar state-3" // } let specialTags = document.querySelectorAll('[data-x]') for(let i=0; i<specialTags.length; i++){ specialTags[i].classList.add('offset') } setTimeout(() => { crollText() }, 300); window.onscroll = function () { window.scrollY > 0 ? (topNavBar.classList.add('sticky')):(topNavBar.classList.remove('sticky')) crollText() } function crollText(){ let specialTags = document.querySelectorAll('[data-x]') let minIndex = 0 for(let i=0;i<specialTags.length;i++){ if(Math.abs(specialTags[i].offsetTop - window.scrollY) < Math.abs(specialTags[minIndex].offsetTop - window.scrollY)){ minIndex = i } } // minIndex就是离窗口顶部最近的元素 specialTags[minIndex].classList.remove('offset') let id = specialTags[minIndex].id let a = document.querySelector('a[href="#'+ id +'"]') let li = a.parentNode let brothersAndme = li.parentNode.children for(let i=0;i<brothersAndme.length;i++){ brothersAndme[i].classList.remove('highlight') } li.classList.add('highlight') } let liTags = document.querySelectorAll('nav.menu > ul > li') for(let i=0; i<liTags.length; i++){ liTags[i].onmouseenter = function (x) { // console.log(this.children[1]) // while(brother.tagName !== 'UL'){ // brother = brother.nextSibling // } x.currentTarget.classList.add('active') } liTags[i].onmouseleave = function (x) { x.currentTarget.classList.remove('active') } } let aTags = document.querySelectorAll('nav.menu > ul > li > a') for(let i=0; i<aTags.length; i++){ aTags[i].onclick = function (x) { x.preventDefault();//取消默认的锚点滚动 // let href = this.getAttribute('href') // let element = document.querySelector(href) let top = document.querySelector(this.getAttribute('href')).offsetTop//获取该div到定点的距离 // let n = 25 //动25次 // let duration = 500 / n //多少时间动一次 let currentTop = window.scrollY //当前高度 let targetTop = top - 80 //目标top // let distance = (targetTop - currentTop)/ n //每次动多少 // let i = 0 // let id = setInterval(() => { // if(i===n){ //等于25次时停止 // window.clearInterval(id) // return // } // i = i + 1 // window.scrollTo(0, currentTop + distance * i) // }, duration) var coords = { y: currentTop }; var tween = new TWEEN.Tween(coords) .to({ y: targetTop }, 500) .easing(TWEEN.Easing.Quadratic.In) .onUpdate(function() { window.scrollTo(0,coords.y) }) .start(); } } // Setup the animation loop. function animate(time) { requestAnimationFrame(animate); TWEEN.update(time); } requestAnimationFrame(animate); } export default fn
3a94bc5b6386ccc889775aa206cda58bb54d5c99
[ "JavaScript", "Markdown" ]
18
JavaScript
Apple-yong/Practice
5f3d10cf4a9caafd8172f6a36c08a3c338ae77f3
a57af55fb7cec1ef1daab98ca85d995d7c588cc2
refs/heads/master
<repo_name>DFAU/toujou-oauth2-server<file_sep>/Classes/Domain/Entity/Typo3Scope.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Entity; use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Entities\Traits\EntityTrait; use League\OAuth2\Server\Entities\Traits\ScopeTrait; class Typo3Scope implements ScopeEntityInterface { use EntityTrait; use ScopeTrait; public function __construct(string $identifier) { $this->identifier = $identifier; } } <file_sep>/Classes/Domain/Repository/Typo3ClientRepository.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Repository; use DFAU\ToujouOauth2Server\Domain\Entity\Typo3Client; use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory; use TYPO3\CMS\Core\Database\ConnectionPool; use TYPO3\CMS\Core\Database\Query\QueryBuilder; use TYPO3\CMS\Core\Utility\GeneralUtility; class Typo3ClientRepository implements ClientRepositoryInterface { public const TABLE_NAME = 'tx_toujou_oauth2_server_client'; /** @var PasswordHashFactory */ protected $hashFactory; /** @var QueryBuilder */ protected $queryBuilder; public function __construct() { $this->hashFactory = GeneralUtility::makeInstance(PasswordHashFactory::class); $this->queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable(static::TABLE_NAME); } public function getClientEntity($clientIdentifier): ?Typo3Client { $clientData = $this->findRawByIdentifier($clientIdentifier, ['name', 'redirect_uris', 'user_uid', 'user_table']); if ($clientData) { $userIdentifier = !empty($clientData['user_table']) && !empty($clientData['user_uid']) ? $clientData['user_table'] . '_' . $clientData['user_uid'] : null; return new Typo3Client( $clientIdentifier, $clientData['name'], GeneralUtility::trimExplode("\n", $clientData['redirect_uris']), $userIdentifier ); } return null; } public function validateClient($clientIdentifier, $clientSecret, $grantType): bool { $client = $this->findRawByIdentifier($clientIdentifier, ['identifier', 'secret']); if ($client) { return $this->hashFactory->get($client['secret'], 'BE')->checkPassword($clientSecret, $client['secret']); } return false; } protected function findRawByIdentifier(string $clientIdentifier, $selects = ['*']): ?array { return $this->queryBuilder ->resetQueryParts() ->select(...$selects) ->from(static::TABLE_NAME) ->where($this->queryBuilder->expr()->eq( 'identifier', $this->queryBuilder->createNamedParameter($clientIdentifier) )) ->setMaxResults(1) ->execute() ->fetch() ?: null; } } <file_sep>/Classes/Middleware/AuthorizationHeaderFixer.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * Fixes situations with rewrite rules in apache when HTTP Headers get a REDIRECT_ prefix */ class AuthorizationHeaderFixer implements MiddlewareInterface { /** * Process an incoming server request. * * Processes an incoming server request in order to produce a response. * If unable to produce the response itself, it may delegate to the provided * request handler to do so. */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { if (!$request->hasHeader('authorization') && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { $request = $request->withAddedHeader('Authorization', $_SERVER['REDIRECT_HTTP_AUTHORIZATION']); } return $handler->handle($request); } } <file_sep>/Classes/Form/UuidClientIdentifierGenerator.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Form; use Ramsey\Uuid\Uuid; use TYPO3\CMS\Backend\Form\FormDataProviderInterface; class UuidClientIdentifierGenerator implements FormDataProviderInterface { /** * Add form data to result array * * @param array $result Initialized result array * * @return array Result filled with more data */ public function addData(array $result): array { if ('new' !== $result['command']) { return $result; } if (!\is_array($result['databaseRow'])) { throw new \UnexpectedValueException( 'databaseRow of table ' . $result['tableName'] . ' is not an array', 1563458054 ); } if ('tx_toujou_oauth2_server_client' === $result['tableName']) { $result['databaseRow']['identifier'] = $result['databaseRow']['identifier'] ?: Uuid::uuid4(); } return $result; } } <file_sep>/Classes/Domain/Repository/Typo3BackendUserRepository.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Repository; use DFAU\ToujouOauth2Server\Authentication\Oauth2BackendUserAuthentication; use DFAU\ToujouOauth2Server\Domain\Entity\Typo3BackendUser; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Entities\UserEntityInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; use TYPO3\CMS\Core\Authentication\LoginType; use TYPO3\CMS\Core\Utility\GeneralUtility; class Typo3BackendUserRepository implements UserRepositoryInterface { /** @var Oauth2BackendUserAuthentication */ protected $backendUser; public function __construct() { $this->backendUser = GeneralUtility::makeInstance(Oauth2BackendUserAuthentication::class); } /** * @param string $username * @param string $password * @param string $grantType */ public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity): ?UserEntityInterface { $this->backendUser->setLoginData($username, $password, LoginType::LOGIN); $this->backendUser->checkAuthentication(); if ($this->backendUser->user) { return GeneralUtility::makeInstance(Typo3BackendUser::class, $username, $this->backendUser->user); } return null; } } <file_sep>/Classes/Authentication/Oauth2BackendUserAuthentication.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Authentication; use TYPO3\CMS\Core\Authentication\BackendUserAuthentication; use TYPO3\CMS\Core\Authentication\LoginType; class Oauth2BackendUserAuthentication extends BackendUserAuthentication { /** @var string */ protected $clientIdentifier; /** @var string */ protected $clientSecret; /** @var string */ protected $clientLoginType; public function __construct() { $this->id = ''; parent::__construct(); } public function setLoginData(string $clientIdentifier, string $clientSecret, string $clientLoginType): void { $this->clientIdentifier = $clientIdentifier; $this->clientSecret = $clientSecret; $this->clientLoginType = $clientLoginType; } public function getLoginFormData(): array { $loginData = [ 'uname' => $this->clientIdentifier, 'uident' => $this->clientSecret, 'status' => $this->clientLoginType, ]; // Only process the login data if a login is requested if (LoginType::LOGIN === $loginData['status']) { $loginData = $this->processLoginData($loginData, 'normal'); } return \array_map('trim', $loginData); } } <file_sep>/Classes/Domain/Entity/Typo3Client.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Entity; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Entities\Traits\ClientTrait; use League\OAuth2\Server\Entities\Traits\EntityTrait; class Typo3Client implements ClientEntityInterface, UserRelatedClientEntityInterface { use EntityTrait; use ClientTrait; /** @var array */ protected $userIdentifier; public function __construct($identifier, string $name, array $redirectUri, string $userIdentifier = null, bool $isConfidential = true) { $this->identifier = $identifier; $this->name = $name; $this->redirectUri = $redirectUri; $this->userIdentifier = $userIdentifier; $this->isConfidential = $isConfidential; } public function getUserIdentifier(): string { return $this->userIdentifier; } } <file_sep>/ext_tables.sql CREATE TABLE be_users ( oauth2_clients int(11) DEFAULT '0' NOT NULL ); CREATE TABLE tx_toujou_oauth2_server_client ( identifier varchar(32) DEFAULT '' NOT NULL, user_uid int(11) DEFAULT '0' NOT NULL, user_table varchar(8) DEFAULT '' NOT NULL, name varchar(255) DEFAULT '' NOT NULL, secret varchar(100) DEFAULT '' NOT NULL, redirect_uris text, description text ); CREATE TABLE tx_toujou_oauth2_server_access_token ( identifier varchar(255) DEFAULT '' NOT NULL, revoked datetime DEFAULT NULL, client_id varchar(32) DEFAULT '' NOT NULL, expiry_date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, scopes varchar(255) DEFAULT '' NOT NULL, PRIMARY KEY (identifier) ); <file_sep>/README.md # Toujou OAuth 2.0 Server A TYPO3 Oauth2 Client Credentials Server, that logs in Backend Users. ## Installation Require and install the plugin $ composer require DFAU/toujou-oauth2-server $ vendor/bin/typo3cms extension:install toujou_oauth2_server ## Development Install php dependencies using composer: $ composer install #### [PHPUnit](https://phpunit.de) Unit tests $ etc/scripts/runTests.sh #### [PHPUnit](https://phpunit.de) Functional tests $ etc/scripts/runTests.sh -s functional #### [Easy-Coding-Standard](https://github.com/Symplify/EasyCodingStandard) Check coding standard violations $ etc/scripts/checkCodingStandards.sh Fix coding standard violations automatically $ etc/scripts/checkCodingStandards.sh --fix <file_sep>/Classes/Domain/Entity/UserRelatedClientEntityInterface.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Entity; interface UserRelatedClientEntityInterface { public function getUserIdentifier(): string; } <file_sep>/Classes/Domain/Repository/Typo3AccessTokenRepository.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Repository; use DFAU\ToujouOauth2Server\Domain\Entity\Typo3AccessToken; use DFAU\ToujouOauth2Server\Domain\Entity\UserRelatedClientEntityInterface; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use TYPO3\CMS\Core\Database\ConnectionPool; use TYPO3\CMS\Core\Database\Query\QueryBuilder; use TYPO3\CMS\Core\Utility\GeneralUtility; class Typo3AccessTokenRepository implements AccessTokenRepositoryInterface { public const TABLE_NAME = 'tx_toujou_oauth2_server_access_token'; /** @var QueryBuilder */ protected $queryBuilder; public function __construct() { $this->queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable(static::TABLE_NAME); } public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null) { if (null === $userIdentifier && $clientEntity instanceof UserRelatedClientEntityInterface) { $userIdentifier = $clientEntity->getUserIdentifier(); } return new Typo3AccessToken($clientEntity, $scopes, $userIdentifier); } public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity): void { // TODO implement UniqueTokenIdentifierConstraintViolationException $this->queryBuilder ->resetQueryParts() ->insert(static::TABLE_NAME) ->values([ 'identifier' => $accessTokenEntity->getIdentifier(), 'client_id' => $accessTokenEntity->getClient()->getIdentifier(), 'expiry_date' => $accessTokenEntity->getExpiryDateTime()->format('Y-m-d h:m:s'), 'scopes' => \implode("\n", $accessTokenEntity->getScopes()), ])->execute(); } public function revokeAccessToken($tokenId): void { $this->queryBuilder ->resetQueryParts() ->update(static::TABLE_NAME) ->set('revoked', \date('Y-m-d')) ->where($this->queryBuilder->expr()->eq('identifier', $this->queryBuilder->quote($tokenId))) ->execute(); } public function isAccessTokenRevoked($tokenId): bool { return (bool) $this->queryBuilder ->resetQueryParts() ->select('revoked') ->from(static::TABLE_NAME) ->where( $this->queryBuilder->expr()->eq('identifier', $this->queryBuilder->quote($tokenId)), $this->queryBuilder->expr()->lt('revoked', 'NOW()') ) ->setMaxResults(1) ->execute() ->fetch(); } } <file_sep>/Classes/Middleware/ResourceServerMiddleware.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Middleware; use DFAU\ToujouOauth2Server\Domain\Repository\Typo3AccessTokenRepository; use League\OAuth2\Server\CryptKey; use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\ResourceServer; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use TYPO3\CMS\Backend\FrontendBackendUserAuthentication; use TYPO3\CMS\Backend\Utility\BackendUtility; use TYPO3\CMS\Core\Context\Context; use TYPO3\CMS\Core\Context\UserAspect; use TYPO3\CMS\Core\Core\Bootstrap; use TYPO3\CMS\Core\Http\Response; use TYPO3\CMS\Core\Utility\GeneralUtility; class ResourceServerMiddleware implements MiddlewareInterface { /** * Process an incoming server request. * * Processes an incoming server request in order to produce a response. * If unable to produce the response itself, it may delegate to the provided * request handler to do so. */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { $request = $this->createServer()->validateAuthenticatedRequest($request); $this->overrideBackendUser($request->getAttribute('oauth_user_id')); } catch (OAuthServerException $exception) { return $exception->generateHttpResponse(new Response()); } catch (\Throwable $exception) { return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500)) ->generateHttpResponse(new Response()); } return $handler->handle($request); } protected function createServer(): ResourceServer { if (!\getenv('TYPO3_OAUTH2_PUBLIC_KEY')) { throw new \InvalidArgumentException('The environment variable "TYPO3_OAUTH2_PUBLIC_KEY" is empty.', 1565883420); } /** @var ResourceServer $server */ $server = GeneralUtility::makeInstance( ResourceServer::class, GeneralUtility::makeInstance(Typo3AccessTokenRepository::class), new CryptKey(\getenv('TYPO3_OAUTH2_PUBLIC_KEY')) ); return $server; } protected function overrideBackendUser($userIdentifier): void { if (null !== $userIdentifier && \str_starts_with($userIdentifier, 'be_users_')) { $backendUserObject = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class); $backendUserObject->user = $backendUserObject->getRawUserByUid(BackendUtility::splitTable_Uid($userIdentifier)[1]); if (!empty($backendUserObject->user['uid'])) { $backendUserObject->loginFailure = false; $backendUserObject->fetchGroupData(); $backendUserObject->createUserSession($backendUserObject->user); $GLOBALS['BE_USER'] = $backendUserObject; Bootstrap::initializeLanguageObject(); Bootstrap::loadExtTables(); // Override the backend user for this request if oauth2 authentication succeeds GeneralUtility::makeInstance(Context::class)->setAspect( 'backend.user', GeneralUtility::makeInstance(UserAspect::class, $backendUserObject) ); } } } } <file_sep>/ext_emconf.php <?php $EM_CONF[$_EXTKEY] = [ 'title' => 'toujou Oauth2 Server', 'description' => 'A TYPO3 Oauth2 Client Credentials Server, that logs in Backend Users', 'category' => 'services', 'version' => '0.0.1', 'state' => 'beta', 'clearCacheOnload' => true, 'author' => '<NAME>', 'author_email' => '<EMAIL>', 'author_company' => 'DFAU', 'constraints' => [ 'depends' => [ 'typo3' => '10.4.0 - 11.99.99' ], 'conflicts' => [], 'suggests' => [], ] ]; <file_sep>/Classes/Middleware/AuthorizationServerMiddleware.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Middleware; use Defuse\Crypto\Key; use DFAU\ToujouOauth2Server\Domain\Repository\Typo3AccessTokenRepository; use DFAU\ToujouOauth2Server\Domain\Repository\Typo3ClientRepository; use DFAU\ToujouOauth2Server\Domain\Repository\Typo3ScopeRepository; use League\OAuth2\Server\AuthorizationServer; use League\OAuth2\Server\CryptKey; use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\Grant\ClientCredentialsGrant; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use TYPO3\CMS\Core\Http\Response; use TYPO3\CMS\Core\Site\Entity\Site; use TYPO3\CMS\Core\Utility\GeneralUtility; class AuthorizationServerMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $site = $request ? $request->getAttribute('site') : null; $tokenEndpoint = $site instanceof Site ? \ltrim($site->getAttribute('oauth2TokenEndpoint') ?? '', '/ ') : null; if (!empty($tokenEndpoint) && \str_starts_with($request->getUri()->getPath(), '/' . $tokenEndpoint)) { try { return $this->createServer()->respondToAccessTokenRequest($request, new Response()); } catch (OAuthServerException $exception) { return $exception->generateHttpResponse(new Response()); } catch (\Throwable $exception) { return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500)) ->generateHttpResponse(new Response()); } } return $handler->handle($request); } protected function createServer(): AuthorizationServer { if (!\getenv('TYPO3_OAUTH2_PRIVATE_KEY')) { throw new \InvalidArgumentException('The environment variable "TYPO3_OAUTH2_PRIVATE_KEY" is empty.', 1565882899); } if (!\getenv('TYPO3_OAUTH2_ENCRYPTION_KEY')) { throw new \InvalidArgumentException('The environment variable "TYPO3_OAUTH2_ENCRYPTION_KEY" is empty.', 1565883415); } /** @var AuthorizationServer $server */ $server = GeneralUtility::makeInstance( AuthorizationServer::class, GeneralUtility::makeInstance(Typo3ClientRepository::class), GeneralUtility::makeInstance(Typo3AccessTokenRepository::class), GeneralUtility::makeInstance(Typo3ScopeRepository::class), new CryptKey(\getenv('TYPO3_OAUTH2_PRIVATE_KEY')), Key::loadFromAsciiSafeString(\getenv('TYPO3_OAUTH2_ENCRYPTION_KEY')) ); $server->enableGrantType( new ClientCredentialsGrant(), new \DateInterval('P1D') // access tokens will expire after 1 hour ); return $server; } } <file_sep>/Configuration/RequestMiddlewares.php <?php declare(strict_types=1); use DFAU\ToujouOauth2Server\Middleware\AuthorizationHeaderFixer; use DFAU\ToujouOauth2Server\Middleware\AuthorizationServerMiddleware; use Middlewares\JsonPayload; return [ 'frontend' => [ 'middlewares/payload/json-payload' => [ 'target' => JsonPayload::class, ], 'dfau/toujou-oauth2-server/authorization-header-fixer' => [ 'target' => AuthorizationHeaderFixer::class, 'before' => ['dfau/toujou-oauth2-server/authorization-server'], ], 'dfau/toujou-oauth2-server/authorization-server' => [ 'target' => AuthorizationServerMiddleware::class, 'after' => ['typo3/cms-frontend/site', 'middlewares/payload/json-payload'], 'before' => ['typo3/cms-frontend/base-redirect-resolver'], ], /*'dfau/toujou-oauth2-server/resource-server' => [ 'target' => \DFAU\ToujouOauth2Server\Middleware\ResourceServerMiddleware::class, ],*/ ], ]; <file_sep>/Classes/Domain/Entity/Typo3BackendUser.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Entity; use League\OAuth2\Server\Entities\Traits\EntityTrait; use League\OAuth2\Server\Entities\UserEntityInterface; class Typo3BackendUser implements UserEntityInterface { use EntityTrait; /** @var array */ protected $userData; public function __construct(string $identifier, array $userData) { $this->identifier = $identifier; $this->userData = $userData; } public function getUserData(): array { return $this->userData; } } <file_sep>/Configuration/TCA/Overrides/be_users.php <?php use TYPO3\CMS\Core\Utility\ExtensionManagementUtility; $GLOBALS['TCA']['be_users']['columns']['oauth2_clients'] = [ 'exclude' => 1, 'label' => 'LLL:EXT:toujou_oauth2_server/Resources/Private/Language/locallang_be_users_tca.xlf:be_users.oauth2_clients.label', 'config' => [ 'type' => 'inline', 'foreign_table' => 'tx_toujou_oauth2_server_client', 'foreign_field' => 'user_uid', 'foreign_table_field' => 'user_table', 'size' => 10, 'maxitems' => 9999, 'autoSizeMax' => 30, 'multiple' => 0, 'appearance' => [ 'collapseAll' => 1, 'levelLinksPosition' => 'top', 'showSynchronizationLink' => 1, 'showPossibleLocalizationRecords' => 1, 'showAllLocalizationLink' => 1, ], ], ]; ExtensionManagementUtility::addToAllTCAtypes( 'be_users', '--div--;LLL:EXT:toujou_oauth2_server/Resources/Private/Language/locallang_be_users_tca.xlf:be_users.oauth2Tab,oauth2_clients' ); <file_sep>/Classes/Domain/Repository/Typo3ScopeRepository.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Repository; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; class Typo3ScopeRepository implements ScopeRepositoryInterface { /** * Return information about a scope. * * @param string $identifier The scope identifier */ public function getScopeEntityByIdentifier($identifier): ?ScopeEntityInterface { // TODO implement scopes return null; } /** * Given a client, grant type and optional user identifier validate the set of scopes requested are valid and optionally * append additional scopes or remove requested scopes. * * @param ScopeEntityInterface[] $scopes * @param string $grantType * @param string|null $userIdentifier * * @return ScopeEntityInterface[] */ public function finalizeScopes(array $scopes, $grantType, ClientEntityInterface $clientEntity, $userIdentifier = null): array { // TODO implement scopes return []; } } <file_sep>/Classes/Domain/Entity/Typo3AccessToken.php <?php declare(strict_types=1); namespace DFAU\ToujouOauth2Server\Domain\Entity; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Entities\Traits\AccessTokenTrait; use League\OAuth2\Server\Entities\Traits\EntityTrait; use League\OAuth2\Server\Entities\Traits\TokenEntityTrait; class Typo3AccessToken implements AccessTokenEntityInterface { use AccessTokenTrait; use EntityTrait; use TokenEntityTrait; public function __construct(ClientEntityInterface $clientEntity, array $scopes = [], $userIdentifier = null) { $this->setClient($clientEntity); $scopes && \array_map([$this, 'addScope'], $scopes); $userIdentifier && $this->setUserIdentifier($userIdentifier); } } <file_sep>/ext_tables.php <?php defined('TYPO3') || die(); $GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['formDataGroup']['tcaDatabaseRecord'][\DFAU\ToujouOauth2Server\Form\UuidClientIdentifierGenerator::class] = [ 'depends' => [ \TYPO3\CMS\Backend\Form\FormDataProvider\DatabaseRowDefaultValues::class ] ]; $iconRegistry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Imaging\IconRegistry::class); $iconRegistry->registerIcon('tcarecords-tx_toujou_oauth2_server_client-default', \TYPO3\CMS\Core\Imaging\IconProvider\FontawesomeIconProvider::class, ['name' => 'id-badge']);
41abd826ba527683218119d21c4b8e46e9818b68
[ "Markdown", "SQL", "PHP" ]
20
PHP
DFAU/toujou-oauth2-server
ae962efff2c1f5b1b3e7843b7d7bf45e48dc003c
1eda6779c0f486a583b3c7befbb7e7d5894e20d0
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-10 19:40 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Field', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField()), ('start', models.TimeField()), ('end', models.TimeField()), ('lunch', models.TimeField(null=True)), ('worked', models.TimeField()), ('overtime', models.TimeField(blank=True, null=True)), ('lacking', models.TimeField(blank=True, null=True)), ('completed', models.TextField(blank=True, null=True)), ], ), migrations.CreateModel( name='Month', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='September', max_length=32)), ], ), migrations.AddField( model_name='field', name='month', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='schedule.Month'), ), ] <file_sep>from __future__ import unicode_literals import datetime from django.db import models class Month(models.Model): name = models.CharField(max_length = 32) def __str__(self): return self.name class Field(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() lunch = models.TimeField(null = True, blank = True) worked = models.TimeField(null = True, blank = True) overtime = models.TimeField(null = True, blank = True) lacking = models.TimeField(null = True, blank = True) completed = models.TextField(null = True, blank = True) # Field objects named after date def __str__(self): return str(self.date)<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-12-26 20:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0003_newfield'), ] operations = [ migrations.DeleteModel( name='NewField', ), migrations.AlterField( model_name='field', name='worked', field=models.TimeField(blank=True, null=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-12-26 17:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0002_auto_20161130_2132'), ] operations = [ migrations.CreateModel( name='NewField', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField()), ('start', models.TimeField()), ('end', models.TimeField()), ('lunch', models.TimeField(blank=True, null=True)), ('worked', models.TimeField()), ('overtime', models.TimeField(blank=True, null=True)), ('lacking', models.TimeField(blank=True, null=True)), ('completed', models.TextField(blank=True, null=True)), ], ), ] <file_sep>from django.http import HttpResponse from django.template import loader from django.shortcuts import get_object_or_404 from datetime import datetime, date import datetime import time from .models import * def getSec(s): l = map(int, s.split(':')) return sum(n * sec for n, sec in zip(l[::-1], (1, 60, 3600))) def index(request): template = loader.get_template('index.html') day = "default diena" dates = [] days = [] start_times = [] end_times = [] lunch_times = [] worked = [] overtime = [] lacking = [] completed = [] for field in Field.objects.all(): dates.append(str(field.date)) days.append(datetime.datetime.strptime(str(field.date), '%Y-%m-%d').strftime('%A')) start = datetime.datetime.strptime(str(field.start), '%H:%M:%S').strftime('%H:%M') end = datetime.datetime.strptime(str(field.end), '%H:%M:%S').strftime('%H:%M') start_times.append(start) end_times.append(end) if field.lunch != None: lunch = datetime.datetime.strptime(str(field.lunch), '%H:%M:%S').strftime('%H:%M') lunch_times.append(lunch) lunch_time_in_sec = getSec(str(field.lunch)) worked_time = datetime.datetime.combine(date.min, field.end) - datetime.datetime.combine(date.min, field.start) worked_time = (worked_time.seconds) - lunch_time_in_sec worked_time = str(datetime.timedelta(seconds = worked_time)) worked_time = datetime.datetime.strptime(str(worked_time), '%H:%M:%S').strftime('%H:%M') else: lunch_times.append("-") worked_time = datetime.datetime.combine(date.min, field.end) - datetime.datetime.combine(date.min, field.start) worked_time = datetime.datetime.strptime(str(worked_time), '%H:%M:%S').strftime('%H:%M') worked.append(worked_time) if field.overtime != None: ot = datetime.datetime.strptime(str(field.overtime), '%H:%M:%S').strftime('%H:%M') overtime.append(ot) else: overtime.append("-") if field.lacking != None: lack = datetime.datetime.strptime(str(field.lacking), '%H:%M:%S').strftime('%H:%M') lacking.append(lack) else: lacking.append("-") if field.completed != None: completed.append(field.completed) else: lacking.append("-") # Define variables to be used in index.html context = { 'day': day, 'months': Month.objects.all(), 'fields': Field.objects.all(), 'fields_range': range(0, len(dates)), 'dates': dates, 'days': days, 'start_times': start_times, 'end_times': end_times, 'lunch_times': lunch_times, 'worked': worked, 'overtime': overtime, 'lacking': lacking, 'completed': completed, } return HttpResponse(template.render(context, request))
0f1358acc80bc2e87a0a4a8e62d3bfe9b67ecafe
[ "Python" ]
5
Python
robertsgreibers/officehours
99abb4d16627c2738b09162848e60195d6e29f09
cc7fada907c1d2e50b03d90a432f9d2a068b8d2e
refs/heads/master
<repo_name>kevinrut/ConfiguredEdge<file_sep>/README.md # ConfiguredEdge Configurator for Solid Edge 3d CAD application <file_sep>/CEdge/CEdge.UI/App.xaml.cs using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace CEdge.UI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { /// <summary> /// Password box helper for watermark /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) { PasswordBox pb = sender as PasswordBox; if (string.IsNullOrEmpty(pb.Password)) { pb.Tag = "True"; } else { pb.Tag = "False"; } } } }
1622542cccb438277b361ee077b01902d5554c32
[ "Markdown", "C#" ]
2
Markdown
kevinrut/ConfiguredEdge
c16d2a0effd12e668302190108d887af27a60f79
62c55d188a874826a97ff3b7c199d5a979873e7c
refs/heads/main
<repo_name>bridgecrew-perf7/tunnelto-deploy<file_sep>/images/server/Dockerfile ##### ## Dockerfile for a tunnelto server ## ## https://github.com/agrinman/tunnelto ##### # Using a named stage here allows us to have ARGs in it ARG TUNNELTO_BUILDER_IMAGE=ghcr.io/stackhpc/tunnelto-build:latest FROM ${TUNNELTO_BUILDER_IMAGE} AS build FROM debian:buster-slim # Add an unprivileged user to run the tunnelto server ENV TUNNELTO_UID 1001 ENV TUNNELTO_GID 1001 ENV TUNNELTO_USER tunnelto ENV TUNNELTO_GROUP tunnelto RUN groupadd --gid $TUNNELTO_GID $TUNNELTO_GROUP && \ useradd \ --no-create-home \ --no-user-group \ --shell /sbin/nologin \ --gid $TUNNELTO_GID \ --uid $TUNNELTO_UID \ $TUNNELTO_USER RUN apt-get update && \ apt-get install -y openssl tini && \ rm -rf /var/lib/apt/lists/* # Copy the server binary from the build COPY --from=build /opt/tunnelto/src/target/release/tunnelto_server /usr/bin/ # HTTP clients connect via this port to access services EXPOSE 8080 # tunnelto clients connect via this port to begin tunnels EXPOSE 5000 # Other tunnelto servers connect via this port for the gossip protocol EXPOSE 6000 USER $TUNNELTO_UID ENTRYPOINT ["/usr/bin/tini", "-g", "--"] CMD ["/usr/bin/tunnelto_server"] <file_sep>/images/client/Dockerfile ##### ## Dockerfile for a tunnelto client ## ## https://github.com/agrinman/tunnelto ##### # Using a named stage here allows us to have ARGs in it ARG TUNNELTO_BUILDER_IMAGE=ghcr.io/stackhpc/tunnelto-build:latest FROM ${TUNNELTO_BUILDER_IMAGE} AS build FROM debian:buster-slim # Add an unprivileged user to run the tunnelto client ENV TUNNELTO_UID 1001 ENV TUNNELTO_GID 1001 ENV TUNNELTO_USER tunnelto ENV TUNNELTO_GROUP tunnelto RUN groupadd --gid $TUNNELTO_GID $TUNNELTO_GROUP && \ useradd \ --no-create-home \ --no-user-group \ --shell /sbin/nologin \ --gid $TUNNELTO_GID \ --uid $TUNNELTO_UID \ $TUNNELTO_USER RUN apt-get update && \ apt-get install -y ca-certificates openssl tini && \ rm -rf /var/lib/apt/lists/* # Copy the client binary from the build COPY --from=build /opt/tunnelto/src/target/release/tunnelto /usr/bin/ # Copy the entrypoint script COPY ./tunnelto-init /usr/bin/ USER $TUNNELTO_UID ENTRYPOINT ["/usr/bin/tini", "-g", "--"] CMD ["/usr/bin/tunnelto-init"] <file_sep>/README.md # tunnelto-deploy This repository contains artifacts for deploying a [tunnelto server](https://github.com/agrinman/tunnelto). <file_sep>/images/build/Dockerfile ##### ## Dockerfile for building tunnelto binaries ## ## https://github.com/agrinman/tunnelto ##### FROM rust:slim AS build # Install required packages RUN apt-get update && \ apt-get install -y git libssl-dev pkg-config && \ rm -rf /var/lib/apt/lists/* # Add the patches # WARNING: THE PATCHES WILL LIKELY NEED TO CHANGE WHEN UPGRADING TUNNELTO COPY ./patch /opt/tunnelto/patch/ ARG TUNNELTO_REPO=https://github.com/agrinman/tunnelto.git ARG TUNNELTO_TAG=0.1.18 # At the time of writing, auth is not configurable via the config # There is an open PR to fix this, and add sqlite as a store # https://github.com/agrinman/tunnelto/pull/50 # For now, we need to manually patch main.rs after cloning RUN git clone --depth 1 --branch $TUNNELTO_TAG $TUNNELTO_REPO /opt/tunnelto/src && \ patch /opt/tunnelto/src/tunnelto_server/src/main.rs /opt/tunnelto/patch/main.rs.patch && \ patch /opt/tunnelto/src/tunnelto_server/src/auth/mod.rs /opt/tunnelto/patch/auth.mod.rs.patch && \ cd /opt/tunnelto/src && \ cargo build --bins --release <file_sep>/images/client/tunnelto-init #!/usr/bin/env bash set -e TUNNELTO_ARGS= # Print control host information if [ -n "$CTRL_HOST" ]; then echo "[INFO] Using control host at $CTRL_HOST:${CTRL_PORT:-443}" else echo "[INFO] Using default control host at tunnelto.dev" # When using the default control host, an API key is required if [ -z "$TUNNELTO_DEV_API_KEY" ]; then echo "[ERROR] API key is required when using tunnelto.dev" 1>&2 exit 1 fi fi # Even when auth is disabled, we still need to specify a dummy API key TUNNELTO_ARGS="$TUNNELTO_ARGS --key ${TUNNELTO_DEV_API_KEY:-dummykey}" if [ -n "$FORWARD_TO_HOST" ]; then TUNNELTO_ARGS="$TUNNELTO_ARGS --host $FORWARD_TO_HOST" else echo "[ERROR] Host to forward to must be specified using FORWARD_TO_HOST" 1>&2 exit 1 fi if [ -n "$FORWARD_TO_PORT" ]; then TUNNELTO_ARGS="$TUNNELTO_ARGS --port $FORWARD_TO_PORT" else echo "[ERROR] Port to forward to must be specified using FORWARD_TO_PORT" 1>&2 exit 1 fi if [ -n "$FORWARD_TO_SCHEME" ]; then TUNNELTO_ARGS="$TUNNELTO_ARGS --scheme $FORWARD_TO_SCHEME" fi echo "[INFO] Forwarding traffic to ${FORWARD_TO_SCHEME:-http}://$FORWARD_TO_HOST:$FORWARD_TO_PORT" if [ -n "$SUBDOMAIN" ]; then TUNNELTO_ARGS="$TUNNELTO_ARGS --port $FORWARD_TO_PORT" echo "[INFO] Requesting explicit subdomain: $SUBDOMAIN" fi exec /usr/bin/tunnelto $TUNNELTO_ARGS
bad41d4aaefaaf9bc234f10b650d4a030bd3e0bf
[ "Markdown", "Dockerfile", "Shell" ]
5
Dockerfile
bridgecrew-perf7/tunnelto-deploy
7e50e12f33c403ca22ee1ecc54b7898cbb19c1ce
e46f3260d181a0467e68dc88790cfbd9218a9308
refs/heads/master
<repo_name>l-zihao/mySpringBoot<file_sep>/src/main/java/com/lin/initializer/MyInitializer.java package com.lin.initializer; import com.lin.app.web.SpringServlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import java.util.Set; /** * @author Lin * @version 1.0 * @date 2020/8/19 21:27 */ /*@HandlesTypes(HttpServlet.class)*/ public class MyInitializer implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException { ServletRegistration.Dynamic registration=servletContext.addServlet("xx",new SpringServlet()); registration.addMapping("/"); } } <file_sep>/src/main/java/com/lin/initializer/Test.java package com.lin.initializer; /** * @author Lin * @version 1.0 * @date 2020/8/19 21:43 */ public interface Test { } <file_sep>/src/main/java/com/lin/app/MyWebApplication.java package com.lin.app; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; /** * @author Lin * @version 1.0 * @date 2020/8/19 17:24 */ public class MyWebApplication implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext (); annotationConfigWebApplicationContext.register(Appconfig.class); annotationConfigWebApplicationContext.refresh(); DispatcherServlet dispatcherServlet = new DispatcherServlet(annotationConfigWebApplicationContext); ServletRegistration.Dynamic registration = servletContext.addServlet("xxx", dispatcherServlet); registration.addMapping("/"); //设置启动顺序,让spring加载时执行init方法 registration.setLoadOnStartup(1); } }
de3ffc32975cb1910215d5cc32125484342f5f20
[ "Java" ]
3
Java
l-zihao/mySpringBoot
c828a6f640098bc4420dfe2c15f02fde6e9fe9e1
a67df52b8636b4b35ba815f0581889a22c54949b
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\House; use Illuminate\Http\Request; use Illuminate\Http\Response; class HousesController extends Controller { public function index(Request $request) { usleep(200000);//for show loader $bedrooms = $request->get('bedrooms'); $bathrooms = $request->get('bathrooms'); $storeys = $request->get('storeys'); $garages = $request->get('garages'); $price_gt = $request->get('price_gt'); $price_lt = $request->get('price_lt'); $query = House::query(); if($bedrooms) { $query->where('bedrooms', $bedrooms); } if($bathrooms) { $query->where('bathrooms', $bathrooms); } if($storeys) { $query->where('storeys', $storeys); } if($garages) { $query->where('garages', $garages); } if($price_gt) { $query->where('price','>=', $price_gt); } if($price_lt) { $query->where('price','<=', $price_lt); } return response($query->get()->jsonSerialize(), Response::HTTP_OK); } } <file_sep># Task Laravel Filters <br> <a target="_blank" href="https://docs.google.com/document/d/1HP2HmQlCaToSmnjJD5_G_1yeoNVxicCj0U6MDZC63qw/edit?usp=sharing">LINK TO TASK DESCRIPTION</a> <br> <br> Demo http://192.168.127.12:3002/ <file_sep><?php use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class FillHousesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::table('houses')->insert([ [ 'name' => '<NAME>', 'price' => 374662, 'bedrooms' => 4, 'bathrooms' => 2, 'storeys' => 2, 'garages' => 2, ], [ 'name' => '<NAME>', 'price' => 513268, 'bedrooms' => 4, 'bathrooms' => 2, 'storeys' => 1, 'garages' => 2, ], [ 'name' => '<NAME>', 'price' => 454990, 'bedrooms' => 4, 'bathrooms' => 3, 'storeys' => 2, 'garages' => 3, ], [ 'name' => '<NAME>', 'price' => 384356, 'bedrooms' => 4, 'bathrooms' => 2, 'storeys' => 2, 'garages' => 2, ], [ 'name' => '<NAME>', 'price' => 572002, 'bedrooms' => 4, 'bathrooms' => 3, 'storeys' => 2, 'garages' => 2, ], [ 'name' => 'The Toorak', 'price' => 521951, 'bedrooms' => 5, 'bathrooms' => 2, 'storeys' => 1, 'garages' => 2, ], [ 'name' => '<NAME>', 'price' => 263604, 'bedrooms' => 3, 'bathrooms' => 2, 'storeys' => 2, 'garages' => 2, ], [ 'name' => '<NAME>', 'price' => 386103, 'bedrooms' => 3, 'bathrooms' => 2, 'storeys' => 1, 'garages' => 1, ], [ 'name' => '<NAME>', 'price' => 390600, 'bedrooms' => 4, 'bathrooms' => 3, 'storeys' => 2, 'garages' => 2, ], ]); } /** * Reverse the migrations. * * @return void */ public function down() { DB::table('houses')->truncate(); } }
13818bd4b907e453d821007952a4bd38b3ed66de
[ "Markdown", "PHP" ]
3
PHP
nikolay-256/LaravelFilters
4d9271496b53882732b0f1676e6bf822261540d8
4bec32f70cdb5b1e340754be91708eb04c25177f
refs/heads/master
<file_sep># Analytics-link.github.io [Demo](https://analytics-link.github.io/) ## Prerequisites ### Requirements * [Ruby](https://www.ruby-lang.org/en/downloads/) version **2.7.1.**, including all development headers (ruby version can be checked by running `ruby -v`) * [RubyGems](https://rubygems.org/pages/download) (which you can check by running `gem -v`) * [GCC](https://gcc.gnu.org/install/) and [Make](https://www.gnu.org/software/make/) (in case your system doesn't have them installed, which you can check by running `gcc -v`,`g++ -v` and `make -v` in your system's command line interface) More info: [Requirements](https://jekyllrb.com/docs/installation/#requirements) ## Instructions 1. Run <code>gem install jekyll bundler</code>. 2. Copy the theme in your desired folder. 3. Enter into the folder by executing <code>cd name-of-the-folder</code>. 4. Run <code>bundle install</code>. 5. If you want to access and customize the theme, use <code>bundle exec jekyll serve</code>. This way it will be accessible on <code>http://localhost:4000</code>. 6. Upload the content of the compiled <code>_site</code> folder on your host server. <file_sep>$(function() { 'use strict'; /* ======================= // Reveal Image ======================= */ var wh = window.innerHeight; $(window).ready(function () { $('body').waitForImages({ finished: function () { setTimeout(function () { $('.preloader').addClass('hide'); setTimeout(function () { reveals(); }, 100); }, 500); }, waitForAll: true }); }); function reveals() { $(window).on('scroll', function () { $(".article-box, .article-first, .post-image-box, .page-image-box, .post-body img, .page-body img, .recent-header").each( function(i) { var el_top = $(this).offset().top, win_bottom = wh + $(window).scrollTop(); if (el_top < win_bottom) { $(this) .delay(i * 100) .queue(function() { $(this).addClass("reveal-in"); }); } } ); }).scroll(); } /* ======================= // Responsive Videos ======================= */ $(".post-content, .page-content").fitVids({ customSelector: ['iframe[src*="ted.com"]'] }); /* ======================= // Scroll Top Button ======================= */ $(".top").click(function () { $("html, body") .stop() .animate({ scrollTop: 0 }, "slow", "swing"); }); });
bafb1a8dcbb79dc92cdcb31368367cccb46a95f1
[ "Markdown", "JavaScript" ]
2
Markdown
analytics-link/analytics-link.github.io
7e10439dbee7ef37313dd9d50a19b35a41e7e059
b7f0c646de14d85df5cee2a75932e87a78e2c585
refs/heads/main
<repo_name>GadW6/oneclick<file_sep>/js/mini.js // // // UI Vars declaration : // // saveBtn = document.querySelector("section.save div.round"); visitBtn = document.querySelector("section.visit div.round"); hiddenSection = document.querySelector("div.hidden"); mainSection = document.querySelector("main"); // // // Here inserting all events listener: // // function allEventListener(){ saveBtn.addEventListener('mouseover', saveFuncOpen); visitBtn.addEventListener('mouseover', visitFuncOpen); mainSection.addEventListener('mouseleave', saveFuncClose); hiddenSection.addEventListener('submit', saveToBookmarks); } // // // Loading the function allEventListener() // // allEventListener(); // // // saveFuncOpen() // // function saveFuncOpen(e){ hiddenSection.style.display = "block"; hiddenSection.innerHTML = ` <form id="save-form"> <section class="section-url"> <h3>URL :</h3> <div class="mini-container"> <input type="url" name="inputUrl" id="inputUrl" value="" placeholder="Ex: &quot;https://google.com&quot;" autocomplete="off" required> <aside></aside> </div> </section> <section class="section-name"> <h3>Name :</h3> <div class="mini-container"> <input type="text" name="inputName" id="inputName" placeholder="Ex: &quot;Google&quot;" autocomplete="off" required> <aside></aside> </div> </section> <input id="saveBookmark-button" type="submit" value="Save Bookmark"> </form> `; // console.log("yes !"); e.preventDefault(); } // // // visitFuncOpen() // // function visitFuncOpen(e) { // Make div.hidden appears hiddenSection.style.display = "block"; // Create table hiddenSection.innerHTML = ` <form id="visit-form"> <div class="header"> <h3>Filter :</h3> <div id="group1"> <input id="filterBox" type="text" value="" placeholder="Ex: &quot;Google&quot;"> <aside></aside> </div> </div> <div class="body-table"> <table class="table"> <thead class="thead-light"> <tr> <th scope="col" style="padding-right: 10px;">#</th> <th scope="col">Bookmarks</th> </tr> </thead> <tbody> </tbody> </table> </div> </form> `; let bookmarksList; if (localStorage.getItem("bookmarksList") === null) { return bookmarksList = []; } else { bookmarksList = JSON.parse(localStorage.getItem("bookmarksList")) } let counter = 1; for (let index = 0; index < bookmarksList.length; index++) { const arrayUnsplit = bookmarksList[index].split(", "); const arraySplit = arrayUnsplit[0].split(": ")[1]; // Insert content to bookmarkElement const bookmarkElement = document.createElement("tr"); bookmarkElement.innerHTML = ` <th scope="row">${counter++}</th> <td>${arraySplit}<span><a href=${bookmarksList[index].split(", ")[1].split(": ")[1]} target="_blank" rel="noopener noreferrer">Visit</a></span></td> `; // Appending the bookmarkElement to the table const appending = document.querySelector("tbody"); appending.append(bookmarkElement); // Stringify it back to the array localStorage.setItem("bookmarksList", JSON.stringify(bookmarksList)); } const filterField = document.querySelector("#filterBox"); filterField.addEventListener("keyup", function(e) { let text = e.target.value.toLowerCase(); hiddenSection.querySelectorAll("tbody td").forEach(function (item) { let eq = item.innerHTML.split("<span>")[0]; if (eq.toLowerCase().includes(text)) { item.parentElement.style.display = ""; } else { item.parentElement.style.display = "none" } // console.log(item); }) }) } // // // saveToBookmarks() // // function saveToBookmarks(e) { let addFormName = document.querySelectorAll("div.mini-container input")[1]; let addFormUrl = document.querySelectorAll("div.mini-container input")[0]; // Store to local storage function function storeToLocalStorage(bookName, bookUrl) { let bookmarksList; if (localStorage.getItem("bookmarksList") === null) { bookmarksList = []; } else { bookmarksList = JSON.parse(localStorage.getItem("bookmarksList")); } // Add element to bookmarksList array bookmarksList.push(`name: ${bookName}, url: ${bookUrl}`); // Stringify it back to the array localStorage.setItem("bookmarksList", JSON.stringify(bookmarksList)); } // Load the function storeToLocalStorage(addFormName.value, addFormUrl.value); // // Loader on Timeout function // setTimeout(function() { // // Loading wheel // let loadingWheel = document.getElementsByClassName("loader")[0]; // loadingWheel.style.cssText = ` // position = relative; // display = block; // right = 100px; // top = 200px; // border-radius: 50%; // border-right: 4px solid yellow; // border-left: 4px solid yellow; // border-top: 4px solid #3498db; // border-bottom: 4px solid #3498db; // width: 20px; // height: 20px; // -webkit-animation: spin 2s linear infinite; /* Safari */ // animation: spin 2s linear infinite; // z-index: 500; // `; // }, 1500) hiddenSection.style.display = "none"; e.preventDefault(); } // // // saveFuncClose() // // function saveFuncClose(e) { hiddenSection.style.display = "none"; // console.log(); e.preventDefault(); }<file_sep>/README.md # OneClick This is the OneClick Chrome Add-on Build in javascript.
add66d1deee3a00337aafba1c54e8c76686cfa9a
[ "JavaScript", "Markdown" ]
2
JavaScript
GadW6/oneclick
e9aab391c99ca3abf58b06e529e9177f0782c663
6de3b898a97d765a349e9da87725ec7ebdf59dba
refs/heads/master
<file_sep>package index; import Struct.Chunk; import Struct.WordTree; import Struct.Term; import Struct.TermList; import java.util.ArrayList; public class SplitWord { //SplitWordArrayList is output Split Word ArrayList public TermList SplitWordArrayList; public ArrayList<Chunk> ChunkArrayList; private int QuerStringLength; //contructor just initialize that arraylist with empty arraylist and given dictionary public SplitWord() throws Exception { this.SplitWordArrayList = new TermList(); this.ChunkArrayList = new ArrayList<Chunk>(); } //initialize the split word public void initialize(String QuerString) { QuerStringLength = QuerString.length(); getChunk(new Chunk(QuerString, 0)); for (Chunk Chunk : ChunkArrayList) { //System.out.println("Chunk:" + Chunk.ChunkString + ":" + Chunk.StartIndex); if (getType(Chunk.ChunkString.charAt(0)) == 4) { getSplitChineseWord(Chunk); } else if (getType(Chunk.ChunkString.charAt(0)) == 1) { getSplitEnglishWord(Chunk); } else if (getType(Chunk.ChunkString.charAt(0)) == 2) { this.SplitWordArrayList.put(Chunk.ChunkString, new Term(Chunk.ChunkString, Chunk.StartIndex, QuerStringLength)); } } } //lexical analysis //split into different chunk public void getChunk(Chunk ChunkItem) { int CurrentType = getType(ChunkItem.ChunkString.charAt(0)); int StartIndex = 0, EndIndex = 0; for (int i = 1; i < ChunkItem.ChunkString.length(); i++) { EndIndex = i; int CurrentTypeLoop = getType(ChunkItem.ChunkString.charAt(i)); if (CurrentTypeLoop != CurrentType) { CurrentType = getType(ChunkItem.ChunkString.charAt(i)); if (ChunkItem.ChunkString.substring(StartIndex, EndIndex).trim().length() >= 2) { ChunkArrayList.add(new Chunk(ChunkItem.ChunkString.substring(StartIndex, EndIndex), StartIndex)); } StartIndex = i; } } ChunkArrayList.add(new Chunk(ChunkItem.ChunkString.substring(StartIndex), StartIndex)); } //generate the split word public void getSplitChineseWord(Chunk QueryChunk) { //generate from the end to the start for (int i = QueryChunk.ChunkString.length() - 1; i >= 0; i--) { String InternalWord = QueryChunk.ChunkString.substring(i); if (WordTree.IsContain(InternalWord, WordTree.NoiseCn) != null) { //if find then end and recusive new getSplitWord getSplitChineseWord(new Chunk(QueryChunk.ChunkString.substring(0, i), i)); return; } else if (WordTree.IsContain(InternalWord, WordTree.Dic) != null) { Term t = new Term(InternalWord, i + QueryChunk.StartIndex, QuerStringLength); SplitWordArrayList.put(InternalWord, t); //if find then end and recusive new getSplitWord getSplitChineseWord(new Chunk(QueryChunk.ChunkString.substring(0, i), i)); return; } } if (QueryChunk.ChunkString.length() == 0) { return; } //if there is no find, we just cut one character from the end and start new getSplitWord getSplitChineseWord(new Chunk(QueryChunk.ChunkString.substring(0, QueryChunk.ChunkString.length() - 1), QueryChunk.StartIndex - 1)); } public void getSplitEnglishWord(Chunk QueryChunk) { for (int i = QueryChunk.ChunkString.length() - 1; i >= 0; i--) { if (i < 1) { break; } if (QueryChunk.ChunkString.substring(i - 1, i).equals(" ")) { WordTree wt = null; if ((wt = WordTree.IsContain(QueryChunk.ChunkString.substring(i).toLowerCase(), WordTree.NoiseEn)) == null) { String KeyWord = Stemmer.getResult(QueryChunk.ChunkString.substring(i)); SplitWordArrayList.put(KeyWord, new Term(KeyWord, i, QuerStringLength)); } } } WordTree wt = null; if ((wt = WordTree.IsContain(QueryChunk.ChunkString.toLowerCase(), WordTree.NoiseEn)) == null) { String KeyWord = Stemmer.getResult(QueryChunk.ChunkString); SplitWordArrayList.put(KeyWord, new Term(KeyWord, QueryChunk.StartIndex, QuerStringLength)); } } //return 1 English word //return 1(2) Number //return 3 Sign //return 4 Other(Chinese) public int getType(char singleChar) { if ((singleChar >= 65 && singleChar <= 90) || (singleChar >= 97 && singleChar <= 122)) { return 1; } else if (singleChar >= 48 && singleChar <= 57) { return 1; } else if (singleChar <= 126) { return 3; } else { return 4; } } public ArrayList<Term> getUnSortedList() { return SplitWordArrayList.UnSort(); } public ArrayList<Term> getSortedList() { return SplitWordArrayList.Sort(); } //ShortCut for static method public static ArrayList<Term> Result(String src) throws Exception { SplitWord sw = new SplitWord(); sw.initialize(src); return sw.getUnSortedList(); } } <file_sep>package edu.pitt.sis.ImageEx; import java.util.ArrayList; public class Compare { private float pr = 1f; private double area = 0; public Compare() { } /** * input particle between 0-1 0 for use all squares 1 for use largest square * Ӣ�ıȽϲ�������õ���ȡ�����������ٷ�֮��������ϵľ��Σ�����1����ȡ�������0��ȫȡ��������п����ȣ�Ӧ�����ǰɣ�Ĭ��50% * * @param particle */ public Compare(float particle) { if (particle <= 1 && particle >= 0) this.pr = particle; } public double toCompare(ArrayList<Square> s1, ArrayList<Square> s2, int area) { this.area = area; double fainllyratio = 0; s1 = Sort(s1); // ����ȡǰ���� s2 = Sort(s2); ArrayList<Square> small = s1.size() < s2.size() ? s1 : s2; ArrayList<Square> large = s1.size() >= s2.size() ? s1 : s2; int tsize = 0; for (int i = 0; i < small.size(); i++) { tsize = tsize + small.get(i).getArea(); } for (int i = 0; i < small.size(); i++) { fainllyratio = fainllyratio + (ratioFrom(small.get(i), large) * small.get(i).getArea() / tsize); // ������Ȳ�ͬ����� // ���ƶ�ռ��Ȩ�ز�ͬ�� } return fainllyratio; } // �㵥�����εı��ʣ����ƶȰɣ����������Ӣ�ĺ���ƴ���ˡ� private double ratioFrom(Square s1, ArrayList<Square> large) { ArrayList<Square> temp = new ArrayList<Square>(); int xend = s1.x + s1.l; int yend = s1.y + s1.l; int xm = s1.getCenterX(); int ym = s1.getCenterX(); Square square = new Square(-1, -1); square.l = 999999999; for (Square s2 : large) { int x1 = s2.getCenterX(); int y1 = s2.getCenterX(); if (x1 <= xend && x1 >= s1.x && y1 <= yend && y1 >= s1.y) { // in the square temp.add(s2); } if ((getAbsolute(x1 - xm) + getAbsolute(y1 - ym)) < square.l) square = s2; } double l1 = 0, l2 = 0, sizeratio = 0, size1 = 0; if (temp.isEmpty()) { temp.add(square); } for (Square s : temp) { size1 = size1 + s.l * s.l; l1 = l1 + s.x + s.l / 2; l2 = l2 + s.y + s.l / 2; } double size2 = s1.l * s1.l; sizeratio = getAbsolute(size1 - size2) / ((size1 + size2) / 2); double l = (l1 / temp.size() - xm) * (l1 / temp.size() - xm) + (l2 / temp.size() - ym) * (l2 / temp.size() - ym); double ratio = Math.sqrt(l) / Math.sqrt(area); ratio = (ratio + sizeratio) / 2; return 1 - ratio; } private double getAbsolute(double i) { return i > 0 ? i : -i; } private ArrayList<Square> Sort(ArrayList<Square> squares) { ArrayList<Square> newsquares = new ArrayList<Square>(); if (squares.size() == 0) return newsquares; while (true) { Square temp = new Square(-1, -1); for (Square s : squares) { if (s.l > temp.l) { temp = s; } } newsquares.add(temp); if (temp.l <= newsquares.get(0).l * pr) break; squares.remove(temp); if (squares.isEmpty()) break; } return newsquares; } }<file_sep>package API; public class config { public static String DicPath="D:\\workspace\\netbeans\\Index\\src\\result.txt"; public static String NoiseCnPath="D:\\workspace\\netbeans\\Index\\src\\sNoiseCn.txt"; public static String NoiseEnPath="D:\\workspace\\netbeans\\Index\\src\\sNoiseEn.txt"; public static String IndexTermPath="D:\\workspace\\netbeans\\Index\\src\\IndexTerm.txt"; public static String IndexPostPath="D:\\workspace\\netbeans\\Index\\src\\IndexPost.txt"; } <file_sep>package DB; import Retrieval.StdRetrieval; import Struct.SpeakerVectorSpace; import Struct.Term; import index.SplitWord; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; public class ExtractData { String path; public ExtractData() { } //Get user interest data public static TreeMap<Integer, ArrayList<Term>> extractUser() { TreeMap<Integer, ArrayList<Term>> vsml = new TreeMap<Integer, ArrayList<Term>>(); try { DB db = new DB(); ResultSet rs = db.getResultSet("SELECT distinct user_id from userprofile"); while (rs.next()) { int user_id = rs.getInt("user_id"); //Bookmark DB db2 = new DB(); ResultSet rs2 = db2.getResultSet("select userprofile_id,usertags,comment from userprofile where user_id=" + user_id); String usertags = ""; String comment = ""; while (rs2.next()) { usertags += rs2.getString("usertags"); comment += rs2.getString("comment"); } db2.close(); //Note DB db3 = new DB(); ResultSet rs3 = db3.getResultSet("select usernote from usernote where user_id=" + user_id); String usernote = ""; while (rs3.next()) { usernote += rs3.getString("usernote"); } db3.close(); //tags DB db4 = new DB(); ResultSet rs4 = db4.getResultSet("select tag from tag where tag_id in (select tag_id from tags where user_id=" + user_id + ")"); String tag = ""; while (rs4.next()) { tag += rs4.getString("tag"); } db4.close(); //comment keyword DB db5 = new DB(); ResultSet rs5 = db5.getResultSet("select keyword,comment from keywordcomment where user_id=" + user_id); String keyword = ""; String commentk = ""; while (rs5.next()) { keyword += rs5.getString("keyword"); commentk += rs5.getString("comment"); } db5.close(); //outerlink DB db6 = new DB(); ResultSet rs6 = db6.getResultSet("select innertext from userouterlink where user_id=" + user_id); String innertext = ""; while (rs6.next()) { innertext += rs6.getString("innertext"); } db6.close(); //progress-base DB db7 = new DB(); ResultSet rs7 = db7.getResultSet("select detail,title from colloquium where col_id in (select col_id from rec_progressbase where user_id= " + user_id + " order by score ) limit 1,3"); String title = ""; String detail = ""; while (rs7.next()) { title += rs7.getString("title"); detail += rs7.getString("detail"); } db7.close(); //community DB db8 = new DB(); ResultSet rs8 = db8.getResultSet("select comm_name, comm_desc from community where comm_id in (select comm_id from contribute where user_id=" + user_id + " ) "); String comm_name = ""; String comm_desc = ""; while (rs8.next()) { comm_name += rs8.getString("comm_name"); comm_desc += rs8.getString("comm_desc"); } db8.close(); //series DB db9 = new DB(); ResultSet rs9 = db9.getResultSet("select name,description from series where user_id=" + user_id); String sname = ""; String sdesc = ""; while (rs9.next()) { sname += rs9.getString("name"); sdesc += rs9.getString("description"); } db9.close(); //extra comment DB db10 = new DB(); ResultSet rs10 = db10.getResultSet("select comment from comment where user_id= " + user_id); String commentx = ""; while (rs10.next()) { commentx += rs10.getString("comment"); } db10.close(); String Data = usertags + " " + comment + " " + usernote + " " + tag + " " + " " + keyword + " " + commentk + " " + title + " " + detail + " " + innertext + " " + comm_name + " " + comm_desc + " " + sname + " " + sdesc + " " + commentx; Data = StdRetrieval.getCleanData(Data); ArrayList<Term> vsm = SplitWord.Result(Data); vsml.put(user_id, vsm); } } catch (Exception ex) { Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex); } return vsml; } //Get user interest data public static TreeMap<Integer, ArrayList<Term>> extractUserBaseOnUserGroup(int rank) { TreeMap<Integer, ArrayList<Term>> vsml = new TreeMap<Integer, ArrayList<Term>>(); try { DB db = new DB(); ResultSet rs = db.getResultSet("SELECT distinct user_id from userprofile"); while (rs.next()) { int user_id = rs.getInt("user_id"); String Data = getDataByUser(user_id); //Collaborative filter DB db0 = new DB(); ResultSet rs0 = db0.getResultSet("SELECT user_idr from usergroup where user_idl=" + user_id + " order by score limit 1," + rank); while (rs0.next()) { Data += getDataByUser(rs0.getInt("user_idr")); } //Collaborative filter Data = StdRetrieval.getCleanData(Data); ArrayList<Term> vsm = SplitWord.Result(Data); if (vsm != null && vsm.size() > 0) { vsml.put(user_id, vsm); System.out.println(user_id); } } } catch (Exception ex) { Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex); } return vsml; } //Get colloquium data public static TreeMap<Integer, ArrayList<Term>> extractColloquium() { TreeMap<Integer, ArrayList<Term>> vsml = new TreeMap<Integer, ArrayList<Term>>(); try { DB db = new DB(); ResultSet rs = db.getResultSet("SELECT distinct col_id from colloquium"); while (rs.next()) { int col_id = rs.getInt("col_id"); //detail title DB db2 = new DB(); ResultSet rs2 = db2.getResultSet("select title,detail from colloquium where col_id=" + col_id); String title = ""; String detail = ""; while (rs2.next()) { title += rs2.getString("title"); detail += rs2.getString("detail"); } db2.close(); //term DB db3 = new DB(); ResultSet rs3 = db3.getResultSet("select term from colterm where col_id=" + col_id); String term = ""; while (rs3.next()) { term += rs3.getString("term"); } db3.close(); //comment DB db4 = new DB(); ResultSet rs4 = db4.getResultSet("select comment from comment where comment_id in (select comment_id from comment_col where col_id=" + col_id + ")"); String comment = ""; while (rs4.next()) { comment += rs4.getString("comment"); } db4.close(); //entity /* * DB db5 = new DB(); ResultSet rs5 = db5.getResultSet("select * entity from entity where entity_id in (select entity_id from * entities where col_id=" + col_id + " ) "); String entity = * ""; while (rs5.next()) { entity += rs5.getString("entity"); } db5.close(); */ //community DB db6 = new DB(); ResultSet rs6 = db6.getResultSet("select comm_name, comm_desc from community where comm_id in (select comm_id from contribute where col_id=" + col_id + " ) "); String comm_name = ""; String comm_desc = ""; while (rs6.next()) { comm_name += rs6.getString("comm_name"); comm_desc += rs6.getString("comm_desc"); } db6.close(); //series DB db7 = new DB(); ResultSet rs7 = db7.getResultSet("select name,description from series where series_id in (select series_id from seriescol where col_id= " + col_id + " ) "); String sname = ""; String sdesc = ""; while (rs7.next()) { sname += rs7.getString("name"); sdesc += rs7.getString("description"); } db7.close(); //affilicate DB db8 = new DB(); ResultSet rs8 = db8.getResultSet("select affiliate from affiliate where affiliate_id in (select affiliate_id from affiliate_col where col_id= " + col_id + " ) "); String affilicate = ""; while (rs8.next()) { affilicate += rs8.getString("affiliate"); } db8.close(); //host DB db9 = new DB(); ResultSet rs9 = db9.getResultSet("select host from host where host_id in (select host_id from colloquium where col_id= " + col_id + " ) "); String host = ""; while (rs9.next()) { host += rs9.getString("host"); } db9.close(); String Data = title + " " + comment + " " + detail + " " + term + " " + " " + comment + " " + comm_name + " " + comm_desc + " " + detail + " " + /* * entity + " " + */ sname + " " + sdesc + " " + affilicate + " " + host; Data = StdRetrieval.getCleanData(Data); ArrayList<Term> vsm = SplitWord.Result(Data); vsml.put(col_id, vsm); } } catch (Exception ex) { Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex); } return vsml; } //Get colloquium data public static TreeMap<Integer, ArrayList<Term>> extractColloquiumBaseOnSpeaker() { TreeMap<Integer, ArrayList<Term>> vsml = new TreeMap<Integer, ArrayList<Term>>(); try { DB db0 = new DB(); ResultSet rs0 = db0.getResultSet("select distinct speaker_id from col_speaker"); int speaker_id = 0; while (rs0.next()) { speaker_id = rs0.getInt("speaker_id"); String Data = ""; DB db = new DB(); ResultSet rs = db.getResultSet("SELECT distinct col_id from colloquium where speaker_id=" + speaker_id); while (rs.next()) { int col_id = rs.getInt("col_id"); //detail title DB db2 = new DB(); ResultSet rs2 = db2.getResultSet("select title,detail from colloquium where col_id=" + col_id); String title = ""; String detail = ""; while (rs2.next()) { title += rs2.getString("title"); detail += rs2.getString("detail"); } db2.close(); //term DB db3 = new DB(); ResultSet rs3 = db3.getResultSet("select term from colterm where col_id=" + col_id); String term = ""; while (rs3.next()) { term += rs3.getString("term"); } db3.close(); //comment DB db4 = new DB(); ResultSet rs4 = db4.getResultSet("select comment from comment where comment_id in (select comment_id from comment_col where col_id=" + col_id + ")"); String comment = ""; while (rs4.next()) { comment += rs4.getString("comment"); } db4.close(); //entity /* * DB db5 = new DB(); ResultSet rs5 = * db5.getResultSet("select entity from entity where * entity_id in (select entity_id from entities where * col_id=" + col_id + " ) "); String entity = ""; while * (rs5.next()) { entity += rs5.getString("entity"); } * db5.close(); */ //community DB db6 = new DB(); ResultSet rs6 = db6.getResultSet("select comm_name, comm_desc from community where comm_id in (select comm_id from contribute where col_id=" + col_id + " ) "); String comm_name = ""; String comm_desc = ""; while (rs6.next()) { comm_name += rs6.getString("comm_name"); comm_desc += rs6.getString("comm_desc"); } db6.close(); //series DB db7 = new DB(); ResultSet rs7 = db7.getResultSet("select name,description from series where series_id in (select series_id from seriescol where col_id= " + col_id + " ) "); String sname = ""; String sdesc = ""; while (rs7.next()) { sname += rs7.getString("name"); sdesc += rs7.getString("description"); } db7.close(); //affilicate DB db8 = new DB(); ResultSet rs8 = db8.getResultSet("select affiliate from affiliate where affiliate_id in (select affiliate_id from affiliate_col where col_id= " + col_id + " ) "); String affilicate = ""; while (rs8.next()) { affilicate += rs8.getString("affiliate"); } db8.close(); //host DB db9 = new DB(); ResultSet rs9 = db9.getResultSet("select host from host where host_id in (select host_id from colloquium where col_id= " + col_id + " ) "); String host = ""; while (rs9.next()) { host += rs9.getString("host"); } db9.close(); Data += title + " " + comment + " " + detail + " " + term + " " + " " + comment + " " + comm_name + " " + comm_desc + " " + detail + " " + /* * entity + */ " " + sname + " " + sdesc + " " + affilicate + " " + host; } Data = StdRetrieval.getCleanData(Data); if (Data.length() > 1) { ArrayList<Term> vsm = SplitWord.Result(Data); if (vsm != null && vsm.size() > 0) { vsml.put(speaker_id, vsm); System.out.println(speaker_id); } } } } catch (Exception ex) { Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex); } return vsml; } //Prgressbase caculation public static void CaculateProgressScore() { DB db = new DB(); ResultSet rs = db.getResultSet("select * from rec_progressbase"); try { while (rs.next()) { int pdg_id = rs.getInt("pdg_id"); float timespan = rs.getFloat("timespan"); float clicknum = rs.getFloat("clicknum"); float movenum = rs.getFloat("movenum"); float score = (float) (Math.log(timespan) / Math.log(1000000000)); score *= (float) (Math.log(clicknum + 500) / Math.log(500)); score *= (float) (Math.log(movenum) / Math.log(10000)); if (Float.isNaN(score) || Float.isInfinite(score)) { score = 0; } DB dbi = new DB(); dbi.executeUpdate("update rec_progressbase set score=" + score + " where pdg_id=" + pdg_id); dbi.close(); } } catch (SQLException ex) { Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex); } db.close(); } public static String getDataByUser(int user_id) throws SQLException { //Bookmark DB db2 = new DB(); ResultSet rs2 = db2.getResultSet("select userprofile_id,usertags,comment from userprofile where user_id=" + user_id); String usertags = ""; String comment = ""; while (rs2.next()) { usertags += rs2.getString("usertags"); comment += rs2.getString("comment"); } db2.close(); //Note DB db3 = new DB(); ResultSet rs3 = db3.getResultSet("select usernote from usernote where user_id=" + user_id); String usernote = ""; while (rs3.next()) { usernote += rs3.getString("usernote"); } db3.close(); //tags DB db4 = new DB(); ResultSet rs4 = db4.getResultSet("select tag from tag where tag_id in (select tag_id from tags where user_id=" + user_id + ")"); String tag = ""; while (rs4.next()) { tag += rs4.getString("tag"); } db4.close(); //comment keyword DB db5 = new DB(); ResultSet rs5 = db5.getResultSet("select keyword,comment from keywordcomment where user_id=" + user_id); String keyword = ""; String commentk = ""; while (rs5.next()) { keyword += rs5.getString("keyword"); commentk += rs5.getString("comment"); } db5.close(); //outerlink DB db6 = new DB(); ResultSet rs6 = db6.getResultSet("select innertext from userouterlink where user_id=" + user_id); String innertext = ""; while (rs6.next()) { innertext += rs6.getString("innertext"); } db6.close(); //progress-base DB db7 = new DB(); ResultSet rs7 = db7.getResultSet("select detail,title from colloquium where col_id in (select col_id from rec_progressbase where user_id= " + user_id + " order by score ) limit 1,3"); String title = ""; String detail = ""; while (rs7.next()) { title += rs7.getString("title"); detail += rs7.getString("detail"); } db7.close(); //community DB db8 = new DB(); ResultSet rs8 = db8.getResultSet("select comm_name, comm_desc from community where comm_id in (select comm_id from contribute where user_id=" + user_id + " ) "); String comm_name = ""; String comm_desc = ""; while (rs8.next()) { comm_name += rs8.getString("comm_name"); comm_desc += rs8.getString("comm_desc"); } db8.close(); //series DB db9 = new DB(); ResultSet rs9 = db9.getResultSet("select name,description from series where user_id=" + user_id); String sname = ""; String sdesc = ""; while (rs9.next()) { sname += rs9.getString("name"); sdesc += rs9.getString("description"); } db9.close(); //extra comment DB db10 = new DB(); ResultSet rs10 = db10.getResultSet("select comment from comment where user_id= " + user_id); String commentx = ""; while (rs10.next()) { commentx += rs10.getString("comment"); } db10.close(); String Data = usertags + " " + comment + " " + usernote + " " + tag + " " + " " + keyword + " " + commentk + " " + title + " " + detail + " " + innertext + " " + comm_name + " " + comm_desc + " " + sname + " " + sdesc + " " + commentx; return Data; } /* * public ExtractData(String path) { this.path = path; } * * public SpeakerVectorSpace writeSPeakerVS() throws Exception { * SpeakerVectorSpace vsml = new SpeakerVectorSpace(); try { DB db = new * DB(); ResultSet rs = db.getResultSet("select distinct speaker_id from * speaker"); while (rs.next()) { int speaker_id = rs.getInt("speaker_id"); * DB db2 = new DB(); ResultSet rs2 = db2.getResultSet("select detail,title * from colloquium where speaker_id in (" + speaker_id + ")"); while * (rs2.next()) { String title = rs2.getString("title"); String detail = * rs2.getString("detail"); //title and detail weight 2:1 ArrayList<Term> * vsm = SplitWord.Result(StdRetrieval.getCleanData(title + title + * detail)); vsml.put(speaker_id, vsm); } db2.close(); } db.close(); return * vsml; } catch (SQLException ex) { * Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, * ex); return null; } } * * public void extractName() { DB db = new DB(); try { String speaker_name = * ""; ResultSet rs = db.getResultSet("select * from col_speaker"); while * (rs.next()) { speaker_name = rs.getString("name").replace(" ", "_"); File * f = new File(path + speaker_name); if (!f.isDirectory()) { f.mkdir(); } * extractColloquium(speaker_name); } db.close(); } catch (SQLException ex) * { Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, * ex); } } * * public void extractColloquium(String speaker_id) { DB db = new DB(); * speaker_id = speaker_id.replace("_", " "); try { String sql = ""; * ResultSet rs = db.getResultSet(sql); while (rs.next()) { int col_id = * rs.getInt("col_id"); String title = rs.getString("title"); String detail * = rs.getString("detail"); String CurrentPath = path + * speaker_id.replace(" ", "_") + "\\" + col_id + "-" + title + ".txt"; File * f = new File(CurrentPath); if (!f.isFile()) { if (f.createNewFile()) { * DataOutputStream dos = new DataOutputStream(new FileOutputStream(f)); * dos.writeUTF(title + "\r\n" + detail); dos.close(); * System.out.println("Finished:" + speaker_id); db.close(); } } } } catch * (SQLException ex) { * Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, * ex); } catch (IOException ee) { } } */ public static void main(String[] args) throws Exception { } } <file_sep>main.class=API.cs run.jvmargs=-Xms512m -Xmx512m <file_sep>package Struct; public class Chunk { public String ChunkString; public int StartIndex; public Chunk(String ChunkString, int StartIndex) { this.ChunkString = ChunkString; this.StartIndex = StartIndex; } } <file_sep>package API; import DB.DB; import DB.ExtractData; import Sim.SimScore; import Struct.Term; import Struct.WordTree; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; public class Rec_Speaker { public static void main(String[] args) throws Exception { WordTree.intitializeWordTree(); TreeMap<Integer, ArrayList<Term>> speaker_vsm = ExtractData.extractColloquiumBaseOnSpeaker(); TreeMap<Integer, ArrayList<Term>> user_vsm = ExtractData.extractUserBaseOnUserGroup(3); for (Map.Entry<Integer, ArrayList<Term>> itemuser : user_vsm.entrySet()) { for (Map.Entry<Integer, ArrayList<Term>> itemspeaker : speaker_vsm.entrySet()) { int user_id = itemuser.getKey(); int speaker_id = itemspeaker.getKey(); ArrayList<Term> user_vsml = itemuser.getValue(); ArrayList<Term> speaker_vsml = itemspeaker.getValue(); if (user_vsml.size() > 0 && speaker_vsml.size() > 0) { double score = new SimScore(user_vsml, speaker_vsml).getVSMScore(); DB db = new DB(); if (Double.isNaN(score) || Double.isInfinite(score)||score==0) { } else { db.executeInsert("insert into rec_speaker(speaker_id,user_id,score) values(" + speaker_id + "," + user_id + "," + score + ")"); System.out.println(score); System.out.println(score); } db.close(); } } } } } <file_sep>package edu.pitt.sis.ImageEx; import java.util.ArrayList; public class Distribution { private boolean isBlackSquare = true; private int picW; private int picH; public Distribution(){ } public Distribution(boolean isBlackSquare){ this.isBlackSquare = isBlackSquare; } public ArrayList<Square> toDistribution(int binary[][]){ picW = binary.length; picH = binary[0].length; //get picture's height width if(!isBlackSquare){ anti(binary); } return getSquareArray(binary); } public int[] getWH(){ int[] xy = new int[2]; xy[0] = picW; xy[1] = picH; return xy; } private ArrayList<Square> getSquareArray(int binary[][]){ ArrayList<Square> squareList = new ArrayList<Square>(); boolean goon = true; int x=0,y=0; int tags = (picW>picH?picW:picH)/100; while(goon) { //Calculate next x,y for(int j= y; j<picH;j++) { for(int i = 0;i <picW;i++) { if(binary[i][j] == 1) { x = i; y = j; i = picW; j = picH; } } } if(binary[x][y] != 1 || (x ==picW-1)&&(y ==picH-1)){ break; } Square square = getSquare(binary,x,y); if(square.l>tags) squareList.add(square); if(x+square.l>=picW&&y+square.l>=picH) goon = false; } return squareList; } private Square getSquare(int binary[][],int x,int y) { Square square = new Square(x,y); int length = 0; int black=0,write=0,writeSum=0; boolean goon = true; while(goon) { black = getSidePoint(binary,x,y,length); write = 2*length -1 -black; writeSum = writeSum +write; length ++; //quit Standard if(x+length >=picW || y+length>=picH || writeSum>=black){ goon = false; } } square.l = length; return square; } /** * get black point in square side ��þ��ε�2���ߵĺڵ���������2����ÿ�ε���x��y ����+1�� * @param binary * @param start_X * @param start_Y * @param length * @return */ private int getSidePoint(int binary[][],int start_X,int start_Y,int length){ /*if(length==0) { //for test! System.out.println("Distribution-->getSidePoint-->legth ==0"); System.exit(0); }*/ int diffPoint = 0; int x ,y; if(binary[start_X+length][start_Y+length]==1) diffPoint--; for(int i=0;i<=length;i++){ x = binary[start_X+i][start_Y+length]; y = binary[start_X+length][start_Y+i]; if(x==1) diffPoint++; if(y==1) diffPoint++; binary[start_X+i][start_Y+length] = -1; binary[start_X+length][start_Y+i] = -1; // Mark Read } return diffPoint; } private void anti(int binary[][]) { for (int x = 0; x < picW; x++) { for (int y = 0; y < picH; y++) { if(binary[x][y] == 1 ){ binary[x][y] = 0 ; /// 0 for White }else{ binary[x][y] = 1 ; /// 1 for black } } } } } <file_sep>package Struct; public class GoogleResultItem { public String title; public String link; public String snippet; public GoogleResultItem(String title, String link, String snippet) { this.title = title; this.link = link; this.snippet = snippet; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.pitt.sis.ImageEx; /** * * @author Administrator */ public class ImageItem { public String URL; public double score; public ImageItem(String uRL, double score) { super(); URL = uRL; this.score = score; } } <file_sep>application.args=-Xms512m -Xmx512m <file_sep>package API; import DB.DB; import Retrieval.StdRetrieval; import Sim.SimScore; import Struct.Term; import Struct.TermList; import Struct.WordTree; import com.mysql.jdbc.ResultSet; import edu.pitt.sis.ImageEx.ImageItem; import edu.pitt.sis.ImageEx.ImageRank; import index.SplitWord; import java.net.URL; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; public class test { public static void main(String[] args) throws Exception { ArrayList<String> list = new ArrayList<String>(); DB db = new DB(); ResultSet rs = (ResultSet) db.getResultSet("select * from speaker where picurl is not null and picurl <> 'http://halley.exp.sis.pitt.edu/comet/images/speaker/avartar.gif'"); while (rs.next()) { String url = rs.getString("picurl"); list.add(url); } URL u = new URL("http://t2.gstatic.com/images?q=tbn:ANd9GcTSjh7L8bI6Qhqczdyy8G3lFRenJGfbk7tymrqDoAlpldChw_p7CKggeOo"); ImageRank ir = new ImageRank(u.openStream(), list); ArrayList<ImageItem> result = ir.getRankedPicUrl(); for (ImageItem it : result) { System.out.println("<img src='"+it.URL + "' /> " + it.score); } } } <file_sep>package API; import DB.DB; import DB.ExtractData; import Sim.SimScore; import Struct.SpeakerVectorSpace; import Struct.Term; import Struct.WordTree; import index.SplitWord; import java.io.*; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; public class Run { public static void main(String[] args) throws Exception { WordTree.intitializeWordTree(); ArrayList<Term> TestData = SplitWord.Result("Machine Learning computer information"); // DB db = new DB(); // db.getResultSet("select * from speaker"); // ArrayList<Term> r1 = SplitWord.Result("Zhao San qiang"); // ArrayList<Term> r2 = SplitWord.Result("Zhao San qiang is pig"); // SimScore ss = new SimScore(r1, r2); // System.out.println(ss.getVSMScore()); // SpeakerVectorSpace svsm = new ExtractData().writeSPeakerVS(); // ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\workspace\\train\\speakervsm.txt")); // oos.writeObject(svsm); // ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\workspace\\train\\speakervsm.txt")); // SpeakerVectorSpace svsm2 = (SpeakerVectorSpace) ois.readObject(); // for (Map.Entry<Integer,ArrayList<Term>> speaker : svsm2.entrySet()) { // ArrayList<Term> TrainData = speaker.getValue(); // System.out.println(new SimScore(TestData, TrainData).getVSMScore()); // } //User Recommend // TreeMap<Integer, ArrayList<Term>> user_vsml = (TreeMap<Integer, ArrayList<Term>>) new ExtractData().extractUser().clone(); // TreeMap<Integer, ArrayList<Term>> user_vsmr = (TreeMap<Integer, ArrayList<Term>>) new ExtractData().extractUser().clone(); // // for (Map.Entry<Integer, ArrayList<Term>> iteml : user_vsml.entrySet()) { // int userl = iteml.getKey(); // ArrayList<Term> userlvsm = iteml.getValue(); // for (Map.Entry<Integer, ArrayList<Term>> itemr : user_vsmr.entrySet()) { // int userr = itemr.getKey(); // ArrayList<Term> userrvsm = itemr.getValue(); // if (userl != userr) { // double score = new SimScore(userlvsm, userrvsm).getVSMScore(); // DB db = new DB(); // if (Double.isNaN(score) || Double.isInfinite(score)/*||score==0*/) { // } else { // db.executeInsert("insert into UserGroup values(" + userl + "," + userr + "," + score + ")"); // } // db.close(); // } // } // } } } <file_sep>package edu.pitt.sis.ImageEx; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; public class API { public static void main(String[] args) throws Exception { Binarization b = new Binarization(); FileInputStream is = new FileInputStream(new File("D:/Web/Image/group_collapse.gif")); int a[][] = b.toBinarization(is); Distribution d = new Distribution(); ArrayList<Square> s = d.toDistribution(a); System.out.println(s.size()); FileInputStream is2 = new FileInputStream(new File("D:/Web/Image/group_expand.gif")); int a2[][] = b.toBinarization(is2); d = new Distribution(); ArrayList<Square> s2 = d.toDistribution(a2); System.out.println(s.size()); Compare c= new Compare(); double m1 = c.toCompare(s, s2, b.getArea()); double m2 = c.toCompare(s2,s, b.getArea()); System.out.println("'''''" +m1 + "," +m2 +"," ); } } <file_sep>package Struct; public class PostingIndex { public String Term; public String DocumentId; public int Frequency; public int StartIndex; public int DocumentLength; public PostingIndex(String Term, String DocumentId, int Frequency, int StartIndex, int DocumentLength) { this.Term = Term; this.DocumentId = DocumentId; this.Frequency = Frequency; this.StartIndex = StartIndex; this.DocumentLength = DocumentLength; } public PostingIndex() { } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package index; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; /** * * @author Administrator */ public class Tool { public static String getlocalText(String path) throws FileNotFoundException, IOException { File f=new File(path); BufferedReader br=new BufferedReader(new FileReader(f)); StringBuilder sb=new StringBuilder(); String line; while ((line=br.readLine())!=null) { sb.append(line).append(" "); } br.close(); return sb.toString(); } public static String getUrlText(String path, boolean Html, String encode) throws FileNotFoundException, IOException { URL u=new URL(path); InputStreamReader isr=new InputStreamReader(u.openStream(),encode); BufferedReader br=new BufferedReader(isr); StringBuilder sb=new StringBuilder(); String line; while ((line=br.readLine())!=null) { sb.append(line).append(" "); } br.close();isr.close(); if (Html) { return sb.toString(); }else { return sb.toString().replaceAll("</?[^>]+>"," ").replace("&nbsp;",""); } } } <file_sep>package Struct; public class QueryResult { public String DocumentId; public double Score; public String Word; public int Frequency; public int DocumentLength; public QueryResult(String DocumentId, String Word, int Frequency, int DocumentLength) { this.DocumentId = DocumentId; this.Word = Word; this.Frequency = Frequency; this.Score = 0; this.DocumentLength = DocumentLength; } }
b97f5ebde361943d02e90fb424df042ddc87cc79
[ "Java", "INI" ]
17
Java
Sanqiang/CoMeT
2eb3714e9c5f60e6245f3f56454b95c8f68dd296
1d0e35b8e409f3beaef9b9b2c2e66c228832aee6
refs/heads/master
<repo_name>zab0707/portfolio<file_sep>/src/components/Main/Home.js import React from 'react'; import SkillDetails from './Home/SkillDetails'; const Home = () => { const skill = { web: {icon: 'ion-code-working', title: 'Web Developer', desc: 'Web Developer with 4+ years of hands-on experience in designing and developing user interfaces, testing, debugging. Proven ability in optimizing web functionality that improve data retrieval and workflow efficiencies.'}, data: {icon: 'ion-stats-bars', title: 'Data Analyst', desc: 'Data Analyst with 1+ years of hands-on experience interpreting and analyzing data in order to drive successful business solutions. Proficient knowledge in statistics, mathematics, and analytics. Excellent understanding of business operations and analytics tools for effective analysis of data.'}, full: {icon: 'ion-navicon-round', title: 'Full Stack Developer', desc: 'Full Stack Developer with 2+ years of hands-on experience in designing, developing and implementing both front-end and back-end applications and solutions using range of technologies and programming languages.'}, }; return( <div> <section className="portfolio-block block-intro"> <div className="container"> <div className="avatar" style={{backgroundImage: 'url(/assets/img/avatars/zabp.jpg)'}}></div> <div className="about-me"> <p>Hello! I am <strong><NAME></strong>. A motivated individual with in-depth knowledge of programming languages and development tools, seeking a position in a growth-oriented company where I can use my skills to the advantage of the company while having the scope to develop my own skills.</p></div> </div> </section> <section className="portfolio-block skills"> <div className="container"> <div className="heading"> <h2>Special Skills</h2> </div> <div className="row"> <div className="col-md-4"> <SkillDetails item={skill['web']} /> </div> <div className="col-md-4"> <SkillDetails item={skill['data']} /> </div> <div className="col-md-4"> <SkillDetails item={skill['full']} /> </div> </div> </div> </section> </div>); } export default Home;<file_sep>/src/components/Main/Resume.js import React from 'react'; import Education from './Resume//Education'; import Skills from './Resume/Skills'; import Certificates from './Resume/Certificates'; const Resume = () => { return( <main className="page cv-page"> <section className="portfolio-block block-intro"> <div className="container"> <div className="row"> <div className="col-md-4"> <div className="avatar" style={{backgroundImage: 'url(/assets/img/avatars/zabp.jpg)'}}></div> </div> <div className="col-md-8"> <div className="about-me text-left"> <h1><strong><NAME></strong></h1> <h5><i className="icon ion-at icon"></i> <EMAIL></h5> <h5><i className="icon ion-ios-telephone icon"></i>+91 8861129859</h5> <p>A motivated individual with in-depth knowledge of programming languages and development tools, seeking a position in a growth-oriented company where I can use my skills to the advantage of the company while having the scope to develop my own skills.</p> </div> </div> </div> </div> </section> <section className="portfolio-block cv"> <div className="container"> {/* <div className="work-experience group"> <div className="heading"> <h2 className="text-center">Work Experience</h2> </div> <div className="item"> <div className="row"> <div className="col-md-6"> <h3>Web Developer</h3> <h4 className="organization">Amazing Co.</h4> </div> <div className="col-md-6"><span className="period">10/2013 - 04/2015</span></div> </div> <p className="text-muted">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eget velit ultricies, feugiat est sed, efficitur nunc, vivamus vel accumsan dui.</p> </div> </div> */} <div className="education group"> <div className="heading"> <h2 className="text-center">Education</h2> </div> <Education /> </div> <div className="group"> <div className="heading"> <h2 className="text-center">Skills</h2> </div> <Skills /> </div> <div className="achievements group"> <div className="heading"> <h2 className="text-center">Achievements</h2> </div> <ul> <li>Secured 1st place in Java programming at Java hackathon in 2020, Organized by PES University.</li> <li>Member of INIT Club at PES University.</li> <li>Awarded Distinction Scholarship for academic performance in December 2019.</li> <li>Attended TECHBHARAT a national conclave of startups on January 17, 18 2020 at Bangalore.</li> <li>Awarded M.R.D Scholarship for academic performance in June 2020.</li> <li>Awarded Distinction Scholarship for academic performance in December 2020.</li> </ul> </div> <div className="personal group"> <div className="heading"> <h2 className="text-center">Personal Profile</h2> </div> <div className="contact-info portfolio-info-card"> <div className="row"> <div className="col-md-6"> <div className="row"> <div className="col-1"><i className="icon ion-android-calendar icon"></i></div> <div className="col-9"><span>07 July 1997</span></div> </div> <div className="row"> <div className="col-1"><i className="icon ion-earth icon"></i></div> <div className="col-9"><span>Indian</span></div> </div> <div className="row"> <div className="col-1"><i className="icon ion-person icon"></i></div> <div className="col-9"><span>Male</span></div> </div> <div className="row"> <div className="col-1"><i className="icon ion-ios-bookmarks icon"></i></div> <div className="col-9"><span>English, Hindi, Urdu</span></div> </div> </div> <div className="col-md-6"> <div className="row"> <div className="col-1"><i className="icon ion-social-github icon"></i></div> <div className="col-9"><span>https://github.com/zab0707</span></div> </div> <div className="row"> <div className="col-1"><i className="icon ion-social-linkedin"></i></div> <div className="col-9"><span>https://www.linkedin.com/in/zain-ali-baig-8a6557195/</span></div> </div> <div className="row"> <div className="col-1"><i className="icon ion-fork-repo icon"></i></div> <div className="col-9"><span>https://www.hackerrank.com/zainbaig8</span></div> </div> <div className="row"> <div className="col-1"><i className="icon ion-code-working icon"></i></div> <div className="col-9"><span>https://www.hackerearth.com/@zainali</span></div> </div> </div> </div> </div> </div> <div className="certificates group"> <div className="heading"> <h2 className="text-center">Certificates & Badges</h2> </div> <Certificates /> </div> </div> </section> </main>); } export default Resume;<file_sep>/src/components/Main/Projects.js import React from 'react'; import Carousel from './Project/Carousel'; import CarouselDetails from './Project/CarouselDetails'; const Projects = () => { const importAll = (r) => { return r.keys().map(r); } const aiImg = importAll(require.context('../../../public/assets/img/projects/ai', false, /\.(png|jpe?g|svg)$/)); const rsImg = importAll(require.context('../../../public/assets/img/projects/rs', false, /\.(png|jpe?g|svg)$/)); const csVid = importAll(require.context('../../../public/assets/img/projects/cs', false, /\.(mp4|mkv)$/)); const cData = { Informatics: {title: 'Informatics', name: 'AI-Based Attendance Monitoring', desc: 'A Web application to manage and update the attendance of students based on the group image captures during a particular className. This application permits the student to raise complaints regarding their attendance, apply for special leave of absence with a document of proof and this application permits the student to view their attendance percentage and how they can improve.', tech: 'Django, SQLite, face-recognition, HTML, CSS, Bootstrap, JavaScript, jQuery, Ajax'}, Housing: {title: 'Housing', name: 'Real Estate Management', desc: 'A Web application to manage a society and houses, their specifications, purchase, sales details, services and reports and to maintain the information of buyer and seller. In this website a user can view different houses available in different locations and can contact to the owner of the house.', tech: 'Microsoft Sql Server 2017, Visual Studio 2017, C#, HTML, CSS, Bootstrap, JavaScript, jQuery, Ajax'}, Cars: {title: 'Cars', name: 'Car Showroom Management', desc: 'A standalone application to manage the details of cars, their specifications, purchase, sales details, generate bills and reports and keep track of cars and to maintain the information of employee and customer.', tech: 'Oracle 11g, Visual Basic 6.0'} }; return(<main className="page projects-page"> <section className="portfolio-block projects-cards"> <div className="container"> <div className="heading"> <h2>Recent Work</h2> </div> <div className="row"> <div className="col-md-8 col-lg-8"> <div className="card border-0"> <div className="card-body"> <Carousel id='carouselAI' item={aiImg}/> </div> </div> </div> <div className="col-md-4 col-lg-4"> <CarouselDetails item={cData['Informatics']} /> </div> </div> <div className="row"> <div className="col-md-8 col-lg-8"> <div className="card border-0"> <div className="card-body"> <Carousel id='carouselRS' item={rsImg}/> </div> </div> </div> <div className="col-md-4 col-lg-4"> <CarouselDetails item={cData['Housing']} /> </div> </div> <div className="row"> <div className="col-md-8 col-lg-8"> <div className="card border-0"> <div className="card-body"> <div className="embed-responsive embed-responsive-16by9"> <iframe title="car" className="embed-responsive-item" src={csVid[0]['default']} allowFullScreen></iframe> </div> </div> </div> </div> <div className="col-md-4 col-lg-4"> <CarouselDetails item={cData['Cars']} /> </div> </div> </div> </section> </main>); } export default Projects;<file_sep>/src/components/Main/Resume/Skills.js import React from 'react'; import SkillItem from './SkillItem'; const Skills = () => { const skill1 = [ {skill: 'C Programming', status: 'Intermediate', percent: '80%'}, {skill: 'Java 11', status: 'Intermediate', percent: '70%'}, {skill: 'Python 3', status: 'Advance', percent: '90%'}, {skill: 'SQL', status: 'Intermediate', percent: '80%'}, {skill: 'NoSQL', status: 'Intermediate', percent: '70%'}, {skill: 'HTML 5', status: 'Advance', percent: '100%'}, {skill: 'CSS 3', status: 'Advance', percent: '100%'}, ]; const skill2 = [ {skill: 'Bootstrap 4', status: 'Intermediate', percent: '90%'}, {skill: 'JavaScript ES6', status: 'Intermediate', percent: '90%'}, {skill: 'Django 3', status: 'Advance', percent: '90%'}, {skill: 'PHP 7.4', status: 'Intermediate', percent: '60%'}, {skill: 'Node.js 14', status: 'Intermediate', percent: '70%'}, {skill: 'React 17', status: 'Intermediate', percent: '70%'}, {skill: 'Angular 10', status: 'Beginner', percent: '40%'}, ]; return ( <div className="row"> <div className="col-md-6"> <div className="skills portfolio-info-card"> {skill1.map((s)=>{ return <SkillItem item={s} key={s.skill} />; })} </div> </div> <div className="col-md-6"> <div className="skills portfolio-info-card"> {skill2.map((s)=>{ return <SkillItem item={s} key={s.skill} />; })} </div> </div> </div> ); }; export default Skills;<file_sep>/src/components/Main/Resume/EduItem.js import React from 'react'; const EduItem = ({item}) => { return( <div className="item"> <div className="row"> <div className="col-md-8"> <h3>{item.course}</h3> <h4 className="organization">{item.college}</h4> </div> <div className="col-4"><span className="period">{item.duration}</span></div> </div> <p className="font-weight-bold">{item.result}</p> </div> ); } export default EduItem;<file_sep>/src/components/Main/Project/Carousel.js import React from 'react'; import CarouselItem from './CarouselItem'; const Carousel = ({id, item}) => { return( <div id={id} className="carousel slide" data-ride="carousel"> <div className="carousel-inner"> {item.map((img, i) => { return <CarouselItem path={img['default']} alt={i} key={i} />; }) } </div> <a className="carousel-control-prev" href={`#${id}`} role="button" data-slide="prev"> <span className="carousel-control-prev-icon" aria-hidden="true"></span> <span className="sr-only">Previous</span> </a> <a className="carousel-control-next" href={`#${id}`} role="button" data-slide="next"> <span className="carousel-control-next-icon" aria-hidden="true"></span> <span className="sr-only">Next</span> </a> </div> ); }; export default Carousel;<file_sep>/src/components/Main/Resume/Certificates.js import React from 'react'; import CerItem from './CerItem'; const Certificates = ({c1, c2}) => { const importAll = (r) => { return r.keys().map(r); } let item = importAll(require.context('../../../../public/assets/certificates/', false, /\.(png|jpe?g|svg)$/)); return( <div id='certificates' className="carousel slide" data-ride="carousel"> <div className="carousel-inner"> {item.map((img, i) => { return <CerItem path={img['default']} alt={i} key={i} />; }) } </div> <a className="carousel-control-prev" href='#certificates' role="button" data-slide="prev"> <span className="carousel-control-prev-icon" aria-hidden="true"></span> <span className="sr-only">Previous</span> </a> <a className="carousel-control-next" href='#certificates' role="button" data-slide="next"> <span className="carousel-control-next-icon" aria-hidden="true"></span> <span className="sr-only">Next</span> </a> </div> ); }; export default Certificates;<file_sep>/src/components/Navigation/MainHeader.js import React from 'react'; const MainHeader = (props) => { return(<nav className="navbar navbar-dark navbar-expand-lg fixed-top bg-white portfolio-navbar gradient">{props.children}</nav>); } export default MainHeader; <file_sep>/src/components/Footer/Footer.js import React from 'react'; import { Link } from 'react-router-dom'; const Footer = () => { return( <footer className="page-footer"> <div className="container"> <div className="links"> <Link to='/'>About me</Link> <Link to='/resume'>Resume</Link> <Link to='/projects'>Projects</Link> </div> <div className="social-icons"> <a rel="noreferrer" href='https://www.facebook.com/zain.baig.0707' target='_blank'><i className="icon ion-social-facebook"></i></a> <a rel="noreferrer" href='https://www.instagram.com/md_zab/' target='_blank'><i className="icon ion-social-instagram-outline"></i></a> <a rel="noreferrer" href='https://twitter.com/ZainBaig07' target='_blank'><i className="icon ion-social-twitter"></i></a></div> </div> </footer> ); } export default Footer; <file_sep>/src/components/Main/Resume/Education.js import React from 'react'; import EduItem from './EduItem'; const Education = () => { const edu = [ {course: 'Master of Computer Applications - MCA', college: 'PES University', duration: 'SEP 2019 - JUL 2022', result: 'CGPA 8.48'}, {course: 'Bachelor of Computer Applications - BCA', college: 'Bangalore University', duration: 'AUG 2016 - JUN 2019', result: 'CGPA 7.2'}, {course: 'Twelfth Grade - PUC', college: 'Department of Pre-University Education Board - Karnataka', duration: 'JUN 2015 - MAY 2016', result: 'Percentage 51.50'}, {course: 'Tenth Grade - SSLC', college: 'Karnataka Secondary Education Examination Board', duration: 'JUL 2012 - MAY 2013', result: 'Percentage 56.32'}, ]; return ( edu.map((e, i) => { return <EduItem item={e} key={i} />; }) ); }; export default Education; <file_sep>/src/components/Main/Resume/SkillItem.js import React from 'react'; const SkillItem = ({item}) => { return( <div> <h3>{item.skill}<span className="float-right">{item.status}</span></h3> <div className="progress"> <div className="progress-bar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style={{width: item.percent}}><span className="sr-only">{item.percent}</span></div> </div> <h6 className="float-right">{item.percent}</h6> </div> ); } export default SkillItem;<file_sep>/src/App.js import './App.css'; import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; import MainNavigation from './components/Navigation/MainNavigation'; import Home from './components/Main/Home'; import Projects from './components/Main/Projects'; import Resume from './components/Main/Resume'; import Footer from './components/Footer/Footer'; const App = ()=> { return ( <div className="App"> <Router> <MainNavigation /> <div style={{marginTop: '80px'}}> <Switch> <Route path='/' exact> <Home /> </Route> <Route path='/projects' exact> <Projects /> </Route> <Route path='/resume' exact> <Resume /> </Route> <Redirect to="/" exact/> </Switch> </div> <Footer /> </Router> </div> ); } export default App; <file_sep>/src/components/Main/Resume/CerItem.js import React from 'react'; const CerItem = (props) => { return ( <div className={(props.alt === 0) ? 'carousel-item active': 'carousel-item'}> <img className="d-block w-100 h-100" src={props.path} alt={`${props.alt} slide`} /> </div> ); }; export default CerItem;<file_sep>/src/components/Main/Home/SkillDetails.js import React from 'react'; const SkillDetails = ({item}) => { return( <div className="card special-skill-item border-0"> <div className="card-header bg-transparent border-0"><i className={`icon ${item.icon}`}></i></div> <div className="card-body"> <h3 className="card-title">{item.title}</h3> <p className="card-text">{item.desc}</p> </div> </div> ); }; export default SkillDetails;
6abd444d7c61eb49c230eefd85398df7b289a417
[ "JavaScript" ]
14
JavaScript
zab0707/portfolio
2251000fa7d5e1c11a6804e5836d15569d6271f0
23ff5283772097da55bb5d7fcb2dcbf0715a4cc9
refs/heads/master
<file_sep>require 'aquanaut' require 'spec_helper' describe Aquanaut::AssetNode do describe "#initialize" do it "stores the URI and type" do uri = URI.parse('http://www.example.com/picture.jpg') node = Aquanaut::AssetNode.new(uri, :image) expect(node.uri).to eq(uri) expect(node.type).to eq(:image) end end end <file_sep>require 'mechanize' require 'public_suffix' # The worker contains the actual crawling procedure. # class Aquanaut::Worker def initialize(target) uri = URI.parse(target) @queue = [uri] @domain = PublicSuffix.parse(uri.host) @visited = Hash.new(false) @agent = Mechanize.new do |agent| agent.open_timeout = 5 agent.read_timeout = 5 end end # Triggers the crawling process. # def explore while not @queue.empty? uri = @queue.shift # dequeue next if @visited[uri] @visited[uri] = true puts "Visit #{uri}" links, assets = links(uri) links.each do |link| @queue.push(link) unless @visited[link] # enqueue end yield uri, links, assets if block_given? end end # Retrieves all links to pages and static assets from a given page. The # decision whether a link points to an internal or external domain cannot be # done by just exmaining the link's URL. Due to possible HTTP 3xx responses # the link needs to be resolved. Hence, each link is processed through a HTTP # HEAD request to retrieve the final location. # # @param uri [URI] the URI from which the page is retrieved. # # @return [Array<URI>, Array<Hash>] list of links and static assets found on # the given page. # def links(uri) page = @agent.get(uri) grabbed = Hash.new(false) return [] unless page.is_a?(Mechanize::Page) assets = page.images.map do |image| uri = URI.join(page.uri, image.url) { 'uri' => uri, 'type' => 'image' } end page.parser.css('link[rel="stylesheet"]').each do |stylesheet| uri = URI.join(page.uri, stylesheet['href']) asset = { 'uri' => uri, 'type' => 'styleshet' } assets << asset end links = page.links.map do |link| begin next if link.uri.nil? reference = URI.join(page.uri, link.uri) next if grabbed[reference] header = @agent.head(reference) location = header.uri next if not internal?(location) or not header.is_a?(Mechanize::Page) grabbed[reference] = true grabbed[location] = true location rescue Mechanize::Error, URI::InvalidURIError, Net::HTTP::Persistent::Error, Net::OpenTimeout, Net::ReadTimeout next end end.compact return links, assets rescue Mechanize::Error, Net::OpenTimeout, Net::ReadTimeout, Net::HTTP::Persistent::Error return [], [] # swallow end # Evaluates if a link stays in the initial domain. # # Used to keep the crawler inside the initial domain. In order to determinate # it uses the second-level and top-level domain. If the public suffix cannot # be detected due to possibly invalidity returns true to make sure the link # does not go unchecked. # # @param link [URI] the link to be checked. # # @return [Boolean] whether the link is internal or not. # def internal?(link) return true unless PublicSuffix.valid?(link.host) link_domain = PublicSuffix.parse(link.host) @domain.sld == link_domain.sld and @domain.tld == link_domain.tld end end <file_sep>module Aquanaut # Version of this gem VERSION = "0.1.2" end <file_sep># Aquanaut [![Build Status](https://travis-ci.org/platzhirsch/aquanaut.png)](http://travis-ci.org/platzhirsch/aquanaut) A web crawler that stays on a given domain and creates a graph representing the different pages, static assets and how they are interlinked. <img src="http://konrad-reiche.com/images/aquanaut.png"> ## Installation Add this line to your application's Gemfile: gem 'aquanaut' And then execute: $ bundle Or install it yourself as: $ gem install aquanaut ## Usage Execute `aquanaut` and specify the domain on which it should be executed. $ aquanaut 'http://www.konrad-reiche.com' The results are written into the directory `sitemap`. ## Contributing 1. Fork it ( http://github.com/<my-github-username>/aquanaut/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) . Create new Pull Request <file_sep>require 'aquanaut' require 'spec_helper' require 'webmock/rspec' describe Aquanaut::Worker do describe "#initialize" do it "initializes the queue with the target address" do target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) queue = worker.instance_variable_get('@queue') expected_queue = [URI.parse(target)] expect(queue).to eq(expected_queue) end it "stores the target address in its different components" do target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) domain = worker.instance_variable_get('@domain') expect(domain.tld).to eq('com') expect(domain.sld).to eq('example') expect(domain.trd).to eq('www') end end describe "#internal?" do it "compares second-level and top-level domain" do target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse('http://www.example.com') expect(worker.internal?(uri)).to be_true uri = URI.parse('http://blog.example.com') expect(worker.internal?(uri)).to be_true uri = URI.parse('http://www.not-example.com') expect(worker.internal?(uri)).to be_false end it "guards against invalid domains" do target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse('/internal.html') expect(worker.internal?(uri)).to be_true end end describe "#links" do it "retrieves no links from a page with no body" do response = { headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse('http://www.example.com') expect(worker.links(uri).first).to be_empty end it "returns a list of URIs for a page with anchor elements" do body = <<-BODY <a href="/home.html">Home</a> <a href="/about.html">About us</a> <a href="/contact.html">Contact</a> BODY response = { body: body, headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) stub_request(:get, 'www.example.com').to_return(response) stub_request(:head, 'www.example.com/home.html').to_return(response) stub_request(:get, 'www.example.com/home.html').to_return(response) stub_request(:head, 'www.example.com/about.html').to_return(response) stub_request(:get, 'www.example.com/about.html').to_return(response) stub_request(:head, 'www.example.com/contact.html').to_return(response) stub_request(:get, 'www.example.com/contact.html').to_return(response) stub_request(:head, 'www.not-example.com').to_return(response) uris = ['http://www.example.com/home.html', 'http://www.example.com/about.html', 'http://www.example.com/contact.html'] uris.map! { |uri| URI.parse(uri) } target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse('http://www.example.com') expect(worker.links(uri).first).to eq(uris) end it "returns the final location when encountering HTTP 3xx" do body = '<a href="http://follow-me.com">Follow me</a>' response = { body: body, headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) end it "filters links that reference an external domain directly" do body = <<-BODY <a href="/home.html">Home</a> <a href="/about.html">About us</a> <a href="/contact.html">Contact</a> <a href="http://www.not-example.com">Not Example</a> BODY response = { body: body, headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) stub_request(:head, 'www.example.com/home.html').to_return(response) stub_request(:get, 'www.example.com/home.html').to_return(response) stub_request(:head, 'www.example.com/about.html').to_return(response) stub_request(:get, 'www.example.com/about.html').to_return(response) stub_request(:head, 'www.example.com/contact.html').to_return(response) stub_request(:get, 'www.example.com/contact.html').to_return(response) stub_request(:head, 'www.not-example.com').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uris = ['http://www.example.com/home.html', 'http://www.example.com/about.html', 'http://www.example.com/contact.html'] uris.map! { |uri| URI.parse(uri) } uri = URI.parse('http://www.example.com') expect(worker.links(uri).first).to eq(uris) end it "filters links that reference an external domain indirectly" do body = <<-BODY <a href="/home.html">Home</a> <a href="/about.html">About us</a> <a href="/contact.html">Contact</a> <a href="/moved.html">Moved</a> BODY other_domain = 'http://www.not-example.com' response = { body: body, headers: { 'Content-Type' => 'text/html'} } forward = { status: 301, headers: { 'Location' => other_domain } } stub_request(:get, 'www.example.com').to_return(response) stub_request(:head, 'www.example.com/home.html').to_return(response) stub_request(:get, 'www.example.com/home.html').to_return(response) stub_request(:head, 'www.example.com/about.html').to_return(response) stub_request(:get, 'www.example.com/about.html').to_return(response) stub_request(:head, 'www.example.com/contact.html').to_return(response) stub_request(:get, 'www.example.com/contact.html').to_return(response) stub_request(:head, 'www.example.com/moved.html').to_return(forward) stub_request(:head, other_domain).to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uris = ['http://www.example.com/home.html', 'http://www.example.com/about.html', 'http://www.example.com/contact.html'] uris.map! { |uri| URI.parse(uri) } uri = URI.parse('http://www.example.com') expect(worker.links(uri).first).to eq(uris) end it "rejects errors raised by Mechanize when retrieving the page" do response = { status: 500 } stub_request(:get, 'www.example.com').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse(target) expect(worker.links(uri).first).to be_empty end it "rejects errors raised by Mechanize when checking the links" do body = <<-BODY <a href="/home.html">Home</a> <a href="/about.html">About us</a> BODY headers = { 'Content-Type' => 'text/html'} response = { body: body, headers: headers } response_500 = { status: 500 } stub_request(:get, 'www.example.com').to_return(response) stub_request(:head, 'www.example.com/home.html').to_return(response) stub_request(:head, 'www.example.com/about.html').to_return(response_500) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse(target) uris = [URI.parse('http://www.example.com/home.html')] expect(worker.links(uri).first).to eq(uris) end it "rejects invalid URIs" do body = '<a href="http:invalid.com">Invalid</a>' headers = { 'Content-Type' => 'text/html'} response = { body: body, headers: headers } stub_request(:get, 'www.example.com').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse(target) expect(worker.links(uri).first).to be_empty end it "rejects anchors with no href attribute" do body = '<a>Empty</a>' headers = { 'Content-Type' => 'text/html'} response = { body: body, headers: headers } stub_request(:get, 'www.example.com').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse(target) expect(worker.links(uri).first).to be_empty end it "rejects links that lead to a timeout" do body = '<a href="/timeout.html">Timeout</a>' headers = { 'Content-Type' => 'text/html'} response = { body: body, headers: headers } stub_request(:get, 'www.example.com').to_return(response) stub_request(:head, 'www.example.com/timeout.html').to_timeout target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse(target) expect(worker.links(uri).first).to be_empty end it "rejects links that have already been grabbed" do body = <<-BODY <a href="/home.html">Home</a> <a href="/home.html">Home</a> BODY response = { body: body, headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) stub_request(:get, 'www.example.com/home.html').to_return(response) stub_request(:head, 'www.example.com/home.html').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) uri = URI.parse(target) result = [URI.parse('http://www.example.com/home.html')] expect(worker.links(uri).first).to eq(result) end end describe "#explore" do it "starts the crawling by processing the first queue element" do response = { headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) worker.explore queue = worker.instance_variable_get('@queue') expect(queue).to be_empty end it "marks visited sites" do response = { headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) target = 'http://www.example.com' worker = Aquanaut::Worker.new(target) visited = worker.instance_variable_get('@visited') expect { worker.explore }.to change { visited.size }.by(1) end it "skips already visited sites" do end end end <file_sep>require 'pathname' require 'slim' # The sitemap class is used to render the results in HTML and JavaScript. # # Uses SLIM as a template engine. # class Aquanaut::Sitemap def initialize(graph, domain, target_dir="#{Dir.pwd}/sitemap") @graph = graph @domain = domain @target_dir = target_dir if Pathname.new(target_dir).relative? @target_dir = File.expand_path("../../../#{target_dir}", __FILE__) end end # Renders the results by initiailizing the dependencies and processingt the template. # def render_results initialize_target_directory options = { disable_escape: true } template_path = File.expand_path('../templates/index.html.slim', __FILE__) rendered_template = Slim::Template.new(template_path, options).render(self) File.open("#{@target_dir}/index.html", 'w') do |file| file.write rendered_template end end private # There are several asset files required. Vendor asset files, but also local # asset files. They need to the copied to the target directory in order to # work properly. # # @private # def initialize_target_directory # create result directory Dir.mkdir(@target_dir) unless Dir.exists?(@target_dir) # copy vendor assets vendor_dir = File.expand_path('../../../vendor/assets', __FILE__) FileUtils.cp_r(vendor_dir, @target_dir, remove_destination: true) # copy local assets assets_dir = File.expand_path('../templates/assets', __FILE__) FileUtils.cp_r(assets_dir, @target_dir) end end <file_sep>module Aquanaut # Base node class which needs to be inherited for special cases. # # @abstract # class Node attr_reader :adjacency_list def initialize() @adjacency_list = [] end # Implements adjacency with an adjacency list. # def add_edge(successor) @adjacency_list << successor end end end <file_sep>require 'json' # A graph representing the sitemap in terms of a data structure. A hash is # used internally to make the nodes accessible through the URIs. # class Aquanaut::Graph include Enumerable def initialize @nodes = Hash.new end # Use this method for making nodes available in the graph. New nodes are # only assigned once. # # @param [Node] node the node to add to the graph. # def add_node(node) @nodes[node.uri] ||= node end # Use this method to easily add new edges without the need to pass actual # node objects. The method delegates the edge creation to the dedicated node # edge method. # # @param [URI] predecessor_uri source node for the edge # @param [URI] successor_uri target node for the edge # def add_edge(predecessor_uri, successor_uri) @nodes[predecessor_uri].add_edge(@nodes[successor_uri]) end # Accessor method to retrieve nodes by their URI. # # @param [URI] uri the URI representing the node. # def [](uri) @nodes[uri] end # Accessor method to iterate the nodes and their adjacency list. # def each @nodes.values.each do |node| yield node, node.adjacency_list end end # Used for visualizing the graph on the front-end. # def to_json model = { 'nodes' => [], 'links' => [] } self.each do |node, adjacency| if node.instance_of?(Aquanaut::PageNode) group = 1 else asset_groups = { 'image' => 2, 'stylesheet' => 3 } group = asset_groups[node.type] end model['nodes'] << { 'name' => node.uri, 'group' => group } source = @nodes.values.index(node) adjacency.each do |adjacency_node| target = @nodes.values.index(adjacency_node) model['links'] << { 'source' => source, 'target' => target } end end return model.to_json end end <file_sep>#!/usr/bin/env ruby # encoding: utf-8 require 'aquanaut' if ARGV.empty? raise ArgumentError, "Specify a target domain in the first argument" end target_domain = ARGV[0] if target_domain =~ URI::regexp graph = Aquanaut.process_domain(target_domain) Aquanaut::Sitemap.new(graph, target_domain).render_results else raise ArgumentError, "#{target_domain} is not a valid URI" end <file_sep>require 'aquanaut' require 'spec_helper' require 'webmock/rspec' describe Aquanaut do describe ".process_domain" do it "builds a graph with pages as nodes and interlinks as edges" do body = <<-BODY <a href="/home.html">Home</a> <a href="/about.html">About us</a> BODY uri = URI.parse('http://www.example.com') response = { body: body, headers: { 'Content-Type' => 'text/html'} } stub_request(:get, 'www.example.com').to_return(response) stub_request(:get, 'www.example.com').to_return(response) stub_request(:head, 'www.example.com/home.html').to_return(response) stub_request(:get, 'www.example.com/home.html').to_return(response) stub_request(:head, 'www.example.com/about.html').to_return(response) stub_request(:get, 'www.example.com/about.html').to_return(response) graph = Aquanaut.process_domain('http://www.example.com') uris = ['http://www.example.com/home.html', 'http://www.example.com/about.html'].map { |u| URI.parse(u) } root_node = graph[uri] page_1_node = graph[uris[0]] page_2_node = graph[uris[1]] expect(root_node).to be_an_instance_of(Aquanaut::PageNode) expect(page_1_node).to be_an_instance_of(Aquanaut::PageNode) expect(page_2_node).to be_an_instance_of(Aquanaut::PageNode) adjacency_list = [page_1_node, page_2_node] expect(root_node.adjacency_list).to eq(adjacency_list) expect(page_1_node.adjacency_list).to eq(adjacency_list) expect(page_2_node.adjacency_list).to eq(adjacency_list) end end end <file_sep>require 'aquanaut' require 'spec_helper' describe Aquanaut::Graph do describe "#initialize" do it "initializes an empty nodes hash" do graph = Aquanaut::Graph.new expect(graph.instance_variable_get('@nodes')).to be_empty end end describe "#add_node" do it "adds the node and hashes the node based on its URI attribute" do uri = URI.parse('http://www.example.com') node = Aquanaut::PageNode.new(uri) graph = Aquanaut::Graph.new graph.add_node(node) expect(graph[node.uri]).to eq(node) end it "does not add a node if it already exists under the given URI" do uri = URI.parse('http://www.example.com') node = Aquanaut::PageNode.new(uri) same_node = Aquanaut::PageNode.new(uri) graph = Aquanaut::Graph.new graph.add_node(node) expect(graph[uri]).to be(node) expect(graph[uri]).to_not be(same_node) end end describe "#add_edge" do it "looks up the predecessor node and delegates to the node's method" do uri = URI.parse('http://www.example.com') node = Aquanaut::PageNode.new(uri) adjacent_uri = URI.parse('http://www.example.com/home.html') adjacent_node = Aquanaut::PageNode.new(adjacent_uri) graph = Aquanaut::Graph.new graph.add_node(node) graph.add_node(adjacent_node) graph.add_edge(uri, adjacent_uri) expect(graph[uri].adjacency_list.first).to eq(adjacent_node) end end describe "#[]" do it "looks up a node based on its URI" do uri = URI.parse('http://www.example.com') node = Aquanaut::PageNode.new(uri) graph = Aquanaut::Graph.new graph.add_node(node) expect(graph[uri]).to be(node) end end describe "#each" do it "returns the node object and its adjacency list in an iteration" do uri = URI.parse('http://www.example.com') node = Aquanaut::PageNode.new(uri) adjacent_uri = URI.parse('http://www.example.com/home.html') adjacent_node = Aquanaut::PageNode.new(adjacent_uri) graph = Aquanaut::Graph.new graph.add_node(node) graph.add_node(adjacent_node) graph.add_edge(uri, adjacent_uri) graph.each do |page_node, adjacency_list| expect(page_node).to be_an_instance_of(Aquanaut::PageNode) expect(page_node).to be(node) expect(adjacency_list).to be(node.adjacency_list) break end end end end <file_sep>require 'aquanaut' require 'spec_helper' describe Aquanaut::PageNode do describe "#initialize" do it "stores the URI" do uri = URI.parse('http://www.example.com') node = Aquanaut::PageNode.new(uri) expect(node.uri).to eq(uri) end end end <file_sep>require 'aquanaut/asset_node' require 'aquanaut/graph' require 'aquanaut/page_node' require 'aquanaut/sitemap' require 'aquanaut/version' require 'aquanaut/worker' # Main module of Aquanaut # module Aquanaut class << self # Processes the given target domain and creates a page and asset graph. # # @param [String] target_address # # @return [Graph] the sitemap graph with pages and static assets # def process_domain(target_address) worker = Worker.new(target_address) graph = Graph.new worker.explore do |page_uri, links, static_assets| graph.add_node(PageNode.new(page_uri)) links.each do |link_uri| graph.add_node(PageNode.new(link_uri)) graph.add_edge(page_uri, link_uri) end static_assets.each do |asset| graph.add_node(AssetNode.new(asset['uri'], asset['type'])) graph.add_edge(page_uri, asset['uri']) end end return graph end end end <file_sep>require 'aquanaut/page_node' module Aquanaut # An asset node is a node that represents a static asset. The type specifies # what kind of static asset it is, for instance image or stylesheet. class AssetNode < PageNode attr_reader :type # Constructor # # @param [URI] uri identifying the static asset uniquely. # # @param [String] type specifying the kind of static asset. # def initialize(uri, type) @type = type super(uri) end end end <file_sep>require 'aquanaut/node' module Aquanaut # A page node represents an actual page in the specified domain. # class PageNode < Node attr_reader :uri def initialize(uri) @uri = uri super() end # Display method used on the front-end for the sitemap in list format. # def display part = "#{@uri.path}#{@uri.query}#{@uri.fragment}" part = @uri.to_s if part.empty? return part end end end <file_sep>source 'https://rubygems.org' # Specify your gem's dependencies in aquanaut.gemspec gemspec gem 'public_suffix' gem 'mechanize' gem 'slim' gem 'webmock' group :test do gem 'rspec' gem 'rspec-core' gem 'guard-rspec', require: false end group :development, :test do gem 'pry' gem 'pry-byebug' end <file_sep>require 'aquanaut' require 'spec_helper' describe Aquanaut::Node do describe "#initialize" do it "initializes an empty adjacency list" do node = Aquanaut::Node.new expect(node.adjacency_list).to be_empty end end describe "#add_edge" do it "adds a successor to the adjacency list" do node = Aquanaut::Node.new adjacent_node = Aquanaut::Node.new expect do node.add_edge(adjacent_node) end.to change { node.adjacency_list.count }.by(1) expect(node.adjacency_list.first).to eq(adjacent_node) end end end <file_sep>require 'aquanaut' require 'spec_helper' describe Aquanaut::Sitemap do describe "#initialize" do it "stores the given graph and domain" do graph = Aquanaut::Graph.new domain = 'http://www.example.com' sitemap = Aquanaut::Sitemap.new(graph, domain) expect(sitemap.instance_variable_get('@graph')).to be(graph) expect(sitemap.instance_variable_get('@domain')).to be(domain) end it "expands the path of the given target directory" do graph = Aquanaut::Graph.new domain = 'http://www.example.com' target_dir = 'spec/sitemap' sitemap = Aquanaut::Sitemap.new(graph, domain, target_dir) expanded_dir = sitemap.instance_variable_get('@target_dir') expect(Pathname.new(expanded_dir).absolute?).to be_true expect(expanded_dir.end_with?("/aquanaut/#{target_dir}")).to be_true end end describe "#initialize_target_directory" do it "creates the directory and copies assets file if neccessary" do graph = Aquanaut::Graph.new domain = 'http://www.example.com' target_dir = 'spec/sitemap' sitemap = Aquanaut::Sitemap.new(graph, domain, target_dir) sitemap.send(:initialize_target_directory) expect(Dir.exist?(target_dir)).to be_true expect(Dir.exist?("#{target_dir}/assets")).to be_true FileUtils.rm_r(target_dir) end end describe "#render_results" do it "the result rendering works for an empty graph" do graph = Aquanaut::Graph.new domain = 'http://www.example.com' target_dir = 'spec/sitemap' sitemap = Aquanaut::Sitemap.new(graph, domain, target_dir) sitemap.render_results expect(File.exist?("#{target_dir}/index.html")) FileUtils.rm_r(target_dir) end end end
18f90207f4c5052951c55f27f8ff3f7cf4a95523
[ "Markdown", "Ruby" ]
18
Ruby
konradreiche/aquanaut
fd987bcf36ce650abb2d68bbcb23282b6f7e1c95
1b9af68f514de6a33b5558b9ed5ab9d542fd8861
refs/heads/master
<repo_name>HenrySlawniak/spellsluts.com<file_sep>/router.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "crypto/sha512" "fmt" "github.com/go-playground/log" "github.com/gorilla/mux" "io/ioutil" "mime" "net/http" "os" "path/filepath" "time" ) var router *mux.Router func setupRouter() { log.Info("Setting up router") router = mux.NewRouter() router.StrictSlash(true) router.NotFoundHandler = handler(notFound) addRoutes() } func addRoutes() { log.Info("Adding routes to router") // Auth handlers router.Path("/auth/").Handler(handler(authHandler)) router.Path("/auth/login/").Handler(handler(loginHandler)) router.Path("/auth/logout/").Handler(handler(logoutHandler)) router.Path("/auth/debug/").Handler(handler(debugHandler)) router.Path("/spell/view/{id}").Handler(handler(spellViewHandler)) // API handlers router.Path("/api/schools").Handler(handler(AllSchoolsHandler)).Methods("GET") router.Path("/api/classes").Handler(handler(AllClassesHandler)).Methods("GET") router.Path("/api/spell/new").Handler(handler(NewSpellHandler)).Methods("POST") router.Path("/api/spell/{id}").Handler(handler(SpellByIDHandler)).Methods("GET") router.Path("/api/spells/all").Handler(handler(SpellListHandler)).Methods("GET") router.Path("/api/spells/all/{page}").Handler(handler(SpellListHandler)).Methods("GET") router.Path("/api/spells/school/{school}").Handler(handler(SpellsBySchoolHandler)).Methods("GET") router.Path("/api/spells/class/{class}").Handler(handler(SpellsByClassHandler)).Methods("GET") router.Path("/api/spells/names").Handler(handler(NameAndIDListHandler)).Methods("GET") router.Path("/api/spells/names/{page}").Handler(handler(NameAndIDListHandler)).Methods("GET") router.Path("/api/profile/permissions").Handler(handler(permissionsHandler)).Methods("GET") router.Path("/api/profile/loggedin").Handler(handler(isLoggedInHandler)).Methods("GET") router.Path("/api/profile/info").Handler(handler(profileInfoHandler)).Methods("GET") router.Path("/api/profile/username/{id}").Handler(handler(usernameHandler)).Methods("GET") // Static handlers router.PathPrefix("/").HandlerFunc(indexHandler()) } func indexHandler() http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path if _, err := os.Stat("./client" + path); err == nil { serveFile(w, r, "./client"+path) } else { serveFile(w, r, "./client/index.html") } }) } func serveFile(w http.ResponseWriter, r *http.Request, path string) { if path == "./client/" { path = "./client/index.html" } content, sum, mod, err := readFile(path) if err != nil { http.Error(w, "Could not read file", http.StatusInternalServerError) fmt.Printf("%s:%s\n", path, err.Error()) return } mime := mime.TypeByExtension(filepath.Ext(path)) w.Header().Set("Content-Type", mime) w.Header().Set("Cache-Control", "public, no-cache") w.Header().Set("Last-Modified", mod.Format(time.RFC1123)) if r.Header.Get("If-None-Match") == sum { w.WriteHeader(http.StatusNotModified) w.Header().Set("ETag", sum) return } w.Header().Set("ETag", sum) w.Write(content) } func readFile(path string) ([]byte, string, time.Time, error) { f, err := os.Open(path) if err != nil { return nil, "", time.Now(), err } defer f.Close() stat, err := os.Stat(path) if err != nil { return nil, "", time.Now(), err } cont, err := ioutil.ReadAll(f) if err != nil { return nil, "", time.Now(), err } return cont, fmt.Sprintf("%x", sha512.Sum512(cont)), stat.ModTime(), nil } <file_sep>/apiutil.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "encoding/json" "encoding/xml" "gopkg.in/mgo.v2/bson" "net/http" ) // NewSpellSubmission encodes the raw input from clients for inside processing type NewSpellSubmission struct { ID bson.ObjectId `bson:"_id,omitempty"` Name string Level int School SpellSchool Cantrip bool Classes []SpellClass CastingTime struct { Src string Content string } Range struct { Src string Content string } Components struct { Src string Content string } Duration struct { Src string Content string } Description struct { Src string Content string } } // ParseSpellInput will decode rasw input JSON into a NewSpellSubmission func ParseSpellInput(input string) (NewSpellSubmission, error) { sub := NewSpellSubmission{} err := json.Unmarshal([]byte(input), &sub) sub.ID = bson.NewObjectId() return sub, err } // APIResponse wraps any data sent via the API with some meta status type APIResponse struct { Meta APIResponseMeta Data interface{} } // APIResponseMeta contains meta data for the API response such as success and error messages type APIResponseMeta struct { Success bool Status int Error string } // WrapBadResponse will return an APIResponse with meta data signifying the error by code func WrapBadResponse(code int, msg string) APIResponse { message := "unspecified error" if _, ok := APIErrorMessages[code]; ok { message = APIErrorMessages[code] } if msg != "" { message = message + ": " + msg } return APIResponse{ Meta: APIResponseMeta{ Success: false, Status: code, Error: message, }, Data: nil, } } // WrapGoodResponse will return an APIResponse with successful meta data func WrapGoodResponse(data interface{}) APIResponse { return APIResponse{ Meta: APIResponseMeta{ Success: true, Status: 200, Error: "", }, Data: data, } } // WriteData will write the data to w using json or xml based on query values in r // also supports indentation on JSON repsonses via writeJSON func WriteData(w http.ResponseWriter, r *http.Request, data interface{}) error { w.Header().Set("Cache-Control", "no-cache,no-store,must-revalidate") w.Header().Set("Pragma", "no-cache") w.Header().Set("Expires", "0") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") if r.URL.Query().Get("format") == "xml" { return writeXML(w, r, data) } return writeJSON(w, r, data) } func writeJSON(w http.ResponseWriter, r *http.Request, data interface{}) error { if r.URL.Query().Get("pretty") == "true" { j, err := json.MarshalIndent(data, "", " ") if err != nil { return err } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "text/plain") w.Write(j) return nil } j, err := json.Marshal(data) if err != nil { return err } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") w.Write(j) return nil } func writeXML(w http.ResponseWriter, r *http.Request, data interface{}) error { x, err := xml.Marshal(data) if err != nil { return err } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/xml") w.Write(x) return nil } <file_sep>/client/static/components/write-form/write-form.js "use strict"; customElements.define("write-form", class extends HTMLElement { static get observedAttributes () { return []; } constructor () { super(); const doc = document.currentScript.ownerDocument; const tmpl = doc.querySelector("#write-tmpl"); this._root = this.attachShadow({mode: "open"}); this._root.appendChild(tmpl.content.cloneNode(true)); this._baseURL = ""; this._submitButton = this._root.querySelector("button#submit-button"); this._markdownSources = this._root.querySelectorAll(".mkdwn-src"); this._spellCard = this._root.querySelector("spell-card"); } connectedCallback () { this.submit = this.submit.bind(this); this.loadSchools = this.loadSchools.bind(this); this.loadClasses = this.loadClasses.bind(this); this._markdownChanged = this._markdownChanged.bind(this); this._addEventListeners(); this.loadSchools(); this.loadClasses(); this._md = window.markdownit({ typographer: true }).use(window.markdownitEmoji); this._md.renderer.rules.emoji = function(token, idx) { return twemoji.parse(token[idx].content); }; } disconnectedCallback () { this._removeEventListeners(); } _addEventListeners () { this._submitButton.addEventListener("click", this.submit); this._markdownSources.forEach(function(e) { this._addMarkdownHandler(e, this._root.querySelector(`#${e.id}-dst`)); }.bind(this)); } _removeEventListeners () { this._submitButton.removeEventListener("click", this.submit); this._markdownSources.forEach(function(e) { this._removeMarkdownHandler(e, this._root.querySelector(`#${e.id}-dst`)); }.bind(this)); } _addMarkdownHandler (s, d) { if (s === null) { console.warn(`Source is missing form Markdown element`); return } else if (d === null) { console.warn(`Destination is missing form Markdown element`); return } s.addEventListener('keyup', this._markdownChanged); s.addEventListener('keydown', this._markdownChanged); } _removeMarkdownHandler (s, d) { if (s === null) { console.warn(`Source is missing form Markdown element`); return } else if (d === null) { console.warn(`Destination is missing form Markdown element`); return } s.removeEventListener('keyup', this._markdownChanged); s.removeEventListener('keydown', this._markdownChanged); } _markdownChanged (evt) { this._markdownSources.forEach(function(e) { var src = e.value; var res = this._md.render(src); this._root.querySelector(`#${e.id}-dst`).innerHTML = res; }.bind(this)); } loadSchools () { var schoolSelect = this._root.querySelector("#school"); const xhr = new XMLHttpRequest(); var url = this._baseURL + "/api/schools"; xhr.open("GET", url, true); xhr.send(null); xhr.onload = _ => { const resp = JSON.parse(xhr.responseText); if (!resp.Meta.Success) { console.warn(`Failed to load the list of schools: (${resp.Meta.Status}) ${resp.Meta.Error}`) } else { resp.Data.forEach(function(e) { var elem = document.createElement("option"); elem.setAttribute("value", e.ID); elem.innerHTML = e.Name; schoolSelect.appendChild(elem); }); } } } loadClasses () { var classSelect = this._root.querySelector("#classes"); const xhr = new XMLHttpRequest(); var url = this._baseURL + "/api/classes"; xhr.open("GET", url, true); xhr.send(null); xhr.onload = _ => { const resp = JSON.parse(xhr.responseText); if (!resp.Meta.Success) { console.warn(`Failed to load the list of classes: (${resp.Meta.Status}) ${resp.Meta.Error}`) } else { resp.Data.forEach(function(e) { var elem = document.createElement("option"); elem.setAttribute("value", e.ID); elem.innerHTML = e.Name; classSelect.appendChild(elem); }); } } } submit () { var classSelect = this._root.querySelector("#classes"); var classes = []; Array.from(classSelect.options).forEach(function(e) { if (e.selected) { classes.push(parseInt(e.value)); } }) const payload = { name: this._root.querySelector("input#name").value, level: parseInt(this._root.querySelector("input#level").value), cantrip: this._root.querySelector("input#cantrip").checked, school: parseInt(this._root.querySelector("#school").value), classes: classes, castingtime: { src: this._root.querySelector("#casting").value, content: this._root.querySelector("#casting-dst").innerHTML }, range: { src: this._root.querySelector("#range").value, content: this._root.querySelector("#range-dst").innerHTML }, components: { src: this._root.querySelector("#components").value, content: this._root.querySelector("#components-dst").innerHTML }, duration: { src: this._root.querySelector("#duration").value, content: this._root.querySelector("#duration-dst").innerHTML }, description: { src: this._root.querySelector("#description").value, content: this._root.querySelector("#description-dst").innerHTML } } console.log(JSON.stringify(payload)); const xhr = new XMLHttpRequest(); var url = this._baseURL + "/api/spell/new" xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(JSON.stringify(payload)); xhr.onload= _ => { const resp = JSON.parse(xhr.responseText); if (!resp.Meta.Success) { console.warn(`We"ve failed (${resp.Meta.Status}) ${resp.Meta.Error}`) } else { console.log(resp.Data); document.location.replace(`/spell/view/${resp.Data.ID}`); } } } }); <file_sep>/spell.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "encoding/json" "github.com/HenrySlawniak/spellsluts.com/util" "gopkg.in/mgo.v2/bson" "strings" "time" ) // Spell encodes our basic fifth edition D&D spell type Spell struct { ID bson.ObjectId `bson:"_id,omitempty"` Author bson.ObjectId `bson:"_author"` LastEdited time.Time Name string Level int School SpellSchool Cantrip bool CastingTime util.MarkdownString Range util.MarkdownString Components util.MarkdownString Duration util.MarkdownString Description util.MarkdownString Classes []SpellClass } // SpellSchool is the school that the spell belongs to type SpellSchool int // AllSchools contains all valid schools for spells var AllSchools = []SpellSchool{ Abjuration, Conjuration, Divination, Enchantment, Evocation, Illusion, Necromancy, Transmutation, } const ( // Abjuration is a spell school Abjuration SpellSchool = iota // Conjuration is a spell school Conjuration // Divination is a spell school Divination // Enchantment is a spell school Enchantment // Evocation is a spell school Evocation // Illusion is a spell school Illusion // Necromancy is a spell school Necromancy // Transmutation is a spell school Transmutation ) func (s SpellSchool) String() string { switch s { case Abjuration: return "Abjuration" case Conjuration: return "Conjuration" case Divination: return "Divination" case Enchantment: return "Enchantment" case Evocation: return "Evocation" case Illusion: return "Illusion" case Necromancy: return "Necromancy" case Transmutation: return "Transmutation" default: return "" } } // MarshalJSON provides custom JSON ooutput for SpellSchool func (s SpellSchool) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { ID int Name string Class string }{ ID: int(s), Name: s.String(), Class: s.CSSClass(), }) } // CSSClass returns the name of the css class to appropriately style the spell card func (s SpellSchool) CSSClass() string { return strings.ToLower(strings.Replace(s.String(), " ", "-", -1)) } // SpellClass are the classes that can cast spells type SpellClass int // AllClasses contains all valid classes for spells var AllClasses = []SpellClass{ Bard, Cleric, Druid, Paladin, Ranger, Sorcerer, Warlock, Wizard, } const ( // Bard is a spell class Bard SpellClass = iota // Cleric is a spell class Cleric // Druid is a spell class Druid // Paladin is a spell class Paladin // Ranger is a spell class Ranger // Sorcerer is a spell class Sorcerer // Warlock is a spell class Warlock // Wizard is a spell class Wizard ) func (s SpellClass) String() string { switch s { case Bard: return "Bard" case Cleric: return "Cleric" case Druid: return "Druid" case Paladin: return "Paladin" case Ranger: return "Ranger" case Sorcerer: return "Sorcerer" case Warlock: return "Warlock" case Wizard: return "Wizard" default: return "" } } // CSSClass returns the name of the css class to appropriately style the spell card func (s SpellClass) CSSClass() string { return strings.ToLower(strings.Replace(s.String(), " ", "-", -1)) } // MarshalJSON provides custom JSON ooutput for SpellClass func (s SpellClass) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { ID int Name string Class string }{ ID: int(s), Name: s.String(), Class: s.CSSClass(), }) } // AuthorUser returns the author of the Spell as a *SpellUser func (s Spell) AuthorUser() (*SpellUser, error) { return GetUserByID(s.ID) } // Edited returns whether or not the Spell has been edited func (s Spell) Edited() bool { return s.ID.Time() != s.LastEdited } <file_sep>/profilehandlers.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "github.com/gorilla/mux" "gopkg.in/mgo.v2/bson" "net/http" ) func permissionsHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return internalError(w, r, err) } if !isValidLogin(session) { return notAuthed(w, r, err) } user, err := GetUserFromSession(session) if err != nil { return internalError(w, r, err) } return WriteData(w, r, WrapGoodResponse(user.Permissions)) } func isLoggedInHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return internalError(w, r, err) } if !isValidLogin(session) { return WriteData(w, r, WrapGoodResponse(false)) } return WriteData(w, r, WrapGoodResponse(true)) } func profileInfoHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return internalError(w, r, err) } if !isValidLogin(session) { return notAuthed(w, r, err) } user, err := GetUserFromSession(session) if err != nil { return internalError(w, r, err) } return WriteData(w, r, WrapGoodResponse(user)) } func usernameHandler(w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) id := vars["id"] if id == "" { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, "You must provide a valid ObjectId string")) } if !bson.IsObjectIdHex(id) { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, "`"+id+"` is not a valid ObjectId string")) } realid := bson.ObjectIdHex(id) user, err := GetUserByID(realid) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusInternalServerError, err.Error())) } // TODO: Need to create a user configurable Display name instead of always using real names return WriteData(w, r, WrapGoodResponse(user.Name)) } <file_sep>/oauth.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "crypto/rand" "encoding/base64" "flag" "golang.org/x/oauth2" ) var ( clientID = flag.String("client-id", "", "Your Google API client ID for G+ logins") clientSecret = flag.String("client-secret", "", "Your Google API client secret for G+ logins") redirectURL = flag.String("redirect-url", "http://localhost:8563/auth", "The redirect URL for G+ logins") config *oauth2.Config ) // EmailResponse encodes the OAuth response we care about type EmailResponse struct { Name string `json:"name"` GivenName string `json:"given_name"` FamilyName string `json:"family_name"` Picture string `json:"picture"` Email string `json:"email"` EmailVerified bool `json:"email_verified"` } // randomString returns a random string with the specified length func randomString(length int) (str string) { b := make([]byte, length) rand.Read(b) return base64.StdEncoding.EncodeToString(b) } func getLoginURL(state string) string { return config.AuthCodeURL(state) } <file_sep>/client/static/components/spell-header/spell-header.js "use strict"; customElements.define("spell-header", class extends HTMLElement { static get observedAttributes () { return []; } constructor () { super(); const doc = document.currentScript.ownerDocument; const tmpl = doc.querySelector("#spell-header-tmpl"); this._root = this.attachShadow({mode: "open"}); this._root.appendChild(tmpl.content.cloneNode(true)); this._list = this._root.querySelector("ul.container"); } connectedCallback () { this._addEventListeners(); } disconnectedCallback () { this._removeEventListeners(); } _addEventListeners () { } _removeEventListeners () { } appendLink (href, title) { const newLink = document.createElement("li"); newLink.innerHTML = `<a href="${href}">${title}</a>`; this._list.appendChild(newLink); } }); <file_sep>/errorhandlers.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "fmt" "net/http" ) // ErrorMessages cotnains our general error messages for http error codes var ErrorMessages map[int]string // APIErrorMessages contains our http error messages for the API interface var APIErrorMessages map[int]string func init() { ErrorMessages = map[int]string{ http.StatusNotFound: "We can't find that page :(", http.StatusUnauthorized: "You are not authorized to do that", http.StatusInternalServerError: "Something is going horribly wrong!", http.StatusBadRequest: "Your request is malformed", http.StatusNotImplemented: "We haven't finished this feature yet", } APIErrorMessages = map[int]string{ http.StatusNotFound: "not found", http.StatusUnauthorized: "not authorized", http.StatusInternalServerError: "internal error", http.StatusBadRequest: "bad request", http.StatusNotImplemented: "nto implemented", } } func httpError(code int, w http.ResponseWriter, r *http.Request, err error) error { w.WriteHeader(code) message := "" if _, ok := ErrorMessages[code]; ok { message = ErrorMessages[code] } if err != nil { w.Write([]byte(fmt.Sprintf("%d: %s (%s)", code, message, err.Error()))) } else { w.Write([]byte(fmt.Sprintf("%d: %s", code, message))) } return nil } func notFound(w http.ResponseWriter, r *http.Request) error { return httpError(http.StatusNotFound, w, r, nil) } func notAuthed(w http.ResponseWriter, r *http.Request, err error) error { return httpError(http.StatusUnauthorized, w, r, err) } func internalError(w http.ResponseWriter, r *http.Request, err error) error { return httpError(http.StatusInternalServerError, w, r, err) } func badRequest(w http.ResponseWriter, r *http.Request, err error) error { return httpError(http.StatusBadRequest, w, r, err) } <file_sep>/user.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "github.com/HenrySlawniak/spellsluts.com/db" "github.com/HenrySlawniak/spellsluts.com/util" "github.com/gorilla/sessions" "github.com/pkg/errors" "gopkg.in/mgo.v2/bson" ) // SpellUser encodes our users type SpellUser struct { ID bson.ObjectId `bson:"_id,omitempty"` Bio util.MarkdownString Email string Sessions []string Name string FirstName string LastName string Picture string Permissions struct { IsAdmin bool IsPrivileged bool } } // GetUserByEmail will return a SpellUser or an error if we cannot find a user by email func GetUserByEmail(email string) (*SpellUser, error) { user := SpellUser{} session := db.GetSession() defer session.Close() err := session.DB(db.DB).C("users").Find(bson.M{"email": email}).One(&user) return &user, err } // HasSession returns whether or not session is a valid SpellSession for the SpellUser func (u *SpellUser) HasSession(sessionID string) bool { for _, sess := range u.Sessions { if sess == sessionID { return true } } return false } // GetUserByID will return a SpellUser or an error if we cannot find a valid user by id func GetUserByID(id bson.ObjectId) (*SpellUser, error) { user := SpellUser{} session := db.GetSession() defer session.Close() err := session.DB(db.DB).C("users").Find(bson.M{"_id": id}).One(&user) return &user, err } // GetUserFromSession will return a SpellUser or an error if we cannot find a valid user by sess func GetUserFromSession(session *sessions.Session) (*SpellUser, error) { if session.Values["userid"] == nil || session.Values["session-id"] == nil { return nil, errors.New("This session does not have all of the required data") } userID := session.Values["userid"].(string) if !bson.IsObjectIdHex(userID) { return nil, errors.New("This session does not have a valid user id") } user := SpellUser{} localsession := db.GetSession() defer localsession.Close() err := localsession.DB(db.DB).C("users").Find(bson.M{"_id": bson.ObjectIdHex(userID)}).One(&user) if err != nil { return nil, err } if !user.HasSession(session.Values["session-id"].(string)) { return nil, errors.New("This session does not have a valid login session") } return &user, nil } // RemoveSession will remove the session with id from the SpellUser u func (u *SpellUser) RemoveSession(id string) error { localsession := db.GetSession() defer localsession.Close() return localsession.DB(db.DB).C("users").Update(bson.M{"_id": u.ID}, bson.M{"$pull": bson.M{"sessions": id}}) } func isValidLogin(session *sessions.Session) bool { _, err := GetUserFromSession(session) return err == nil } <file_sep>/spellhandlers.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "github.com/HenrySlawniak/spellsluts.com/db" "github.com/gorilla/mux" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "html/template" "net/http" ) func spellViewHandler(w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) id := vars["id"] if id == "" { return notFound(w, r) } if !bson.IsObjectIdHex(id) { return badRequest(w, r, nil) } realid := bson.ObjectIdHex(id) spell := Spell{} localsession := db.GetSession() defer localsession.Close() err := localsession.DB(db.DB).C("spells").Find(bson.M{"_id": realid}).One(&spell) if err == mgo.ErrNotFound { return notFound(w, r) } // TODO: Let's move this to client-side at some point tpl, err := template.ParseFiles("templates/spell.tpl.html") if err != nil { return internalError(w, r, err) } return tpl.Execute(w, spell) } <file_sep>/main.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "crypto/sha256" "crypto/tls" "flag" "fmt" "github.com/HenrySlawniak/spellsluts.com/db" "github.com/go-playground/log" "github.com/go-playground/log/handlers/console" "github.com/gorilla/sessions" "golang.org/x/crypto/acme/autocert" "golang.org/x/net/http2" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "net" "net/http" "strings" "time" ) var ( listen = flag.String("listen", "127.0.0.1:8563", "The address to listen on") dial = flag.String("dial", "mongodb://127.0.0.1:27017/spellsluts", "The mongodb dial url `[mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options]`") devMode = flag.Bool("dev", false, "Puts the server in developer mode, will bind to :34265 and will not autocert") domains = flag.String("domain", "spellsluts.com", "A comma-seperaated list of domains to get a certificate for.") cookieSecret string buildTime string commit string ) func init() { flag.Parse() cLog := console.New() cLog.SetTimestampFormat(time.RFC3339) log.RegisterHandler(cLog, log.AllLevels...) config = &oauth2.Config{ ClientID: *clientID, ClientSecret: *clientSecret, RedirectURL: *redirectURL, Scopes: []string{ "https://www.googleapis.com/auth/userinfo.email", }, Endpoint: google.Endpoint, } addrs := []string{} ifs, _ := net.Interfaces() for _, v := range ifs { h := v.HardwareAddr.String() if len(h) == 0 { continue } addrs = append(addrs, h) } cookieSecret = strings.Join(addrs, "|") log.Info("MAC Addresses: " + cookieSecret) hasher := sha256.New() hasher.Write([]byte(cookieSecret)) cookieSecret = fmt.Sprintf("%x", hasher.Sum(nil)) log.Info("Cookie Secret: " + cookieSecret) } // This is a bad way to get a secret var store = sessions.NewCookieStore([]byte(cookieSecret)) func getSession(r *http.Request) (*sessions.Session, error) { return store.Get(r, "spell-auth") } func main() { log.Info("Starting the Spellbook") log.Info("Built: " + buildTime) log.Info("Revision: " + commit) setupRouter() err := db.Open(*dial) if err != nil { panic(err) } if *devMode { srv := &http.Server{ Addr: ":34265", Handler: router, } log.Info("Listening on :34265") srv.ListenAndServe() } domainList := strings.Split(*domains, ",") for i, d := range domainList { domainList[i] = strings.TrimSpace(d) } m := autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(domainList...), Cache: autocert.DirCache("certs"), } httpSrv := &http.Server{ Addr: ":http", Handler: http.HandlerFunc(httpRedirectHandler), } go httpSrv.ListenAndServe() rootSrv := &http.Server{ Addr: ":https", TLSConfig: &tls.Config{GetCertificate: m.GetCertificate}, Handler: router, } log.Info("Listening on :https") http2.ConfigureServer(rootSrv, &http2.Server{}) rootSrv.ListenAndServeTLS("", "") } func httpRedirectHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "https://"+r.Host+r.URL.String(), http.StatusMovedPermanently) } <file_sep>/apihandlers.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "github.com/HenrySlawniak/spellsluts.com/db" "github.com/HenrySlawniak/spellsluts.com/util" "github.com/gorilla/mux" "gopkg.in/mgo.v2/bson" "io/ioutil" "net/http" "strconv" "strings" ) // NewSpellHandler is the api handler to submit new spells func NewSpellHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusInternalServerError, err.Error())) } user, err := GetUserFromSession(session) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusUnauthorized, "You are not logged in")) } bod, err := ioutil.ReadAll(r.Body) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, err.Error())) } defer r.Body.Close() newSpell, err := ParseSpellInput(string(bod)) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, err.Error())) } if newSpell.Name == "" { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, "Your spell must have a name")) } realSpell := Spell{ ID: newSpell.ID, Author: user.ID, LastEdited: newSpell.ID.Time().UTC(), Name: newSpell.Name, Level: newSpell.Level, School: SpellSchool(newSpell.School), Cantrip: newSpell.Cantrip, Classes: newSpell.Classes, CastingTime: util.NewMarkdownString(newSpell.CastingTime.Src, newSpell.CastingTime.Content), Range: util.NewMarkdownString(newSpell.Range.Src, newSpell.Range.Content), Components: util.NewMarkdownString(newSpell.Components.Src, newSpell.Components.Content), Duration: util.NewMarkdownString(newSpell.Duration.Src, newSpell.Duration.Content), Description: util.NewMarkdownString(newSpell.Description.Src, newSpell.Description.Content), } localsession := db.GetSession() defer localsession.Close() err = localsession.DB(db.DB).C("spells").Insert(realSpell) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusInternalServerError, err.Error())) } return WriteData(w, r, WrapGoodResponse(realSpell)) } // SpellByIDHandler expects an ObjectId in the url func SpellByIDHandler(w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) id := vars["id"] if id == "" { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, "You must provide an ID")) } if !bson.IsObjectIdHex(id) { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, id+" is not a valid ID")) } realid := bson.ObjectIdHex(id) spell := Spell{} localsession := db.GetSession() defer localsession.Close() err := localsession.DB(db.DB).C("spells").Find(bson.M{"_id": realid}).One(&spell) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusNotFound, id+" not found")) } return WriteData(w, r, WrapGoodResponse(spell)) } // SpellListHandler will return a paginated list of all spells func SpellListHandler(w http.ResponseWriter, r *http.Request) error { var realpage int var err error vars := mux.Vars(r) page := vars["page"] if page == "" { realpage = 1 } else { realpage, err = strconv.Atoi(page) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, err.Error())) } } skip := 0 if realpage > 1 { skip = realpage * 25 } spells := []Spell{} localsession := db.GetSession() defer localsession.Close() err = localsession.DB(db.DB).C("spells").Find(bson.M{}).Sort("name").Limit(25).Skip(skip).All(&spells) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusInternalServerError, err.Error())) } return WriteData(w, r, WrapGoodResponse(spells)) } // NameAndIDListHandler will return a list of all spells and their IDs func NameAndIDListHandler(w http.ResponseWriter, r *http.Request) error { var realpage int var err error vars := mux.Vars(r) page := vars["page"] if page == "" { realpage = 1 } else { realpage, err = strconv.Atoi(page) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, err.Error())) } } skip := 0 if realpage > 1 { skip = realpage * 25 } spells := []Spell{} localsession := db.GetSession() defer localsession.Close() err = localsession.DB(db.DB).C("spells").Find(bson.M{}).Sort("name").Limit(25).Skip(skip).All(&spells) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusInternalServerError, err.Error())) } namesAndIDs := []struct { Name string ID bson.ObjectId }{} for _, spell := range spells { namesAndIDs = append(namesAndIDs, struct { Name string ID bson.ObjectId }{ Name: spell.Name, ID: spell.ID, }) } return WriteData(w, r, WrapGoodResponse(namesAndIDs)) } // AllSchoolsHandler will return a list of all avaiable spell schools func AllSchoolsHandler(w http.ResponseWriter, r *http.Request) error { return WriteData(w, r, WrapGoodResponse(AllSchools)) } // AllClassesHandler will return a list of all avaiable spell classes func AllClassesHandler(w http.ResponseWriter, r *http.Request) error { return WriteData(w, r, WrapGoodResponse(AllClasses)) } // SpellsBySchoolHandler is the handler for querying spells by SpellSchool func SpellsBySchoolHandler(w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) schoolstring := vars["school"] if schoolstring == "" { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, "You must provide a comma deliminated list of spell schools")) } rawSchools := strings.Split(schoolstring, ",") schools := []SpellSchool{} for _, s := range rawSchools { id, err := strconv.Atoi(s) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, err.Error())) } schools = append(schools, SpellSchool(id)) } spells := []Spell{} localsession := db.GetSession() defer localsession.Close() err := localsession.DB(db.DB).C("spells").Find(bson.M{"school": bson.M{"$in": schools}}).Sort("-_id").All(&spells) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusInternalServerError, err.Error())) } return WriteData(w, r, WrapGoodResponse(spells)) } // SpellsByClassHandler is the handler for querying spells by SpellSchool func SpellsByClassHandler(w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) classString := vars["class"] if classString == "" { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, "You must provide a comma deliminated list of spell classes")) } rawClasses := strings.Split(classString, ",") classes := []SpellClass{} for _, s := range rawClasses { id, err := strconv.Atoi(s) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusBadRequest, err.Error())) } classes = append(classes, SpellClass(id)) } spells := []Spell{} localsession := db.GetSession() defer localsession.Close() err := localsession.DB(db.DB).C("spells").Find(bson.M{"classes": bson.M{"$in": classes}}).Sort("-_id").All(&spells) if err != nil { return WriteData(w, r, WrapBadResponse(http.StatusInternalServerError, err.Error())) } return WriteData(w, r, WrapGoodResponse(spells)) } <file_sep>/client/static/components/spell-footer/spell-footer.js "use strict"; customElements.define("spell-footer", class extends HTMLElement { static get observedAttributes () { return []; } constructor () { super(); const doc = document.currentScript.ownerDocument; const tmpl = doc.querySelector("#spell-footer-tmpl"); this._root = this.attachShadow({mode: "open"}); this._root.appendChild(tmpl.content.cloneNode(true)); } connectedCallback () { this._updateLogin = this._updateLogin.bind(this); this._addEventListeners(); this._updateLogin() } disconnectedCallback () { this._removeEventListeners(); } _addEventListeners () { } _removeEventListeners () { } _updateLogin () { const xhr = new XMLHttpRequest(); var url = "/api/profile/loggedin" xhr.open("GET", url, true); xhr.onload= _ => { const resp = JSON.parse(xhr.responseText); if (!resp.Meta.Success) { console.warn(`We"ve failed (${resp.Meta.Status}) ${resp.Meta.Error}`) } else { if (resp.Data === true) { this._updateProfileInfo(); } } } xhr.send(null); } _updateProfileInfo () { const xhr = new XMLHttpRequest(); var url = "/api/profile/info" xhr.open("GET", url, true); xhr.onload= _ => { const resp = JSON.parse(xhr.responseText); if (!resp.Meta.Success) { console.warn(`We"ve failed (${resp.Meta.Status}) ${resp.Meta.Error}`) } else { this._root.querySelector("#login-status").innerHTML = `<span>Welcome, ${resp.Data.FirstName}</span> <img class="avatar" src="${resp.Data.Picture}"/> <a href="/auth/logout">Logout</a>` } } xhr.send(null); } }); <file_sep>/client/static/components/spell-card/spell-card.js "use strict"; customElements.define("spell-card", class extends HTMLElement { static get observedAttributes () { return [ "oid", "data" ]; } constructor () { super(); const doc = document.currentScript.ownerDocument; const tmpl = doc.querySelector("#spell-card-tmpl"); this._root = this.attachShadow({mode: "open"}); this._root.appendChild(tmpl.content.cloneNode(true)); this._card = this._root.querySelector(".card"); this._title = this._root.querySelector(".title"); this._subtitle = this._root.querySelector(".subtitle"); this._meta = this._root.querySelector(".meta"); this._castingTime = this._root.querySelector("#casting-time"); this._range = this._root.querySelector("#range"); this._components = this._root.querySelector("#components"); this._duration = this._root.querySelector("#duration"); this._description = this._root.querySelector(".description"); } set oid (_oid) { if (!_oid) { return; } this._oid = _oid; this._refreshFromOID(); } get oid () { return this._oid; } set data (_data) { if (!_data) { return; } this._data = JSON.parse(_data); this._fillData(this._data); } get data () { return this._data; } connectedCallback () { this._fillData = this._fillData.bind(this); this._addEventListeners(); } disconnectedCallback () { this._removeEventListeners(); } attributeChangedCallback (name, oldValue, newValue) { if (name == "oid") { this.oid = newValue; } else if (name == "data") { this.data = newValue; } } _refreshFromOID () { if (!this._oid) { return } const xhr = new XMLHttpRequest(); const url = `/api/spell/${this._oid}`; xhr.open("GET", url, true); xhr.onload= _ => { const resp = JSON.parse(xhr.responseText); if (!resp.Meta.Success) { const errorElem = document.createElement("h3"); errorElem.classList.add("error"); errorElem.innerHTML = `We can't load this spell (${resp.Meta.Status}) ${resp.Meta.Error}`; this._card.appendChild(errorElem); } else { this._fillData(resp.Data); } } xhr.send(null); } _fillData (dat) { this._title.innerHTML = dat.Name; this._card.classList.add(dat.School.Class); if (dat.Cantrip) { this._subtitle.innerHTML = getGetOrdinal(dat.Level) + " Level Cantrip"; } else { this._subtitle.innerHTML = getGetOrdinal(dat.Level) + " Level " + dat.School.Name; } this._castingTime.innerHTML = dat.CastingTime.Safe; this._range.innerHTML = dat.Range.Safe; this._components.innerHTML = dat.Components.Safe; this._duration.innerHTML = dat.Duration.Safe; this._meta.classList.remove("hidden"); this._description.innerHTML = dat.Description.Safe; } _addEventListeners () { } _removeEventListeners () { } }); function getGetOrdinal(n) { var s=["th","st","nd","rd"], v=n%100; return n+(s[(v-20)%10]||s[v]||s[0]); } <file_sep>/authhandlers.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package main import ( "encoding/json" "fmt" "github.com/HenrySlawniak/spellsluts.com/db" "github.com/HenrySlawniak/spellsluts.com/util" "github.com/go-playground/log" "golang.org/x/oauth2" "gopkg.in/mgo.v2/bson" "io/ioutil" "net/http" "runtime/debug" "strings" ) func debugHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return internalError(w, r, err) } j, _ := json.MarshalIndent(session.Values, "", " ") w.Header().Set("Content-Type", "text/plain") w.Write([]byte(string(j))) w.Write([]byte(fmt.Sprintf("%v", session.Values["userid"]) + "\n")) w.Write([]byte(fmt.Sprintf("%v", session.Values["session-id"]) + "\n")) w.WriteHeader(http.StatusOK) return nil } func authHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return internalError(w, r, err) } if isValidLogin(session) { session.Save(r, w) http.Redirect(w, r, "/auth/debug/", http.StatusFound) } retrievedState := session.Values["state"] if r.URL.Query().Get("state") != retrievedState { return notAuthed(w, r, err) } tok, err := config.Exchange(oauth2.NoContext, r.URL.Query().Get("code")) if err != nil { return badRequest(w, r, err) } client := config.Client(oauth2.NoContext, tok) email, err := client.Get("https://www.googleapis.com/oauth2/v3/userinfo") if err != nil { return badRequest(w, r, err) } defer email.Body.Close() data, err := ioutil.ReadAll(email.Body) if err != nil { return internalError(w, r, err) } session.Values["state"] = nil response := EmailResponse{} err = json.Unmarshal(data, &response) if err != nil { return internalError(w, r, err) } ip := strings.Split(r.RemoteAddr, ":")[0] if ip == "127.0.0.1" { if r.Header.Get("X-Real-IP") != "" { ip = r.Header.Get("X-Real-IP") } } internalSesison := randomString(64) dbSession := db.GetSession() defer dbSession.Close() user, err := GetUserByEmail(response.Email) if err != nil { if response.EmailVerified { user = &SpellUser{ ID: bson.NewObjectId(), Bio: util.NewMarkdownString("", ""), Email: response.Email, Sessions: []string{}, Name: response.Name, FirstName: response.GivenName, LastName: response.FamilyName, Picture: response.Picture, } err = dbSession.DB(db.DB).C("users").Insert(*user) if err != nil { return internalError(w, r, err) } } else { session.AddFlash("You have not verified your email with Google") session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return nil } } err = dbSession.DB(db.DB).C("users").Update(bson.M{"_id": user.ID}, bson.M{"$push": bson.M{"sessions": internalSesison}}) if err != nil { return internalError(w, r, err) } session.Values["userid"] = user.ID.Hex() session.Values["session-id"] = internalSesison session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return nil } func loginHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return internalError(w, r, err) } if isValidLogin(session) { session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return nil } state := randomString(32) session.Values["state"] = state session.Save(r, w) http.Redirect(w, r, getLoginURL(state), http.StatusFound) return nil } func logoutHandler(w http.ResponseWriter, r *http.Request) error { session, err := getSession(r) if err != nil { return internalError(w, r, err) } if !isValidLogin(session) { session.Values = nil session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return nil } user, err := GetUserFromSession(session) if err != nil { return err } for _, sessionID := range user.Sessions { if sessionID == session.Values["session-id"].(string) { err := user.RemoveSession(session.Values["session-id"].(string)) if err != nil { debug.PrintStack() log.Error(err.Error()) } } } session.Values = nil session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return nil } <file_sep>/util/markdown.go // Copyright (c) 2016 <NAME> <https://henry.computer/> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package util import ( "github.com/microcosm-cc/bluemonday" "html/template" ) // NamedMarkdownString encodes a MarkdownString along with a named field // TODO: Why is this here, at some point it made sense to me type NamedMarkdownString struct { Name string Content MarkdownString } // MarkdownString encodes a markdown formatted string // MarkdownString also provides methods for safe and unsafe HTML type MarkdownString struct { Source string Safe string Unsafe string } // NewMarkdownString returns a MarkdownString based on source markdown func NewMarkdownString(src, content string) MarkdownString { return MarkdownString{ Source: src, Safe: string(bluemonday.UGCPolicy().RequireNoFollowOnLinks(true).SanitizeBytes([]byte(content))), Unsafe: string([]byte(content)), } } func (m MarkdownString) String() string { return m.Safe } // HTML returns a user-generated-content safe HTML version of the MarkdownString func (m MarkdownString) HTML() template.HTML { return template.HTML(m.Safe) } // UnsafeHTML returns an unsafe HTML version of the MarkdownString func (m MarkdownString) UnsafeHTML() template.HTML { return template.HTML(m.Unsafe) } <file_sep>/compile.sh #!/bin/bash mkdir -p bin/ go get -v bash -c "go build -ldflags '-w -X main.buildTime=$(date +%Y-%m-%d:%H:%M:%S) -X main.commit=$(git describe --always --dirty=*)' -v ."
384b5229d830e620f561db37460702ccaeecf67c
[ "JavaScript", "Go", "Shell" ]
17
Go
HenrySlawniak/spellsluts.com
d598f77ee2a5673fe477395b81198ea8033b25b9
d5e8bbe198c62ff129543ccdf3c0f2415519691e
refs/heads/master
<repo_name>Evantilton/wordfinder<file_sep>/README.md Word Find Solver Write a program that given a string input of the following form "A T L L F U V D E Y O B Z V D W F B N E D X G H E A N P O R O T V B Y L A L G T D K E A A D O O W D R A H H E L A S P Z A P P E A K H R O F X W L X O W B R G A S O M M B R O K E R M C X G X O U I E O K M Y K W A O E F M R S L S N L R S I I S N P D B C E Q P R I U K U Q T E G R I P E B O Q U I Q S C B P A S D Q P E T X J P S E S B R K R R E U E T T D Z D K L L B J B C B B L E U B I U R F L N H S F H T K R K G H Y A M O J H D N Q A J S Q P L R M U" Will find all 4 letter or longer words. Notes ● The words can go in any direction: up, down, left, or right (not diagonal) ● It should handle arbitrarily sized puzzle inputs. The above is 15x15 but the solution should work just as well with any other size ● The solution can just print out the list of found words, it does not need to print out their position or direction ● You can use any language you like although we would like to be able to run your submission, so please include instructions on compiling/running if you think it’s necessary ● Hint: You may want to use the dictionary that is included on your system ○ For OS X: /usr/share/dict/words Bonus ● Only return the longest valid word in a sequence of letters: ○ Don't return "broke" and "broker": only "broker" ○ Don’t return “hard” and “wood”; only “hardwood” Criteria for Success ● Correctness Does the program work as requested against both the provided input above and additional word find inputs? ● Readability Is the code easy to understand? -- do we feel it would be easy to safely modify the code in the future if needed ● Testability You do not need to write unit tests for this assignment, but we are interested in seeing code that would be easy to write tests for ● Performance This is less important than the other criteria, but a faster program would be a bonus TASK LIST: [x] figure out how long the string is (1x1, 2x2, 15x15), we will need to know that I think. for this I just take the length and find the square root. [] I should probably make sure it only takes in alphbetical characters too. [] have it take each line horizontally forward and backward and put it into an object. [] have it take each line vertically, forward and backward and put it into an object. [] have it take each line diagonally, forward and backward and put it into an object. [] double check that the dictionary works as intended. Dependencies: word-list<file_sep>/index.js const fs = require('fs'); // Returns the path to the word list which is separated by `\n` const wordListPath = require('word-list'); const wordArray = fs.readFileSync(wordListPath, 'utf8').split('\n'); //=> […, 'abmhos', 'abnegate', …] //begin wordFinder function wordFinder(columns, string) { newString = [...string]; let numberOfColumns = columns; newString = newString.filter(function(str) { return /\S/.test(str); }); let numberCharacters = newString.length; console.log("newString", newString); console.log("number of Characters",numberCharacters); console.log("number of columns",numberOfColumns); let horizontalArray = horizontalParser(newString, numberOfColumns); console.log("THIS IS HORIZONTAL ARRAY", horizontalArray); //the array.reverse() method can be used to test the reverse of the lines I need after I successfully run them. let verticalArray = verticalParser(newString, numberOfColumns); console.log("THIS IS VERTICAL ARRAY", verticalArray) } function horizontalParser(newString, numberOfColumns) { let i,j,horizontalArray = [],chunk = numberOfColumns; for (i=0,j=newString.length; i<j; i+=chunk) { horizontalArray.push(newString.slice(i,i+chunk)); } return(horizontalArray); } function verticalParser(newString, numberOfColumns) { let verticalArray = []; for (let i = 0, j = 0; i < newString.length; i++) { j = (i+1)%numberOfColumns; if(!verticalArray[j]) { verticalArray[j]= []; } verticalArray[j].push(newString[i]); } return verticalArray; } wordFinder (15,` A T L L F U V D E Y O B Z V D W F B N E D X G H E A N P O R O T V B Y L A L G T D K E A A D O O W D R A H H E L A S P Z A P P E A K H R O F X W L X O W B R G A S O M M B R O K E R M C X G X O U I E O K M Y K W A O E F M R S L S N L R S I I S N P D B C E Q P R I U K U Q T E G R I P E B O Q U I Q S C B P A S D Q P E T X J P S E S B R K R R E U E T T D Z D K L L B J B C B B L E U B I U R F L N H S F H T K R K G H Y A M O J H D N Q A J S Q P L R M U `) wordFinder (15, ` 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 1 2 3 4 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 1 2 3 4 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 1 2 3 4 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 1 2 3 4 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 1 2 3 4 `)
49555c321aea7bbcac236e8f4782ed64043564f2
[ "Markdown", "JavaScript" ]
2
Markdown
Evantilton/wordfinder
8c53edf0ecedf965ed960478ae29a2c58d090f78
f3d4d34bca3be9242fe3639bbc3e968699ad40c6
refs/heads/master
<file_sep>package main import ( "encoding/json" "fmt" "reflect" "go-game-server/proto" "go-game-server/proto/proto2" "golang.org/x/net/websocket" ) type NetDataConn struct { Connection *websocket.Conn MD5 string } func (this *NetDataConn) PullFromClient() { for { var content string if err := websocket.Message.Receive(this.Connection, &content); err != nil { break } if len(content) == 0 { break } this.SyncMessageFun(content) } return } func (this *NetDataConn) SyncMessageFun(content string) { fmt.Println("content: ", content) protocolData, err := Json2map(content) if err != nil { fmt.Println("解析失败: ", err) } this.HandleCltProtocol(protocolData["protocol"], protocolData["protocol2"], protocolData) } func (this *NetDataConn) HandleCltProtocol(protocol interface{}, protocol2 interface{}, protocolData map[string]interface{}) { switch protocol { case float64(proto.GameDataProto): { this.HandleCltProtocol2(protocol2, protocolData) } case float64(proto.GameDataDBProto): { } default: panic("主协议不存在") } } func (this *NetDataConn) HandleCltProtocol2(protocol2 interface{}, protocolData map[string]interface{}) { switch protocol2 { case float64(proto2.C2SPlayerLoginProto2): { this.PlayerLogin(protocolData) } default: panic("子协议不存在") } return } func (this *NetDataConn) PlayerLogin(protocolData map[string]interface{}) { if protocolData["code"] == nil { panic("主协议 1,子协议 1,登录功能数据错误") } code := protocolData["code"].(string) fmt.Println("code: ", code) data := proto2.S2CPlayerLogin{ Protocol: proto.GameDataProto, Protoco2: proto2.S2CPlayerLoginProto2, PlayerData: nil, } this.PlayerSendMessage(data) return } func (this *NetDataConn) PlayerSendMessage(msg interface{}) { bs, err := json.Marshal(msg) if err != nil { fmt.Println("err: ", err) return } fmt.Println("bs: ", string(bs[0:])) err = websocket.JSON.Send(this.Connection, bs) if err != nil { fmt.Println("err: ", err) return } return } func Json2map(data string) (map[string]interface{}, error) { var result map[string]interface{} err := json.Unmarshal([]byte(data), &result) if err != nil { fmt.Println("err: ", err) return nil, err } return result, nil } func typeof(v interface{}) string { return reflect.TypeOf(v).String() } <file_sep>module go-game-server go 1.15 require ( github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b golang.org/x/net v0.0.0-20210119194325-5f4716e94777 ) <file_sep>package main import ( "fmt" "golang.org/x/net/websocket" ) func funcW(ws *websocket.Conn) { data := ws.Request().URL.Query().Get("data") fmt.Println("data: ", data) conn := &NetDataConn{ Connection: ws, MD5: "", } conn.PullFromClient() } <file_sep>package proto2 const ( _ = iota C2SPlayerLoginProto2 //用户登录请求 S2CPlayerLoginProto2 //用户登录响应 C2SChooseRoomProto2 //选择房间请求 S2CChooseRoomProto2 //选择房间响应 ) type Player struct { UID int PlayerName string OpenID string } type C2SPlayerLogin struct { Protocol int `json:"protocol"` Protoco2 int `json:"protocol2"` Code string `json:"code"` } type S2CPlayerLogin struct { Protocol int Protoco2 int PlayerData *Player } <file_sep>package proto const ( _ = iota GameDataProto // 1 游戏主协议 GameDataDBProto // 2 游戏DB主协议 ) <file_sep>package main import ( "flag" "net/http" "golang.org/x/net/websocket" ) func init() { flag.Set("log_dir", "./log") flag.Set("alsologtostderr", "true") flag.Set("v", "3") flag.Parse() } func main() { http.Handle("/socket", websocket.Handler(funcW)) http.ListenAndServe(":8888", nil) }
87c6a5b78863d99163284f44d983a353166562c9
[ "Go Module", "Go" ]
6
Go
xufei1987/go-game-server
918d047cdeecd0e57c3a18cef4715ccf92efa9de
eba5496a3799c3983f4790757f818069f9ed3688
refs/heads/master
<file_sep>from django.shortcuts import render from django.http import HttpResponseServerError from django.views.generic import ( View, TemplateView, ListView, DetailView ) class HomeView(TemplateView): template_name = "home/index.html" class VistaEmjemplo(TemplateView): template_name = "home/ejemplo.html" def get_context_data(self, **kwargs): context = super(VistaEmjemplo, self).get_context_data(**kwargs) a = 'prueba' print(a/10) return context class Error404View(TemplateView): template_name = "home/error_404.html" class Error505View(TemplateView): template_name = "home/error_500.html" @classmethod def as_error_view(cls): v = cls.as_view() def view(request): r = v(request) r.render() return r return view <file_sep># django from django.urls import path # local from . import views app_name="home_app" urlpatterns = [ # path( '', views.HomeView.as_view(), name="index" ), path( 'ejemplo', views.VistaEmjemplo.as_view(), name="ejemplo" ), ]
42109a80f485ede2c6452d6943ee99f00db308cc
[ "Python" ]
2
Python
neunapp/Error404-500
a5981276c9429b57246506f86e9fb10c64528a66
b2dcdc8258f2f881a37d89cdf43be4bb4e19851e
refs/heads/master
<file_sep>// // ViewController.swift // ZenGarden // // Created by Flatiron School on 6/30/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var swordInStoneImage: UIImageView! @IBOutlet weak var bushImage: UIImageView! @IBOutlet weak var rockImage: UIImageView! @IBOutlet weak var rakeImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() setUpImageView() setConstraints() } func setUpImageView() { rakeImage.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(ViewController.whilePanning))) rockImage.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(ViewController.whilePanning))) bushImage.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(ViewController.whilePanning))) swordInStoneImage.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(ViewController.whilePanning))) } func setConstraints() { view.removeConstraints(view.constraints) view.translatesAutoresizingMaskIntoConstraints = false swordInStoneImage.translatesAutoresizingMaskIntoConstraints = false bushImage.translatesAutoresizingMaskIntoConstraints = false rockImage.translatesAutoresizingMaskIntoConstraints = false rakeImage.translatesAutoresizingMaskIntoConstraints = false rakeImage.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: 0).active = true rakeImage.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: 0).active = true rakeImage.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: (rakeImage.frame.size.height / rakeImage.frame.size.width) * 0.25).active = true rakeImage.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: (rakeImage.frame.size.width / rakeImage.frame.size.height) * 0.25).active = true rockImage.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: 0).active = true rockImage.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: 0).active = true rockImage.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: (rockImage.frame.size.height / rockImage.frame.size.width) * 0.25).active = true rockImage.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: (rockImage.frame.size.width / rockImage.frame.size.height) * 0.25).active = true swordInStoneImage.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: 0).active = true swordInStoneImage.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: 0).active = true swordInStoneImage.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: (swordInStoneImage.frame.size.height / swordInStoneImage.frame.size.width) * 0.25).active = true swordInStoneImage.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: (swordInStoneImage.frame.size.width / swordInStoneImage.frame.size.height) * 0.25).active = true bushImage.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: 0).active = true bushImage.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: 0).active = true bushImage.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: (bushImage.frame.size.height / bushImage.frame.size.width) * 0.25).active = true bushImage.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: (bushImage.frame.size.width / bushImage.frame.size.height) * 0.25).active = true } func whilePanning(sender: UIPanGestureRecognizer) { let translation = sender.translationInView(self.view) guard let startCenterX = sender.view?.center.x else { return } guard let startCenterY = sender.view?.center.y else { return } let endCenterX = startCenterX + translation.x let endCenterY = startCenterY + translation.y sender.view?.center = CGPointMake(endCenterX, endCenterY) sender.setTranslation(CGPointZero, inView: self.view) defer { checkForWin() } } func checkForWin() { guard bushImage.distanceToView(rakeImage) <= 80 else { return } guard swordInStoneImage.frame.minX <= 0 && swordInStoneImage.frame.maxY >= view.frame.maxY || swordInStoneImage.frame.minX <= 5 && swordInStoneImage.frame.minY <= 20 else { return } guard swordInStoneImage.distanceToView(rockImage) >= Double(view.frame.maxY / 1.15) else { return } presentWin() } func presentWin() { let alertController = UIAlertController(title: "Congrats", message: "You won!", preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(OKAction) self.presentViewController(alertController, animated: true, completion: nil) setConstraints() } } extension UIView { func distanceToView(sender:UIView) -> Double { return sqrt(pow(Double(sender.center.x - self.center.x), 2) + pow(Double(sender.center.y - self.center.y), 2)) } }
eaae50e56b74365b1e68df4c8d4cd5625d044f09
[ "Swift" ]
1
Swift
Cordavi/swift-zenGarden-lab-ios-0616
dfdfafb6281aa5f52fd3daf3ca2e510d7d27c548
b1cedf9275ce09dff2f7750dae5ba35db8a3df43
refs/heads/master
<repo_name>Kolpa/DeathmicChatbot<file_sep>/BobDeathmic/ChatCommands/Args/ChatCommandOutput.cs using BobDeathmic.Eventbus; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands.Args { public class ChatCommandOutput { public EventType Type { get; set; } public dynamic EventData { get; set; } public bool ExecuteEvent { get; set; } } } <file_sep>/BobDeathmic/Controllers/StreamCommandsController.cs using BobDeathmic.Data; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Models; using BobDeathmic.ViewModels.ReactDataClasses.Table; using BobDeathmic.ViewModels.ReactDataClasses.Table.Columns; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Controllers { public class StreamCommandsController : Controller { private readonly ApplicationDbContext _context; public StreamCommandsController(ApplicationDbContext context) { _context = context; } // GET: StreamCommands public async Task<IActionResult> Index() { //await _context.StreamCommand.Include(sc => sc.stream).ToListAsync() return View(); } [Authorize(Roles = "User,Dev,Admin")] public async Task<string> Data() { Table table = new Table(); Row Header = new Row(false, true); Header.AddColumn(new TextColumn(0, "Command", true)); Header.AddColumn(new TextColumn(1, "Text", false)); Header.AddColumn(new TextColumn(2, "Mode", false)); Header.AddColumn(new TextColumn(3, "AutoInterval", false)); Header.AddColumn(new TextColumn(4, "Stream", true)); Header.AddColumn(new TextColumn(5, "")); Header.AddColumn(new TextColumn(6, "")); table.AddRow(Header); foreach (var command in _context.StreamCommand.Include(sc => sc.stream)) { Row commandrow = new Row(); commandrow.AddColumn(new TextColumn(0, command.name)); commandrow.AddColumn(new TextColumn(1, command.response)); commandrow.AddColumn(new TextColumn(2, command.Mode.ToString())); commandrow.AddColumn(new TextColumn(3, command.AutoInverval.ToString())); commandrow.AddColumn(new TextColumn(4, command.stream.StreamName)); commandrow.AddColumn(new ObjectDeleteColumn(5, "Löschen", command.DeleteLink(), command.DeleteText())) ; commandrow.AddColumn(new StreamCommandEditColumn(6, "Edit",command.ID)) ; table.AddRow(commandrow); } return table.getJson(); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<String> GetCreateData() { try { var data = new BobDeathmic.ViewModels.ReactDataClasses.Other.StreamCommandEditData(_context.StreamModels.ToList()); return data.ToJSON(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return ""; } } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<String> GetEditData(int streamCommandID) { try { var streamcommand = _context.StreamCommand.Where(x => x.ID == streamCommandID).Include(x => x.stream).FirstOrDefault(); if (streamcommand != null) { var data = new BobDeathmic.ViewModels.ReactDataClasses.Other.StreamCommandEditData(streamcommand, _context.StreamModels.ToList()); return data.ToJSON(); } return ""; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return ""; } } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task<bool> CreateCommand(string Name, string Response, StreamCommandMode Mode, int StreamID) { try { var command = new StreamCommand(); command.name = Name; command.response = Response; command.Mode = Mode; command.streamID = StreamID; _context.StreamCommand.Add(command); _context.SaveChanges(); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return false; } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task<bool> SaveCommand(int ID, string Name,string Response, StreamCommandMode Mode, int StreamID) { try { var command = _context.StreamCommand.Where(x => x.ID == ID).FirstOrDefault(); if (command != null) { command.name = Name; command.response = Response; command.Mode = Mode; command.streamID = StreamID; _context.SaveChanges(); return true; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return false; } // GET: StreamCommands/Create public IActionResult Create() { ViewData["Streams"] = _context.StreamModels.ToList(); ViewData["Modes"] = new List<StreamCommandMode> { StreamCommandMode.Manual, StreamCommandMode.Auto }; return View(); } // POST: StreamCommands/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ID,name,response,Mode,AutoInverval,streamID")] StreamCommand streamCommand) { if (ModelState.IsValid) { _context.Add(streamCommand); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(streamCommand); } // GET: StreamCommands/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var streamCommand = await _context.StreamCommand.FindAsync(id); if (streamCommand == null) { return NotFound(); } streamCommand.SetSelectableStreams(_context.StreamModels.Select(a => new SelectListItem() { Value = a.ID.ToString(), Text = a.StreamName }).ToList()); ViewData["Streams"] = _context.StreamModels.ToList(); ViewData["Modes"] = new List<StreamCommandMode> { StreamCommandMode.Manual, StreamCommandMode.Auto, StreamCommandMode.Random }; return View(streamCommand); } // POST: StreamCommands/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("ID,name,response,Mode,AutoInverval,streamID")] StreamCommand streamCommand) { if (id != streamCommand.ID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(streamCommand); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StreamCommandExists(streamCommand.ID)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(streamCommand); } // GET: StreamCommands/Delete/5 [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<bool> Delete(int CommandID) { if (CommandID == null) { return false; } var streamCommand = await _context.StreamCommand .FirstOrDefaultAsync(m => m.ID == CommandID); if (streamCommand != null) { _context.StreamCommand.Remove(streamCommand); _context.SaveChanges(); return true; } return false; } private bool StreamCommandExists(int id) { return _context.StreamCommand.Any(e => e.ID == id); } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Other/SubscribableStream.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Other { public class SubscribableStream { public string Name { get; set; } public int StreamID { get; set; } public SubscribableStream(string name, int id) { Name = name; StreamID = id; } } } <file_sep>/BobDeathmic/wwwroot/js/site.js // Write your JavaScript code. jQuery(".submenuopener").click(function () { if (jQuery(this).closest(".menuitem").find(".submenu").height() === 0) { jQuery(this).closest(".menuitem").addClass("open"); jQuery(this).closest(".menuitem").find(".submenu").height(jQuery(this).closest(".menuitem").find(".heightgiver").outerHeight()); ChangeMobileHeight(jQuery(this).closest(".menuitem").find(".heightgiver").outerHeight()); } else { jQuery(this).closest(".menuitem").find(".submenu").height(0); jQuery(this).closest(".menuitem").removeClass("open"); ChangeMobileHeight(-jQuery(this).closest(".menuitem").find(".heightgiver").outerHeight()); } }); function ChangeMobileHeight(value) { if (jQuery(window).width() < 768) { jQuery(".mobile_overflowcontainer").height(jQuery(".mobile_overflowcontainer").height() + value); } } jQuery(".mobile_nav_opener").click(function () { if (jQuery(".mobile_overflowcontainer").height() == 0) { jQuery(".mobile_overflowcontainer").height(jQuery(".mobile_overflowcontainer > div").outerHeight()); } else { jQuery(".mobile_overflowcontainer").height(0); } }); jQuery(document).ready(function () { jQuery(window).on("resize", handleMobileSwitch); jQuery(window).ready(handleMobileSwitch); function handleMobileSwitch() { if (jQuery(window).width() < 768) { jQuery(".mobile_overflowcontainer").height(0); } else { jQuery(".mobile_overflowcontainer").css("height", "auto"); } } })<file_sep>/BobDeathmic/Services/Streams/Checker/Twitch/TwitchChecker.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Eventbus; using BobDeathmic.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TwitchLib.Api; using BobDeathmic.Services; using BobDeathmic; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using TwitchLib.Api.Helix.Models.Streams; namespace BobDeathmic.Services.Streams.Checker.Twitch { public class TwitchChecker : BackgroundService { //private readonly IEventBus _eventbus; protected TwitchAPI api; private readonly IServiceScopeFactory _scopeFactory; private System.Timers.Timer _timer; private bool _inProgress; private IEventBus _eventBus; public IConfiguration Configuration { get; } public TwitchChecker(IServiceScopeFactory scopeFactory, IEventBus eventBus) { _scopeFactory = scopeFactory; _eventBus = eventBus; api = new TwitchAPI(); using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var token = _context.SecurityTokens.Where(x => x.service == TokenType.Twitch).FirstOrDefault(); if(token != null) { api.Settings.AccessToken = token.token; api.Settings.ClientId = token.ClientID; } } } public override Task StopAsync(CancellationToken cancellationToken) { return base.StopAsync(cancellationToken); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); SecurityToken data = null; while (data == null) { data = _context.SecurityTokens.Where(securitykey => securitykey.service == TokenType.Twitch).FirstOrDefault(); if (data == null) { //Just to prevent if from sleeping when it has data await Task.Delay(10000, stoppingToken); } } if (data != null) { api.Settings.ClientId = data.ClientID; api.Settings.AccessToken = data.token; } } _timer = new System.Timers.Timer(10000); _timer.Elapsed += (sender, args) => CheckOnlineStreams(); _timer.Start(); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } } public bool TriggerUpTime(Data.DBModels.StreamModels.Stream stream) { if (stream.UpTimeInterval > 0) { if (stream.Started > stream.LastUpTime) { stream.LastUpTime = stream.Started; } var UpTime = DateTime.Now - stream.LastUpTime; if (UpTime.TotalMinutes > stream.UpTimeInterval) { return true; } } return false; } public TimeSpan GetUpTime(Data.DBModels.StreamModels.Stream stream) { return DateTime.Now - stream.Started; } public async Task CheckOnlineStreams() { try { if (!_inProgress) { _inProgress = true; await FillClientIDs(); GetStreamsResponse StreamsData = await GetStreamData(); List<string> OnlineStreamIDs = StreamsData.Streams.Select(x => x.UserId).ToList(); await SetStreamsOffline(OnlineStreamIDs); if (StreamsData.Streams.Count() > 0) { await SetStreamsOnline(OnlineStreamIDs, StreamsData); } _inProgress = false; } } catch (Exception ex) { _inProgress = false; } return; } private async Task FillClientIDs() { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var Streams = _context.StreamModels; var StreamNameList = Streams.Where(x => string.IsNullOrEmpty(x.UserID)).Select(x => x.StreamName).ToList(); if (StreamNameList.Any()) { var userdata = await api.Helix.Users.GetUsersAsync(logins: StreamNameList); foreach (var user in userdata.Users) { Data.DBModels.StreamModels.Stream stream = Streams.Where(x => x.StreamName.ToLower() == user.Login.ToLower()).FirstOrDefault(); stream.UserID = user.Id; } _context.SaveChanges(); } } } private async Task<GetStreamsResponse> GetStreamData() { try { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var Streams = _context.StreamModels; List<string> StreamIdList = Streams.Where(x => !string.IsNullOrEmpty(x.UserID) && x.Type == StreamProviderTypes.Twitch).Select(x => x.UserID).ToList(); if (StreamIdList.Any()) { return await api.Helix.Streams.GetStreamsAsync(userIds: StreamIdList); } } } catch(TwitchLib.Api.Core.Exceptions.BadScopeException ex) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var token = _context.SecurityTokens.Where(x => x.service == TokenType.Twitch).FirstOrDefault(); if (token != null) { api.Settings.AccessToken = token.token; api.Settings.ClientId = token.ClientID; } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return null; } string[] RandomDiscordRelayChannels = { "stream_1", "stream_2", "stream_3" }; private async Task<bool> SetStreamsOffline(List<string> OnlineStreamIDs) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var Streams = _context.StreamModels.Where(s => !OnlineStreamIDs.Contains(s.UserID)); foreach (Data.DBModels.StreamModels.Stream stream in Streams.Where(x => x.StreamState != StreamState.NotRunning && x.Type == StreamProviderTypes.Twitch)) { if(DateTime.Now.Subtract(stream.Started) > TimeSpan.FromSeconds(600)) { Console.WriteLine("Stream offline"); stream.StreamState = StreamState.NotRunning; if (RandomDiscordRelayChannels.Contains(stream.DiscordRelayChannel)) { stream.DiscordRelayChannel = "An"; } } } _context.SaveChanges(); } return true; } private async Task<bool> SetStreamsOnline(List<string> OnlineStreamIDs, GetStreamsResponse StreamsData) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var Streams = _context.StreamModels.Where(s => OnlineStreamIDs.Contains(s.UserID) && s.Type == StreamProviderTypes.Twitch).Include(x => x.StreamSubscriptions).ThenInclude(y => y.User); Boolean write = false; foreach (Data.DBModels.StreamModels.Stream stream in Streams) { TwitchLib.Api.Helix.Models.Streams.Stream streamdata = StreamsData.Streams.Single(sd => sd.UserId == stream.UserID); if (stream.StreamState == StreamState.NotRunning) { stream.StreamState = StreamState.Running; stream.Started = streamdata.StartedAt.ToLocalTime(); write = true; if(stream.DiscordRelayChannel == "An") { stream.DiscordRelayChannel = getRandomRelayChannel(); } NotifyUsers(stream, streamdata); } } if (write) { _context.SaveChanges(); } } return true; } private async Task NotifyUsers(Data.DBModels.StreamModels.Stream stream, TwitchLib.Api.Helix.Models.Streams.Stream streamdata) { int longDelayCounter = 0; foreach (string username in stream.GetActiveSubscribers()) { longDelayCounter++; if (longDelayCounter == 5) { longDelayCounter = 0; await Task.Delay(2000); } _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs() { Message = stream.StreamStartedMessage(streamdata.Title, GetStreamUrl(stream)), RecipientName = username }); await Task.Delay(100); } } private string getRandomRelayChannel() { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); string[] occupiedchannels = _context.StreamModels.Where(x => RandomDiscordRelayChannels.Contains(x.DiscordRelayChannel)).Select(x => x.DiscordRelayChannel).ToArray(); return RandomDiscordRelayChannels.Except(occupiedchannels).FirstOrDefault(); } } private string GetStreamUrl(Data.DBModels.StreamModels.Stream stream) { if (string.IsNullOrEmpty(stream.Url)) { stream.Url = "https://www.twitch.tv/" + stream.StreamName; } return stream.Url; } } } <file_sep>/BobDeathmic/ChatCommands/Strawpoll.cs using BobDeathmic.Args; using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data.Enums; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.JSONObjects; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands { public class Strawpoll : ICommand { public string Trigger => "!strawpoll"; public string Alias => "!poll"; public string Description => "Erstellt einen Strawpoll (!strawpoll q='Frage' o='Option1|Option2' [m='true/false'])"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { if (args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias)) { return CommandEventType.Strawpoll; } return CommandEventType.None; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { if(args.elevatedPermissions) { var strawpollargs = extractStrawpollData(args.Message); strawpollargs.StreamName = args.ChannelName; switch (args.Type) { case ChatType.Discord: throw new NotImplementedException("Discord has not yet been implemented for Strawpollcommand"); break; case ChatType.Twitch: strawpollargs.Type = StreamProviderTypes.Twitch; break; default: return null; } return new ChatCommandOutput() { Type = Eventbus.EventType.StrawPollRequested, ExecuteEvent = true, EventData = strawpollargs }; } return null; } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } private StrawPollRequestEventArgs extractStrawpollData(string message) { var questionRegex = Regex.Match(message, @"q=\'(.*?)\'"); var optionsRegex = Regex.Match(message, @"o=\'(.*?)\'"); var multiRegex = Regex.Match(message, @"m=\'(.*?)\'"); StrawPollPostData values = null; string question = ""; List<string> Options = new List<string>(); bool multi = false; if (questionRegex.Success && optionsRegex.Success) { Options = optionsRegex.Value.Replace("o='", "").Replace("'", "").Split('|').ToList(); question = questionRegex.Value.Replace("q='", "").Replace("'", ""); if (multiRegex.Success) { switch (multiRegex.Value) { case "true": case "j": multi = true; break; } } } else { // for the forgetfull string[] parameters = message.Replace("!strawpoll ", "").Split('|'); question = parameters[0]; for (var i = 1; i < parameters.Count(); i++) { Options.Add(parameters[i]); } } StrawPollRequestEventArgs arg = new StrawPollRequestEventArgs(); arg.Answers = Options.ToArray(); arg.Question = question.Trim(); arg.multiple = multi; return arg; } } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/MessageArgs.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Args { public class MessageArgs { public string RecipientName { get; set; } public string channelName { get; set; } public string Message { get; set; } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/EventDateFinder/Vote/VoteReactData.cs using BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.Vote; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic; namespace BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.Vote { public class VoteReactData { public List<EventDateData> Header { get; set; } } } <file_sep>/BobDeathmic/Services/Strawpoll/JSONDataTypes/StrawPollResponseData.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.JSONObjects { public class StrawPollResponseData { public double id { get; set; } public string title { get; set; } public string[] options { get; set; } public int[] votes { get; set; } public bool multi { get; set; } public string dupcheck { get; set; } public string captcha { get; set; } public string Url() { return "https://www.strawpoll.me/" + id; } } } <file_sep>/BobDeathmic/Cron/Setup/IScheduledTask.cs using BobDeathmic; using BobDeathmic.Cron.Setup; using BobDeathmic.Services; using BobDeathmic.Services.Helper; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Cron.Setup { public interface IScheduledTask { string Schedule { get; } Task ExecuteAsync(CancellationToken cancellationToken); } } <file_sep>/BobDeathmic/Data/DBModels/StreamModels/StreamCommand.cs using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.StreamModels { public class StreamCommand { public int ID { get; set; } [Required] [DataType(DataType.Text)] [MinLength(3)] public string name { get; set; } [Required] [MinLength(3)] public string response { get; set; } public StreamCommandMode Mode { get; set; } public int AutoInverval { get; set; } public DateTime LastExecution { get; set; } [Required] public int streamID { get; set; } public Stream stream { get; set; } private List<SelectListItem> SelectableStreams { get; set; } public List<SelectListItem> GetSelectableStreams() { return SelectableStreams; } public void SetSelectableStreams(List<SelectListItem> List) { SelectableStreams = List; } public string DeleteLink() { return "StreamCommands/Delete?CommandID=" + ID; } public string DeleteText() { return "Bist dir sicher den Command löschen zu wollen?"; } } public enum StreamCommandMode { Auto = 0, Manual = 1, Random = 2 } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/EventDateFinder/OverView/ChatUser.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic; namespace BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.OverView { public class ChatUser { public string Name; public int key; } } <file_sep>/BobDeathmic/Data/Enums/Stream/StreamProviderTypes.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.Enums.Stream { public enum StreamProviderTypes { Twitch = 1, Mixer = 2, DLive = 3, None = 4 } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/Table/Columns/StreamDeleteColumn.jsx class StreamDeleteColumn extends React.Component { constructor(props) { super(props); this.handleDeleteClick = this.handleDeleteClick.bind(this); this.handleCancelClick = this.handleCancelClick.bind(this); this.handleToggleDeleteForm = this.handleToggleDeleteForm.bind(this); this.state = { Open: false }; } handleCancelClick(e) { this.setState({ Open: false }); } handleDeleteClick(e) { const xhr = new XMLHttpRequest(); var thisreference = this; xhr.open('GET', "/Stream/DeleteStream?streamID=" + this.props.data.StreamID, true); xhr.onload = function () { if (xhr.responseText !== false) { this.setState({ Open: true }); window.dispatchEvent(new Event('updateTable')); } }; xhr.send(); } handleToggleDeleteForm(e) { this.setState({ Open: true }); } render() { if (this.props.data !== undefined) { if (this.state.Open) { return <td> {this.props.data.Text} <div className="shadowlayer"></div> <div className="statictest grid column-4 row-3"> <h1 className="deleteText">Bist dir sicher den Stream löschen zu wollen?</h1> <span onClick={this.handleDeleteClick} className="btn btn_primary deletebtn">Endgültig löschen</span> <span onClick={this.handleCancel} className="btn btn_primary canceldeletebtn">Abbrechen</span> </div> </td>; } else { return <td className="pointer" onClick={this.handleToggleDeleteForm}> {this.props.data.Text} </td>; } } else { return null; } } } <file_sep>/BobDeathmic/Controllers/DownloadController.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MimeKit; namespace BobDeathmic.Controllers { public class DownloadController : Controller { private IHostingEnvironment env; public DownloadController(IHostingEnvironment env) { this.env = env; } [Authorize(Roles = "Dev,Admin")] public IActionResult Index() { return View(); } [HttpPost] [Authorize(Roles = "Dev,Admin")] [RequestSizeLimit(60_914_560)] public async Task<bool> UploadAPKFile(List<IFormFile> Files) { long size = Files.Sum(f => f.Length); foreach (var formFile in Files) { if (formFile.Length > 0) { var filePath = Path.Combine(new string[] { env.WebRootPath, "Downloads","APK", formFile.FileName }); using (var stream = System.IO.File.Create(filePath)) { await formFile.CopyToAsync(stream); } } } // Process uploaded files // Don't rely on or trust the FileName property without validation. return true; } [HttpGet] public IActionResult DownloadTest(string FileName) { var filePath = Path.Combine(new string[] { env.WebRootPath, "Downloads", "character paladin.png" }); return PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath)); } } }<file_sep>/BobDeathmic/Services/Twitch/TwitchAPICalls.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Eventbus; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using TwitchLib.Api; namespace BobDeathmic.Services { public class TwitchAPICalls : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly IEventBus _eventBus; private readonly IConfiguration _configuration; public TwitchAPICalls(IServiceScopeFactory scopeFactory, IEventBus eventBus, IConfiguration configuration) { _scopeFactory = scopeFactory; _eventBus = eventBus; _configuration = configuration; } protected async override Task ExecuteAsync(CancellationToken stoppingToken) { _eventBus.StreamTitleChangeRequested += StreamTitleChangeRequested; while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } } private async Task<string> RefreshToken(string streamname) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); Stream stream = _context.StreamModels.Where(sm => sm.StreamName.ToLower().Equals(streamname) && sm.Type == StreamProviderTypes.Twitch).FirstOrDefault(); if (stream != null && stream.RefreshToken != null && stream.RefreshToken != "") { var httpclient = new HttpClient(); string baseUrl = _configuration.GetValue<string>("WebServerWebAddress"); string url = $"https://id.twitch.tv/oauth2/token?grant_type=refresh_token&refresh_token={stream.RefreshToken}&client_id={stream.ClientID}&client_secret={stream.Secret}"; var response = await httpclient.PostAsync(url, new StringContent("", System.Text.Encoding.UTF8, "text/plain")); var responsestring = await response.Content.ReadAsStringAsync(); JSONObjects.TwitchRefreshTokenData refresh = JsonConvert.DeserializeObject<JSONObjects.TwitchRefreshTokenData>(responsestring); if (refresh.error == null) { stream.AccessToken = refresh.access_token; stream.RefreshToken = refresh.refresh_token; _context.SaveChanges(); return refresh.access_token; } } } return ""; } private async void StreamTitleChangeRequested(object sender, StreamTitleChangeArgs e) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); Stream stream = _context.StreamModels.Where(sm => sm.StreamName.ToLower().Equals(e.StreamName.ToLower())).FirstOrDefault(); if (stream != null && stream.ClientID != null && stream.ClientID != "" && stream.AccessToken != null && stream.AccessToken != "") { TwitchAPI api = new TwitchAPI(); api.Settings.ClientId = stream.ClientID; api.Settings.AccessToken = stream.AccessToken; string message = ""; try { if (e.Game != "" && e.Title != "") { var test = await api.V5.Channels.UpdateChannelAsync(channelId: stream.UserID, status: e.Title, game: e.Game); if (test.Game == e.Game && test.Status == e.Title) { message = "Stream Updated"; } else { message = "Error while updating"; } } if (e.Game != "" && e.Title == "") { var test = await api.V5.Channels.UpdateChannelAsync(channelId: stream.UserID, game: e.Game); //Does not actually work as request just returns the entered game irrelevant of actual change (always returns true) if(test.Game == e.Game) { message = "Game Updated"; } else { message = "Twitch game mismatch"; } } if (e.Game == "" && e.Title != "") { var test = await api.V5.Channels.UpdateChannelAsync(channelId: stream.UserID, status: e.Title); if (test.Status == e.Title) { message = "Title Updated"; } else { message = "Title not Updated"; } } } catch (Exception ex) when (ex is TwitchLib.Api.Core.Exceptions.InvalidCredentialException || ex is TwitchLib.Api.Core.Exceptions.BadScopeException) { api.Settings.AccessToken = await RefreshToken(stream.StreamName); if (api.Settings.AccessToken != "") { if (e.Game != "" && e.Title != "") { var test = await api.V5.Channels.UpdateChannelAsync(channelId: stream.UserID, status: e.Title, game: e.Game); } if (e.Game != "" && e.Title == "") { var test = await api.V5.Channels.UpdateChannelAsync(channelId: stream.UserID, game: e.Game); } if (e.Game == "" && e.Title != "") { var test = await api.V5.Channels.UpdateChannelAsync(channelId: stream.UserID, status: e.Title); } } } _eventBus.TriggerEvent(EventType.RelayMessageReceived, new Args.RelayMessageArgs() { SourceChannel = stream.DiscordRelayChannel, StreamType = StreamProviderTypes.Twitch, TargetChannel = stream.StreamName, Message = message }); } else { _eventBus.TriggerEvent(EventType.RelayMessageReceived, new Args.RelayMessageArgs() { SourceChannel = stream.DiscordRelayChannel, StreamType = StreamProviderTypes.Twitch, TargetChannel = stream.StreamName, Message = "Stream can't be updated no Authorization key detected." }); } } return; } } } <file_sep>/BobDeathmic/Controllers/QuoteController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.Data; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using BobDeathmic.ViewModels.ReactDataClasses.Table; using BobDeathmic.ViewModels.ReactDataClasses.Table.Columns; namespace BobDeathmic.Controllers { public class QuoteController : Controller { private readonly ApplicationDbContext _context; public QuoteController(ApplicationDbContext context) { _context = context; } [Authorize(Roles = "User,Dev,Admin")] public IActionResult Index() { return View(); } [Authorize(Roles = "User,Dev,Admin")] public async Task<string> QuotesData() { Table table = new Table(); Row Header = new Row(false, true); Header.AddColumn(new TextColumn(0,"Streamer",true)); Header.AddColumn(new TextColumn(1,"Erstellt",false)); Header.AddColumn(new TextColumn(2,"Quote", false)); Header.AddColumn(new TextColumn(3,"ID", false)); table.AddRow(Header); foreach(var quote in _context.Quotes) { Row quoterow = new Row(); quoterow.AddColumn(new TextColumn(0, quote.Streamer)); quoterow.AddColumn(new TextColumn(1, quote.Created.ToString("dd MMMM yyyy"))); quoterow.AddColumn(new TextColumn(2, quote.Text)); quoterow.AddColumn(new TextColumn(3, quote.Id.ToString())); table.AddRow(quoterow); } return table.getJson(); } } }<file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/StreamSubColumn.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class StreamSubColumn : Column { public string ReactComponentName { get { return "StreamSubColumn"; } } public int key { get; set; } public bool Status { get; set; } public int SubID { get; set; } public StreamSubColumn(int key, bool Status,int SubID) { this.key = key; this.Status = Status; this.canSort = false; this.SubID = SubID; } } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/StreamEventArgs.cs using BobDeathmic.Data.Enums.Relay; using BobDeathmic.Data.Enums.Stream; using System; namespace BobDeathmic.Args { public class StreamEventArgs { public string stream; public string game; //state 1:started;2:running;3:stopped; //TODO: Change state to Database.Classes.StreamState public StreamState state; public string link; public string Notification; public RelayState relayactive; public StreamProviderTypes StreamType; public bool PostUpTime; public TimeSpan Uptime; } } <file_sep>/README.md # DeathmicChatbot ein Chatbot für deathmic's irc Setup guide TODO Information Currently Rewriting adding Unit Tests and Reorganizing in Progress in UnitTestAndRefactor Branch <file_sep>/BobDeathmic/wwwroot/ReactComponents/GiveAway/Admin/ParticipantList.jsx class ParticipantList extends React.Component { constructor(props) { super(props); } render() { let key = 0; let curthis = this; const participants = this.props.Participants.map(function (item) { key++; return ( <li key={key}> <h5>{item}{curthis.props.currentWinners.includes(item) && <i style={{color: "gold"}} className="fas fa-crown ml-2"/>}</h5> </li> ); }); return ( <div> <h2>Teilnehmer</h2> <ol> {participants} </ol> </div> ); } } <file_sep>/BobDeathmic/Data/DBModels/Quote/Quote.cs using System; using System.ComponentModel.DataAnnotations; namespace BobDeathmic.Data.DBModels.Quote { public class Quote { public int Id { get; set; } [Required] public string Streamer { get; set; } [Required] public DateTime Created { get; set; } [Required] public string Text { get; set; } public override string ToString() { return $"\"{Text}\" - {Streamer}, {Created:MMMM yyyy} (ID {Id})"; } } }<file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/StreamEditColumn.cs using BobDeathmic.Data.DBModels.Relay; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class StreamEditColumn: Column { public string ReactComponentName { get { return "StreamEditColumn"; } } public int key { get; set; } public string Text { get; set; } public int StreamID { get; set; } public StreamEditColumn(int key, string Text, Stream stream) { this.key = key; this.Text = Text; this.canSort = false; this.StreamID = stream.ID; } } public class StreamEditData { public string StreamName { get; set; } public string[] StreamTypes { get; } public StreamProviderTypes Type { get; set; } public string RelayChannel { get; set; } public string[] RelayChannels { get; } public int UpTimeInterval { get; set; } public int QuoteInterval { get; set; } public StreamEditData(Stream stream,RelayChannels[] channels) { this.StreamTypes = stream.EnumStreamTypes().ToArray(); this.Type = stream.Type; this.UpTimeInterval = stream.UpTimeInterval; this.QuoteInterval = stream.QuoteInterval; } } } <file_sep>/BobDeathmic/ChatCommands/Args/ChatCommandArguments.cs using BobDeathmic.Data.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands.Args { public class ChatCommandInputArgs { public string Message { get; set; } public string Sender { get; set; } public ChatType Type {get; set;} public string ChannelName { get; set; } public bool elevatedPermissions { get; set; } } } <file_sep>/BobDeathmic/Services/Strawpoll/JSONDataTypes/StrawPollPostData.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.JSONObjects { public class StrawPollPostData { public string title { get; set; } public string[] options { get; set; } public bool multi { get; set; } } } <file_sep>/BobDeathmic/ChatCommands/Setup/CommandEventType.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands.Setup { public enum CommandEventType { TwitchTitle = 1, Strawpoll = 2, None = 0 } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/StreamTitleChangeArgs.cs using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Args { public class StreamTitleChangeArgs { public StreamProviderTypes Type { get; set; } public string StreamName { get; set; } public string Message { get; set; } public string Game { get; set; } public string Title { get; set; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinder/Vote/Calendar.jsx class Calendar extends React.Component { constructor(props) { super(props); this.state = { data: [], eventEmitter: new EventEmitter(), mode: "default" }; this.changeMode = this.changeMode.bind(this); } componentWillMount() { var thisreference = this; const xhr = new XMLHttpRequest(); xhr.open('GET', "/Events/GetEventDates/" + this.props.ID, true); xhr.onload = function () { thisreference.setState({ data: JSON.parse(xhr.responseText) }); }; xhr.send(); } changeMode(event) { this.setState({ mode: event.target.value }); } render() { if (this.state.data.Header !== undefined && this.state.data.Header.length > 0) { var tempthis = this; var headerNodes = this.state.data.Header.map(function (Header) { return <EventDate mode={tempthis.state.mode} key={Header.Date + Header.Time} Data={Header}/>; }); return ( <div> <select className="ml-3 mb-5" onChange={this.changeMode}> <option value="default">Standard</option> <option value="fallback">Mobile Fallback</option> </select> <div className="EventDateContainer"> {headerNodes} </div> </div> ); } else { return <span>Loading</span>; } } } <file_sep>/BobDeathmic/Controllers/StreamController.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Eventbus; using BobDeathmic.Models; using BobDeathmic.ViewModels.ReactDataClasses.Table; using BobDeathmic.ViewModels.ReactDataClasses.Table.Columns; using BobDeathmic.ViewModels.StreamModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace BobDeathmic.Controllers { public class StreamController : Controller { private readonly ApplicationDbContext _context; private readonly IConfiguration _configuration; private readonly IEventBus _eventBus; public StreamController(ApplicationDbContext context, IConfiguration configuration, IEventBus eventBus) { _context = context; _configuration = configuration; _eventBus = eventBus; } [Authorize(Roles = "User,Dev,Admin")] public IActionResult Index() { return RedirectToAction(nameof(Status)); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Status() { StreamListDataModel model = new StreamListDataModel(); model.StreamList = await _context.StreamModels.ToListAsync(); model.StatusMessage = StatusMessage; return View(model); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Verwaltung() { return View(); StreamListDataModel model = new StreamListDataModel(); model.StreamList = await _context.StreamModels.ToListAsync(); model.StatusMessage = StatusMessage; return View(model); } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task<bool> SaveStreamEdit(int StreamID, string StreamName,StreamProviderTypes Type,int UpTime,int Quote,string Relay) { try { var stream = _context.StreamModels.Where(x => x.ID == StreamID).FirstOrDefault(); if (stream != null) { stream.StreamName = StreamName; stream.Type = Type; stream.UpTimeInterval = UpTime; stream.QuoteInterval = Quote; stream.DiscordRelayChannel = Relay; _context.SaveChanges(); return true; } }catch(Exception ex) { Console.WriteLine(ex.ToString()); } return false; } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<String> GetStreamEditData(int streamID) { try { var stream = _context.StreamModels.Where(x => x.ID == streamID).FirstOrDefault(); if (stream != null) { var data = new BobDeathmic.ViewModels.ReactDataClasses.Other.StreamEditData(stream, _context.RelayChannels.Select(x => x.Name).ToList()); return data.ToJSON(); } return ""; } catch(Exception ex) { Console.WriteLine(ex.ToString()); return ""; } } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<String> RelayChannels() { List<string> channels = new List<string>(); channels.Add("Aus"); channels.Add("An"); channels.AddRange(_context.RelayChannels.Select(x => x.Name).ToList()); return JsonConvert.SerializeObject(channels); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<String> StreamsData() { Table table = new Table(); Row row = new Row(false, true); row.AddColumn(new TextColumn(0, "StreamName", true)); row.AddColumn(new TextColumn(1, "Type")); row.AddColumn(new TextColumn(2, "")); row.AddColumn(new TextColumn(3, "")); row.AddColumn(new TextColumn(4, "")); table.AddRow(row); foreach (var stream in _context.StreamModels) { Row newrow = new Row(); newrow.AddColumn(new TextColumn(0, stream.StreamName)); newrow.AddColumn(new TextColumn(1, stream.Type.ToString())); newrow.AddColumn(new StreamEditColumn(2, "Edit",stream)); if(stream.Type == StreamProviderTypes.Twitch) { newrow.AddColumn(new LinkColumn(3, "Authorisieren", $"/Stream/TwitchOAuth/{stream.ID}")); } else { newrow.AddColumn(new TextColumn(3, "")); } newrow.AddColumn(new StreamDeleteColumn(4, "Delete", stream)); table.AddRow(newrow); } return table.getJson(); } /* [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var stream = await _context.StreamModels.FindAsync(id); if (stream == null) { return NotFound(); } StreamEditViewDataModel model = new StreamEditViewDataModel(); model.stream = stream; model.StreamTypes = stream.EnumStreamTypes(); model.RelayChannels = await _context.RelayChannels.ToListAsync(); model.SelectedRelayChannel = stream.DiscordRelayChannel; model.StatusMessage = StatusMessage; return View(model); }*/ // POST: Streams2/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task<bool> Create(string StreamName, StreamProviderTypes Type, int UpTime, int Quote, string Relay) { try { Stream newstream = new Stream(); newstream.StreamName = StreamName; newstream.Type = Type; newstream.UpTimeInterval = UpTime; newstream.QuoteInterval = Quote; newstream.DiscordRelayChannel = Relay; _context.StreamModels.Add(newstream); _context.SaveChanges(); //handleCreated(newstream); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return false; } private async Task handleCreated(Stream stream) { string address = _configuration.GetValue<string>("WebServerWebAddress") + "/User/Subscriptions"; MessageArgs args = new MessageArgs(); args.Message = $"Der Stream {stream.StreamName} wurde hinzugefügt. Da kannst du für {address} ein Abonnement ausführen tun."; foreach (ChatUserModel user in _context.ChatUserModels) { args.RecipientName = user.ChatUserName; _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, args); } } [TempData] public string StatusMessage { get; set; } // GET: Streams2/Delete/5 [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<bool> DeleteStream(int? streamID) { if (streamID == null) { return false; } var stream = await _context.StreamModels .FirstOrDefaultAsync(m => m.ID == streamID); if (stream == null) { return false; } _context.StreamModels.Remove(stream); _context.SaveChanges(); return true; } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> TwitchOAuth(int? id) { if (id == null) { return NotFound(); } var stream = await _context.StreamModels.FindAsync(id); if (stream == null) { return NotFound(); } StreamOAuthDataModel model = new StreamOAuthDataModel(); model.Id = stream.ID.ToString(); string baseurl = _configuration.GetSection("WebServerWebAddress").Value; model.RedirectLinkForTwitch = $"{baseurl}/Stream/TwitchReturnUrlAction"; model.StatusMessage = StatusMessage; return View(model); } [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> TwitchOAuth(int id, [Bind("Id,ClientId,Secret")] StreamOAuthDataModel StreamOAuthData) { if (id != Int32.Parse(StreamOAuthData.Id)) { return NotFound(); } if (ModelState.IsValid && StreamOAuthData.ClientId != "" && StreamOAuthData.Secret != "") { var baseUrl = _configuration.GetSection("WebServerWebAddress").Value; string state = StreamOAuthData.Id + StreamOAuthData.Secret; Stream stream = _context.StreamModels.Where(sm => sm.ID == Int32.Parse(StreamOAuthData.Id)).FirstOrDefault(); if (stream != null) { stream.Secret = StreamOAuthData.Secret; stream.ClientID = StreamOAuthData.ClientId; } await _context.SaveChangesAsync(); return Redirect($"https://id.twitch.tv/oauth2/authorize?response_type=code&client_id={StreamOAuthData.ClientId}&redirect_uri={baseUrl}/Stream/TwitchReturnUrlAction&scope=channel_editor+user:edit&state={state}"); } StatusMessage = "ClientID und Secret entweder leer oder falsch"; return View(nameof(TwitchOAuth)); } [HttpGet] [AllowAnonymous] public async Task<IActionResult> TwitchReturnUrlAction(string code, string scope, string state) { var client = new HttpClient(); Stream stream = _context.StreamModels.Where(sm => state.Contains(sm.Secret)).FirstOrDefault(); if (stream != null) { var baseUrl = _configuration.GetSection("WebServerWebAddress").Value; string url = $"https://id.twitch.tv/oauth2/token?client_id={stream.ClientID}&client_secret={stream.Secret}&code={code}&grant_type=authorization_code&redirect_uri={baseUrl}/Stream/TwitchReturnUrlAction"; var response = await client.PostAsync(url, new StringContent("", System.Text.Encoding.UTF8, "text/plain")); var responsestring = await response.Content.ReadAsStringAsync(); JSONObjects.TwitchAuthToken authtoken = JsonConvert.DeserializeObject<JSONObjects.TwitchAuthToken>(responsestring); stream.AccessToken = authtoken.access_token; stream.RefreshToken = authtoken.refresh_token; await _context.SaveChangesAsync(); StatusMessage = "Stream Oauth complete"; } return RedirectToAction(nameof(Verwaltung)); } private bool StreamExists(int id) { return _context.StreamModels.Any(e => e.ID == id); } } }<file_sep>/BobDeathmic/Data/SeedData.cs using BobDeathmic.Data.DBModels.User; using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; namespace BobDeathmic.Models { public static class SeedData { public async static Task Seed(IServiceProvider serviceProvider) { Contract.Ensures(Contract.Result<Task>() != null); using (var context = new Data.ApplicationDbContext(serviceProvider.GetRequiredService<DbContextOptions<Data.ApplicationDbContext>>())) { if (context.ChatUserModels.Any()) { return; } var usermanager = serviceProvider.GetRequiredService<UserManager<ChatUserModel>>(); var dev = new ChatUserModel { UserName = "Dev", ChatUserName = "Dev" }; await usermanager.CreateAsync(dev, "SetupPassword"); await SeedData.CreateOrAddUserRoles("Dev", "Dev", serviceProvider); } return; } private static async Task CreateOrAddUserRoles(string role, string name, IServiceProvider serviceProvider) { try { var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var UserManager = serviceProvider.GetRequiredService<UserManager<ChatUserModel>>(); IdentityResult roleResult; //Adding Admin Role var roleCheck = await RoleManager.RoleExistsAsync(role); if (!roleCheck) { //create the roles and seed them to the database roleResult = await RoleManager.CreateAsync(new IdentityRole(role)); } //Assign Admin role to the main User here we have given our newly registered //login id for Admin management ChatUserModel user = await UserManager.FindByNameAsync(name); await UserManager.AddToRoleAsync(user, role); } catch (Exception) { } } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/StreamCommandDeleteColumn.cs using BobDeathmic.Data.DBModels.StreamModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class ObjectDeleteColumn: Column { public string ReactComponentName { get { return "ObjectDeleteColumn"; } } public int key { get; set; } public string Text { get; set; } public string DeleteLink { get; set; } public string DeleteText { get; set; } public ObjectDeleteColumn(int key, string Text, string DeleteLink,string DeleteText) { this.key = key; this.Text = Text; this.canSort = false; this.DeleteLink = DeleteLink; this.DeleteText = DeleteText; } } } <file_sep>/BobDeathmic/ChatCommands/TwitchStreamTitle.cs using BobDeathmic.Args; using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data.Enums; using BobDeathmic.Data.Enums.Stream; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands { public class TwitchStreamTitle : ICommand { public string Trigger => "!stream"; public string Alias => "!cst"; public string Description => "Ändert den StreamTitel (!stream game='Bla' title='Bla')"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { if (args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias)) { return CommandEventType.TwitchTitle; } return CommandEventType.None; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { return null; /* if (message["message"].ToLower().StartsWith(Trigger) || message["message"].ToLower().StartsWith(alias)) { return CommandEventType.TwitchTitle; } return CommandEventType.None; */ } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } public class Game : ICommand { public string Trigger => "!game"; public string Alias => "!game"; public string Description => "Ändert das Stream Spiel"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { if (args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias)) { return CommandEventType.TwitchTitle; } return CommandEventType.None; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { if (!args.elevatedPermissions) { return null; } return new ChatCommandOutput() { ExecuteEvent = true, Type = Eventbus.EventType.StreamTitleChangeRequested, EventData = TwitchStreamTitleHelper.PrepareStreamTitleChange(args.ChannelName, args.Message) }; } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } public class Title : ICommand { public string Trigger => "!title"; public string Alias => "!titel"; public string Description => "Ändert den Stream Titel"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { if (args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias)) { return CommandEventType.TwitchTitle; } return CommandEventType.None; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { if(!args.elevatedPermissions) { return null; } return new ChatCommandOutput() { ExecuteEvent = true, Type = Eventbus.EventType.StreamTitleChangeRequested, EventData = TwitchStreamTitleHelper.PrepareStreamTitleChange(args.ChannelName,args.Message) }; } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } public static class TwitchStreamTitleHelper { public static StreamTitleChangeArgs PrepareStreamTitleChange(string StreamName, string Message) { var arg = new StreamTitleChangeArgs(); arg.StreamName = StreamName; arg.Type = StreamProviderTypes.Twitch; if (Message.StartsWith("!stream")) { var questionRegex = Regex.Match(Message, @"game=\'(.*?)\'"); var GameRegex = Regex.Match(Message, @"game=\'(.*?)\'"); string Game = ""; if (GameRegex.Success) { Game = GameRegex.Value; } var TitleRegex = Regex.Match(Message, @"title=\'(.*?)\'"); string Title = ""; if (TitleRegex.Success) { Title = TitleRegex.Value; } arg.Game = Game; arg.Title = Title; } else { if (Message.StartsWith("!game")) { arg.Game = Message.Replace("!game ", ""); arg.Title = ""; } if (Message.StartsWith("!title")) { arg.Title = Message.Replace("!title ", ""); arg.Game = ""; } } return arg; } } } <file_sep>/BobDeathmic/Controllers/HelpController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Services.Commands; using BobDeathmic.Services.Helper; using Microsoft.AspNetCore.Mvc; namespace BobDeathmic.Controllers { public class HelpController : Controller { private ICommandService commandService; public HelpController(ICommandService commandService) { this.commandService = commandService; } public IActionResult Index() { return View("Index", commandService.GetCommands(Data.Enums.ChatType.Twitch)); } } }<file_sep>/BobDeathmic/ViewModels/ReactDataClasses/EventDateFinder/Vote/VoteRequest.cs using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Models.Events; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic; namespace BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.Vote { public class VoteRequest { public string UserName { get; set; } public string AppointmentRequestID { get; set; } public AppointmentRequestState State { get; set; } public string Date { get; set; } public string Time { get; set; } public bool canEdit { get; set; } public string Comment { get; set; } public string[] States { get { return new string[] { "NotYetVoted", "Available", "NotAvailable", "IfNeedBe" }; } } } } <file_sep>/BobDeathmic/Services/Discords/DiscordService.cs using BobDeathmic; using BobDeathmic.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.GiveAway.manymany; using BobDeathmic.Data.DBModels.Relay; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Eventbus; using BobDeathmic.Models; using BobDeathmic.Services; using BobDeathmic.Services.Commands; using BobDeathmic.Services.Helper; using Discord; using Discord.Net; using Discord.WebSocket; using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Services.Discords { public interface IDiscordService { } public class DiscordService : BackgroundService, IDiscordService { private readonly IServiceScopeFactory _scopeFactory; private IEventBus _eventBus; private DiscordSocketClient _client; private List<ICommand> _commandList; private Random random; private ICommandService commandService; public DiscordService(IServiceScopeFactory scopeFactory, IEventBus eventBus,ICommandService commandService) { _scopeFactory = scopeFactory; _eventBus = eventBus; _eventBus.TwitchMessageReceived += TwitchMessageReceived; _eventBus.PasswordRequestReceived += PasswordRequestReceived; _eventBus.DiscordMessageSendRequested += SendMessage; _eventBus.CommandOutputReceived += handleCommandResponse; this.commandService = commandService; SetupClient(); } private void SetupClient() { var discordConfig = new DiscordSocketConfig { MessageCacheSize = 100 }; discordConfig.AlwaysDownloadUsers = true; discordConfig.LargeThreshold = 250; _client = new DiscordSocketClient(discordConfig); } private void PasswordRequestReceived(object sender, PasswordRequestArgs e) { var server = _client.Guilds.Where(g => g.Name.ToLower() == "deathmic").FirstOrDefault(); var users = server?.Users.Where(u => u.Username.ToLower() == e.UserName.ToLower() && u.Status != UserStatus.Offline); var user = users.FirstOrDefault(); user?.SendMessageAsync("Dein neues Passwort ist: " + e.TempPassword); } protected async override Task ExecuteAsync(CancellationToken stoppingToken) { random = new Random(DateTime.Now.Second * DateTime.Now.Millisecond / (DateTime.Now.Hour + 1)); if (await ConnectToDiscord()) { while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } } return; } public async override Task StopAsync(CancellationToken cancellationToken) { await base.StopAsync(cancellationToken); await _client.StopAsync(); Dispose(); } private async Task<bool> ConnectToDiscord() { string token = GetDiscordToken(); if (token != string.Empty) { await _client.LoginAsync(Discord.TokenType.Bot, token); await _client.StartAsync(); InitializeEvents(); return true; } return false; } private void InitializeEvents() { _client.MessageReceived += MessageReceived; _client.UserJoined += ClientJoined; _client.ChannelCreated += ChannelCreated; _client.ChannelDestroyed += ChannelDestroyed; } private async Task ChannelDestroyed(SocketChannel arg) { if(arg.GetType() == typeof(SocketTextChannel)) { SocketTextChannel destroyedchannel = (SocketTextChannel)arg; RemoveRelayChannel(destroyedchannel.Name); } } public void RemoveRelayChannel(string name) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var channel = _context.RelayChannels.Where(x => x.Name.ToLower() == name.ToLower()).FirstOrDefault(); if (channel != null) { _context.RelayChannels.Remove(channel); _context.SaveChanges(); } } } private async Task ChannelCreated(SocketChannel arg) { if (arg.GetType() == typeof(SocketTextChannel) && Regex.Match(((SocketTextChannel) arg).Name.ToLower(), @"stream_").Success) { SocketTextChannel createdchannel = (SocketTextChannel)arg; AddRelayChannel(createdchannel.Name); } } public void AddRelayChannel(string name) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if (_context.RelayChannels.Where(x => x.Name.ToLower() == name.ToLower()).FirstOrDefault() == null) { _context.RelayChannels.Add(new RelayChannels(name.ToLower())); _context.SaveChanges(); } } } private string GetDiscordToken() { using (var scope = _scopeFactory.CreateScope()) { var token = string.Empty; var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var tokens = _context.SecurityTokens.Where(st => st.service == Data.Enums.Stream.TokenType.Discord).FirstOrDefault(); if (tokens != null) { if (tokens.token == null) { token = tokens.ClientID; } else { token = tokens.token; } } return token; } } private async Task ClientJoined(SocketGuildUser arg) { arg.SendMessageAsync("Um Bot Notifications/Features nutzen zu können müsst ihr euch über den Befehl \"!WebInterfaceLink\" beim Bot registrieren"); } private async Task MessageReceived(SocketMessage arg) { if (arg.Author.Username != "BobDeathmic") { string commandresult = string.Empty; if (arg.Content.StartsWith("!WebInterfaceLink", StringComparison.CurrentCulture) || arg.Content.StartsWith("!wil", StringComparison.CurrentCulture)) { SendWebInterfaceLink(arg); } ChatCommands.Args.ChatCommandInputArgs inputargs = new ChatCommands.Args.ChatCommandInputArgs() { Message = arg.Content, ChannelName = arg.Channel.Name, elevatedPermissions = false, Sender = arg.Author.Username, Type = Data.Enums.ChatType.Discord }; commandService.handleCommand(inputargs, Data.Enums.ChatType.Discord,arg.Author.Username); RelayMessage(arg); } } private async Task SendWebInterfaceLink(SocketMessage arg) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); List<ulong> blocked = _context.DiscordBans.Select(x => x.DiscordID).ToList(); if (!blocked.Contains(arg.Author.Id)) { string message = await GetUserLogin(arg); arg.Author.SendMessageAsync(message); } else { await arg.Author.SendMessageAsync($"Bitte Discord Namen ändern und an einen Admin wenden und folgenden Wert mitteilen {arg.Author.Id}"); } } } private void RelayMessage(SocketMessage arg) { if (arg.Channel.Name.StartsWith("stream_", StringComparison.CurrentCulture)) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var stream = _context.StreamModels.Where(sm => sm.DiscordRelayChannel.ToLower() == arg.Channel.Name.ToLower()).FirstOrDefault(); if (stream != null) { _eventBus.TriggerEvent(EventType.RelayMessageReceived, new RelayMessageArgs(arg.Channel.Name, stream.StreamName, stream.Type, arg.Author.Username + ": " + arg.Content)); } } } } #region AccountStuff private async Task<string> GetUserLogin(SocketMessage arg) { using (var scope = _scopeFactory.CreateScope()) { var usermanager = scope.ServiceProvider.GetRequiredService<UserManager<ChatUserModel>>(); var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var user = _context.ChatUserModels.Where(cm => cm.ChatUserName.ToLower() == arg.Author.Username.ToLower()).FirstOrDefault(); var Configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>(); if (user == null) { user = await GenerateUser(arg); } string Message = "Adresse: "; Message += Configuration.GetValue<string>("WebServerWebAddress"); if (usermanager.CheckPasswordAsync(user, user.InitialPassword).Result) { Message += Environment.NewLine + "UserName; " + user.UserName; Message += Environment.NewLine + "Initiales Passwort: " + user.InitialPassword; } return Message; } } private async Task<ChatUserModel> GenerateUser(SocketMessage arg) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); ChatUserModel newUser = new ChatUserModel(arg.Author.Username, _context.StreamModels.Where(x => x.StreamName != null)); newUser.SetInitialPassword(); var usermanager = scope.ServiceProvider.GetRequiredService<UserManager<ChatUserModel>>(); await usermanager.CreateAsync(newUser, newUser.InitialPassword); await CreateOrAddUserRoles("User", newUser.UserName); return newUser; } } private async Task CreateOrAddUserRoles(string role, string name) { try { using (var scope = _scopeFactory.CreateScope()) { var RoleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var UserManager = scope.ServiceProvider.GetRequiredService<UserManager<ChatUserModel>>(); var roleCheck = await RoleManager.RoleExistsAsync(role); if (!roleCheck) { await RoleManager.CreateAsync(new IdentityRole(role)); } ChatUserModel user = await UserManager.FindByNameAsync(name); await UserManager.AddToRoleAsync(user, role); } } catch (Exception) { } } private void SendMessage(object sender, MessageArgs e) { SendPrivateMessage(e.RecipientName.ToLower(), e.Message); } private void TwitchMessageReceived(object sender, TwitchMessageArgs e) { try { SendChannelMessage(e.Target.ToLower(), e.Message); } catch (InvalidOperationException) { //just an annoyance on start.. } } private void SendChannelMessage(string channel,string message) { _client.Guilds.Single(g => g.Name.ToLower() == "deathmic")?.TextChannels.Single(c => c.Name.ToLower() == channel.ToLower())?.SendMessageAsync(message); } private void SendPrivateMessage(string username,string message) { _client.Guilds.Where(g => g.Name.ToLower() == "deathmic").FirstOrDefault()?.Users.Where(x => x.Username.ToLower() == username.ToLower()).FirstOrDefault()?.SendMessageAsync(message); } void handleCommandResponse(object sender, CommandResponseArgs e) { if(e.Chat == Data.Enums.ChatType.Discord) { switch(e.MessageType) { case Eventbus.MessageType.ChannelMessage: SendChannelMessage(e.Channel, e.Message); break; case Eventbus.MessageType.PrivateMessage: SendPrivateMessage(e.Sender, e.Message); break; } } } #endregion } } <file_sep>/BobDeathmic/Controllers/ServicesController.cs using BobDeathmic.Services; using BobDeathmic.Services.Discords; using BobDeathmic.Services.Streams.Relay.Twitch; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Controllers { public class ServicesController : Controller { private readonly IEnumerable<Microsoft.Extensions.Hosting.IHostedService> _microservices; public ServicesController(IEnumerable<Microsoft.Extensions.Hosting.IHostedService> microservices) { _microservices = microservices; } public IActionResult Index() { //use this to enable killing service for "reboot" purposes //services.Remove(services.FirstOrDefault(x => x.ImplementationType == typeof(TwitchRelayCenter))); return NotFound(); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> ServiceControls() { return View(); } [Authorize(Roles = "Dev,Admin")] public async Task<string> StartDiscord() { try { await _microservices.Where(ms => ms.GetType() == typeof(DiscordService)).FirstOrDefault()?.StartAsync(new System.Threading.CancellationToken(false)); } catch (Exception ex) { } return "Started"; } [Authorize(Roles = "Dev,Admin")] public async Task<string> StopDiscord() { try { await _microservices.Where(ms => ms.GetType() == typeof(DiscordService)).FirstOrDefault()?.StopAsync(new System.Threading.CancellationToken(true)); } catch (Exception ex) { } return "Stopped"; } [Authorize(Roles = "Dev,Admin")] public async Task<string> RestartDiscord() { try { await _microservices.Where(ms => ms.GetType() == typeof(DiscordService)).FirstOrDefault()?.StopAsync(new System.Threading.CancellationToken(true)); await _microservices.Where(ms => ms.GetType() == typeof(DiscordService)).FirstOrDefault()?.StartAsync(new System.Threading.CancellationToken(false)); } catch (Exception ex) { } return "Restart"; } [Authorize(Roles = "Dev,Admin")] public async Task<string> StopTwitchRelay() { try { var test = _microservices.Where(ms => ms.GetType() == typeof(TwitchRelayCenter)).FirstOrDefault(); await test?.StopAsync(new System.Threading.CancellationToken(true)); } catch (Exception ex) { } return "Stopped"; } [Authorize(Roles = "User,Dev,Admin")] public async Task<string> RestartTwitchRelay() { try { await _microservices.Where(ms => ms.GetType() == typeof(TwitchRelayCenter)).FirstOrDefault()?.StopAsync(new System.Threading.CancellationToken(true)); GC.Collect(); await _microservices.Where(ms => ms.GetType() == typeof(TwitchRelayCenter)).FirstOrDefault()?.StartAsync(new System.Threading.CancellationToken(false)); } catch (Exception ex) { } return "Restart"; } } }<file_sep>/BobDeathmic/Data/DBModels/EventCalendar/EventDate.cs using BobDeathmic.Data.DBModels.EventCalendar; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.Models.Events; using BobDeathmic; using BobDeathmic.Models; namespace BobDeathmic.Data.DBModels.EventCalendar { //Wird in der Abstimmung generiert für z.b. 14 Tage im Vorraus und dann jeden Tag wird das älteste bzw "15 te" gelöscht public class EventDate { public string ID { get; set; } public int CalendarId { get; set; } public Event Event { get; set; } public string EventDateTemplateID { get; set; } public List<AppointmentRequest> Teilnahmen { get; set; } public DateTime StartTime { get; set; } public DateTime StopTime { get; set; } public DateTime Date { get; set; } internal string AdminNotification(string name = "Calendar") { return $"Möglicher Termin für {name}: {Date.ToString("dd.MM.yyyy HH:mm")}"; } } }<file_sep>/BobDeathmic/Data/JSONModels/MobileResponse.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.JSONModels { public class MobileResponse { public string Response { get; set; } } } <file_sep>/BobDeathmic/Data/DBModels/EventCalendar/AppointmentRequest.cs using BobDeathmic; using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Models; using BobDeathmic.Models.Events; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.EventCalendar { //Missing counter relation to ChatUserModel public class AppointmentRequest { public string ID { get; set; } public EventDate EventDate { get; set; } public ChatUserModel Owner { get; set; } public AppointmentRequestState State { get; set; } public string Comment { get; set; } public AppointmentRequest() { State = 0; } public AppointmentRequest(ChatUserModel Owner, EventDate EventDate) { this.EventDate = EventDate; this.Owner = Owner; State = 0; } } public enum AppointmentRequestState { NotYetVoted = 0, Available = 1, NotAvailable = 2, IfNeedBe = 3 } } <file_sep>/BobDeathmic/ChatCommands/Setup/CommandConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands.Setup { public class AppConfig { public Command[] Commands { get; set; } } public class Command { public string Name { get; set; } public bool Twitch { get; set; } public bool Discord { get; set; } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/Column.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class Column { public int Key { get; set; } public bool canSort { get; set; } } } <file_sep>/BobDeathmic/Services/Streams/Checker/DLive/JSONDataTypes/DLiveStreamOnlineData.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.JSONObjects.DLive { public class DLiveStreamOnlineData { public data data { get; set; } } public class data { public userByDisplayName userByDisplayName { get; set; } } public class userByDisplayName { public livestream livestream { get; set; } } public class livestream { public string id { get; set; } public string title { get; set; } public category category { get; set; } } public class category { public string title { get; set; } } } <file_sep>/BobDeathmic/Services/Streams/Relay/Twitch/TwitchRelayCenter.cs using BobDeathmic; using BobDeathmic.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data; using BobDeathmic.Eventbus; using BobDeathmic.Models; using BobDeathmic.Services; using BobDeathmic.Services.Helper; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MySql.Data.MySqlClient; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Timers; using TwitchLib.Client; using TwitchLib.Client.Enums; using TwitchLib.Client.Events; using TwitchLib.Client.Extensions; using TwitchLib.Client.Models; using TwitchLib.Communication.Events; using BobDeathmic; using BobDeathmic.Services; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Services.Commands; namespace BobDeathmic.Services.Streams.Relay.Twitch { public class TwitchRelayCenter : BackgroundService { private readonly IEventBus _eventBus; private TwitchClient client; //MessageQueue private Dictionary<string, List<string>> MessageQueues; private readonly IServiceScopeFactory _scopeFactory; private System.Timers.Timer _MessageTimer; private System.Timers.Timer _AutoCommandTimer; private System.Timers.Timer _RelayCheckTimer; private readonly IConfiguration _configuration; //TODO once CommandService Finished Remove next line private List<ICommand> CommandList; private Random random; private ICommandService commandService; public async override Task StopAsync(CancellationToken cancellationToken) { await base.StopAsync(cancellationToken); client.Disconnect(); } public TwitchRelayCenter(IServiceScopeFactory scopeFactory, IEventBus eventBus, IConfiguration configuration, ICommandService commandService) { _configuration = configuration; _scopeFactory = scopeFactory; _eventBus = eventBus; this.commandService = commandService; random = new Random(); } protected async override Task ExecuteAsync(CancellationToken stoppingToken) { await InitTwitchClient(); InitRelayBusEvents(); InitMessageQueue(); _MessageTimer = new System.Timers.Timer(50); _MessageTimer.Elapsed += (sender, args) => SendMessages(); _MessageTimer.Start(); _RelayCheckTimer = new System.Timers.Timer(5000); _RelayCheckTimer.Elapsed += CheckRelays; _RelayCheckTimer.Start(); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } return; } private async void CheckRelays(object sender, ElapsedEventArgs e) { while (ConnectionChangeInProgress) { await Task.Delay(5000); } if (!client.IsConnected) { await Connect(); } using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); handleRelayStart(_context); handleRelayEnd(_context); handleUpTime(_context); handleConnectionUpkeep(_context); } } private void handleUpTime(ApplicationDbContext _context) { foreach(var stream in _context.StreamModels.Where(x => x.UpTimeQueued() && MessageQueues.Keys.Contains(x.StreamName))) { MessageQueues[stream.StreamName].Add(stream.UptimeMessage()); } _context.SaveChanges(); } private void handleConnectionUpkeep(ApplicationDbContext _context) { foreach (var stream in _context.StreamModels.Where(x => x.StreamState == StreamState.Running && MessageQueues.Keys.Contains(x.StreamName.ToLower()) && x.DiscordRelayChannel != "Aus")) { if (client.JoinedChannels.Where(x => x.Channel.ToLower() == stream.StreamName.ToLower()).Count() == 0) { JoinChannel(stream.StreamName); } } } private void handleRelayStart(ApplicationDbContext _context) { foreach (var stream in _context.StreamModels.Where(x => x.StreamState == StreamState.Running && !MessageQueues.Keys.Contains(x.StreamName.ToLower()) && (x.DiscordRelayChannel != "Aus" && x.DiscordRelayChannel != "" && x.DiscordRelayChannel != null ))) { AddMessageQueue(stream.StreamName); JoinChannel(stream.StreamName); } } private void handleRelayEnd(ApplicationDbContext _context) { foreach (var stream in _context.StreamModels.Where(x => x.StreamState == StreamState.NotRunning && MessageQueues.Keys.Contains(x.StreamName.ToLower()) && x.DiscordRelayChannel != "Aus")) { RemoveMessageQueue(stream.StreamName); LeaveChannel(stream.StreamName); } } private async Task SendMessages() { if (MessageQueues != null && client != null && client.IsConnected) { if (MessageQueues.Count() > 0) { foreach (var MessageQueue in MessageQueues.Where(mq => mq.Value.Count > 0)) { await Task.Delay(100); client.SendMessage(MessageQueue.Key, MessageQueue.Value.First()); MessageQueue.Value.RemoveAt(0); } } } } private void SendPriorityMessage(string channel,string message) { try { _MessageTimer.Stop(); client.SendMessage(channel, message); }catch(Exception ex) { //don't care }finally { _MessageTimer.Start(); } } private async Task InitTwitchClient() { client = new TwitchClient(); client.OnConnected += HasConnected; client.OnConnectionError += ConnectionError; client.OnDisconnected += Disconnected; client.OnIncorrectLogin += LoginAuthFailed; client.OnJoinedChannel += ChannelJoined; client.OnLeftChannel += ChannelLeft; client.OnMessageReceived += MessageReceived; client.OnError += ErrorReceived; client.OnMessageThrottled += MessageThrottled; client.OnWhisperReceived += WhisperReceived; client.Initialize(await GetTwitchCredentials()); } void ErrorReceived(object sender, OnErrorEventArgs e) { Console.WriteLine(e.Exception); } void MessageThrottled(object sender, OnMessageThrottledEventArgs e) { Console.WriteLine(e.Message); } void WhisperReceived(object sender, OnWhisperReceivedArgs e) { Console.WriteLine(e.WhisperMessage); } private void InitRelayBusEvents() { _eventBus.RelayMessageReceived += RelayMessageReceived; _eventBus.CommandOutputReceived += handleCommandResponse; } private bool ConnectionChangeInProgress; private async Task Connect() { if (!ConnectionChangeInProgress) { ConnectionChangeInProgress = true; client.Connect(); } } #region EventHandler #region TwitchClientEvents private void HasConnected(object sender, OnConnectedArgs e) { ConnectionChangeInProgress = false; if (_AutoCommandTimer == null) { _AutoCommandTimer = new System.Timers.Timer(); _AutoCommandTimer = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds); _AutoCommandTimer.Elapsed += (autocommandsender, args) => ExecuteAutoCommands(); _AutoCommandTimer.Elapsed += (quotesender, args) => HandleAutoQuotes(); } if (!_AutoCommandTimer.Enabled) { _AutoCommandTimer.Start(); } } private void ExecuteAutoCommands() { if (MessageQueues.Count() > 0) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); foreach (var messageQueue in MessageQueues) { var commands = _context.StreamCommand.Include(sc => sc.stream).Where(sc => sc.Mode == StreamCommandMode.Auto && sc.stream.StreamName == messageQueue.Key && sc.AutoInverval > 0 && (DateTime.Now - sc.LastExecution).Minutes > sc.AutoInverval); foreach (StreamCommand command in commands) { messageQueue.Value.Add(command.response); command.LastExecution = DateTime.Now; } } _context.SaveChanges(); } } } private void HandleAutoQuotes() { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var streamsWithQuoteInterval = _context.StreamModels.Where(x => x.QuoteInterval > 0); foreach(var stream in streamsWithQuoteInterval) { if(DateTime.Now.Subtract(stream.LastRandomQuote) > TimeSpan.FromMinutes(stream.QuoteInterval)) { var QuoteList = _context.Quotes.Where(x => x.Streamer.ToLower() == stream.StreamName.ToLower()); var MessageQueue = MessageQueues.Where(x => x.Key == stream.StreamName).FirstOrDefault(); if (!MessageQueue.Equals(default(KeyValuePair<string, List<string>>))) { MessageQueue.Value.Add(QuoteList.ToArray()[random.Next(QuoteList.Count() - 1)].ToString()); stream.LastRandomQuote = DateTime.Now; _context.SaveChanges(); } } } } } private async void LoginAuthFailed(object sender, OnIncorrectLoginArgs e) { ConnectionChangeInProgress = false; await RefreshToken(); client.Disconnect(); client.SetConnectionCredentials(await GetTwitchCredentials()); } private void Disconnected(object sender, OnDisconnectedEventArgs e) { ConnectionChangeInProgress = false; if (_AutoCommandTimer != null) { _AutoCommandTimer.Stop(); } RefreshToken(); } private void ConnectionError(object sender, OnConnectionErrorArgs e) { ConnectionChangeInProgress = false; } private void ChannelJoined(object sender, OnJoinedChannelArgs e) { var twitchchannel = client.JoinedChannels.Where(channel => channel.Channel == e.Channel).FirstOrDefault(); client.SendMessage(twitchchannel, "Relay Started"); //Trigger Event to Send "Relay Started" to discord or somesuch string target = ""; using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var stream = _context.StreamModels.Where(sm => sm.StreamName.ToLower() == e.Channel.ToLower()).FirstOrDefault(); if (stream != null) { target = stream.DiscordRelayChannel; } } if (!string.IsNullOrEmpty(target)) { _eventBus.TriggerEvent(EventType.TwitchMessageReceived, new TwitchMessageArgs { Source = e.Channel, Message = $"Relay Started ({e.Channel})", Target = target }); } } private void ChannelLeft(object sender, OnLeftChannelArgs e) { } private async void MessageReceived(object sender, OnMessageReceivedArgs e) { if (!e.ChatMessage.IsMe) { using (var scope = _scopeFactory.CreateScope()) { if (MessageQueues.ContainsKey(e.ChatMessage.Channel.ToLower())) { string message = GetManualCommandResponse(e.ChatMessage.Channel, e.ChatMessage.Message); if (message != "") { MessageQueues[e.ChatMessage.Channel].Add(message); } } } if (!e.ChatMessage.Message.StartsWith("!", StringComparison.CurrentCulture)) { string target = ""; using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var stream = _context.StreamModels.Where(sm => sm.StreamName.ToLower() == e.ChatMessage.Channel.ToLower()).FirstOrDefault(); if (stream != null) { target = stream.DiscordRelayChannel; } } if (target != null && target != "") { _eventBus.TriggerEvent(EventType.TwitchMessageReceived, new TwitchMessageArgs { Source = e.ChatMessage.Channel, Message = e.ChatMessage.Username + ": " + e.ChatMessage.Message, Target = target }); } } else { ChatCommands.Args.ChatCommandInputArgs inputargs = new ChatCommands.Args.ChatCommandInputArgs() { Message = e.ChatMessage.Message, Sender = e.ChatMessage.Username, ChannelName = e.ChatMessage.Channel, elevatedPermissions = (e.ChatMessage.IsModerator || e.ChatMessage.IsBroadcaster), Type = Data.Enums.ChatType.Twitch }; commandService.handleCommand(inputargs,Data.Enums.ChatType.Twitch,e.ChatMessage.Username); } } } private string GetManualCommandResponse(string streamname, string message) { try { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var command = _context.StreamCommand.Include(sc => sc.stream).Where(sc => sc.Mode == StreamCommandMode.Manual && sc.stream.StreamName == streamname && message.Contains(sc.name)).FirstOrDefault(); if (command != null) { return command.response; } return ""; } }catch(MySqlException e) { var test = streamname; var test2 = message; return ""; } } #endregion #region RelayBus Events private void LeaveChannel(string name) { if (client.IsConnected && client.JoinedChannels.Any(x => x.Channel == name)) { SendPriorityMessage(name, "Relay is leaving"); using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var stream = _context.StreamModels.Where(x => x.StreamName.ToLower() == name.ToLower()).FirstOrDefault(); if(stream != null) { _eventBus.TriggerEvent(EventType.TwitchMessageReceived, new TwitchMessageArgs { Message = $"Relay left ({stream.StreamName})", Target = stream.DiscordRelayChannel }); } } client.LeaveChannel(name); } } private void JoinChannel(string name) { if (client.IsConnected && client.JoinedChannels.Where(x => x.Channel == name).Count() == 0) { try { client.JoinChannel(name.ToLower()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } private void RelayMessageReceived(object sender, RelayMessageArgs e) { if (e.StreamType == StreamProviderTypes.Twitch) { MessageQueues[e.TargetChannel].Add(e.Message); } } #endregion #endregion private void InitMessageQueue() { if (MessageQueues == null) { MessageQueues = new Dictionary<string, List<string>>(); } } private void AddMessageQueue(string name) { if (!MessageQueues.ContainsKey(name)) { MessageQueues.Add(name, new List<string>()); } } private void AddMessageToQueue(string name,string message) { if (!MessageQueues.ContainsKey(name)) { AddMessageQueue(name); } MessageQueues[name].Add(message); } private void RemoveMessageQueue(string name) { if (MessageQueues.ContainsKey(name)) { MessageQueues.Remove(name); } } private async Task<ConnectionCredentials> GetTwitchCredentials() { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); SecurityToken token = null; while (token == null || token != null && token.token == "") { token = _context.SecurityTokens.Where(st => st.service == TokenType.Twitch).FirstOrDefault(); if (token == null || token != null && token.token == "") { await Task.Delay(1000); } } ConnectionCredentials credentials = new ConnectionCredentials("BobDeathmic", "oauth:" + token.token); return credentials; } } private async Task RefreshToken() { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var savedtoken = _context.SecurityTokens.Where(x => x.service == TokenType.Twitch).FirstOrDefault(); if (savedtoken != null && savedtoken.RefreshToken != null && savedtoken.RefreshToken != "") { var httpclient = new HttpClient(); string baseUrl = _configuration.GetValue<string>("WebServerWebAddress"); string url = $"https://id.twitch.tv/oauth2/token?grant_type=refresh_token&refresh_token={savedtoken.RefreshToken}&client_id={savedtoken.ClientID}&client_secret={savedtoken.secret}"; var response = await httpclient.PostAsync(url, new StringContent("", System.Text.Encoding.UTF8, "text/plain")); var responsestring = await response.Content.ReadAsStringAsync(); JSONObjects.TwitchRefreshTokenData refresh = JsonConvert.DeserializeObject<JSONObjects.TwitchRefreshTokenData>(responsestring); if (refresh.error == null) { savedtoken.token = refresh.access_token; savedtoken.RefreshToken = refresh.refresh_token; _context.SaveChanges(); } } } } public void handleCommandResponse(object sender, CommandResponseArgs e) { if (e.Chat == Data.Enums.ChatType.Twitch) { switch (e.MessageType) { case Eventbus.MessageType.ChannelMessage: AddMessageToQueue(e.Channel, e.Message); break; case Eventbus.MessageType.PrivateMessage: client.SendWhisper(e.Sender, e.Message); break; } } } } } <file_sep>/BobDeathmic/Controllers/MainController.cs using BobDeathmic.Data; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Data.JSONModels; using BobDeathmic.Eventbus; using BobDeathmic.Models; using BobDeathmic.Services; using BobDeathmic.ViewModels; using BobDeathmic.ViewModels.User; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using static BobDeathmic.Controllers.UserController; namespace BobDeathmic.Controllers { public class MainController : Controller { public IActionResult Index() { if (User.Identity.IsAuthenticated) { return RedirectToAction("Subscriptions", "User"); } //return View(); return RedirectToAction("Login"); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } private readonly UserManager<ChatUserModel> _userManager; private readonly SignInManager<ChatUserModel> _signInManager; private readonly ILogger _logger; private readonly IEventBus _eventBus; private readonly ApplicationDbContext _dbcontext; public MainController( UserManager<ChatUserModel> userManager, SignInManager<ChatUserModel> signInManager, ILogger<MainController> logger, IEventBus eventBus, ApplicationDbContext dbcontext) { _userManager = userManager; _signInManager = signInManager; _logger = logger; _eventBus = eventBus; _dbcontext = dbcontext; } [TempData] public string ErrorMessage { get; set; } [HttpGet] [AllowAnonymous] public async Task<IActionResult> Login(string returnUrl = null) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpPost] [AllowAnonymous] public async Task<String> LoginMobile() { using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { string json = await reader.ReadToEndAsync(); MobileLoginData data = JsonConvert.DeserializeObject<MobileLoginData>(json); var result = await _signInManager.PasswordSignInAsync(data.user, data.pass, true, false); return JsonConvert.SerializeObject(new MobileResponse() { Response = "true"}); } return JsonConvert.SerializeObject(new MobileResponse() { Response = "false" }); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation("User logged in."); if (returnUrl != null) { return Redirect(returnUrl); } else { return RedirectToAction("Subscriptions", "User"); } } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return RedirectToAction(nameof(Lockout)); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } [HttpGet] [AllowAnonymous] public IActionResult Lockout() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); _logger.LogInformation("User logged out."); return RedirectToAction(nameof(MainController.Index), "Main"); } [HttpGet] public IActionResult AccessDenied() { return View(); } public IActionResult ForgotPassword() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RequestPasswort(RequestPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = _dbcontext.ChatUserModels.Where(cu => cu.ChatUserName.ToLower() == model.UserName.ToLower() || cu.UserName.ToLower() == model.UserName.ToLower()).FirstOrDefault(); if (user != null) { var RemovePasswordResult = await _userManager.RemovePasswordAsync(user); if (RemovePasswordResult.Succeeded) { string password = <PASSWORD>(); var AddPasswordResult = await _userManager.AddPasswordAsync(user, password); if (AddPasswordResult.Succeeded) { _eventBus.TriggerEvent(EventType.PasswordRequestReceived, new Args.PasswordRequestArgs { UserName = user.ChatUserName, TempPassword = <PASSWORD> }); } } } return RedirectToAction(nameof(Login)); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(MainController.Index), "Main"); } } #endregion } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/TextColumn.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class TextColumn : Column { public string ReactComponentName { get { return "TextColumn"; } } public int key { get; set; } public string Text { get; set; } public TextColumn(int key, string Text, bool canSort = false) { this.key = key; this.Text = Text; this.canSort = canSort; } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/LinkColumn.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class LinkColumn: Column { public string ReactComponentName { get { return "LinkColumn"; } } public int key { get; set; } public string Text { get; set; } public string Link { get; set; } public LinkColumn(int key, string Text, string Link) { this.key = key; this.Text = Text; this.canSort = false; this.Link = Link; } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/StreamCommandEditColumn.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class StreamCommandEditColumn : Column { public string ReactComponentName { get { return "StreamCommandEditColumn"; } } public string Text { get; set; } public int CommandID { get; set; } public StreamCommandEditColumn(int key, string Text,int CommandID) { this.Key = key; this.Text = Text; this.canSort = false; this.CommandID = CommandID; } } } <file_sep>/BobDeathmic/ViewModels/User/ChangePasswordViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.User { public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "Momentanes Passwort")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "Das {0} muss mindestens zwischen {2} und {1} Zeichen lang sein.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Neues Passwort")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Passwort bestätigen")] [Compare("NewPassword", ErrorMessage = "Die Passwörter stimmen nicht überein.")] public string ConfirmPassword { get; set; } public string StatusMessage { get; set; } } } <file_sep>/BobDeathmic/Data/Enums/ChatType.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.Enums { public enum ChatType { Discord, Twitch, NotImplemented } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinder/Edit_Create/InvitedMemberList.jsx class InvitedUserList extends React.Component { constructor(props) { super(props); this.state = { InvitedUsers: [] }; this.handleUpdateChatMembers = this.handleUpdateChatMembers.bind(this); this.handleOnRemoveClick = this.handleOnRemoveClick.bind(this); } componentWillMount() { var thisreference = this; $.ajax({ url: "/Events/InvitedUsers/" + this.props.ID, type: "GET", data: {}, success: function (result) { thisreference.setState({ InvitedUsers: result }); } }); this.props.eventEmitter.addListener("UpdateChatMembers", thisreference.handleUpdateChatMembers); } handleUpdateChatMembers(event) { var thisreference = this; $.ajax({ url: "/Events/InvitedUsers/" + thisreference.props.ID, type: "GET", data: {}, success: function (result) { thisreference.setState({ InvitedUsers: result }); } }); } handleOnRemoveClick(event) { var thisreference = this; event.persist(); $.ajax({ url: "/Events/RemoveInvitedUser/", type: "POST", data: { ID: thisreference.props.ID, ChatUser: event.target.dataset.value }, success: function (result) { thisreference.props.eventEmitter.emitEvent("UpdateChatMembers"); } }); } handleOnClick(event) { } handleOnChange(event) { } render() { chatUserNodes = ""; if (this.state.InvitedUsers.length > 0) { var tempthis = this; var chatUserNodes = this.state.InvitedUsers.map(function (chatUser) { return (<div key={chatUser.key} className="col-12 userListItem"> <span>{chatUser.name}</span><span onClick={tempthis.handleOnRemoveClick} data-value={chatUser.name} className="button">remove</span> </div>); }); return ( <div> <div className="row" key={this.props.key}> {chatUserNodes} </div> </div> ); } return <p> No Users Loaded</p>; } }<file_sep>/BobDeathmic/Data/DBModels/GiveAway/manymany/User_GiveAwayItem.cs  using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using BobDeathmic; using BobDeathmic.Models; using BobDeathmic.Data.DBModels.User; namespace BobDeathmic.Data.DBModels.GiveAway.manymany { public class User_GiveAwayItem { [Key] public int User_GiveAwayItemID; public string UserID { get; set; } public ChatUserModel User { get; set; } public string GiveAwayItemID { get; set; } public GiveAwayItem GiveAwayItem { get; set; } public User_GiveAwayItem() { } public User_GiveAwayItem(ChatUserModel user, GiveAwayItem item) { UserID = user.Id; User = user; GiveAwayItemID = item.Id; GiveAwayItem = item; } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Other/StreamCommandEditData.cs using BobDeathmic.Data.DBModels.StreamModels; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Other { public class StreamCommandEditData { public string Name { get; set; } public string Response { get; set; } public string Mode { get; set; } public int AutoInterval { get; set; } public string StreamName { get; set; } public int StreamID { get; set; } public List<StreamData> Streams { get; set; } public StreamCommandEditData(StreamCommand command,IEnumerable<Stream> Streamlist) { Name = command.name; Response = command.response; Mode = command.Mode.ToString(); AutoInterval = command.AutoInverval; StreamName = command.stream.StreamName; StreamID = command.stream.ID; Streams = new List<StreamData>(); foreach(Stream stream in Streamlist) { Streams.Add(new StreamData(stream.StreamName,stream.ID)); } } public StreamCommandEditData(IEnumerable<Stream> Streamlist) { Name = ""; Response = ""; Mode = ""; AutoInterval = 0; StreamName = ""; StreamID = 0; Streams = new List<StreamData>(); foreach (Stream stream in Streamlist) { Streams.Add(new StreamData(stream.StreamName, stream.ID)); } } public string ToJSON() { return JsonConvert.SerializeObject(this); } } public class StreamData { public string Name { get; set; } public int ID { get; set; } public StreamData(string Name,int ID) { this.Name = Name; this.ID = ID; } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/EventDateFinder/OverView/OverView.cs using BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.OverView; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic; namespace BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.OverView { public class OverView { public List<Calendar> Calendars { get; set; } public string AddCalendarLink { get; set; } } } <file_sep>/BobDeathmic/Services/Commands/ICommandService.cs using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Services.Commands { public interface ICommandService { List<ICommand> GetCommands(ChatType type); Task handleCommand(ChatCommandInputArgs args, ChatType chatType, string sender); } } <file_sep>/BobDeathmic/ViewModels/StreamModels/StreamEditViewDataModel.cs using BobDeathmic.Data.DBModels.Relay; using BobDeathmic.Data.DBModels.StreamModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.StreamModels { public class StreamEditViewDataModel { public Stream stream { get; set; } public List<string> StreamTypes { get; set; } public List<RelayChannels> RelayChannels { get; set; } public string SelectedRelayChannel { get; set; } public string StatusMessage { get; set; } } } <file_sep>/BobDeathmic/Data/Enums/Stream/SubscriptionState.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.Enums.Stream { public enum SubscriptionState { Subscribed = 1, Unsubscribed = 0 } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinder/Edit_Create/TemplateList.jsx class TemplateList extends React.Component { constructor(props) { super(props); this.state = { Templates: [] }; this.handleAddTemplateClick = this.handleAddTemplateClick.bind(this); this.handleAddTemplateClick = this.handleAddTemplateClick.bind(this); this.handleUpdateTemplates = this.handleUpdateTemplates.bind(this); } componentWillMount() { var thisreference = this; $.ajax({ url: "/Events/Templates/" + this.props.ID, type: "GET", data: {}, success: function (result) { thisreference.setState({ Templates: result }); } }); this.props.eventEmitter.addListener("UpdateTemplates", thisreference.handleUpdateTemplates); } handleUpdateTemplates(event) { var tempthis = this; $.ajax({ url: "/Events/Templates/" + this.props.ID, type: "GET", data: {}, success: function (result) { tempthis.setState({ Templates: result }); } }); } handleAddTemplateClick(event) { var tempthis = this; $.ajax({ url: "/Events/AddTemplate/" + this.props.ID, type: "GET", data: {}, success: function (result) { var temptemplates = tempthis.state.Templates; temptemplates.push(result); tempthis.setState({ Templates: temptemplates }); } }); } render() { if (this.state.Templates.length > 0) { var tempthis = this; var templateNodes = this.state.Templates.map(function (template) { return <Template calendar={tempthis.props.ID} eventEmitter={tempthis.props.eventEmitter} key={template.key} name={template.key} day={template.Day} start={template.Start} stop={template.Stop} />; }); return ( <div> <div className="row" key={this.props.key}> <div className="col-12"> <span onClick={this.handleAddTemplateClick} className="button">Add Template</span> </div> <div className="col-12"> {templateNodes} </div> </div> </div> ); } return (<div className="row"> <div className="col-12"> <span onClick={this.handleAddTemplateClick} className="button">Add Template</span> </div> </div>); } }<file_sep>/BobDeathmic.Tests/Helper/EventCalendar/MutableTupleTests.cs using BobDeathmic.Helper.EventCalendar; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace BobDeathmic.Tests.Helper.EventCalendar { [TestFixture] public class MutableTupleTests { [Test] public void MutableTuple_ChangeValue_ExpectedChange() { MutableTuple<string, string> test = new MutableTuple<string, string>("V1", "V2"); test.First = "Test"; Assert.That(test.First,Is.EqualTo("Test")); Assert.That(test.Second,Is.EqualTo("V2")); } } } <file_sep>/BobDeathmic/Data/ReadME.txt Do not rename Namespaces according to folder. Reorganized Structure and otherwise one would need to refactor migrations and possible database<file_sep>/BobDeathmic/Data/DBModels/EventCalendar/EventDateTemplate.cs using BobDeathmic.Data.DBModels.EventCalendar; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.Models.Events; using BobDeathmic; using BobDeathmic.Models; namespace BobDeathmic.Data.DBModels.EventCalendar { //Template aus dem EventDates generiert werden //TODO Rename is confusing cause in reality it is a EventDateTemplate public class EventDateTemplate { public string ID { get; set; } public Event Event { get; set; } public DateTime StartTime { get; set; } public DateTime StopTime { get; set; } public Day Day { get; set; } //Pos 1 / 2 cause only showing 2 weeks) public EventDate CreateEventDate(int Pos) { EventDate Clone = new EventDate(); Clone.Event = Event; Clone.StartTime = StartTime; Clone.StopTime = StopTime; TimeSpan add = new TimeSpan(); DateTime today = DateTime.Today.Add(new TimeSpan(1, StartTime.Hour, StartTime.Minute, 0)); // The (... + 7) % 7 ensures we end up with a value in the range [0, 6] int daysUntilTargetDay = (((int)Day - (int)today.DayOfWeek + 7) % 7) + Pos * 7; DateTime nextDayOccurence = today.AddDays(daysUntilTargetDay); Clone.Date = nextDayOccurence; return Clone; } } public enum Day { Montag = 1, Dienstag = 2, Mittwoch = 3, Donnerstag = 4, Freitag = 5, Samstag = 6, Sonntag = 7 } } <file_sep>/BobDeathmic/Services/Commands/CommandService.cs using BobDeathmic.ChatCommands; using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data.Enums; using BobDeathmic.Eventbus; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Services.Commands { public class CommandService : BackgroundService,ICommandService { private List<ICommand> Commands; private IServiceScopeFactory scopefactory; private IEventBus eventBus; protected async override Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } } public CommandService(IServiceScopeFactory scopefactory,IEventBus evenbus) { initCommands(); this.scopefactory = scopefactory; this.eventBus = evenbus; } private void initCommands() { Commands = new List<ICommand>(); Commands.Add(new TwitchStreamTitle()); Commands.Add(new Game()); Commands.Add(new Title()); Commands.Add(new Strawpoll()); Commands.Add(new RandomChatUserRegisterCommand()); Commands.Add(new PickNextRandChatUserForNameCommand()); Commands.Add(new PickNextChatUserForNameCommand()); Commands.Add(new ListRandUsersInListCommand()); Commands.Add(new SkipLastRandUserCommand()); Commands.Add(new QuoteCommand()); Commands.Add(new GiveAwayApply()); Commands.Add(new GiveAwayCease()); Commands.Add(new Help(Commands)); } public List<ICommand> GetCommands(ChatType type) { return Commands.Where(x => x.ChatSupported(type) && x.GetType() != typeof(Help)).ToList(); } public async Task handleCommand(ChatCommandInputArgs args, ChatType chatType, string sender) { foreach(ICommand command in Commands.Where(x => x.ChatSupported(chatType) && x.isCommand(args.Message))) { ChatCommandOutput output = await command.execute(args, scopefactory); if(output.ExecuteEvent) { eventBus.TriggerEvent(output.Type, output.EventData); } } } } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/PasswordRequestArgs.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Args { public class PasswordRequestArgs { public string UserName { get; set; } public string TempPassword { get; set; } } } <file_sep>/BobDeathmic/ChatCommands/GiveAway.cs using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.GiveAway.manymany; using BobDeathmic.Data.Enums; using BobDeathmic.Eventbus; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands { public class GiveAwayApply : ICommand { public string Trigger => "!Gapply"; public string Description => "Command um an momentaner Verlosung teilzunehmen"; public string Category => "GiveAway"; public string Alias => "!Gapply"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Discord; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = true; output.Type = Eventbus.EventType.CommandResponseReceived; string message = ""; using (var scope = scopefactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var GiveAwayItem = _context.GiveAwayItems.Include(x => x.Applicants).Where(x => x.current).FirstOrDefault(); if (GiveAwayItem.Applicants == null) { GiveAwayItem.Applicants = new List<User_GiveAwayItem>(); } var user = _context.ChatUserModels.Where(x => x.ChatUserName.ToLower() == args.Sender.ToLower()).FirstOrDefault(); if (GiveAwayItem.Applicants.Where(x => x.UserID == user.Id).Count() == 0) { var item = _context.GiveAwayItems.Where(x => x.current).FirstOrDefault(); if (user != null && item != null) { User_GiveAwayItem relation = new User_GiveAwayItem(user, item); relation.User = user; if (user.AppliedTo == null) { user.AppliedTo = new List<User_GiveAwayItem>(); } if (item.Applicants == null) { item.Applicants = new List<User_GiveAwayItem>(); } user.AppliedTo.Add(relation); item.Applicants.Add(relation); message= "Teilnahme erfolgreich"; } else { message = "Gibt nichs zum teilnehmen"; } } else { message = "Nimmst schon teil."; } _context.SaveChanges(); } output.EventData = new CommandResponseArgs( ChatType.Discord, message, MessageType.PrivateMessage, args.Sender, args.ChannelName ); return output; } public bool isCommand(string message) { return message.ToLower().StartsWith(Trigger.ToLower()); } } public class GiveAwayCease : ICommand { public string Trigger => "!Gcease"; public string Description => "Command um momentaner Teilnahme zurückzuziehen"; public string Category => "GiveAway"; public string Alias => "!Gcease"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Discord; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = false; output.Type = Eventbus.EventType.CommandResponseReceived; string message = ""; using (var scope = scopefactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var user = _context.ChatUserModels.Where(x => x.ChatUserName.ToLower() == args.Sender.ToLower()).FirstOrDefault(); var remove = _context.User_GiveAway.Where(x => x.UserID == user.Id).FirstOrDefault(); if (remove != null) { _context.User_GiveAway.Remove(remove); _context.SaveChanges(); } } return output; } public bool isCommand(string message) { return message.ToLower().StartsWith(Trigger.ToLower()); } } } <file_sep>/BobDeathmic/Data/DBModels/Commands/RandomChatUser.cs using BobDeathmic; using BobDeathmic.Data.DBModels.Commands; using BobDeathmic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.Commands { public class RandomChatUser { public int ID { get; set; } public string Stream { get; set; } public int Sort { get; set; } public string ChatUser { get; set; } public bool lastchecked { get; set; } } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/TwitchMessageArgs.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Args { public class TwitchMessageArgs { public string Message { get; set; } public string Source { get; set; } public string Target { get; set; } } } <file_sep>/BobDeathmic/Data/ApplicationDbContext.cs using BobDeathmic.Data.DBModels.Commands; using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Data.DBModels.EventCalendar.manymany; using BobDeathmic.Data.DBModels.GiveAway; using BobDeathmic.Data.DBModels.GiveAway.manymany; using BobDeathmic.Data.DBModels.Quote; using BobDeathmic.Data.DBModels.Relay; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Models; using BobDeathmic.Models.Events; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data { public class ApplicationDbContext : IdentityDbContext<ChatUserModel> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); builder.Entity<ChatUserModel>() .HasMany(u => u.StreamSubscriptions) .WithOne(ss => ss.User) .OnDelete(DeleteBehavior.Cascade); builder.Entity<ChatUserModel>() .HasMany(u => u.OwnedStreams) .WithOne(s => s.Owner) .OnDelete(DeleteBehavior.Cascade); builder.Entity<Stream>() .HasMany(s => s.StreamSubscriptions) .WithOne(ss => ss.Stream) .OnDelete(DeleteBehavior.Cascade); builder.Entity<Stream>() .HasMany(s => s.Commands) .WithOne(sc => sc.stream) .OnDelete(DeleteBehavior.Cascade); builder.Entity<Stream>().HasOne(s => s.Owner).WithMany(u => u.OwnedStreams); builder.Entity<GiveAwayItem>() .HasOne(gai => gai.Owner) .WithMany(u => u.OwnedItems) .OnDelete(DeleteBehavior.ClientSetNull); builder.Entity<GiveAwayItem>() .HasOne(gai => gai.Receiver) .WithMany(u => u.ReceivedItems) .OnDelete(DeleteBehavior.ClientSetNull); builder.Entity<User_GiveAwayItem>() .HasKey(t => new { t.UserID, t.GiveAwayItemID }); builder.Entity<User_GiveAwayItem>() .HasOne(pt => pt.User) .WithMany(p => p.AppliedTo) .HasForeignKey(pt => pt.UserID); builder.Entity<User_GiveAwayItem>() .HasOne(pt => pt.GiveAwayItem) .WithMany(t => t.Applicants) .HasForeignKey(pt => pt.GiveAwayItemID); builder.Entity<ChatUserModel>() .HasMany(x => x.Calendars) .WithOne(x => x.ChatUserModel) .OnDelete(DeleteBehavior.SetNull); builder.Entity<Event>() .HasOne(c => c.Admin) .WithMany(u => u.AdministratedCalendars) .OnDelete(DeleteBehavior.SetNull); builder.Entity<Event>() .HasMany(x => x.EventDates) .WithOne(y => y.Event) .OnDelete(DeleteBehavior.Cascade); builder.Entity<EventDate>() .HasOne(x => x.Event) .WithMany(y => y.EventDates) .OnDelete(DeleteBehavior.ClientSetNull); builder.Entity<EventDate>() .HasMany(x => x.Teilnahmen) .WithOne(x => x.EventDate) .OnDelete(DeleteBehavior.Cascade); builder.Entity<Event>() .HasMany(x => x.EventDateTemplates) .WithOne(y => y.Event) .OnDelete(DeleteBehavior.Cascade); builder.Entity<AppointmentRequest>() .HasOne(x => x.Owner) .WithMany(x => x.AppointmentRequests) .OnDelete(DeleteBehavior.ClientSetNull); } //a foreign key constraint fails (`bobcoreef`.`appointmentrequests`, CONSTRAINT `FK_AppointmentRequests_EventDates_EventDateID` FOREIGN KEY (`EventDateID`) REFERENCES `eventdates` (`ID`)) --- public DbSet<ChatUserModel> ChatUserModels { get; set; } public DbSet<Stream> StreamModels { get; set; } public DbSet<StreamSubscription> StreamSubscriptions { get; set; } public DbSet<SecurityToken> SecurityTokens { get; set; } public DbSet<RelayChannels> RelayChannels { get; set; } public DbSet<DiscordBan> DiscordBans { get; set; } public DbSet<StreamCommand> StreamCommand { get; set; } public DbSet<GiveAwayItem> GiveAwayItems { get; set; } public DbSet<User_GiveAwayItem> User_GiveAway { get; set; } public DbSet<Event> Events { get; set; } public DbSet<AppointmentRequest> AppointmentRequests { get; set; } public DbSet<EventDateTemplate> EventDateTemplates { get; set; } public DbSet<EventDate> EventDates { get; set; } public DbSet<ChatUserModel_Event> ChatUserModel_Event { get; set; } public DbSet<RandomChatUser> RandomChatUser { get; set; } public DbSet<Quote> Quotes { get; set; } } } <file_sep>/BobDeathmic.Tests/Data/DBModels/User/ChatUserTests.cs using System; using System.Collections.Generic; using System.Text; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.DBModels.User; using NUnit.Framework; using Microsoft.Extensions.Identity; namespace BobDeathmic.Tests.Data.DBModels.User { [TestFixture] class ChatUserTests { [Test] [TestCase("TestName",true)] [TestCase("StreamNotIncluded",false)] public void IsSubscribed_PreparedChatUserModelWithSubscriptions_ReturnsExpectedResult(string streamname, bool expectedResult) { Stream stream = new Stream("TestName"); ChatUserModel model = new ChatUserModel(new List<Stream>() { stream }); Assert.That(model.IsSubscribed(streamname), Is.EqualTo(expectedResult)); } [Test] public void IsSubscribed_PreparedChatUserModelWithEmptySubscriptions_ReturnsFalse() { ChatUserModel model = new ChatUserModel(); string streamName = "StreamName"; Assert.That(model.IsSubscribed(streamName), Is.EqualTo(false)); } [Test] public void IsSubscribed_EmptyStreamName_Throws() { ChatUserModel model = new ChatUserModel(); string streamName = ""; Assert.That(() => model.IsSubscribed(streamName), Throws.ArgumentException); } [Test] [TestCase("Test|UserName","TestUserName")] [TestCase("Test'fülk","Testfülk")] public void ChatUserModel_InputUserName_HasCorrectlyCleanedUserName(string UserName,string expectedResult) { ChatUserModel model = new ChatUserModel(UserName); Assert.That(model.UserName, Is.EqualTo(expectedResult)); } //TODO Write Test the ensures SetInitialPassword sets an Initial Password } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinderList.jsx  /* class CommentBox extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } componentWillMount() { const xhr = new XMLHttpRequest(); xhr.open('get', this.props.url, true); xhr.onload = () => { const data = JSON.parse(xhr.responseText); this.setState({ data: data }); }; xhr.send(); } render() { return ( <div className="commentBox"> <CommentList data={this.state.data} /> </div> ); } } class CommentList extends React.Component { render() { const commentNodes = this.props.data.map(function (comment) { console.log(comment) return <Comment author={comment.author} key={comment.id} text={comment.text}/> }); console.log(this.props.data); return <div className="commentList">{commentNodes}</div>; } } class Comment extends React.Component { render() { return (<div className="Comment">Author: {this.props.author} <br/>Text: {this.props.text}</div>) } } ReactDOM.render(<CommentBox url="/TestData" />, document.getElementById('reactcontent')); */<file_sep>/BobDeathmic/Services/Streams/Checker/Mixer/JSONDataTypes/MixerChannelInfo.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.JSONObjects { public class MixerChannelInfo { public bool featured { get; set; } public int? id { get; set; } public int? userId { get; set; } public string token { get; set; } public bool online { get; set; } public int? featureLevel { get; set; } public bool partnered { get; set; } public int? transcodingProfileId { get; set; } public bool suspended { get; set; } public string name { get; set; } public string audience { get; set; } public int? viewersTotal { get; set; } public int? viewersCurrent { get; set; } public int? numFollowers { get; set; } public string description { get; set; } public int? typeId { get; set; } public bool interactive { get; set; } public int? interactiveGameId { get; set; } public int? ftl { get; set; } public bool hasVod { get; set; } public int? langaugeId { get; set; } public int? coverId { get; set; } public int? thumbnailId { get; set; } public int? badgeId { get; set; } public string bannerUrl { get; set; } public int? hosteeId { get; set; } public bool hasTranscodes { get; set; } public bool vodsEnabled { get; set; } public int? costreamId { get; set; } public DateTime? createdAt { get; set; } public DateTime? updatedAt { get; set; } public DateTime? deletedAt { get; set; } public MixerType type { get; set; } } public class MixerType { public string name { get; set; } } } <file_sep>/BobDeathmic/Data/DBModels/EventCalendar/manymany/ChatUserModel_Event.cs using BobDeathmic; using BobDeathmic.Data.DBModels.EventCalendar.manymany; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Models; using BobDeathmic.Models.Events; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.EventCalendar.manymany { public class ChatUserModel_Event { public string ChatUserModel_EventID { get; set; } public int CalendarID { get; set; } public Event Calendar { get; set; } public string ChatUserModelID { get; set; } public ChatUserModel ChatUserModel { get; set; } } } <file_sep>/BobDeathmic/Data/Enums/Stream/TokenType.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.Enums.Stream { public enum TokenType { Twitch = 1, Mixer = 2, Discord = 3 } } <file_sep>/BobDeathmic/ViewModels/User/UserRolesViewModel.cs using BobDeathmic.Data.DBModels.User; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.User { public class UserRolesViewModel { public ChatUserModel User { get; set; } public IList<string> Roles { get; set; } } } <file_sep>/BobDeathmic/Data/DBModels/StreamModels/Stream.cs using BobDeathmic.Data.DBModels.User; using BobDeathmic.Data.Enums.Relay; using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.StreamModels { public class Stream { public int ID { get; set; } public string StreamName { get; set; } public string Game { get; set; } public string UserID { get; set; } public string Url { get; set; } public StreamProviderTypes Type { get; set; } public string AccessToken { get; set; } public string Secret { get; set; } public string ClientID { get; set; } public string RefreshToken { get; set; } public DateTime Started { get; set; } public DateTime Stopped { get; set; } public DateTime LastNotice { get; set; } public StreamState StreamState { get; set; } public string DiscordRelayChannel { get; set; } public List<StreamSubscription> StreamSubscriptions { get; set; } public ChatUserModel Owner { get; set; } public int UpTimeInterval { get; set; } public DateTime LastUpTime { get; set; } public int QuoteInterval { get; set; } public DateTime LastRandomQuote { get; set; } public List<StreamCommand> Commands { get; set; } public Stream() { } public Stream(string name) { StreamName = name; } public String[] GetActiveSubscribers() { //If you read this you probably forgot to "Include" either StreamSubscriptions or User in your EF Query return StreamSubscriptions.Where(x => x.Subscribed == SubscriptionState.Subscribed).Select(x => x.User.ChatUserName).ToArray(); } public List<string> EnumStreamTypes() { List<string> EnumTypes = new List<string>(); EnumTypes.Add("Twitch"); EnumTypes.Add("Mixer"); EnumTypes.Add("DLive"); return EnumTypes; } public static List<string> StaticEnumStreamTypes() { List<string> EnumTypes = new List<string>(); EnumTypes.Add("Twitch"); EnumTypes.Add("Mixer"); EnumTypes.Add("DLive"); return EnumTypes; } public string UptimeMessage() { LastUpTime = DateTime.Now; return $"Stream läuft seit {DateTime.Now.Subtract(Started).Hours} Stunden und {DateTime.Now.Subtract(Started).Minutes} Minuten"; } public bool UpTimeQueued() { return UpTimeInterval != 0 && LastUpTime.Add(new TimeSpan(0, UpTimeInterval, 0)) < DateTime.Now; } public string StreamStartedMessage(string title,string url = "") { string message = ""; message = $"{StreamName} hat angefangen {title} auf {Url} zu streamen."; if (Type == StreamProviderTypes.Twitch && DiscordRelayChannel != null && DiscordRelayChannel != "" && DiscordRelayChannel != "An" && DiscordRelayChannel != "Aus") { message += $" Relay befindet sich in Channel {DiscordRelayChannel}"; } return message; } public RelayState RelayState() { if (DiscordRelayChannel != "Aus" && DiscordRelayChannel != "") { return Enums.Relay.RelayState.Activated; } return Enums.Relay.RelayState.NotActivated; } } } <file_sep>/BobDeathmic/Cron/Setup/SchedulerHostService.cs using BobDeathmic.Cron.Setup; using BobDeathmic.Services.Helper; using Microsoft.Extensions.Hosting; using NCrontab; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Cron.Setup { public class SchedulerHostService : HostedService { List<SchedulerTaskWrapper> _scheduledTasks = new List<SchedulerTaskWrapper>(); public SchedulerHostService(IEnumerable<IScheduledTask> scheduledTasks) { foreach (var scheduledTask in scheduledTasks) { var Scheduler = new SchedulerTaskWrapper { Schedule = CrontabSchedule.Parse(scheduledTask.Schedule), Task = scheduledTask, Init = true }; _scheduledTasks.Add(Scheduler); } } protected override async Task ExecuteAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { await ExecuteOnceAsync(cancellationToken); await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken); } } private async Task ExecuteOnceAsync(CancellationToken cancellationToken) { var taskFactory = new TaskFactory(TaskScheduler.Current); var referenceTime = DateTime.Now; List<SchedulerTaskWrapper> tasksThatShouldRun = _scheduledTasks.Where(t => t.ShouldRun()).ToList(); foreach (var taskThatShouldRun in tasksThatShouldRun) { taskThatShouldRun.Increment(); await taskFactory.StartNew( async () => { try { await taskThatShouldRun.Task.ExecuteAsync(cancellationToken); } catch (Exception ex) { var args = new UnobservedTaskExceptionEventArgs( ex as AggregateException ?? new AggregateException(ex)); if (!args.Observed) { throw; } } }, cancellationToken); } } } } <file_sep>/BobDeathmic.Tests/Services/Discord/DiscordServiceTests.cs using BobDeathmic.Data; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Eventbus; using BobDeathmic.Services.Discords; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using NUnit.Framework; using System; using System.Threading.Tasks; namespace BobDeathmic.Tests.Services.Discord { [TestFixture] public class DiscordServiceTests { private DbContextOptions<ApplicationDbContext> options; private DiscordService Dservice; [SetUp] public void Init() { options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "Test") .Options; using (var context = new ApplicationDbContext(options)) { context.ChatUserModels.Add(new ChatUserModel()); context.SecurityTokens.Add(new BobDeathmic.Data.DBModels.StreamModels.SecurityToken { ClientID = "Test", token = "Token" }); context.SaveChanges(); } IEventBus eventbus = Substitute.For<IEventBus>(); IServiceScope scope = Substitute.For<IServiceScope>(); scope.ServiceProvider.GetService(typeof(ApplicationDbContext)).ReturnsForAnyArgs(new ApplicationDbContext(options)); IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); scopefactory.CreateScope().ReturnsForAnyArgs(scope); Dservice = new DiscordService(scopefactory, eventbus,null); } [Test] public async Task StopAsync_DService_IsInactive() { //await Dservice.StopAsync(new System.Threading.CancellationToken()); Assert.That(false, Is.False); } } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/RelayMessageArgs.cs using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Args { public class RelayMessageArgs: MessageArgs { public string SourceChannel { get; set; } public string TargetChannel { get; set; } public StreamProviderTypes StreamType { get; set; } public RelayMessageArgs() {} public RelayMessageArgs(string SourceChannel,string TargetChannel,StreamProviderTypes type,string Message) { this.SourceChannel = SourceChannel; this.TargetChannel = TargetChannel; this.StreamType = type; this.Message = Message; } } } <file_sep>/BobDeathmic/Data/Enums/Relay/RelayState.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.Enums.Relay { public enum RelayState { Activated = 0, NotActivated = 1 } } <file_sep>/BobDeathmic/Data/DBModels/User/DiscordBan.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.User { public class DiscordBan { public int Id { get; set; } public ulong DiscordID { get; set; } } } <file_sep>/BobDeathmic/Services/Twitch/JSONDataTypes/TwitchRefreshTokenData.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.JSONObjects { public class TwitchRefreshTokenData { public string access_token { get; set; } public string refresh_token { get; set; } public string[] scope { get; set; } public string error { get; set; } public int status { get; set; } public string message { get; set; } } } <file_sep>/BobDeathmic/Cron/EventCalendarTask.cs using BobDeathmic.Args; using BobDeathmic.Cron.Setup; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Eventbus; using BobDeathmic.Helper; using BobDeathmic.Helper.EventCalendar; using BobDeathmic.Models.Events; using BobDeathmic.Services.Helper; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Cron { public class EventCalendarTask : IScheduledTask { public string Schedule => "0 18 * * *"; private readonly IServiceScopeFactory _scopeFactory; private IEventBus _eventBus; private IConfiguration _configuration; public EventCalendarTask(IServiceScopeFactory scopeFactory, IEventBus eventBus, IConfiguration Configuration) { _scopeFactory = scopeFactory; _eventBus = eventBus; _configuration = Configuration; } public async Task ExecuteAsync(CancellationToken cancellationToken) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if (_context != null) { var ApplicableCalendars = _context.Events.Include(x => x.EventDateTemplates).Include(x => x.EventDates).ThenInclude(x => x.Teilnahmen).Include(x => x.Members).ThenInclude(x => x.ChatUserModel).Where(x => x.Members.Count() > 0 && x.EventDateTemplates.Count() > 0); RemovePassedEventDates(); foreach (Event calendar in ApplicableCalendars) { AddEventDatesOnCalendar(calendar.Id); UpdateEventDates(calendar.Id); _context.SaveChanges(); NotifyUsers(calendar); NotifyAdmin(calendar); } } } } private void NotifyAdmin(Event calendar) { var NotifiableEventDates = calendar.EventDates.Where(x => x.Teilnahmen.Where(y => y.State == AppointmentRequestState.Available || y.State == AppointmentRequestState.IfNeedBe).Count() == x.Teilnahmen.Count()); foreach (EventDate date in NotifiableEventDates) { _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = calendar.Admin.ChatUserName, Message = date.AdminNotification(calendar.Name) }); } } private void NotifyUsers(Event calendar) { string address = _configuration.GetValue<string>("WebServerWebAddress"); List<MutableTuple<string, string>> GroupedNotifications = new List<MutableTuple<string, string>>(); foreach (EventDate date in calendar.EventDates.Where(x => x.Date.Date == DateTime.Now.Add(TimeSpan.FromDays(1)).Date)) { foreach (AppointmentRequest request in date.Teilnahmen.Where(x => x.State == AppointmentRequestState.NotYetVoted)) { if (GroupedNotifications.Where(x => x.First == request.Owner.UserName).Count() == 0) { GroupedNotifications.Add(new MutableTuple<string, string>(request.Owner.UserName, $"Freundliche Errinnerung {request.Owner.UserName} du musst im Kalendar {request.EventDate.Event.Name} für den {request.EventDate.Date.ToString("dd.MM.yyyy HH:mm")} abstimmen. {address}/Events/VoteOnCalendar/{calendar.Id}")); } else { GroupedNotifications.Where(x => x.First == request.Owner.UserName).FirstOrDefault().Second += Environment.NewLine + $"Freundliche Errinnerung {request.Owner.UserName} du musst im Kalender {request.EventDate.Event.Name} für den {request.EventDate.Date.ToString("dd.MM.yyyy HH:mm")} abstimmen. {address}/Events/VoteOnCalendar/{calendar.Id}"; } } } foreach (MutableTuple<string, string> tuple in GroupedNotifications) { _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = tuple.First, Message = tuple.Second }); } } private void RemovePassedEventDates() { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var EventDatesToRemove = _context.EventDates.Where(x => x.Date < DateTime.Now); foreach (EventDate remove in EventDatesToRemove) { _context.EventDates.Remove(remove); } _context.SaveChanges(); foreach (Event calendar in _context.Events) { var EventDatesInCalendarToRemove = calendar.EventDates.Where(x => x.Date < DateTime.Now); foreach (EventDate remove in EventDatesInCalendarToRemove) { calendar.EventDates.Remove(remove); } } _context.SaveChanges(); } } private void AddEventDatesOnCalendar(int id) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var calendar = _context.Events.Include(x => x.EventDateTemplates).Include(x => x.EventDates).ThenInclude(x => x.Teilnahmen).Include(x => x.Members).ThenInclude(x => x.ChatUserModel).Where(x => x.Id == id).FirstOrDefault(); if(calendar != null) { // Next 2 weeks for (int week = 0; week < 2; week++) { foreach (EventDateTemplate template in calendar.EventDateTemplates) { EventDate eventdate = template.CreateEventDate(week); eventdate.EventDateTemplateID = template.ID; if (calendar.EventDates.Where(x => x.Date == eventdate.Date).Count() == 0) { eventdate.Teilnahmen = calendar.GenerateAppointmentRequests(eventdate); _context.EventDates.Add(eventdate); calendar.EventDates.Add(eventdate); } } } _context.SaveChanges(); } } } private void UpdateEventDates(int id) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var calendar = _context.Events.Include(x => x.EventDateTemplates).Include(x => x.EventDates).ThenInclude(x => x.Teilnahmen).Include(x => x.Members).ThenInclude(x => x.ChatUserModel).Where(x => x.Id == id).FirstOrDefault(); if(calendar != null) { foreach (EventDate update in calendar.EventDates) { var template = _context.EventDateTemplates.Where(x => x.ID == update.EventDateTemplateID).FirstOrDefault(); if (template != null) { update.StartTime = template.StartTime; update.StopTime = template.StopTime; update.Date = DateTime.ParseExact(update.Date.ToString("dd-MM-yyyy") + " " + update.StartTime.ToString("HH:mm"), "dd-MM-yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture); } } _context.SaveChanges(); } } } } } <file_sep>/BobDeathmic/Data/DBModels/StreamModels/SecurityToken.cs using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.StreamModels { public class SecurityToken { public int ID { get; set; } public string ClientID { get; set; } public string token { get; set; } public TokenType service { get; set; } public string code { get; set; } public string secret { get; set; } public string RefreshToken { get; set; } } } <file_sep>/BobDeathmic/Controllers/UserController.cs using BobDeathmic.Data; using BobDeathmic.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using BobDeathmic.Models; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.ViewModels.User; using BobDeathmic.ViewModels.ReactDataClasses.Table; using BobDeathmic.ViewModels.ReactDataClasses.Table.Columns; using BobDeathmic.ViewModels.ReactDataClasses.Other; using Newtonsoft.Json; namespace BobDeathmic.Controllers { public class UserController : Controller { private readonly ApplicationDbContext _context; private UserManager<ChatUserModel> _userManager; private readonly SignInManager<ChatUserModel> _signInManager; public UserController(ApplicationDbContext context, UserManager<ChatUserModel> userManager, SignInManager<ChatUserModel> signInManager) { _context = context; _userManager = userManager; _signInManager = signInManager; } [TempData] public string StatusMessage { get; set; } [Authorize(Roles = "User,Dev,Admin")] public IActionResult Index() { return View(); } /* [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Subscriptions() { ChatUserModel usermodel = await _userManager.GetUserAsync(this.User); List<StreamSubscription> streamsubs = _context.StreamSubscriptions.Include(ss => ss.User).Include(ss => ss.Stream).Where(ss => ss.User == usermodel).ToList(); List<Stream> FilteredStreams = new List<Stream>(); foreach (var stream in _context.StreamModels) { bool add = true; if (streamsubs != null && streamsubs.Where(ss => ss.Stream.StreamName == stream.StreamName && ss.Stream.Type == stream.Type).Count() > 0) { add = false; } if (add) { FilteredStreams.Add(stream); } } AddSubscriptionViewModel model = new AddSubscriptionViewModel(); if (FilteredStreams.Count() > 0) { model.SubscribableStreams = FilteredStreams; } model.Subscriptions = streamsubs; return View(model); } */ [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Subscriptions() { return View(); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<String> SubscriptionsData() { ChatUserModel usermodel = await _userManager.GetUserAsync(this.User); List<StreamSubscription> streamsubs = _context.StreamSubscriptions.Include(ss => ss.User).Include(ss => ss.Stream).Where(ss => ss.User == usermodel).ToList(); Table table = new Table(); Row row = new Row(false,true); row.AddColumn(new TextColumn(0, "StreamName",true)); row.AddColumn(new TextColumn(1, "Sub Status")); table.AddRow(row); //TODO Second Request for Streams not yet added foreach (var streamsub in streamsubs) { Row newrow = new Row(); newrow.AddColumn(new TextColumn(0, streamsub.Stream.StreamName)); if (streamsub.Subscribed == SubscriptionState.Subscribed) { newrow.AddColumn(new StreamSubColumn(1, true, streamsub.ID)); } else { newrow.AddColumn(new StreamSubColumn(1, false, streamsub.ID)); } table.AddRow(newrow); } return table.getJson(); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<String> SubscribableStreamsData() { ChatUserModel usermodel = await _userManager.GetUserAsync(this.User); List<StreamSubscription> streamsubs = _context.StreamSubscriptions.Include(ss => ss.User).Include(ss => ss.Stream).Where(ss => ss.User == usermodel).ToList(); List<SubscribableStream> FilteredStreams = new List<SubscribableStream>(); foreach (var stream in _context.StreamModels) { bool add = true; if (streamsubs != null && streamsubs.Where(ss => ss.Stream.StreamName == stream.StreamName && ss.Stream.Type == stream.Type).Count() > 0) { add = false; } if (add) { FilteredStreams.Add(new SubscribableStream(stream.StreamName,stream.ID)); } } return JsonConvert.SerializeObject(FilteredStreams); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<bool> AddSubscription(int streamid) { var stream = _context.StreamModels.Where(s => s.ID == streamid).FirstOrDefault(); ChatUserModel user = await _userManager.GetUserAsync(this.User); if (stream != null) { if (user.StreamSubscriptions == null) { user.StreamSubscriptions = new List<StreamSubscription>(); } StreamSubscription newsub = new StreamSubscription(); newsub.Stream = stream; newsub.User = user; newsub.Subscribed = SubscriptionState.Subscribed; _context.StreamSubscriptions.Add(newsub); user.StreamSubscriptions.Add(newsub); await _context.SaveChangesAsync(); return true; } return false; } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task<string> ChangeSubscription(int id) { if (id == null) { return "error"; //return NotFound(); } StreamSubscription sub = _context.StreamSubscriptions.Where(ss => ss.ID == id).FirstOrDefault(); DateTime start = DateTime.Now; string @return = "error"; if (sub != null) { switch (sub.Subscribed) { case SubscriptionState.Subscribed: sub.Subscribed = SubscriptionState.Unsubscribed; @return = "false"; break; case SubscriptionState.Unsubscribed: sub.Subscribed = SubscriptionState.Subscribed; @return = "true"; break; } await _context.SaveChangesAsync(); } return @return; //return RedirectToAction(nameof(Subscriptions)); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> DeleteUser() { return View(); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> DeleteUser(int? id) { var user = await _userManager.GetUserAsync(this.User); await _userManager.DeleteAsync(user); return Redirect(nameof(MainController.Index)); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public IActionResult ChangePassword() { var model = new ChangePasswordViewModel { StatusMessage = StatusMessage }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(this.User); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); StatusMessage = "Passwort wurde geändert."; return RedirectToAction(nameof(ChangePassword)); } StatusMessage = "Passwort wurde nicht geändert."; return RedirectToAction(nameof(ChangePassword)); } return RedirectToAction(nameof(ChangePassword)); } #region Helpers public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } #endregion } }<file_sep>/BobDeathmic/Helper/EventCalendar/MutableTuple.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.Helper; using BobDeathmic; namespace BobDeathmic.Helper.EventCalendar { public class MutableTuple<T1, T2> { public T1 First { get; set; } public T2 Second { get; set; } public MutableTuple(T1 First, T2 Second) { this.First = First; this.Second = Second; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinder/Vote/StateSelect.jsx class StateSelect extends React.Component { constructor(props) { super(props); this.state = { possibleStates: props.possibleStates, State: props.state, RetryCount: 0,comment: props.comment}; //this.handleOnChange = this.handleOnChange.bind(this); this.handleClick = this.handleClick.bind(this); } handleClick(event) { event.target.classList.add("processing"); var thisreference = this; var tmpevent = event; var element = event.target; let value = tmpevent.target.getAttribute("data-value"); let comment = ""; if (value === "3") { comment = prompt("Kommentar eingeben", ""); } thisreference.SyncStateToServer(thisreference.props.requestID, value, element,comment); } SyncStateToServer(ID, State, element,comment) { var thisreference = this; $.ajax({ url: "/Events/UpdateRequestState/", type: "GET", data: { requestID: ID, state: State, comment: comment }, success: function (result) { if (result > 0) { thisreference.setState({ State: parseInt(element.getAttribute("data-value")), comment: comment }); } else { if (thisreference.state.RetryCount === 3) { confirm("Einer deiner Abstimmungen will grade wohl nicht. Später nochmal probieren"); thisreference.setState({ RetryCount: 0 }); } else { var newcount = thisreference.state.RetryCount + 1; thisreference.setState({ RetryCount: newcount }); thisreference.SyncStateToServer(ID, State, element); } } element.classList.remove("processing"); } }); } render() { var tmpthis = this; if (this.props.canEdit) { if (this.state.possibleStates.length > 0) { var states = this.state.possibleStates.map(function (state) { if (state === "NotYetVoted") { if (tmpthis.state.State === 0) { return (<span className="voteoption active" data-value="0" key={tmpthis.props.key}> <i className="fas fa-minus" /> </span>); } else { if (tmpthis.props.mode === "default") { return (<span className="voteoption" data-value="0" onClick={tmpthis.handleClick} key={tmpthis.props.key}> <i className="fas fa-minus" /> <span className="lds-dual-ring" /> </span>); } else { return (<a href={"/Events/UpdateRequestState/?fallback=true&requestID=" + tmpthis.props.requestID+"&state=0"} target="_blank" className="voteoption" data-value="0" key={tmpthis.props.key}> <i className="fas fa-minus" /> <span className="lds-dual-ring" /> </a>); } } } if (state === "Available") { if (tmpthis.state.State === 1) { return (<span className="voteoption greenbg active" data-value="1" key={tmpthis.props.key}> <i className="fas fa-check" /> <span className="lds-dual-ring"/> </span>); } else { if (tmpthis.props.mode === "default") { return (<span className="voteoption greenbg" data-value="1" onClick={tmpthis.handleClick} onTouchEnd={tmpthis.handleClick} key={tmpthis.props.key}> <i className="fas fa-check" /> <span className="lds-dual-ring" /> </span>); } else { return (<a href={"/Events/UpdateRequestState/?fallback=true&requestID=" + tmpthis.props.requestID + "&state=1"} target="_blank" className="voteoption greenbg" data-value="1" key={tmpthis.props.key}> <i className="fas fa-check" /> <span className="lds-dual-ring" /> </a>); } } } if (state === "NotAvailable") { if (tmpthis.state.State === 2) { return (<span className="voteoption redbg active" data-value="2" key={tmpthis.props.key}> <i className="fas fa-times" /> <span className="lds-dual-ring" /> </span>); } else { if (tmpthis.props.mode === "default") { return (<span className="voteoption redbg" data-value="2" onClick={tmpthis.handleClick} onTouchEnd={tmpthis.handleClick} key={tmpthis.props.key}> <i className="fas fa-times" /> <span className="lds-dual-ring" /> </span>); } else { return (<a href={"/Events/UpdateRequestState/?fallback=true&requestID=" + tmpthis.props.requestID + "&state=2"} target="_blank" className="voteoption redbg" data-value="2" onClick={tmpthis.handleClick} onTouchEnd={tmpthis.handleClick} key={tmpthis.props.key}> <i className="fas fa-times" /> <span className="lds-dual-ring" /> </a>); } } } if (state === "IfNeedBe") { console.log(tmpthis.state); if (tmpthis.state.State === 3) { return (<span className="voteoption yellowbg active" data-value="3" key={tmpthis.props.key} onClick={tmpthis.handleClick} onTouchEnd={tmpthis.handleClick}> <i className="fas fa-question" /> <span className="lds-dual-ring" /> {tmpthis.state.comment !== "" && tmpthis.state.comment !== undefined && tmpthis.state.comment !== null && <i className="fas fa-info" /> } {tmpthis.state.comment !== "" && tmpthis.state.comment !== undefined && tmpthis.state.comment !== null && <span className="commentBox">{tmpthis.state.comment}</span> } </span>); } else { if (tmpthis.props.mode === "default") { return (<span className="voteoption yellowbg" data-value="3" onClick={tmpthis.handleClick} onTouchEnd={tmpthis.handleClick} key={tmpthis.props.key}> <i className="fas fa-question" /> <span className="lds-dual-ring" /> </span>); } else { return (<a href={"/Events/UpdateRequestState/?fallback=true&requestID=" + tmpthis.props.requestID + "&state=3"} target="_blank" className="voteoption yellowbg" data-value="3" onClick={tmpthis.handleClick} onTouchEnd={tmpthis.handleClick} key={tmpthis.props.key}> <i className="fas fa-question" /> <span className="lds-dual-ring" /> </a>); } } } }); return ( <span data-state={this.state.State} className="requestNode col-6 pt-0 pb-0 pr-0 pl-0"> <div className="d-flex"> {states} </div> </span> ); } } else { switch (this.state.State) { case 0: return ( <span className="requestNode col-6 pt-0 pb-0 pr-0 pl-0" data-state={this.state.State}> <div className="d-flex"> <span className="voteoption voteoptionforeign" key={tmpthis.props.key}> <i className="fas fa-minus" /> </span> </div> </span> ); case 1: return ( <span className="requestNode col-6 pt-0 pb-0 pr-0 pl-0" data-state={this.state.State}> <div className="d-flex"> <span className="voteoption greenbg voteoptionforeign" key={tmpthis.props.key}> <i className="fas fa-check" /> </span> </div> </span> ); case 2: return ( <span className="requestNode col-6 pt-0 pb-0 pr-0 pl-0" data-state={this.state.State}> <div className="d-flex"> <span className="voteoption redbg voteoptionforeign" key={tmpthis.props.key}> <i className="fas fa-times" /> </span> </div> </span> ); case 3: return ( <span className="requestNode col-6 pt-0 pb-0 pr-0 pl-0" data-state={this.state.State}> <div className="d-flex"> <span className="voteoption yellowbg voteoptionforeign" key={tmpthis.props.key}> <i className="fas fa-question" /> {tmpthis.state.comment !== "" && tmpthis.state.comment !== undefined && tmpthis.state.comment !== null && <i className="fas fa-info" /> } {tmpthis.state.comment !== "" && tmpthis.state.comment !== undefined && tmpthis.state.comment !== null && <span className="commentBox">{tmpthis.state.comment}</span> } </span> </div> </span> ); } } return <p> No Users Loaded</p>; } }<file_sep>/BobDeathmic/wwwroot/ReactComponents/GiveAway/Admin/UI.jsx class UI extends React.Component { constructor(props) { super(props); this.state = { Game: "",Link: "", Participants: [],Channels: [], CurrentChannel: "",CurrentWinners: [] }; this.NextItemCall = this.NextItemCall.bind(this); this.RaffleCall = this.RaffleCall.bind(this); this.changeSelectedChannel = this.changeSelectedChannel.bind(this); this.UpdateParticipantList = this.UpdateParticipantList.bind(this); } componentDidMount() { //TODO: Initialize Data var request = new XMLHttpRequest(); request.open("GET", "/GiveAway/InitialAdminData"); var curthis = this; request.onload = function () { let data = JSON.parse(request.responseText); curthis.setState({ Game: data.Item, Link: data.Link, Participants: data.Applicants, Channels: data.Channels, CurrentChannel: data.Channels[0] }); }; request.send(); this.interval = setInterval(this.UpdateParticipantList, 5000); } componentWillUnmount() { clearInterval(this.interval); } UpdateParticipantList() { var request = new XMLHttpRequest(); request.open("GET", "/GiveAway/UpdateParticipantList"); var curthis = this; request.onload = function () { let data = JSON.parse(request.responseText); curthis.setState({ Participants: data }); }; request.send(); } NextItemCall() { var request = new XMLHttpRequest(); request.open("GET", "/GiveAway/NextItem?channel=" + this.state.CurrentChannel, false); request.send(null); let data = JSON.parse(request.responseText); this.interval = setInterval(this.UpdateParticipantList, 5000); this.setState({ Game: data.Item, Link: data.Link, Participants: data.Applicants, CurrentWinners: [] }); } RaffleCall() { var request = new XMLHttpRequest(); request.open("GET", "/GiveAway/Raffle?channel=" + this.state.CurrentChannel, false); request.send(null); let data = JSON.parse(request.responseText); this.setState({ CurrentWinners: data }); clearInterval(this.interval); } changeSelectedChannel(e) { this.setState({ CurrentChannel: e}); } render() { return ( <div> <ChannelSelector changeSelectedChannel={this.changeSelectedChannel} Channels={this.state.Channels} /> <NextItemAction NextItemCall={this.NextItemCall} /> <CurrentItemInfo Game={this.state.Game} Link={this.state.Link} /> <ParticipantList currentWinners={this.state.CurrentWinners} Participants={this.state.Participants} /> <RaffleAction RaffleCall={this.RaffleCall} /> </div> ); } } <file_sep>/BobDeathmic/Controllers/AdminController.cs using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; namespace BobDeathmic.Controllers { public class AdminController : Controller { private readonly Data.ApplicationDbContext _context; private readonly IServiceProvider _serviceProvider; private readonly IConfiguration _configuration; private Random random; public AdminController(Data.ApplicationDbContext context, IServiceProvider serviceProvider, IConfiguration configuration) { _context = context; _serviceProvider = serviceProvider; _configuration = configuration; random = new Random(DateTime.Now.Second * DateTime.Now.Millisecond / DateTime.Now.Hour); } [Authorize(Roles = "Dev,Admin")] public IActionResult Index() { return View(); } private async Task<Boolean> SaveFileToLocalAsync(List<IFormFile> files, string filePath) { using (var stream = new FileStream(filePath, FileMode.Create)) { await files.FirstOrDefault()?.CopyToAsync(stream); } return true; } [Authorize(Roles = "Admin")] public IActionResult SecurityTokens() { ViewData["TokenTypes"] = new List<TokenType> { TokenType.Twitch, TokenType.Discord, TokenType.Mixer }; return View(); } [HttpPost] [Authorize(Roles = "Admin")] public async Task<IActionResult> AddSecurityToken([Bind("ClientID,secret,service")] SecurityToken token) { switch (token.service) { case TokenType.Twitch: return await AquireTwitchToken(token); case TokenType.Discord: await SaveDiscordToken(token); break; } return RedirectToAction(nameof(SecurityTokens)); } public async Task SaveDiscordToken(SecurityToken token) { if (_context.SecurityTokens.Where(st => st.service == token.service).Count() == 0) { _context.SecurityTokens.Add(token); } else { var oldtoken = _context.SecurityTokens.Where(st => st.service == token.service).FirstOrDefault(); oldtoken.token = token.ClientID; } await _context.SaveChangesAsync(); } public async Task<IActionResult> AquireTwitchToken(SecurityToken token) { string baseUrl = _configuration.GetValue<string>("WebServerWebAddress"); if (_context.SecurityTokens.Where(st => st.service == token.service).Count() == 0) { _context.SecurityTokens.Add(token); await _context.SaveChangesAsync(); } else { var oldtoken = _context.SecurityTokens.Where(st => st.service == token.service).FirstOrDefault(); oldtoken = token; await _context.SaveChangesAsync(); } string state = "as435aerfaw45w456"; return Redirect($"https://id.twitch.tv/oauth2/authorize?response_type=code&client_id={token.ClientID}&redirect_uri={baseUrl}/Admin/TwitchReturnUrlAction&scope=channel_editor+chat_login+user:edit&state={state}"); } [HttpGet] [AllowAnonymous] public async Task<IActionResult> TwitchReturnUrlAction(string code, string scope, string state) { var savedtoken = _context.SecurityTokens.Where(st => st.service == TokenType.Twitch).FirstOrDefault(); savedtoken.code = code; var client = new HttpClient(); string baseUrl = _configuration.GetValue<string>("WebServerWebAddress"); string url = $"https://id.twitch.tv/oauth2/token?client_id={savedtoken.ClientID}&client_secret={savedtoken.secret}&code={code}&grant_type=authorization_code&redirect_uri={baseUrl}/Admin/TwitchReturnUrlAction"; var response = await client.PostAsync(url, new StringContent("", System.Text.Encoding.UTF8, "text/plain")); var responsestring = await response.Content.ReadAsStringAsync(); JSONObjects.TwitchAuthToken authtoken = JsonConvert.DeserializeObject<JSONObjects.TwitchAuthToken>(responsestring); savedtoken.token = authtoken.access_token; savedtoken.RefreshToken = <PASSWORD>token; await _context.SaveChangesAsync(); return RedirectToAction(nameof(SecurityTokens)); } } }<file_sep>/BobDeathmic/Controllers/GiveAwayController.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.GiveAway; using BobDeathmic.Data.DBModels.GiveAway.manymany; using BobDeathmic.Data.DBModels.Relay; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Eventbus; using BobDeathmic.Models; using BobDeathmic.ViewModels.GiveAway; using Discord; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Rewrite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MoreLinq; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Controllers { public class GiveAwayController : Controller { private readonly Data.ApplicationDbContext _context; private readonly IServiceProvider _serviceProvider; private readonly IServiceScopeFactory _scopeFactory; private readonly IConfiguration _configuration; private readonly UserManager<ChatUserModel> _manager; private readonly IEventBus _eventBus; private IMemoryCache _cache; private Random random; [TempData] public string StatusMessage { get; set; } public GiveAwayController(IServiceScopeFactory scopeFactory, Data.ApplicationDbContext context, IServiceProvider serviceProvider, IConfiguration configuration, UserManager<ChatUserModel> manager, IEventBus eventBus, IMemoryCache memoryCache) { _context = context; _serviceProvider = serviceProvider; _scopeFactory = scopeFactory; _configuration = configuration; _manager = manager; _eventBus = eventBus; random = new Random(); _cache = memoryCache; } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Index() { var user = await _manager.GetUserAsync(HttpContext.User); user = _context.ChatUserModels.Where(x => x.Id == user.Id).Include(x => x.OwnedItems).FirstOrDefault(); return View("GiveAwayList", user); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Winnings() { var user = await _manager.GetUserAsync(HttpContext.User); user = _context.ChatUserModels.Where(x => x.Id == user.Id).Include(x => x.ReceivedItems).ThenInclude(x => x.Owner).FirstOrDefault(); return View("Winnings", user); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Create() { return View(); } // POST: Streams2/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Create([Bind("GiveAwayItemId,Title,Key,SteamID,Link,Views,Owner,Receiver")] GiveAwayItem item) { if (ModelState.IsValid) { //TODO: Attribute Verification aka if links are links and etc var user = await _manager.GetUserAsync(HttpContext.User); user = _context.ChatUserModels.Where(x => x.Id == user.Id).Include(x => x.OwnedItems).FirstOrDefault(); item.Owner = user; _context.Add(item); await _context.SaveChangesAsync(); } else { return View(item); } return RedirectToAction(nameof(Index)); } [HttpGet()] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Edit(string id) { var user = await _manager.GetUserAsync(HttpContext.User); user = _context.ChatUserModels.Where(x => x.Id == user.Id).Include(x => x.OwnedItems).FirstOrDefault(); var item = _context.GiveAwayItems.Where(x => x.Id == id.ToString() && x.Owner == user).FirstOrDefault(); if (item != null) { return View(item); } return RedirectToAction(nameof(Index)); } // POST: Streams2/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Edit([Bind("Id,Title,Key,SteamID,Link,Views,Owner,Receiver")] GiveAwayItem item) { if (ModelState.IsValid) { var storedItem = _context.GiveAwayItems.Where(x => x.Id == item.Id).FirstOrDefault(); if(storedItem != null) { storedItem.Title = item.Title; storedItem.Key = item.Key; storedItem.SteamID = item.SteamID; storedItem.Link = item.Link; } await _context.SaveChangesAsync(); } else { return View(item); } return RedirectToAction(nameof(Index)); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Delete(string id) { if (id == null) { return NotFound(); } var stream = await _context.GiveAwayItems .FirstOrDefaultAsync(m => m.Id == id.ToString()); if (stream == null) { return NotFound(); } return View(stream); } // POST: Streams2/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> DeleteConfirmed(string id) { var giveawayitem = await _context.GiveAwayItems.FindAsync(id); _context.GiveAwayItems.Remove(giveawayitem); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } [Authorize(Roles = "Admin,Dev")] public async Task<IActionResult> Admin() { return View(); } private List<string> getApplicants(GiveAwayItem item) { List<string> result = new List<string>(); foreach (var applicant in item.Applicants) { result.Add(_context.ChatUserModels.Where(u => u.Id == applicant.UserID).FirstOrDefault().ChatUserName); } return result; } private async Task SetNextGiveAwayItem() { await ResetCurrentItem(); var GiveAwayItems = _context.GiveAwayItems.MinBy(g => g.Views).Where(x => !x.current && x.ReceiverID == null); if (GiveAwayItems.Count() > 0) { var item = GiveAwayItems.ElementAt(random.Next(0, GiveAwayItems.Count() - 1)); item.current = true; item.Views++; _context.SaveChanges(); } } private async Task ResetCurrentItem() { var item = _context.GiveAwayItems.Where(x => x.current).FirstOrDefault(); if (item != null) { item.current = false; await _context.SaveChangesAsync(); } } private GiveAwayItem GetCurrentGiveAwayItem() { var GiveAwayItems = _context.GiveAwayItems.Where(x => x.current).Include(x => x.Applicants); if (GiveAwayItems.Count() > 0) { return GiveAwayItems.FirstOrDefault(); } return null; } private List<String> getChatChannels() { List<String> Channels = new List<string>(); var val = ""; _cache.TryGetValue("Channel", out val); if (val == "") { _cache.Set("Channel", _context.RelayChannels.FirstOrDefault().Name); } foreach (RelayChannels channel in _context.RelayChannels) { if (channel.Name == val && Channels.Count() > 0) { var temp = Channels[0]; Channels[0] = channel.Name; Channels.Add(temp); } else { Channels.Add(channel.Name); } } return Channels; } [HttpGet, ActionName("InitialAdminData")] [Authorize(Roles = "Admin,Dev")] public async Task<string> InitialAdminData() { GiveAwayAdminViewModel model = new GiveAwayAdminViewModel(); if (GetCurrentGiveAwayItem() == null) { await SetNextGiveAwayItem(); } model.Item = GetCurrentGiveAwayItem().Title; model.Link = GetCurrentGiveAwayItem().Link; model.Channels = getChatChannels(); if (model.Item != null) { model.Applicants = getApplicants(GetCurrentGiveAwayItem()); } return JsonConvert.SerializeObject(model); } [HttpGet, ActionName("NextItem")] [Authorize(Roles = "Admin,Dev")] public async Task<string> NextItem(string channel) { //Do Stuff await SetNextGiveAwayItem(); _cache.Set("Channel", channel); GiveAwayAdminViewModel model = new GiveAwayAdminViewModel(); model.Item = GetCurrentGiveAwayItem().Title; model.Link = GetCurrentGiveAwayItem().Link; if (model.Item != null) { model.Applicants = getApplicants(GetCurrentGiveAwayItem()); } if (_context.GiveAwayItems.Where(x => x.current).FirstOrDefault() != null) { _eventBus.TriggerEvent(EventType.CommandResponseReceived, new CommandResponseArgs { Channel = channel, MessageType = Eventbus.MessageType.ChannelMessage, Message = $"Zur Verlosung steht {_context.GiveAwayItems.Where(x => x.current).FirstOrDefault()?.Title} bitte mit !Gapply teilnehmen" }); } return JsonConvert.SerializeObject(model); } [HttpGet, ActionName("Raffle")] [Authorize(Roles = "Admin,Dev")] public async Task<string> Raffle(string channel) { //Do Stuff List<string> winners = doRaffle(channel); return JsonConvert.SerializeObject(winners); } [HttpGet, ActionName("UpdateParticipantList")] [Authorize(Roles = "Admin,Dev")] public async Task<string> UpdateParticipantList() { return JsonConvert.SerializeObject(getApplicants(GetCurrentGiveAwayItem())); } private List<string> doRaffle(string channel) { List<string> winners = new List<string>(); bool repeatRaffle = false; using (var scope = _scopeFactory.CreateScope()) { var tmpcontext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var currentitem = tmpcontext.GiveAwayItems.Include(x => x.Applicants).ThenInclude(y => y.User).ThenInclude(x => x.ReceivedItems).Where(x => x.current).FirstOrDefault(); List<ChatUserModel> Applicants = null; ChatUserModel tmpwinner = null; if (currentitem != null && currentitem.Applicants.Count() > 0) { int min = getLeastGiveAwayCount(currentitem.Applicants); var elligableUsers = currentitem.Applicants.Where(x => x.User.ReceivedItems.Count() == min); int winnerindex = random.Next(elligableUsers.Count()); var winner = elligableUsers.ToArray()[winnerindex]; winners.Add(winner.User.ChatUserName); currentitem.Receiver = winner.User; tmpwinner = winner.User; currentitem.ReceiverID = winner.UserID; tmpcontext.SaveChanges(); _eventBus.TriggerEvent(EventType.CommandResponseReceived, new CommandResponseArgs { Channel = channel, MessageType = Eventbus.MessageType.ChannelMessage, Message = $"Gewonnen hat {winner.User.ChatUserName}" }); } if (currentitem.Applicants.Count() > 1 && tmpcontext.GiveAwayItems.Include(x => x.Applicants).ThenInclude(y => y.User).Where(x => x.Title == currentitem.Title && x.Id != currentitem.Id && x.ReceiverID == null).Count() > 0) { var newitem = tmpcontext.GiveAwayItems.Include(x => x.Applicants).ThenInclude(y => y.User).Where(x => x.Title == currentitem.Title && x.ReceiverID == null && x.current == false).FirstOrDefault(); foreach (var user in currentitem.Applicants.Where(x => x.UserID != tmpwinner.Id).ToList()) { var m_n_relation = new User_GiveAwayItem(user.User, newitem); newitem.Applicants.Add(m_n_relation); user.User.AppliedTo.Add(m_n_relation); } currentitem.current = false; newitem.current = true; tmpcontext.SaveChanges(); repeatRaffle = true; } } if (repeatRaffle) { winners.AddRange(doRaffle(channel)); } return winners; } private int getLeastGiveAwayCount(List<User_GiveAwayItem> items) { int value = 99999; foreach (var item in items) { if (value > item.User.ReceivedItems.Count()) { value = item.User.ReceivedItems.Count(); } } if (value == 99999) { return 0; } return value; } } }<file_sep>/BobDeathmic/Services/Strawpoll/StrawPollService.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Eventbus; using BobDeathmic.JSONObjects; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Services { public class StrawPollService : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly IEventBus _eventBus; private static readonly HttpClient client = new HttpClient(); public StrawPollService(IEventBus eventBus, IServiceScopeFactory scopeFactory) { _eventBus = eventBus; _scopeFactory = scopeFactory; } protected async override Task ExecuteAsync(CancellationToken stoppingToken) { _eventBus.StrawPollRequested += StrawPollRequested; while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } } private async void StrawPollRequested(object sender, StrawPollRequestEventArgs e) { if (e.Question.Count() > 1) { var values = new StrawPollPostData { title = e.Question, options = e.Answers, multi = e.multiple }; var response = await client.PostAsJsonAsync("https://www.strawpoll.me/api/v2/polls", values); var responseString = await response.Content.ReadAsStringAsync(); var StrawPollData = JsonConvert.DeserializeObject<StrawPollResponseData>(responseString); using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); Stream stream = _context.StreamModels.Where(sm => sm.StreamName.ToLower().Equals(e.StreamName.ToLower())).FirstOrDefault(); _eventBus.TriggerEvent(EventType.RelayMessageReceived, new Args.RelayMessageArgs() { SourceChannel = stream.DiscordRelayChannel, StreamType = StreamProviderTypes.Twitch, TargetChannel = stream.StreamName, Message = StrawPollData.Url() }); } } else { //Error Message you must have at least 2 options using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); Stream stream = _context.StreamModels.Where(sm => sm.StreamName.ToLower().Equals(e.StreamName.ToLower())).FirstOrDefault(); _eventBus.TriggerEvent(EventType.RelayMessageReceived, new Args.RelayMessageArgs() { SourceChannel = stream.DiscordRelayChannel, StreamType = StreamProviderTypes.Twitch, TargetChannel = stream.StreamName, Message = "You need at least 2 Options" }); } } } } } <file_sep>/BobDeathmic/Data/DBModels/EventCalendar/Event.cs using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Data.DBModels.EventCalendar.manymany; using BobDeathmic.Data.DBModels.User; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Models.Events { public class Event { public int Id { get; set; } public string Name { get; set; } public List<EventDateTemplate> EventDateTemplates { get; set; } public List<ChatUserModel_Event> Members { get; set; } public string AdministratorID { get; set; } public ChatUserModel Admin { get; set; } public List<EventDate> EventDates { get; set; } public Event() { EventDateTemplates = new List<EventDateTemplate>(); Members = new List<ChatUserModel_Event>(); EventDates = new List<EventDate>(); } public List<ChatUserModel> getMembers() { List<ChatUserModel> Users = new List<ChatUserModel>(); foreach (ChatUserModel_Event member in Members) { Users.Add(member.ChatUserModel); } return Users; } public List<AppointmentRequest> GenerateAppointmentRequests(EventDate eventDate) { List<AppointmentRequest> tmp = new List<AppointmentRequest>(); foreach (ChatUserModel_Event MemberRelation in Members) { tmp.Add(new AppointmentRequest { Owner = MemberRelation.ChatUserModel, EventDate = eventDate }); } return tmp; } } } <file_sep>/BobDeathmic/Services/Streams/Checker/Mixer/MixerChecker.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Relay; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Eventbus; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Services { public class MixerChecker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private IEventBus _eventBus; private System.Timers.Timer _timer; private bool _inProgress = false; public MixerChecker(IServiceScopeFactory scopeFactory, IEventBus eventBus) { _scopeFactory = scopeFactory; _eventBus = eventBus; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _timer = new System.Timers.Timer(10000); _timer.Elapsed += (sender, args) => CheckOnlineStreams(); _timer.Start(); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } } private async Task CheckOnlineStreams() { if (!_inProgress) { _inProgress = true; try { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); HttpClient client = new HttpClient(); string baseUrl = "https://mixer.com/api/v1/channels/"; IQueryable<Stream> GetStreams() { return _context.StreamModels.Where(x => x.Type == StreamProviderTypes.Mixer).Include(x => x.StreamSubscriptions).ThenInclude(x => x.User); } foreach (Stream stream in GetStreams()) { string RequestLink = baseUrl + stream.StreamName; var response = await client.GetAsync(RequestLink); var responsestring = await response.Content.ReadAsStringAsync(); Regex regex = new Regex("\"description\":.*\"languageId\""); responsestring = regex.Replace(responsestring, "\"languageId\""); JSONObjects.MixerChannelInfo streamInfo = JsonConvert.DeserializeObject<JSONObjects.MixerChannelInfo>(responsestring); if (streamInfo.online) { if (stream.StreamState == StreamState.NotRunning) { SetStreamOnline(); StreamStarted(); void SetStreamOnline() { stream.Started = DateTime.Now; if (streamInfo.type != null) { stream.Game = streamInfo.type.name; } else { stream.Game = "Undefined"; } stream.StreamState = StreamState.Started; stream.Url = $"https://mixer.com/{stream.StreamName}"; } async Task StreamStarted() { int longDelayCounter = 0; foreach (string username in stream.GetActiveSubscribers()) { longDelayCounter++; if (longDelayCounter == 5) { longDelayCounter = 0; await Task.Delay(2000); } _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs() { Message = stream.StreamStartedMessage(stream.Game, stream.Url), RecipientName = username }); await Task.Delay(100); } } } else { stream.StreamState = StreamState.Running; } } else { SetStreamOffline(); void SetStreamOffline() { stream.StreamState = StreamState.NotRunning; } void StreamStopped() { // Implement when/if relay Integrated } } } await _context.SaveChangesAsync(); _inProgress = false; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); _inProgress = false; } } } public override Task StopAsync(CancellationToken cancellationToken) { return base.StopAsync(cancellationToken); } } } <file_sep>/BobDeathmic/Data/DBModels/StreamModels/StreamSubscription.cs using BobDeathmic.Data.DBModels.User; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.StreamModels { public class StreamSubscription { public int ID { get; set; } public Stream Stream { get; set; } public SubscriptionState Subscribed { get; set; } public ChatUserModel User { get; set; } public StreamSubscription() { } public StreamSubscription(Stream stream,SubscriptionState state) { Stream = stream; Subscribed = state; } public StreamSubscription(ChatUserModel user, Stream stream, SubscriptionState state) { Stream = stream; Subscribed = state; User = user; } } } <file_sep>/BobDeathmic/Data/Enums/Stream/StreamState.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.Enums.Stream { public enum StreamState { Running = 1, NotRunning = 0, Started = 2 } } <file_sep>/BobDeathmic/Controllers/UserAdminController.cs using BobDeathmic.Data.DBModels.User; using BobDeathmic.Models; using BobDeathmic.ViewModels.User; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static Microsoft.ApplicationInsights.MetricDimensionNames.TelemetryContext; namespace BobDeathmic.Controllers { public class UserAdminController : Controller { private Data.ApplicationDbContext _context; private IServiceProvider _serviceProvider; private readonly UserManager<ChatUserModel> _userManager; private readonly RoleManager<IdentityRole> _roleManager; public UserAdminController(Data.ApplicationDbContext context, IServiceProvider serviceProvider, UserManager<ChatUserModel> userManager, RoleManager<IdentityRole> roleManager) { _context = context; _serviceProvider = serviceProvider; _userManager = userManager; _roleManager = roleManager; } public async Task<IActionResult> Index() { List<UserRolesViewModel> UserList = new List<UserRolesViewModel>(); foreach (ChatUserModel user in _context.Users) { UserRolesViewModel newUserRolesModel = new UserRolesViewModel(); newUserRolesModel.User = user; newUserRolesModel.Roles = await _userManager.GetRolesAsync(user); UserList.Add(newUserRolesModel); } ViewData["PossibleRoles"] = new String[] { "Admin", "User" }; return View(UserList); } public async Task<bool> SaveUserRoles(string UserId, int isAdmin) { var user = _context.ChatUserModels.Where(cum => cum.Id == UserId).FirstOrDefault(); IdentityResult result = null; if (isAdmin == 1) { result = await _userManager.AddToRoleAsync(user, "Admin"); } else { result = await _userManager.RemoveFromRoleAsync(user, "Admin"); } return result.Succeeded; } } }<file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Table.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table { public class Table { public List<Row> Rows { get;} public Table() { Rows = new List<Row>(); } public void AddRow(Row row) { Rows.Add(row); } public string getJson() { return JsonConvert.SerializeObject(this); } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/EventDateFinder/Vote/ChatUser.cs using BobDeathmic.Models.Events; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic; namespace BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.Vote { public class VoteChatUser { public List<VoteRequest> Requests { get; set; } public bool canEdit { get; set; } public string Name { get; set; } public string key { get; set; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinder/Edit_Create/EditEvent.jsx class EditEvent extends React.Component { constructor(props) { super(props); this.state = { data: [], eventEmitter: new EventEmitter()}; } componentWillMount() { var thisreference = this; $.ajax({ url: "/Events/GetEvent/" + this.props.ID, type: "GET", data: {}, success: function (result) { thisreference.setState({ data: result }); } }); } render() { if (this.state.data.name === undefined) { return ( <div className="OverView"> <NameField owner={this.props.ID} value="" /> </div> ); } else { return ( <div className="OverView"> <span>Name</span> <NameField owner={this.props.ID} value={this.state.data.name} /> <ChatUserSelect ID={this.props.ID} eventEmitter={this.state.eventEmitter} /> <InvitedUserList ID={this.props.ID} eventEmitter={this.state.eventEmitter} /> <TemplateList ID={this.props.ID} eventEmitter={this.state.eventEmitter} /> </div> ); } } } <file_sep>/BobDeathmic/Controllers/DiscordBansController.cs using BobDeathmic.Data; using BobDeathmic.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Controllers { public class DiscordBansController : Controller { private readonly ApplicationDbContext _context; public DiscordBansController(ApplicationDbContext context) { _context = context; } // GET: DiscordBans [Authorize(Roles = "Dev,Admin")] public async Task<IActionResult> Index() { return View(await _context.DiscordBans.ToListAsync()); } // GET: DiscordBans/Delete/5 [Authorize(Roles = "Dev,Admin")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var discordBan = await _context.DiscordBans .FirstOrDefaultAsync(m => m.Id == id); if (discordBan == null) { return NotFound(); } return View(discordBan); } // POST: DiscordBans/Delete/5 [Authorize(Roles = "Dev,Admin")] [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var discordBan = await _context.DiscordBans.FindAsync(id); _context.DiscordBans.Remove(discordBan); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool DiscordBanExists(int id) { return _context.DiscordBans.Any(e => e.Id == id); } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/EventDateFinder/Vote/EventDateHeader.cs using BobDeathmic.Models.Events; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic; namespace BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.Vote { public class EventDateData { public string Date { get; set; } public string Time { get; set; } public List<VoteRequest> Requests { get; set; } } } <file_sep>/BobDeathmic/Cron/TwitchTokenRefreshTask.cs using BobDeathmic.Args; using BobDeathmic.Cron.Setup; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Eventbus; using BobDeathmic.Helper; using BobDeathmic.Helper.EventCalendar; using BobDeathmic.Models.Events; using BobDeathmic.Services.Helper; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Cron { public class TwitchTokenRefreshTask : IScheduledTask { public string Schedule => "0 */3 * * *"; private readonly IServiceScopeFactory _scopeFactory; private IConfiguration _configuration; public TwitchTokenRefreshTask(IServiceScopeFactory scopeFactory, IConfiguration Configuration) { _scopeFactory = scopeFactory; _configuration = Configuration; } public async Task ExecuteAsync(CancellationToken cancellationToken) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if (_context != null) { SecurityToken token = _context.SecurityTokens.Where(t => t.service == Data.Enums.Stream.TokenType.Twitch).FirstOrDefault(); if (token != null && token.RefreshToken != null && token.RefreshToken != "") { var httpclient = new HttpClient(); string baseUrl = _configuration.GetValue<string>("WebServerWebAddress"); string url = $"https://id.twitch.tv/oauth2/token?grant_type=refresh_token&refresh_token={token.RefreshToken}&client_id={token.ClientID}&client_secret={token.secret}"; var response = await httpclient.PostAsync(url, new StringContent("", System.Text.Encoding.UTF8, "text/plain")); var responsestring = await response.Content.ReadAsStringAsync(); JSONObjects.TwitchRefreshTokenData refresh = JsonConvert.DeserializeObject<JSONObjects.TwitchRefreshTokenData>(responsestring); if (refresh.error == null) { token.token = refresh.access_token; token.RefreshToken = refresh.refresh_token; _context.SaveChanges(); } } } } } } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/GiveAwayEventArgs.cs using BobDeathmic.Data.DBModels.User; using BobDeathmic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Args { public class GiveAwayEventArgs { public string channel { get; set; } public ChatUserModel winner { get; set; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/Table/Table.jsx class Table extends React.Component { constructor(props) { super(props); //Sort init,desc,asc this.state = { Rows: [], Filter: "" ,Sort: "init", SortColumn: 0}; this.Search = this.Search.bind(this); this.Sort = this.Sort.bind(this); this.handleUpdateEvent = this.handleUpdateEvent.bind(this); } handleUpdateEvent(e) { this.UpdateData(); } componentDidMount() { window.addEventListener('updateTable', this.handleUpdateEvent); } componentWillMount() { this.UpdateData(); } UpdateData() { var thisreference = this; const xhr = new XMLHttpRequest(); xhr.open('GET', thisreference.props.DataLink, true); xhr.onload = function () { thisreference.setState({ Table: JSON.parse(xhr.responseText) }); }; xhr.send(); } Search(value) { this.setState({Filter: value}); } Sort(field) { let sort = ""; switch (this.state.Sort) { case "init": sort = "asc"; break; case "desc": sort = "asc"; break; case "asc": sort = "desc"; break; } this.setState({SortColumn: field,Sort: sort}); } render() { if (this.state.Table !== undefined && this.state.Table.Rows.length > 0) { let i = 0; var curthis = this; var TableRows = this.state.Table.Rows; if (this.state.SortColumn !== 0 && this.state.Sort !== "init") { TableRows.sort(function (a, b) { let index = curthis.state.SortColumn - 1; //could solve this another way by filtering first row as header row but ... if (a.isStatic || b.isStatic) { return 0; } else { if (curthis.state.Sort === "desc") { if (a.Columns[index].Text.toLowerCase() > b.Columns[index].Text.toLowerCase()) { return -1; } if (a.Columns[index].Text.toLowerCase() < b.Columns[index].Text.toLowerCase()) { return 1; } } else { if (a.Columns[index].Text.toLowerCase() < b.Columns[index].Text.toLowerCase()) { return -1; } if (a.Columns[index].Text.toLowerCase() > b.Columns[index].Text.toLowerCase()) { return 1; } } return 0; } }); } const Rows = TableRows.map((row) => { i++; if (curthis.state.Filter !== "") { if (!row.canFilter || row.canFilter && row.Filter.toLowerCase().includes(curthis.state.Filter.toLowerCase())) { return <Row ColumnTypes={this.props.Columns} Sort={curthis.Sort} key={i} Columns={row.Columns} />; } } else { return <Row ColumnTypes={this.props.Columns} Sort={curthis.Sort} key={i} Columns={row.Columns} />; } }); return (<div className="relative d-inline-block"> <Search callback={this.Search} /> <table> <tbody> {Rows} </tbody> </table> </div>); } else { return <span>Loading</span>; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinder/Vote/EventDate.jsx class EventDate extends React.Component { constructor(props) { super(props); this.state = { Data: this.props.Data }; } render() { var tmpthis = this; var key = 0; var requestnodes = this.state.Data.Requests.map(function (request) { key++; return ( <div className="row usernode mr-0 ml-0"> <span className="col-6 pt-0 pb-0 pl-0 pr-0">{request.UserName}</span> <StateSelect mode={tmpthis.props.mode} key={key} canEdit={request.canEdit} requestID={request.AppointmentRequestID} possibleStates={request.States} state={request.State} comment={request.Comment} /> </div> ); }); if (requestnodes.length > 0) { return ( <div key={this.key} className="EventDate"> <div className="row ml-0 mr-0"> <span className="col-12 text-center bg_dark"> <span className="date">{this.state.Data.Date}</span><br /> <span className="time">{this.state.Data.Time}</span> </span> </div> {requestnodes} </div> ); } else { return ( <div key={this.key} className="VoteUser"> <span className="VoteUser_Name">{this.props.Name}</span> </div> ); } } } <file_sep>/BobDeathmic/ViewModels/GiveAway/GiveAwayAdminViewModel.cs using BobDeathmic.Data.DBModels.GiveAway; using BobDeathmic.Data.DBModels.User; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic; using BobDeathmic.Models; namespace BobDeathmic.ViewModels.GiveAway { public class GiveAwayAdminViewModel { public string Item; public List<String> Channels; public List<string> Applicants; public string Link { get; set; } } } <file_sep>/BobDeathmic/Services/Streams/Checker/DLive/DLiveChecker.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Eventbus; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BobDeathmic.Services { public class DLiveChecker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private System.Timers.Timer _timer; private bool _inProgress; private IEventBus _eventBus; public DLiveChecker(IServiceScopeFactory scopeFactory, IEventBus eventBus) { _scopeFactory = scopeFactory; _eventBus = eventBus; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _timer = new System.Timers.Timer(10000); _timer.Elapsed += (sender, args) => CheckOnlineStreams(); _timer.Start(); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(5000, stoppingToken); } } private async void CheckOnlineStreams() { try { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); HttpClient client = new HttpClient(); string baseurl = "https://graphigo.prd.dlive.tv/"; var Streams = _context.StreamModels.Where(x => x.Type == StreamProviderTypes.DLive).Include(x => x.StreamSubscriptions).ThenInclude(x => x.User); foreach (Stream stream in Streams) { var content = new StringContent("{\"query\":\"{ userByDisplayName(displayname: \\\""+stream.StreamName+"\\\") {livestream{id}}}\"}", Encoding.UTF8, "application/json"); var response = await client.PostAsync(baseurl, content); var responsestring = await response.Content.ReadAsStringAsync(); JSONObjects.DLive.DLiveStreamOnlineData streamInfo = JsonConvert.DeserializeObject<JSONObjects.DLive.DLiveStreamOnlineData>(responsestring); if(streamInfo.data.userByDisplayName.livestream != null) { SetStreamOnline(); await StreamStarted(); void SetStreamOnline() { stream.Started = DateTime.Now; if (streamInfo.data.userByDisplayName.livestream.category != null) { stream.Game = streamInfo.data.userByDisplayName.livestream.category.title; } else { stream.Game = "Undefined"; } if(stream.StreamState == StreamState.NotRunning) { stream.StreamState = StreamState.Started; } stream.Url = $"https://dlive.tv/{stream.StreamName}"; } async Task StreamStarted() { if(stream.StreamState == StreamState.Started) { foreach (string username in stream.GetActiveSubscribers()) { _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs() { Message = stream.StreamStartedMessage(streamInfo.data.userByDisplayName.livestream.title, stream.Url), RecipientName = username }); await Task.Delay(100); } stream.StreamState = StreamState.Running; _context.SaveChanges(); } } } else { SetStreamOffline(); void SetStreamOffline() { stream.StreamState = StreamState.NotRunning; } } } await _context.SaveChangesAsync(); } }catch (Exception ex) { } } } } <file_sep>/BobDeathmic/Controllers/CharacterController.cs using BobDeathmic.Args; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Eventbus; using BobDeathmic.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Controllers { public class CharacterController : Controller { private readonly ApplicationDbContext _context; private readonly IConfiguration _configuration; private UserManager<ChatUserModel> _userManager; private readonly IEventBus _eventBus; private Random random; public CharacterController(IEventBus eventBus, ApplicationDbContext context, IConfiguration configuration, UserManager<ChatUserModel> userManager) { _context = context; _configuration = configuration; _userManager = userManager; _eventBus = eventBus; random = new Random(); } [Authorize(Roles = "User,Dev,Admin")] public IActionResult Index() { return View(Users()); } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> RollGold(string GM, int numdies, int die, int multiplikator) { int gold = Roll(numdies, die) * multiplikator; ChatUserModel user = await _userManager.GetUserAsync(this.User); if (GM != user.ChatUserName) { _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = GM, Message = $"{user.ChatUserName} hat {gold} gold für den Charakter gewürfelt." }); } _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = user.ChatUserName, Message = $"Du hast {gold} gold für den Charakter gewürfelt." }); return RedirectToAction("Index"); } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> RollStats(string GM) { string stats = ""; int sum = 0; for (int i = 0; i < 6; i++) { int result = Roll(4, 6, 1); sum += result; stats += result.ToString() + $" ({getBoni(result)})"; if (i != 5) { stats += ","; } } ChatUserModel user = await _userManager.GetUserAsync(this.User); if (GM != user.ChatUserName) { _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = GM, Message = $"{user.ChatUserName} hat {stats} Stats ({sum}) für den Charakter gewürfelt " }); } _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = user.ChatUserName, Message = $"Du hast {stats} Stats ({sum}) für den Charakter gewürfelt." }); return RedirectToAction("Index"); } private string getBoni(int stat) { int boni = 0; int preparedStat = stat - 10; if (preparedStat < 0) { //Negative Boni boni = (int)Math.Round(Math.Floor((double)preparedStat / 2), 0); return boni.ToString(); } else { //Positive Boni boni = preparedStat / 2; return "+" + boni.ToString(); } } private int Roll(int numdies, int die) { int total = 0; for (int i = 0; i < numdies; i++) { //die+1 cause max value ist exclusive of that value total += random.Next(1, die + 1); } return total; } private int Roll(int numdies, int die, int removelowestdies) { List<int> rolls = new List<int>(6); for (int i = 0; i < numdies; i++) { //die+1 cause max value ist exclusive of that value rolls.Add(random.Next(1, die + 1)); } for (int i = 0; i < removelowestdies; i++) { rolls.Remove(rolls.Min()); } return rolls.Sum(); } private List<ChatUserModel> Users() { return _context.ChatUserModels.ToList(); } } }<file_sep>/BobDeathmic/ChatCommands/Setup/IfCommand.cs using BobDeathmic.ChatCommands.Args; using BobDeathmic.Data.Enums; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands.Setup { public interface ICommand { string Trigger { get; } string Description { get; } string Category { get; } string Alias { get; } bool ChatSupported(ChatType chat); Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory); bool isCommand(string message); } } <file_sep>/BobDeathmic/ChatCommands/Quote.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.Quote; using BobDeathmic.Data.Enums; using BobDeathmic.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MoreLinq; using BobDeathmic.Eventbus; namespace BobDeathmic.ChatCommands { public class QuoteCommand : ICommand { public string Trigger => "!quote"; public string Description => "Add a quote to the current streamer's quote database. !quote [add/delete] [quote/id]"; public string Category => "stream"; public string Alias => ""; private async Task<bool> DeleteQuoteFromStreamer(string sStreamer, int iQuoteId, ApplicationDbContext context) { var quote = await context.Quotes.FirstOrDefaultAsync(q => q.Streamer == sStreamer && q.Id == iQuoteId); if (quote == null) { return false; } context.Quotes.Remove(quote); await context.SaveChangesAsync(); return true; } private async Task<string> GetRandomQuoteFromStreamer(string sStreamer, ApplicationDbContext context) { var quotes = context.Quotes.Where(q => q.Streamer == sStreamer).ToArray(); return quotes.Length == 0 ? $"Found no quotes from {sStreamer}." : quotes.RandomSubset(1).First().ToString(); } private async Task<string> GetQuoteFromStreamer(string sStreamer, int iQuoteId, ApplicationDbContext context) { var quote = await context.Quotes.FirstOrDefaultAsync(q => q.Streamer == sStreamer && q.Id == iQuoteId); return quote?.ToString() ?? $"Found no quote with ID {iQuoteId} from {sStreamer}."; } private async Task<int> AddQuoteToStreamer(string sStreamer, string sQuote, ApplicationDbContext context) { var quote = new Quote { Streamer = sStreamer, Created = DateTime.Now, Text = sQuote }; await context.Quotes.AddAsync(quote); await context.SaveChangesAsync(); return quote.Id; } public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopeFactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = false; output.Type = Eventbus.EventType.CommandResponseReceived; output.EventData = new CommandResponseArgs() { Channel = args.ChannelName, Chat = args.Type, MessageType = MessageType.ChannelMessage, Sender = args.Sender }; if (!args.Message.ToLower().StartsWith(Trigger) || args.Type != ChatType.Twitch) { return output; } using (var scope = scopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var saMessageSplit = args.Message.Split(" "); // !quote without any arguments prints a random quote of the current streamer. if (saMessageSplit.Length == 1) { output.ExecuteEvent = true; output.EventData.Message = await GetRandomQuoteFromStreamer(args.ChannelName, context); return output; } // Non mods can only print quotes, not add or delete. if (!args.elevatedPermissions) { return output; } int iQuoteId; switch (saMessageSplit[1].ToLower()) { case "add": if (saMessageSplit.Length == 2) { output.EventData.Message = "Usage: !quote add <add funny quote here>"; } else { iQuoteId = await AddQuoteToStreamer(args.ChannelName, string.Join(" ", saMessageSplit.Skip(2)), context); output.EventData.Message = "Quote '"+ string.Join(" ", saMessageSplit.Skip(2)) + "' added"; } break; case "delete": if (saMessageSplit.Length == 2) { output.EventData.Message = "Usage: !quote delete <quote ID here>"; } if (!int.TryParse(saMessageSplit[2], out iQuoteId)) { output.EventData.Message = $"'{saMessageSplit[2]}' is not a quote ID."; } output.EventData.Message = await DeleteQuoteFromStreamer(args.ChannelName, iQuoteId, context) ? "Quote deleted." : $"Quote ID {iQuoteId} not found."; break; default: if (!int.TryParse(saMessageSplit[1], out iQuoteId)) { output.EventData.Message = $"'{saMessageSplit[1]}' is not a quote ID."; } output.EventData.Message = await GetQuoteFromStreamer(args.ChannelName, iQuoteId, context); break; } return output; } } } }<file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/StrawPollRequestEventArgs.cs using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Args { public class StrawPollRequestEventArgs { public string StreamName { get; set; } public string Question { get; set; } public string[] Answers { get; set; } public bool multiple { get; set; } public StreamProviderTypes Type { get; set; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/Table/Columns/LinkColumn.jsx class LinkColumn extends React.Component { constructor(props) { super(props); } render() { return <td><a href={this.props.data.Link}>{this.props.data.Text}</a></td>; } } <file_sep>/BobDeathmic/Data/DBModels/GiveAway/GiveAwayItem.cs using BobDeathmic.Data.DBModels.GiveAway.manymany; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.GiveAway { public class GiveAwayItem { public string Id { get; set; } [Required] public string Title { get; set; } public string Key { get; set; } public string SteamID { get; set; } [Required] [Url] public string Link { get; set; } public int Views { get; set; } public bool current { get; set; } public string OwnerID { get; set; } public ChatUserModel Owner { get; set; } public string ReceiverID { get; set; } public ChatUserModel Receiver { get; set; } public List<User_GiveAwayItem> Applicants { get; set; } public string Announcement() { return "GiveAway für " + Title + " mit !Gapply teilnehmen"; } public string WinnerAnnouncment() { return "Gewonnen hat " + Receiver.ChatUserName; } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Row.cs using BobDeathmic.ViewModels.ReactDataClasses.Table.Columns; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table { public class Row { public List<Columns.Column> Columns { get;} public string Filter { get; private set; } public bool canFilter { get; set; } public bool isStatic { get; set; } public Row(bool canFilter = true, bool isStatic = false) { Columns = new List<Columns.Column>(); this.canFilter = canFilter; this.isStatic = isStatic; } public void AddColumn(Columns.Column column) { var test = column.GetType().ToString(); if (canFilter && (Filter == "" || Filter == null) && column.GetType() == typeof(TextColumn)) { Filter = ((TextColumn)column).Text; } Columns.Add(column); } } } <file_sep>/BobDeathmic/ViewModels/StreamModels/StreamOAuthDataModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.StreamModels { public class StreamOAuthDataModel { [Required] [DataType(DataType.Text)] public string Id { get; set; } [Required] [DataType(DataType.Text)] public string ClientId { get; set; } [Required] [DataType(DataType.Text)] public string Secret { get; set; } public string RedirectLinkForTwitch { get; set; } public string StatusMessage { get; set; } } } <file_sep>/BobDeathmic/ChatCommands/RandomChatUserCommand.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data; using BobDeathmic.Data.DBModels.Commands; using BobDeathmic.Data.Enums; using BobDeathmic.Eventbus; using BobDeathmic.Models; using Microsoft.Extensions.DependencyInjection; namespace BobDeathmic.ChatCommands { public class RandomChatUserRegisterCommand : ICommand { public string Trigger => "!registerraffle"; public string Alias => "!registername"; public string Description => "Registers User To Raffle"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { return CommandEventType.None; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = true; output.Type = Eventbus.EventType.CommandResponseReceived; string message = ""; using (var scope = scopefactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if (_context.RandomChatUser.Where(x => x.ChatUser.ToLower() == args.Sender.ToLower() && x.Stream.ToLower() == args.ChannelName.ToLower()).Count() == 0) { RandomChatUser tmp = new RandomChatUser(); tmp.ChatUser = args.Sender; tmp.Stream = args.ChannelName; if (_context.RandomChatUser.Where(x => x.Stream.ToLower() == args.ChannelName.ToLower()).Count() == 0) { tmp.Sort = 1; } else { tmp.Sort = _context.RandomChatUser.Where(x => x.Stream.ToLower() == args.ChannelName.ToLower()).Max(t => t.Sort) + 1; } _context.RandomChatUser.Add(tmp); _context.SaveChanges(); message = "You were added."; } else { message = "Already in the List"; } } output.EventData = new CommandResponseArgs(args.Type, message, MessageType.PrivateMessage, args.Sender,args.ChannelName); return output; } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { if(args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias)) { using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if(_context.RandomChatUser.Where(x => x.ChatUser == args["username"] && x.Stream == args["channel"]).Count() == 0) { RandomChatUser tmp = new RandomChatUser(); tmp.ChatUser = args["username"]; tmp.Stream = args["channel"]; if(_context.RandomChatUser.Where(x => x.Stream == args["channel"]).Count() == 0) { tmp.Sort = 1; } else { tmp.Sort = _context.RandomChatUser.Where(x => x.Stream == args["channel"]).Max(t => t.Sort) + 1; } _context.RandomChatUser.Add(tmp); _context.SaveChanges(); return "You were added."; } else { return "Already in the List"; } } } return ""; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } public class PickNextChatUserForNameCommand : ICommand { public string Trigger => "!next"; public string Alias => "!next"; public string Description => "Outputs next Member in List"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { return CommandEventType.None; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopeFactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = false; output.Type = Eventbus.EventType.CommandResponseReceived; string message = "No User found/in List"; if (args.elevatedPermissions && (args.Message.ToLower().StartsWith(Trigger) || args.Message.ToLower().StartsWith(Alias))) { output.ExecuteEvent = true; using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var delete = _context.RandomChatUser.Where(x => x.Stream == args.ChannelName && x.lastchecked).FirstOrDefault(); if (delete != null) { _context.RandomChatUser.Remove(delete); _context.SaveChanges(); } if (_context.RandomChatUser.Where(x => x.Stream == args.ChannelName).Count() > 0) { var user = _context.RandomChatUser.Where(x => x.Stream == args.ChannelName).OrderBy(s => s.Sort).First(); user.lastchecked = true; _context.SaveChanges(); message = user.ChatUser; } } output.EventData = new CommandResponseArgs(args.Type, message, MessageType.ChannelMessage, args.Sender,args.ChannelName); } return output; } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { if (args["elevatedPermissions"] == "True" && (args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias))) { using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var delete = _context.RandomChatUser.Where(x => x.Stream == args["channel"] && x.lastchecked).FirstOrDefault(); if (delete != null) { _context.RandomChatUser.Remove(delete); _context.SaveChanges(); } if (_context.RandomChatUser.Where(x => x.Stream == args["channel"]).Count() > 0) { var user = _context.RandomChatUser.Where(x => x.Stream == args["channel"]).OrderBy(s => s.Sort).First(); user.lastchecked = true; _context.SaveChanges(); return user.ChatUser; } } } return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } public class PickNextRandChatUserForNameCommand : ICommand { public string Trigger => "!randnext"; public string Alias => "!randnext"; private Random rnd = new Random(); public string Description => "Outputs weighted random Member in List"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { return CommandEventType.None; } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { if (args["elevatedPermissions"] == "True" && (args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias))) { using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var delete = _context.RandomChatUser.Where(x => x.Stream == args["channel"] && x.lastchecked).FirstOrDefault(); if(delete != null) { _context.RandomChatUser.Remove(delete); _context.SaveChanges(); } if (_context.RandomChatUser.Where(x => x.Stream == args["channel"]).Count() > 0) { if(_context.RandomChatUser.Where(x => x.Stream == args["channel"]).Count() == 1) { _context.RandomChatUser.Where(x => x.Stream == args["channel"]).FirstOrDefault().lastchecked = true; _context.SaveChanges(); return _context.RandomChatUser.Where(x => x.Stream == args["channel"]).FirstOrDefault().ChatUser; } var users = _context.RandomChatUser.Where(x => x.Stream == args["channel"]); var count = users.Count(); List<string> Names = new List<string>(); foreach(RandomChatUser usertemplate in users) { for(int i = count; i > 0;i--) { Names.Add(usertemplate.ChatUser); } count--; } var nextuser = Names[rnd.Next(Names.Count() + 1)]; try { _context.RandomChatUser.Where(x => x.ChatUser == nextuser).First().lastchecked = true; _context.SaveChanges(); }catch(Exception ex) { Console.WriteLine(ex.ToString()); } return nextuser; } return "Liste ist leer"; } } return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopeFactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = false; output.Type = Eventbus.EventType.CommandResponseReceived; string message = "No User found/in List"; if (args.elevatedPermissions && (args.Message.ToLower().StartsWith(Trigger) || args.Message.ToLower().StartsWith(Alias))) { output.ExecuteEvent = true; using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var delete = _context.RandomChatUser.Where(x => x.Stream == args.ChannelName && x.lastchecked).FirstOrDefault(); if (delete != null) { _context.RandomChatUser.Remove(delete); _context.SaveChanges(); } if (_context.RandomChatUser.Where(x => x.Stream == args.ChannelName).Count() > 0) { if (_context.RandomChatUser.Where(x => x.Stream == args.ChannelName).Count() == 1) { _context.RandomChatUser.Where(x => x.Stream == args.ChannelName).FirstOrDefault().lastchecked = true; _context.SaveChanges(); message = _context.RandomChatUser.Where(x => x.Stream == args.ChannelName).FirstOrDefault().ChatUser; } else { var users = _context.RandomChatUser.Where(x => x.Stream == args.ChannelName); var count = users.Count(); List<string> Names = new List<string>(); foreach (RandomChatUser usertemplate in users) { for (int i = count; i > 0; i--) { Names.Add(usertemplate.ChatUser); } count--; } var nextuser = Names[rnd.Next(Names.Count() + 1)]; try { _context.RandomChatUser.Where(x => x.ChatUser == nextuser).First().lastchecked = true; _context.SaveChanges(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } message = nextuser; } } } output.EventData = new CommandResponseArgs(args.Type, message, MessageType.ChannelMessage, args.Sender, args.ChannelName); } return output; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } public class ListRandUsersInListCommand : ICommand { public string Trigger => "!list"; public string Alias => "!list"; private Random rnd = new Random(); public string Description => "Outputs List"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<CommandEventType> EventToBeTriggered(Dictionary<string, string> args) { return CommandEventType.None; } public async Task<string> ExecuteCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { if ((args["message"].ToLower().StartsWith(Trigger) || args["message"].ToLower().StartsWith(Alias))) { using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if (_context.RandomChatUser.Where(x => x.Stream == args["channel"]).Count() > 0) { string message = "Users in List: "; foreach (var user in _context.RandomChatUser.Where(x => x.Stream == args["channel"]).OrderBy(s => s.Sort)) { message += user.ChatUser + "\n"; } return message; } } } return ""; } public async Task<string> ExecuteWhisperCommandIfApplicable(Dictionary<string, string> args, IServiceScopeFactory scopeFactory) { return ""; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopeFactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = false; output.Type = Eventbus.EventType.CommandResponseReceived; string message = "No User found/in List"; if (args.elevatedPermissions && (args.Message.ToLower().StartsWith(Trigger) || args.Message.ToLower().StartsWith(Alias))) { output.ExecuteEvent = true; using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if (_context.RandomChatUser.Where(x => x.Stream == args.ChannelName).Count() > 0) { message = "Users in List: "; foreach (var user in _context.RandomChatUser.Where(x => x.Stream == args.ChannelName).OrderBy(s => s.Sort)) { message += user.ChatUser + "\n"; } } } output.EventData = new CommandResponseArgs(args.Type, message, MessageType.ChannelMessage, args.Sender, args.ChannelName); } return output; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } public class SkipLastRandUserCommand : ICommand { public string Trigger => "!skip"; public string Alias => "!skip"; private Random rnd = new Random(); public string Description => "Skips last selected user"; public string Category => "stream"; public bool ChatSupported(ChatType chat) { return chat == ChatType.Twitch; } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopeFactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = false; output.Type = Eventbus.EventType.CommandResponseReceived; string message = "No skippable user found"; if (args.elevatedPermissions && (args.Message.ToLower().StartsWith(Trigger) || args.Message.ToLower().StartsWith(Alias))) { output.ExecuteEvent = true; using (var scope = scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); if (_context.RandomChatUser.Where(x => x.Stream == args.ChannelName && x.lastchecked).Count() > 0) { var skippeduser = _context.RandomChatUser.Where(x => x.Stream == args.ChannelName && x.lastchecked).FirstOrDefault(); if (skippeduser != null) { _context.RandomChatUser.Remove(skippeduser); RandomChatUser tmp = new RandomChatUser(); tmp.ChatUser = skippeduser.ChatUser; tmp.lastchecked = false; if (_context.RandomChatUser.Where(x => x.Stream == args.ChannelName).Count() == 0) { tmp.Sort = 1; } else { tmp.Sort = _context.RandomChatUser.Where(x => x.Stream == args.ChannelName).Max(t => t.Sort) + 1; } tmp.Stream = skippeduser.Stream; _context.RandomChatUser.Add(tmp); _context.SaveChanges(); message = "User skipped"; } } } output.EventData = new CommandResponseArgs(args.Type, message, MessageType.ChannelMessage, args.Sender, args.ChannelName); } return output; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } } } <file_sep>/BobDeathmic.Tests/Services/Commands/CommandServiceTests.cs using BobDeathmic.Args; using BobDeathmic.ChatCommands.Args; using BobDeathmic.Data; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Eventbus; using BobDeathmic.Services.Commands; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace BobDeathmic.Tests.Services.Commands { [TestFixture] public class CommandServiceTests { [Test] public async Task handleCommand_GameCommand_StreamTitleChangeEventTriggered() { IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); IEventBus eventbus = new EventBusLocal(); StreamTitleChangeArgs receivedEventsArg = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.StreamTitleChangeRequested += delegate (object sender, StreamTitleChangeArgs e) { receivedEventsArg = e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!game neuer spiele titel", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch,"deathmic"); Assert.AreNotEqual(null, receivedEventsArg); Assert.AreEqual("neuer spiele titel", receivedEventsArg.Game); Assert.AreEqual("deathmic", receivedEventsArg.StreamName); Assert.AreEqual(StreamProviderTypes.Twitch, receivedEventsArg.Type); } [Test] public async Task handleCommand_TitleCommand_StreamTitleChangeEventTriggered() { IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); IEventBus eventbus = new EventBusLocal(); StreamTitleChangeArgs receivedEventsArgs = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.StreamTitleChangeRequested += delegate (object sender, StreamTitleChangeArgs e) { receivedEventsArgs=e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!title neuer spiele titel", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch, "deathmic"); Assert.AreNotEqual(null, receivedEventsArgs); Assert.AreEqual("neuer spiele titel", receivedEventsArgs.Title); Assert.AreEqual("deathmic", receivedEventsArgs.StreamName); Assert.AreEqual(StreamProviderTypes.Twitch, receivedEventsArgs.Type); } [Test] public async Task handleCommand_Strawpoll_StrawPollRequestedEventTriggered() { IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); IEventBus eventbus = new EventBusLocal(); StrawPollRequestEventArgs receivedEventsArgs = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.StrawPollRequested += delegate (object sender, StrawPollRequestEventArgs e) { receivedEventsArgs = e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!strawpoll Tolle Frage hier? | antwort 1 | antwort2", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch, "deathmic"); Assert.AreNotEqual(null, receivedEventsArgs); Assert.AreEqual("Tolle Frage hier?", receivedEventsArgs.Question); Assert.AreEqual(2, receivedEventsArgs.Answers.Length); Assert.AreEqual("deathmic", receivedEventsArgs.StreamName); Assert.AreEqual(StreamProviderTypes.Twitch, receivedEventsArgs.Type); } [Test] public async Task handleCommand_RegisterRaffle_CommandResponseReceivedEventTriggered() { DbContextOptions<ApplicationDbContext> options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "Test") .Options; IServiceScope scope = Substitute.For<IServiceScope>(); scope.ServiceProvider.GetService(typeof(ApplicationDbContext)).ReturnsForAnyArgs(new ApplicationDbContext(options)); IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); scopefactory.CreateScope().ReturnsForAnyArgs(scope); IEventBus eventbus = new EventBusLocal(); CommandResponseArgs receivedEventsArgs = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.CommandOutputReceived += delegate (object sender, CommandResponseArgs e) { receivedEventsArgs = e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!registerraffle", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch, "deathmic"); Assert.AreNotEqual(null, receivedEventsArgs); Assert.AreEqual("chromos33", receivedEventsArgs.Sender); Assert.AreEqual("You were added.", receivedEventsArgs.Message); } [Test] public async Task handleCommand_PickNext_CommandResponseReceivedEventTriggered() { DbContextOptions<ApplicationDbContext> options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "Test") .Options; IServiceScope scope = Substitute.For<IServiceScope>(); scope.ServiceProvider.GetService(typeof(ApplicationDbContext)).ReturnsForAnyArgs(new ApplicationDbContext(options)); IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); scopefactory.CreateScope().ReturnsForAnyArgs(scope); IEventBus eventbus = new EventBusLocal(); CommandResponseArgs receivedEventsArgs = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.CommandOutputReceived += delegate (object sender, CommandResponseArgs e) { receivedEventsArgs = e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!next", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch, "deathmic"); Assert.AreNotEqual(null, receivedEventsArgs); Assert.AreEqual("chromos33", receivedEventsArgs.Sender); } [Test] public async Task handleCommand_PickNextRand_CommandResponseReceivedEventTriggered() { DbContextOptions<ApplicationDbContext> options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "Test") .Options; IServiceScope scope = Substitute.For<IServiceScope>(); scope.ServiceProvider.GetService(typeof(ApplicationDbContext)).ReturnsForAnyArgs(new ApplicationDbContext(options)); IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); scopefactory.CreateScope().ReturnsForAnyArgs(scope); IEventBus eventbus = new EventBusLocal(); CommandResponseArgs receivedEventsArgs = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.CommandOutputReceived += delegate (object sender, CommandResponseArgs e) { receivedEventsArgs = e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!randnext", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch, "deathmic"); Assert.AreNotEqual(null, receivedEventsArgs); Assert.AreEqual("chromos33", receivedEventsArgs.Sender); } [Test] public async Task handleCommand_SkipLast_CommandResponseReceivedEventTriggered() { DbContextOptions<ApplicationDbContext> options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "Test") .Options; IServiceScope scope = Substitute.For<IServiceScope>(); scope.ServiceProvider.GetService(typeof(ApplicationDbContext)).ReturnsForAnyArgs(new ApplicationDbContext(options)); IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); scopefactory.CreateScope().ReturnsForAnyArgs(scope); IEventBus eventbus = new EventBusLocal(); CommandResponseArgs receivedEventsArgs = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.CommandOutputReceived += delegate (object sender, CommandResponseArgs e) { receivedEventsArgs = e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!skip", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch, "deathmic"); Assert.AreNotEqual(null, receivedEventsArgs); Assert.AreEqual("chromos33", receivedEventsArgs.Sender); Assert.AreEqual("No skippable user found", receivedEventsArgs.Message); } [Test] public async Task handleCommand_ListRandUsers_CommandResponseReceivedEventTriggered() { DbContextOptions<ApplicationDbContext> options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "Test") .Options; IServiceScope scope = Substitute.For<IServiceScope>(); scope.ServiceProvider.GetService(typeof(ApplicationDbContext)).ReturnsForAnyArgs(new ApplicationDbContext(options)); IServiceScopeFactory scopefactory = Substitute.For<IServiceScopeFactory>(); scopefactory.CreateScope().ReturnsForAnyArgs(scope); IEventBus eventbus = new EventBusLocal(); CommandResponseArgs receivedEventsArgs = null; //eventbus.TriggerEvent(EventType.).For CommandService service = new CommandService(scopefactory, eventbus); eventbus.CommandOutputReceived += delegate (object sender, CommandResponseArgs e) { receivedEventsArgs = e; }; ChatCommandInputArgs args = new ChatCommandInputArgs() { Message = "!list", Sender = "chromos33", ChannelName = "deathmic", Type = BobDeathmic.Data.Enums.ChatType.Twitch, elevatedPermissions = true }; await service.handleCommand(args, BobDeathmic.Data.Enums.ChatType.Twitch, "deathmic"); Assert.AreNotEqual(null, receivedEventsArgs); Assert.AreEqual("chromos33", receivedEventsArgs.Sender); Assert.AreEqual("No User found/in List", receivedEventsArgs.Message); } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/StreamAddComponent.jsx class StreamAddComponent extends React.Component { constructor(props) { super(props); this.handleSave = this.handleSave.bind(this); this.handleLoadCreateForm = this.handleLoadCreateForm.bind(this); this.handleCancel = this.handleCancel.bind(this); this.handleNameChange = this.handleNameChange.bind(this); this.handleUptimeChange = this.handleUptimeChange.bind(this); this.handleQuoteChange = this.handleQuoteChange.bind(this); this.channelswitch = this.channelswitch.bind(this); this.handleTypeClick = this.handleTypeClick.bind(this); this.state = { Open: false, CanSave: true, StreamName: "", Type: "", UpTime: 0, Quote: 0, Relay: "Aus", Channels: [] }; } handleSave(e) { if (this.state.CanSave) { var request = new XMLHttpRequest(); request.open("POST", "/Stream/Create", true); var curthis = this; request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.onreadystatechange = function () { // Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { curthis.setState({ Open: false }); window.dispatchEvent(new Event('updateTable')); } } request.send("StreamName=" + this.state.StreamName + "&Type=" + this.state.Type + "&UpTime=" + this.state.UpTime + "&Quote=" + this.state.Quote + "&Relay=" + this.state.Relay); } } handleCancel(e) { this.setState({Open: false}); } handleNameChange(e) { if (e.target.value === "") { this.setState({ StreamName: e.target.value, CanSave: false }); } else { this.setState({ StreamName: e.target.value, CanSave: true }); } } handleUptimeChange(e) { this.setState({ UpTime: e.target.value }); } channelswitch(e) { let index = e.nativeEvent.target.selectedIndex; this.setState({ Relay: this.state.Channels[index] }); } handleQuoteChange(e) { this.setState({ Quote: e.target.value }); } handleTypeClick(e) { this.setState({ Type: e.target.getAttribute("data-type") }); } getTypeSwitchCSSClasses(type) { let classes = "typeswitch"; if (type === this.state.Type) { classes += " active"; } classes += " " + type; return classes; } handleLoadCreateForm(e) { const xhr = new XMLHttpRequest(); var thisreference = this; xhr.open('GET', "/Stream/RelayChannels", true); xhr.onload = function () { if (xhr.responseText !== "") { let data = JSON.parse(xhr.responseText); console.log(data); thisreference.setState({ Open: true, Channels: data }); } }; xhr.send(); this.setState({Open: true}); } render() { if (this.state.Open) { const options = this.state.Channels.map((e) => { return <option key={e} value={e}>{e}</option> }) return ( <div> <span className="pointer btn btn_primary mb-3"><i className="fa fa-plus"></i> Hinzufügen</span> <div className="statictest grid column-5 row-11"> <label className="namelabel">Streamname</label> <input className="namefield" name="streamname" value={this.state.StreamName} onChange={this.handleNameChange} type="text" /> <label className="typelabel">Type</label> <span data-type="twitch" onClick={this.handleTypeClick} className={this.getTypeSwitchCSSClasses("twitch")}>Twitch</span> <span data-type="dlive" onClick={this.handleTypeClick} className={this.getTypeSwitchCSSClasses("dlive")}>D-Live</span> <span data-type="mixer" onClick={this.handleTypeClick} className={this.getTypeSwitchCSSClasses("mixer")}>Mixer</span> <div className="grid row-2 column-2 timergrid"> <label className="uptimelabel">Uptime Interval</label> <input value={this.state.UpTime} onChange={this.handleUptimeChange} className="uptimefield" type="number" /> <label className="quotelabel">Quote Interval</label> <input value={this.state.Quote} onChange={this.handleQuoteChange} className="quotefield" type="number" /> </div> <label className="relaylabel">Relay</label> <select className="relayselect" value={this.state.RelayChannel} onChange={this.channelswitch}>{options}</select> <span onClick={this.handleSave} className="btn btn_primary savebtn">Speichern</span> <span onClick={this.handleCancel} className="btn btn_primary cancelbtn">Abbrechen</span> </div> </div> ); } else { return (<span onClick={this.handleLoadCreateForm} className="pointer btn btn_primary mb-3"><i className="fa fa-plus"></i> Hinzufügen</span>) } } }<file_sep>/BobDeathmic/wwwroot/Downloads/APK/README.txt using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.wwwroot.Downloads.APK { public class README { } } <file_sep>/BobDeathmic/Services/Twitch/JSONDataTypes/TwitchAuthToken.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.JSONObjects { public class TwitchAuthToken { public string access_token { get; set; } public string id_token { get; set; } public string refresh_token { get; set; } public string[] scope { get; set; } } } <file_sep>/BobDeathmic/Cron/Setup/SchedulerTaskWrapper.cs using BobDeathmic.Cron.Setup; using BobDeathmic.Services.Helper; using System; namespace BobDeathmic.Cron.Setup { internal class SchedulerTaskWrapper { public NCrontab.CrontabSchedule Schedule { get; set; } public IScheduledTask Task { get; set; } public DateTime NextRunTime { get; set; } public bool Init; public SchedulerTaskWrapper() { NextRunTime = DateTime.Now.Subtract(TimeSpan.FromMinutes(1)); } public bool ShouldRun() { if (Init) { Init = false; Increment(); return false; } var next = Schedule.GetNextOccurrence(DateTime.Now); if (NextRunTime < DateTime.Now) { return true; } return false; //return NextRunTime.Hour == Schedule.GetNextOccurrence(DateTime.Now).Hour && NextRunTime.Minute == Schedule.GetNextOccurrence(DateTime.Now).Minute; } public void Increment() { NextRunTime = Schedule.GetNextOccurrence(DateTime.Now); } } }<file_sep>/BobDeathmic/Services/InterServiceCommunication/Args/CommandResponseArgs.cs using BobDeathmic.Data.Enums; namespace BobDeathmic.Eventbus { public class CommandResponseArgs { public ChatType Chat { get; set; } public string Message { get; set; } public MessageType MessageType { get; set; } public string Sender { get; set; } public string Channel { get; set; } public CommandResponseArgs(ChatType chat,string message,MessageType messageType,string sender,string channel) { Chat = chat; Message = message; MessageType = messageType; Sender = sender; Channel = channel; } public CommandResponseArgs() { } } public enum MessageType { PrivateMessage = 0, ChannelMessage = 1 } }<file_sep>/BobDeathmic/Controllers/EventsController.cs using BobDeathmic.Data; using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Data.DBModels.EventCalendar.manymany; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Data.JSONModels; using BobDeathmic.Models; using BobDeathmic.Models.Events; using BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.OverView; using BobDeathmic.ViewModels.ReactDataClasses.EventDateFinder.Vote; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using MimeKit; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Controllers { public class EventsController : Controller { private readonly ApplicationDbContext _context; private readonly IConfiguration _configuration; private UserManager<ChatUserModel> _userManager; private IHostingEnvironment env; public EventsController(ApplicationDbContext context, IConfiguration configuration, UserManager<ChatUserModel> userManager, IHostingEnvironment env) { _context = context; _configuration = configuration; _userManager = userManager; this.env = env; } [Authorize(Roles = "User,Dev,Admin")] public IActionResult Index() { return View("Index"); } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<IActionResult> OverViewData() { OverView data = new OverView(); data.AddCalendarLink = this.Url.Action("CreateEvent"); ChatUserModel user = await _userManager.GetUserAsync(this.User); data.Calendars = getRelevantCalendars(user); return Json(data); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public IActionResult DownloadAPK() { DirectoryInfo info = new DirectoryInfo(Path.Combine(new string[] { env.WebRootPath, "Downloads", "APK" })); FileInfo[] files = info.GetFiles().OrderByDescending(p => p.CreationTime).ToArray(); int i = 0; FileInfo DownloadFile = null; foreach (FileInfo file in files) { if(i == 0) { DownloadFile = file; } i++; if(i > 3) { //keep last 3 versions file.Delete(); } } if(DownloadFile == null) { return Index(); } return PhysicalFile(DownloadFile.FullName, MimeTypes.GetMimeType(DownloadFile.FullName), Path.GetFileName(DownloadFile.FullName)); } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public String ISUpdateAvailable(int majorRevision, int minorRevision) { DirectoryInfo info = new DirectoryInfo(Path.Combine(new string[] { env.WebRootPath, "Downloads", "APK" })); FileInfo[] files = info.GetFiles().OrderByDescending(p => p.CreationTime).ToArray(); FileInfo DownloadFile = files.FirstOrDefault(); int Major_Revision = 0; int Minor_Revision = 0; if (DownloadFile != null) { Tuple<int, int> VersionsFromFile = getVersionFromString(DownloadFile.FullName); if (VersionsFromFile.Item1 > majorRevision) { return JsonConvert.SerializeObject(new MobileResponse() { Response = "true" }); } if (VersionsFromFile.Item1 == majorRevision && VersionsFromFile.Item2 > minorRevision) { return JsonConvert.SerializeObject(new MobileResponse() { Response = "true" }); } } return JsonConvert.SerializeObject(new MobileResponse() { Response = "false" }); } private Tuple<int,int> getVersionFromString(string version) { try { string[] versions = version.Split("__")[1].Split(".")[0].Split("_"); return new Tuple<int, int>(int.Parse(versions[0]), int.Parse(versions[1])); } catch( ArgumentNullException ex) { return new Tuple<int, int>(0,0); } catch (FormatException ex) { return new Tuple<int, int>(0, 0); } catch (OverflowException ex) { return new Tuple<int, int>(0, 0); } } private List<Calendar> getRelevantCalendars(ChatUserModel user) { List<Calendar> Calendars = new List<Calendar>(); foreach (Models.Events.Event calendar in _context.Events.Include(x => x.Admin).Include(x => x.Members).ThenInclude(x => x.ChatUserModel).Where(x => x.Admin.Id == user.Id || x.Members.Where(y => y.ChatUserModelID == user.Id).Count() > 0)) { //TODO make a custom CalendarMember object to facilitate better security (no need to lay open all data) if (calendar.Admin == user) { Calendars.Add(new Calendar { Id = calendar.Id, key = calendar.Id, DeleteLink = this.Url.Action("Delete", "Events", new { ID = calendar.Id }), EditLink = this.Url.Action("EditCalendar", "Events", new { ID = calendar.Id }), Name = calendar.Name, VoteLink = this.Url.Action("VoteOnCalendar", "Events", new { ID = calendar.Id }) }); } else { Calendars.Add(new Calendar { Id = calendar.Id, key = calendar.Id, DeleteLink = "", EditLink = "", Name = calendar.Name, VoteLink = this.Url.Action("VoteOnCalendar", "Events", new { ID = calendar.Id }) }); } } return Calendars; } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task UpdateEventTitle(string ID, string Title) { if (Int32.TryParse(ID, out int _ID)) { var Calendar = _context.Events.Where(x => x.Id == _ID).FirstOrDefault(); if (Calendar != null) { Calendar.Name = Title; await _context.SaveChangesAsync(); } } } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var calendar = await _context.Events .FirstOrDefaultAsync(m => m.Id == id); if (calendar == null) { return NotFound(); } return View(calendar); } // POST: Streams2/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> DeleteConfirmed(int id) { var stream = await _context.Events.FindAsync(id); _context.Events.Remove(stream); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task AddInvitedUser(string ID, string ChatUser) { if (Int32.TryParse(ID, out int _ID)) { var Calendar = _context.Events.Where(x => x.Id == _ID).FirstOrDefault(); if (Calendar != null) { if (Calendar.Members.Where(x => x.ChatUserModel.ChatUserName == ChatUser).Count() == 0) { ChatUserModel user = _context.ChatUserModels.Where(x => x.ChatUserName.ToLower() == ChatUser.ToLower()).FirstOrDefault(); if (user != null) { ChatUserModel_Event newrelation = new ChatUserModel_Event(); newrelation.Calendar = Calendar; newrelation.ChatUserModel = user; if (Calendar.Members == null) { Calendar.Members = new List<ChatUserModel_Event>(); } Calendar.Members.Add(newrelation); if (user.Calendars == null) { user.Calendars = new List<ChatUserModel_Event>(); } user.Calendars.Add(newrelation); _context.ChatUserModel_Event.Add(newrelation); await _context.SaveChangesAsync(); } } } } } [HttpGet] [Authorize(Roles = "User,Dev,Admin")] public async Task<int> UpdateRequestState(string requestID, string state,string comment) { var Request = _context.AppointmentRequests.Where(x => x.ID == requestID).FirstOrDefault(); if (Request != null) { Request.State = (AppointmentRequestState)Enum.Parse(typeof(AppointmentRequestState), state); Request.Comment = comment; return _context.SaveChanges(); } return 0; } [HttpPost] [Authorize(Roles = "User,Dev,Admin")] public async Task RemoveInvitedUser(string ID, string ChatUser) { if (Int32.TryParse(ID, out int _ID)) { var RelationToDelete = _context.ChatUserModel_Event.Include(x => x.ChatUserModel).Where(x => x.CalendarID == _ID && x.ChatUserModel.ChatUserName == ChatUser).FirstOrDefault(); if (RelationToDelete != null) { _context.ChatUserModel_Event.Remove(RelationToDelete); _context.SaveChanges(); } } } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<JsonResult> InvitableUsers(int ID) { Models.Events.Event _calendar = _context.Events.Include(x => x.Members).Where(x => x.Id == ID).FirstOrDefault(); if (_calendar != null) { //TODO get real Filtered Members List<ChatUserModel_Event> relation = _context.ChatUserModel_Event.Include(x => x.ChatUserModel).Where(x => x.Calendar == _calendar).ToList(); List<ChatUserModel> ToFilterMembers = new List<ChatUserModel>(); foreach (ChatUserModel_Event temp in relation) { ToFilterMembers.Add(temp.ChatUserModel); } List<ChatUserModel> FilteredMembers = _context.ChatUserModels.Where(x => !ToFilterMembers.Contains(x)).ToList(); List<ChatUser> Members = new List<ChatUser>(); foreach (ChatUserModel Member in FilteredMembers) { Members.Add(new ChatUser { Name = Member.ChatUserName }); } return Json(Members.ToArray()); } return null; } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<JsonResult> GetEventDates(int ID) { List<EventDate> EventDates = _context.EventDates.Include(x => x.Event).Include(x => x.Teilnahmen).ThenInclude(x => x.Owner).Where(x => x.Event.Id == ID).OrderBy(x => x.Date).ThenBy(x => x.StartTime).ToList(); if (EventDates.Count() > 0) { VoteReactData ReactData = new VoteReactData(); ReactData.Header = new List<EventDateData>(); ChatUserModel user = await _userManager.GetUserAsync(this.User); foreach (EventDate EventDate in EventDates) { if (ReactData.Header.Where(x => x.Date == EventDate.Date.ToString("dd.MM.yy") && x.Time == EventDate.StartTime.ToString("HH:mm") + " - " + EventDate.StopTime.ToString("HH:mm")).Count() == 0) { EventDateData newData = new EventDateData { Requests = new List<VoteRequest>(), Date = EventDate.Date.ToString("dd.MM.yy"), Time = EventDate.StartTime.ToString("HH:mm") + " - " + EventDate.StopTime.ToString("HH:mm") }; // foreach (AppointmentRequest request in EventDate.Teilnahmen.OrderBy(x => x.EventDate.Date).ThenBy(x => x.EventDate.StartTime).ThenBy(x => x.Owner.ChatUserName)) { VoteRequest tmp = new VoteRequest(); tmp.AppointmentRequestID = request.ID; tmp.UserName = request.Owner.ChatUserName; tmp.State = request.State; tmp.Date = request.EventDate.Date.ToString("dd.MM.yy"); tmp.Time = request.EventDate.StartTime.ToString("HH:mm") + "-" + request.EventDate.StopTime.ToString("HH:mm"); tmp.canEdit = request.Owner == user; tmp.Comment = request.Comment; newData.Requests.Add(tmp); } ReactData.Header.Add(newData); } } var json = Json(ReactData, new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); return json; } return new JsonResult(""); } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<JsonResult> InvitedUsers(int ID) { Models.Events.Event _calendar = _context.Events.Include(x => x.Members).ThenInclude(x => x.ChatUserModel).Where(x => x.Id == ID).FirstOrDefault(); if (_calendar != null) { ChatUser[] Members = new ChatUser[_calendar.Members.Count()]; for (int i = 0; i < _calendar.Members.Count(); i++) { Members[i] = new ChatUser { Name = _calendar.Members[i].ChatUserModel.ChatUserName, key = i }; } return Json(Members); } return null; } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<JsonResult> Templates(int ID) { Models.Events.Event _calendar = _context.Events.Include(x => x.EventDateTemplates).Include(x => x.Members).ThenInclude(x => x.ChatUserModel).Where(x => x.Id == ID).FirstOrDefault(); if (_calendar != null) { return Json(_calendar.EventDateTemplates.Select(x => new { key = x.ID, Day = x.Day, Start = x.StartTime.ToString("HH:mm"), Stop = x.StopTime.ToString("HH:mm") }), new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); } return null; } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<bool> SetDayOfTemplate(string ID, int Day) { EventDateTemplate template = _context.EventDateTemplates.Where(x => x.ID == ID).FirstOrDefault(); if (template != null) { template.Day = (Day)Enum.ToObject(typeof(Day), Day); _context.SaveChanges(); return true; } return false; } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<bool> SetStartOfTemplate(string ID, string Start) { EventDateTemplate template = _context.EventDateTemplates.Where(x => x.ID == ID).FirstOrDefault(); if (template != null) { template.StartTime = DateTime.ParseExact(Start, "HH:mm", System.Globalization.CultureInfo.InvariantCulture); _context.SaveChanges(); return true; } return false; } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<bool> SetStopOfTemplate(string ID, string Stop) { EventDateTemplate template = _context.EventDateTemplates.Where(x => x.ID == ID).FirstOrDefault(); if (template != null) { template.StopTime = DateTime.ParseExact(Stop, "HH:mm", System.Globalization.CultureInfo.InvariantCulture); _context.SaveChanges(); return true; } return false; } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<JsonResult> AddTemplate(int ID) { Models.Events.Event _calendar = _context.Events.Include(x => x.Members).ThenInclude(x => x.ChatUserModel).Where(x => x.Id == ID).FirstOrDefault(); if (_calendar != null) { EventDateTemplate item = new EventDateTemplate(); item.Event = _calendar; _calendar.EventDateTemplates.Add(item); _context.EventDateTemplates.Add(item); _context.SaveChanges(); return Json(new { key = item.ID, Day = item.Day, Start = item.StartTime, Stop = item.StopTime }, new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); } return null; } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public void RemoveTemplate(string ID, int CalendarID) { var calendar = _context.Events.Where(x => x.Id == CalendarID).FirstOrDefault(); var template = _context.EventDateTemplates.Where(x => x.ID == ID).FirstOrDefault(); if (calendar != null && template != null) { calendar.EventDateTemplates.Remove(template); _context.Remove(template); _context.SaveChanges(); } } [Authorize(Roles = "User,Dev,Admin")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<IActionResult> GetEvent(int ID) { Models.Events.Event _calendar = _context.Events.Where(x => x.Id == ID).FirstOrDefault(); if (_calendar != null) { if (_calendar.Name == null) { _calendar.Name = ""; _context.SaveChangesAsync(); } return Json(_calendar); } return RedirectToAction("OverViewData"); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> CreateEvent(int? ID) { if (ID == null) { ChatUserModel admin = await _userManager.GetUserAsync(this.User); Models.Events.Event newCalendar = new Models.Events.Event(); if (admin.AdministratedCalendars == null) { admin.AdministratedCalendars = new List<Models.Events.Event>(); } admin.AdministratedCalendars.Add(newCalendar); if (admin.Calendars == null) { admin.Calendars = new List<ChatUserModel_Event>(); } ChatUserModel_Event JoinTable = new ChatUserModel_Event(); JoinTable.Calendar = newCalendar; JoinTable.ChatUserModel = admin; admin.Calendars.Add(JoinTable); newCalendar.Members.Add(JoinTable); _context.Events.Add(newCalendar); _context.ChatUserModel_Event.Add(JoinTable); _context.SaveChanges(); return View(newCalendar.Id); } //Create Calendar here stuff return View(ID); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> EditCalendar(int ID) { return RedirectToAction("CreateEvent", new { ID = ID }); } [Authorize(Roles = "User,Dev,Admin")] public async Task<IActionResult> VoteOnCalendar(int ID) { return View(ID); } } }<file_sep>/BobDeathmic/Services/InterServiceCommunication/IEventBus.cs using BobDeathmic.Args; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Eventbus { public interface IEventBus { event EventHandler<RelayMessageArgs> RelayMessageReceived; event EventHandler<TwitchMessageArgs> TwitchMessageReceived; event EventHandler<PasswordRequestArgs> PasswordRequestReceived; event EventHandler<StreamTitleChangeArgs> StreamTitleChangeRequested; event EventHandler<StreamTitleChangeArgs> StreamTitleChanged; event EventHandler<StrawPollRequestEventArgs> StrawPollRequested; event EventHandler<MessageArgs> DiscordMessageSendRequested; event EventHandler<CommandResponseArgs> CommandOutputReceived; void TriggerEvent(EventType @event, dynamic EventData); } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/EventDateFinder/Edit_Create/ChatUserSelect.jsx class ChatUserSelect extends React.Component { constructor(props) { super(props); this.state = { chatUsers: [], selectedUser: "" }; this.handleOnClick = this.handleOnClick.bind(this); this.handleOnChange = this.handleOnChange.bind(this); } componentWillMount() { var thisreference = this; $.ajax({ url: "/Events/InvitableUsers/" + this.props.ID, type: "GET", data: {}, success: function (result) { thisreference.setState({ chatUsers: result, selectedUser: result[0].name }); } }); } handleOnClick(event) { var thisreference = this; $.ajax({ url: "/Events/AddInvitedUser/", type: "POST", data: { ID: thisreference.props.ID, ChatUser: thisreference.state.selectedUser }, success: function (result) { thisreference.props.eventEmitter.emitEvent("UpdateChatMembers"); } }); } handleOnChange(event) { console.log(event.target.value); this.setState({ selectedUser: event.target.value}); } render() { if (this.state.chatUsers.length > 0) { var chatUserNodes = this.state.chatUsers.map(function (chatUser) { return <option key={chatUser.name} value={chatUser.name}>{chatUser.name}</option>; }); return ( <div> <select key={this.props.key} value={this.state.selectedUser} onChange={this.handleOnChange} className={"chatUser_" + this.props.key}> {chatUserNodes} </select> <span className="button" onClick={this.handleOnClick}>Invite</span> </div> ); } return <p> No Users Loaded</p>; } }<file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Other/StreamEditData.cs using BobDeathmic.Data.DBModels.StreamModels; using Jurassic.Library; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Other { public class StreamEditData { public string StreamName { get; set; } public string Type { get; set; } public int UpTime { get; set; } public int Quote { get; set; } public string RelayChannel { get; set; } public string[] RelayChannels { get; set; } public StreamEditData(Stream stream,List<string> channels) { StreamName = stream.StreamName; Type = stream.Type.ToString(); UpTime = stream.UpTimeInterval; Quote = stream.QuoteInterval; List<string> tmpchannels = new List<string>(); tmpchannels.Add("Aus"); tmpchannels.Add("An"); tmpchannels.AddRange(channels); RelayChannel = stream.DiscordRelayChannel; RelayChannels = tmpchannels.ToArray(); } public string ToJSON() { return JsonConvert.SerializeObject(this); } } } <file_sep>/BobDeathmic/ViewModels/StreamModels/StreamListDataModel.cs using BobDeathmic.Data.DBModels.StreamModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.StreamModels { public class StreamListDataModel { public List<Stream> StreamList { get; set; } public string StatusMessage { get; set; } } } <file_sep>/BobDeathmic/Startup.cs using BobDeathmic.Data; using BobDeathmic.Eventbus; using BobDeathmic.Models; using BobDeathmic.Services; using BobDeathmic.Services.Helper; using BobDeathmic.Services.Streams.Checker.Twitch; using JavaScriptEngineSwitcher.ChakraCore; using JavaScriptEngineSwitcher.Extensions.MsDependencyInjection; using JavaScriptEngineSwitcher.Jurassic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using React.AspNet; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BobDeathmic.Cron.Setup; using BobDeathmic.Cron; using BobDeathmic.Data.DBModels.User; using BobDeathmic.Services.Discords; using BobDeathmic.Services.Streams.Relay.Twitch; using BobDeathmic.Services.Commands; namespace BobDeathmic { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), mysqlOptions => { mysqlOptions.ServerVersion(new Version(10, 3, 8), ServerType.MariaDb); }) ); services.AddIdentity<ChatUserModel, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); services.Configure<IdentityOptions>(options => { options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(2); options.Lockout.MaxFailedAccessAttempts = 10; //options.User.RequireUniqueEmail = false; options.Password.RequireDigit = false; options.Password.RequiredLength = 2; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireNonAlphanumeric = false; }); services.ConfigureApplicationCookie(options => { options.ExpireTimeSpan = TimeSpan.FromDays(30); options.LoginPath = "/Main/Login"; }); // Add application services. services.AddMemoryCache(); services.AddSingleton<IEventBus, EventBusLocal>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TwitchChecker>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, DLiveChecker>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, Services.MixerChecker>(); services.AddSingleton<ICommandService, CommandService>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, DiscordService>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TwitchRelayCenter>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TwitchAPICalls>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, StrawPollService>(); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, SchedulerHostService>(); services.AddSingleton<IScheduledTask, EventCalendarTask>(); services.AddSingleton<IScheduledTask, TwitchTokenRefreshTask>(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddReact(); services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName).AddChakraCore(); //services.AddJsEngineSwitcher().AddJurassic(); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, IServiceProvider services) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Main/Error"); } app.UseReact(config => { config.AllowJavaScriptPrecompilation = true; config.SetLoadBabel(false); config.SetLoadReact(true); config.UseServerSideRendering = false; // If you want to use server-side rendering of React components, // add all the necessary JavaScript files here. This includes // your components as well as all of their dependencies. // See http://reactjs.net/ for more information. Example: //config // .AddScript("~/Scripts/First.jsx") // .AddScript("~/Scripts/Second.jsx"); // If you use an external build too (for example, Babel, Webpack, // Browserify or Gulp), you can improve performance by disabling // ReactJS.NET's version of Babel and loading the pre-transpiled // scripts. Example: //config // .SetLoadBabel(false) // .AddScriptWithoutTransform("~/Scripts/bundle.server.js"); }); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Main}/{action=Index}/{id?}"); }); } } } <file_sep>/BobDeathmic/ViewModels/ReactDataClasses/Table/Columns/StreamDeleteColumn.cs using BobDeathmic.Data.DBModels.Relay; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.ReactDataClasses.Table.Columns { public class StreamDeleteColumn : Column { public string ReactComponentName { get { return "StreamDeleteColumn"; } } public int key { get; set; } public string Text { get; set; } public int StreamID { get; set; } public StreamDeleteColumn(int key, string Text, Stream stream) { this.key = key; this.Text = Text; this.canSort = false; this.StreamID = stream.ID; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/GiveAway/Admin/ChannelSelector.jsx class ChannelSelector extends React.Component { constructor(props) { super(props); this.state = { activeChannel: props.Channels[0] }; this.onChange = this.onChange.bind(this); this.getOptions = this.getOptions.bind(this); } onChange(e) { let index = e.nativeEvent.target.selectedIndex; this.setState({ activeChannel: this.props.Channels[index] }); this.props.changeSelectedChannel(this.props.Channels[index]); } getOptions() { let channelcount = 0; const channels = this.props.Channels.map(function (item) { channelcount++; return ( <option value={item} key={channelcount} > {item}</ option> ); }); return channels; } render() { return ( <div> <h2>Ausgabe Channel</h2> <select onChange={this.onChange} value={this.state.activeChannel}> {this.getOptions()} </select> </div> ); } } <file_sep>/BobDeathmic/Data/DBModels/User/ChatUser.cs using BobDeathmic.Data.DBModels.EventCalendar; using BobDeathmic.Data.DBModels.EventCalendar.manymany; using BobDeathmic.Data.DBModels.GiveAway; using BobDeathmic.Data.DBModels.GiveAway.manymany; using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using BobDeathmic.Models.Events; using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BobDeathmic.Data.DBModels.User { // Add profile data for application users by adding properties to the ChatUserModel class public class ChatUserModel : IdentityUser { public string ChatUserName { get; set; } public List<StreamSubscription> StreamSubscriptions { get; set; } public string InitialPassword { get; set; } public List<Stream> OwnedStreams { get; set; } public List<GiveAwayItem> OwnedItems { get; set; } public List<GiveAwayItem> ReceivedItems { get; set; } public List<User_GiveAwayItem> AppliedTo { get; set; } public List<ChatUserModel_Event> Calendars { get; set; } public List<Event> AdministratedCalendars { get; set; } public List<AppointmentRequest> AppointmentRequests { get; set; } public ChatUserModel(): this(new List<Stream>()) {} public ChatUserModel(string username) : this(username, new List<Stream>()) {} public ChatUserModel(IEnumerable<Stream> Streams): this(String.Empty,Streams) {} public ChatUserModel(string username,IEnumerable<Stream> Streams) { ChatUserName = username; UserName = cleanedUserName(username); StreamSubscriptions = new List<StreamSubscription>(); foreach (Stream stream in Streams) { StreamSubscriptions.Add(new StreamSubscription(stream, SubscriptionState.Subscribed)); } } public void SetInitialPassword() { if(InitialPassword == "" || InitialPassword == null) { InitialPassword = GeneratePassword(); } } public string GeneratePassword() { byte[] salt = new byte[128 / 8]; byte[] pwd = new byte[64]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); rng.GetBytes(pwd); } string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: <PASSWORD>(), salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); return hashed; } private string cleanedUserName(string username) { return Regex.Replace(username.Replace(" ", string.Empty).Replace("/", string.Empty).Replace("\\", string.Empty), @"[\[\]\\\^\$\.\|\?\'\*\+\(\)\{\}%,;><!@#&\-\+]", string.Empty); } public bool IsSubscribed(string streamname) { if(streamname == null || streamname == "") { throw new ArgumentException("StreamName must be not be null or empty"); } if (StreamSubscriptions != null && StreamSubscriptions.Where(ss => ss.Stream != null && ss.Stream.StreamName.ToLower() == streamname.ToLower() && ss.Subscribed == SubscriptionState.Subscribed).FirstOrDefault() != null) { return true; } return false; } } } <file_sep>/BobDeathmic/wwwroot/ReactComponents/Table/Row.jsx class Row extends React.Component { constructor(props) { super(props); } render() { if (this.props.Columns.length > 0) { var i = 0; var curthis = this; const Columns = this.props.Columns.map((column) => { i++ const ColumnType = this.props.ColumnTypes[column.ReactComponentName]; return <ColumnType Sort={curthis.props.Sort} key={i} id={i} data={column} />; }); return (<tr>{Columns}</tr>); } else { return <tr>ERROR</tr>; } } } <file_sep>/BobDeathmic/ViewModels/User/AddSubscriptionViewModel.cs using BobDeathmic.Data.DBModels.StreamModels; using BobDeathmic.Data.Enums.Stream; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ViewModels.User { public class AddSubscriptionViewModel { [Required] [DataType(DataType.Text)] [Display(Name = "Stream")] public string StreamNameForSubscription { get; set; } public StreamProviderTypes type { get; set; } public List<Stream> SubscribableStreams { get; set; } public List<StreamSubscription> Subscriptions { get; set; } } } <file_sep>/BobDeathmic/ChatCommands/Help.cs using BobDeathmic.ChatCommands.Args; using BobDeathmic.ChatCommands.Setup; using BobDeathmic.Data.Enums; using BobDeathmic.Eventbus; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.ChatCommands { public class Help : ICommand { public string Trigger { get { return "!help"; } } public string Description { get { return "Listet Commands auf"; } } public string Category { get { return "General"; } } public string Alias => "!help"; private List<ICommand> Commands; public bool ChatSupported(ChatType chat) { return true; } public Help(List<ICommand> Commands) { this.Commands = Commands; } private ChatType getChatType(string input) { switch(input) { case "twitch": return ChatType.Twitch; case "discord": return ChatType.Discord; } return ChatType.NotImplemented; } public string getHelp(ChatType type) { string currentCategory = string.Empty; string sCommandMessage = "Viele Befehle haben einen help parameter (!Befehl help)" + Environment.NewLine; sCommandMessage += "Dev"; sCommandMessage += Environment.NewLine; sCommandMessage += Environment.NewLine; sCommandMessage += $"[WebInterface]{Environment.NewLine}"; sCommandMessage += "!WebInterfaceLink (!wil) : Gibt den Link zum Webinterface zurück" + Environment.NewLine; foreach (ICommand command in Commands.Where(x => x.ChatSupported(type))) { if (currentCategory != command.Category) { sCommandMessage += Environment.NewLine; sCommandMessage += Environment.NewLine; currentCategory = command.Category; sCommandMessage += $"[{command.Category}]{Environment.NewLine}"; } sCommandMessage += command.Trigger + " : " + command.Description + Environment.NewLine; } return sCommandMessage; } public bool isCommand(string str) { return str.ToLower().StartsWith(Trigger) || str.ToLower().StartsWith(Alias); } public async Task<ChatCommandOutput> execute(ChatCommandInputArgs args, IServiceScopeFactory scopefactory) { ChatCommandOutput output = new ChatCommandOutput(); output.ExecuteEvent = true; output.Type = Eventbus.EventType.CommandResponseReceived; output.EventData = new CommandResponseArgs( args.Type, getHelp(args.Type), MessageType.PrivateMessage, args.Sender, args.ChannelName ); return output; } } } <file_sep>/BobDeathmic/Data/IApplicationDbContext.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Data { public interface IApplicationDbContext { } } <file_sep>/BobDeathmic/Services/InterServiceCommunication/EventBusLocal.cs using BobDeathmic.Args; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BobDeathmic.Eventbus { public class EventBusLocal : IEventBus { public event EventHandler<StreamTitleChangeArgs> StreamTitleChangeRequested; public event EventHandler<StreamTitleChangeArgs> StreamTitleChanged; public event EventHandler<MessageArgs> DiscordMessageSendRequested; public event EventHandler<PasswordRequestArgs> PasswordRequestReceived; public event EventHandler<TwitchMessageArgs> TwitchMessageReceived; public event EventHandler<RelayMessageArgs> RelayMessageReceived; public event EventHandler<StrawPollRequestEventArgs> StrawPollRequested; public event EventHandler<CommandResponseArgs> CommandOutputReceived; public void TriggerEvent(EventType @event, dynamic EventData) { switch (@event) { case EventType.RelayMessageReceived: RelayMessageReceived(this, EventData); break; case EventType.TwitchMessageReceived: TwitchMessageReceived(this, EventData); break; case EventType.PasswordRequestReceived: PasswordRequestReceived(this, EventData); break; case EventType.StreamTitleChangeRequested: StreamTitleChangeRequested(this, EventData); break; case EventType.StreamTitleChanged: StreamTitleChanged(this, EventData); break; case EventType.StrawPollRequested: StrawPollRequested(this, EventData); break; case EventType.DiscordMessageSendRequested: DiscordMessageSendRequested(this, EventData); break; case EventType.CommandResponseReceived: CommandOutputReceived(this, EventData); break; } } } public enum EventType { RelayMessageReceived = 2, TwitchMessageReceived = 3, PasswordRequestReceived = 4, StreamTitleChangeRequested = 5, StreamTitleChanged = 6, StrawPollRequested = 9, DiscordMessageSendRequested = 10, CommandResponseReceived = 11 } }
339d539307bc0c49affdd3d2130e9bdd8723fd24
[ "JavaScript", "C#", "Text", "Markdown" ]
133
C#
Kolpa/DeathmicChatbot
ac55a33a93c21ba37eea9c6d7cfb80116d0853ee
582aaf86f88ba0acd044449423888c6a4223a896
refs/heads/main
<file_sep>#!/usr/bin/env bash -e cd images for file in *.*; do convert $file -resize 50% medium/$file; convert $file -resize 25% small/$file; done<file_sep>import { registerRoute } from "workbox-routing"; import { CacheFirst, StaleWhileRevalidate } from "workbox-strategies"; registerRoute( ({ request, url }) => request.destination === "image" || url.origin === "https://fonts.googleapis.com" || url.origin === "https://fonts.gstatic.com", new CacheFirst() ); registerRoute( ({ request, url }) => request.destination === "script" || request.destination === "style" || url.pathname.startsWith("/recipes/") || url.pathname === "/index.html" || url.pathname === "/", new StaleWhileRevalidate() );
e04ac8a06ff0fc34190eae0c0511dccd1dd5383c
[ "JavaScript", "Shell" ]
2
Shell
mushishi78/elmas-recipes
bf5159cd9b8ed57c262f562ed8ca7411237f2705
d7fa2d377a6fd54d101947d735501976680bae63
refs/heads/master
<file_sep>#include <gb/gb.h> #include <gb/hardware.h> #include "graphics/red.c" #include "graphics/newTilesc.c" void start_game(); void update_player(); void move_player_sprite(int direction, int reversed); void walk(int direction); UINT8 player_x, player_y; UINT8 last_keys; unsigned char bkgtilea[] = {0}; unsigned char bkgtileb[] = {2}; void main() { start_game(); while(1){ update_player(); last_keys = joypad(); wait_vbl_done(); } } void move_player_sprite(int direction, int reversed) { // Function to move all 4 quadrants of sprite at the same time // TO DO: // WALKING ANIMATION // FUNCTIONALISE DIFFERENT ACTIONS FOR OTHER SPRITES int tile; for(tile=0;tile<4;tile++) { set_sprite_tile(tile,tile + direction); if (!reversed) { // i.e. don't flip the sprite set_sprite_prop(tile,get_sprite_prop(0) & ~S_FLIPX); move_sprite(0,player_x,player_y); move_sprite(1,player_x+8,player_y); move_sprite(2,player_x,player_y+8); move_sprite(3,player_x+8,player_y+8); } else { set_sprite_prop(tile,S_FLIPX); move_sprite(0,player_x+8,player_y); move_sprite(1,player_x,player_y); move_sprite(2,player_x+8,player_y+8); move_sprite(3,player_x,player_y+8); } } } void walk(int direction) { // Slow because of delays, need to find a way around this int tile; int time = 100; delay(time); for(tile=0;tile<4;tile++) { set_sprite_tile(tile,tile + direction + 12); } delay(time); } void start_game() { int i, j, k; int base = 75; DISPLAY_ON; NR52_REG = 0x8F; NR51_REG = 0x11; NR50_REG = 0x1F; player_x = 80; player_y = 80; SPRITES_8x8; set_sprite_data(0, 47, red_tile_data); move_player_sprite(0,0); SHOW_SPRITES; set_bkg_data(0,3,newTiles); // Box around the screen for(i=0 ; i<20 ; i++) { // top set_bkg_tiles(i,0,1,1,bkgtilea); /* x,y,w,h,tilenumber */ //left set_bkg_tiles(0,i,1,1,bkgtilea); //bottom set_bkg_tiles(i,17,1,1,bkgtilea); //right set_bkg_tiles(19,i,1,1,bkgtilea); } // Interior for (k=1;k<17;k++){ for (j=1;j<19;j++) { set_bkg_tiles(j,k,1,1,bkgtileb); } } SHOW_BKG; } void update_player() { // UP if (joypad() & J_UP) { player_y--; move_player_sprite(4,0); walk(4); if (player_y == 15) { player_y = 16; } } // DOWN if (joypad() & J_DOWN) { player_y++; move_player_sprite(0,0); walk(0); if (player_y == 153) { player_y = 152; } } // LEFT if (joypad() & J_LEFT) { player_x--; move_player_sprite(8,0); walk(8); if (player_x == 7) { player_x = 8; } } // RIGHT if (joypad() & J_RIGHT) { player_x++; move_player_sprite(8,1); walk(8); if (player_x == 161) { player_x = 160; } } } <file_sep># gameboy_rpg A basic RPG for the gameboy, written in C using GBDK. Work in progress.
628f286dfd99520d32f2f78c158b098cd28b1415
[ "Markdown", "C" ]
2
C
Liro451/gameboy_rpg
19275736c529bfb8599573fc660adaca7c087e23
c51856f90f05785eb3c2f0e02f5131d09aee6d7a
refs/heads/master
<repo_name>HelloDarkLotus/ProjectIntegration<file_sep>/ProjectIntegration/config.ini [ProjectInfo] version=RAN19067_0416 projname=CK_Persimmon [RedmineInfo] username=jinjinc password=<PASSWORD> baseurl=http://192.168.100.103/redmine/ [CompileInfo] basepath=/home/arm-cc1/workspace/<version>/build targetpath=/home/arm-cc1/localCodePath/<version>/ecTelematicsApp/master gitrepo=git@192.168.16.136:/opt/git/A-IVI2nd_ecTelematicsApp.git<file_sep>/ProjectIntegration/analysis.py import csv class DataAnalysis(object): def __init__(self, csvFile): self.file = csvFile self.stsTbl = dict() self.totalNum = 0 def GenDataDict(self): with open(self.file) as f: handler = csv.reader(f) next(handler) self.totalNum = len(list(handler)) for row in handler: if 'New' in row: self.stsTbl[r'New'] += 1 elif 'Assigned' in row: self.stsTbl[r'Assigned'] += 1 elif 'Working' in row: self.stsTbl[r'Working'] += 1 elif 'Resolved' in row: self.stsTbl[r'Resolved'] += 1 elif 'Rejected' in row: self.stsTbl[r'Rejected'] += 1 elif 'Verified' in row: self.stsTbl[r'Verified'] += 1 elif 'Closed' in row: self.stsTbl[r'Closed'] += 1 else: self.stsTbl[r'Pending'] += 1<file_sep>/ProjectIntegration/__init__.py from .analysis import DataAnalysis from .compile import CompileModule from .pipeline import PipeLine def GetData(): pipeItem = PipeLine() cfgFilePath = pipeItem.GetConfigPath() pipeItem.ConfigMethod(cfgFilePath) pipeItem.GenHeader() pipeItem.LoginMethod() bugInfo = pipeItem.SpiderMethod() pipeItem.StoreData(bugInfo) def CompileData(): serverip = r"192.168.16.108" username = r"arm-cc1" password = r"<PASSWORD>" obj = CompileModule(serverip, username, password) obj.ConnectServer() def AnalysisData(): obj = DataAnalysis() obj.GenDataDict() if __name__ == "__main__": GetData() CompileData() AnalysisData()<file_sep>/ProjectIntegration/compile.py import os import paramiko from git import Repo class CompileModule(object): def __init__(self, ip, username, password): self.Ssh = "" self.ServerIP = ip self.UserName = username self.PassWord = <PASSWORD> def ConnectServer(self): self.Ssh = paramiko.SSHClient() self.Ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.Ssh.connect(self.ServerIP, 22, self.UserName, self.PassWord) def ExecuteCommand(self, cmd): stdout = self.Ssh.exec_command(cmd) print(stdout.readlines()) def CloseConnection(self): self.Ssh.close() def CloneCodeFromGit(self, repoPath, srcPath): if not os.path.exists(srcPath): Repo.clone_from(repoPath, srcPath) else: Repo.clone(srcPath)<file_sep>/ProjectIntegration/pipeline.py import os import configparser import csv import requests from bs4 import BeautifulSoup class PipeLine(object): def __init__(self): self.userName = "" self.passWord = "" self.versionNumber = "" self.projectName = "" self.baseUrl = "" self.basePath = "" self.targetPath = "" self.gitRepo = "" self.session = "" self.headers = "" # return configure file's path def GetConfigPath(self): return os.getcwd() + r'\config.ini' # parser configure file than get configure parameters def ConfigMethod(self, fileName): config = configparser.ConfigParser() config.read(fileName) self.userName = config.get("RedmineInfo", "username") self.passWord = config.get("RedmineInfo", "password") self.baseUrl = config.get("RedmineInfo", "baseurl") self.versionNumber = config.get("ProjectInfo", "version") self.projectName = config.get("ProjectInfo", "projname") self.basePath = config.get("CompileInfo", "basepath") self.targetPath = config.get("CompileInfo", "targetpath") self.gitRepo = config.get("CompileInfo", "gitrepo") # generate HTTP request header def GenHeader(self): accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' accept_encoding = 'gzip,deflate,sdch' accept_language = 'zh-CN,zh;q=0.8' user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36' self.headers = { 'Accept': accept, 'Accept-Encoding': accept_encoding, 'Accept-Language': accept_language, 'User-Agent': user_agent, } # get token string for login authentication def GetLoginToken(self): loginUrl = self.baseUrl + r'login' self.session = requests.Session() r = self.session.get(loginUrl, headers=self.headers) soup = BeautifulSoup(r.text, 'lxml') return soup.find('input', {'name': 'authenticity_token'})['value'] # login redmine def LoginMethod(self): token = self.GetLoginToken() if token is not None: post_data = { 'username': self.userName, 'password': <PASSWORD>, 'authenticity_token': token, } # because redmine login successful will redirect, so should forbidden it self.session.post(self.baseUrl + r'login', data=post_data, headers=self.headers, allow_redirects=False) # spider bug information and store into list def SpiderMethod(self): roadmapUrl = self.baseUrl + r'projects/' + self.projectName.lower() + r'/roadmap' r = self.session.get(roadmapUrl) soup = BeautifulSoup(r.text, 'lxml') href = soup.find('a', {'name': self.versionNumber})['href'] siUrl = r'http://192.168.100.103' + href # get all bug information r = self.session.get(siUrl) soup = BeautifulSoup(r.text, 'lxml') bugNumLst = list() for issue in soup.find_all('tr', {'class': 'issue hascontextmenu'}): bugNumLst.append(issue.find('input')['value']) # enter into each bug tickets then get its information bugInfo = list() for bugNum in bugNumLst: url = self.baseUrl + r'issues/' + bugNum r = self.session.get(url) soup = BeautifulSoup(r.text, 'lxml') # bug title bugTtl = soup.find('div', {'class': 'subject'}).find('h3').text # bug status bugSts = soup.find('div', {'class': 'status attribute'}).find('div', {'class': 'value'}).text # bug processor bugPrssr = soup.find('div', {'class': 'assigned-to attribute'}).find('a', {'class': 'user active'}).text # bug process start time bugStrt = soup.find('div', {'class': 'start-date attribute'}).find('div', {'class': 'value'}).text # bug progress bugPrgrss = soup.find('div', {'class': 'progress attribute'}).find('p', {'class': 'percent'}).text bugInfo.append((bugNum, bugTtl, bugSts, bugPrssr, bugStrt, bugPrgrss)) return bugInfo def StoreData(self, *kargs): with open('tmp.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow([r'Redmine票号', r'问题标题', r'问题状态', r'问题处理人', r'开始时间', r'处理进度']) for bugItem in kargs: writer.writerows([bugItem])
29709da9810960be622b0779293b0b1555a42448
[ "Python", "INI" ]
5
INI
HelloDarkLotus/ProjectIntegration
3bd2b89d1b6e7cd78b6978cc2a819d305f6178e4
339ecb587fdc9560c57e69e95a10039009534803
refs/heads/main
<file_sep> from rest_framework import generics, filters from rest_framework.permissions import IsAuthenticated from django_filters.rest_framework import DjangoFilterBackend from product.models import Product from product.serializers import ProductSerializer from .filter import ProductFilter class ListCategoryView(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (DjangoFilterBackend,) filterset_class = ProductFilter permission_classes = [IsAuthenticated] class DynamicSearchFilter(filters.SearchFilter): def get_search_fields(self, view, request): return request.GET.getlist('search_fields', []) class SearchView(generics.ListCreateAPIView): filter_backends = (DynamicSearchFilter,) queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAuthenticated]<file_sep>from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=self.normalize_email(username), ) user.set_unusable_password() user.save(using=self._db) return user def create_superuser(self, email, username): user = self.create_user(username=username,email=email) user.is_admin = True user.set_unusable_password() user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True, blank=True, null=True, default=None) username= models.CharField(max_length=30,unique=True, blank=True, null=True) password = <PASSWORD> objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username']<file_sep>import uuid from django.utils import timezone from django.shortcuts import get_object_or_404, redirect from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework import status from .models import Order, OrderItem from .serializers import OrderSummarySerializer, CheckoutSerializer, OrderHistorySerializer from product.models import Product class OrderSummaryView(APIView): permission_classes = [IsAuthenticated] def get(self, request): queryset = Order.objects.get(user=request.user, ordered=False) serializer = OrderSummarySerializer(queryset) return Response(serializer.data) class CartView(APIView): permission_classes = [IsAuthenticated] def post(self, request): pk = request.data.get('item_id', '') item = get_object_or_404(Product, pk=pk) order = Order.objects.filter(user=request.user, ordered=False).first() order_id = order.order_item.order_id if order != None else str(uuid.uuid4()) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, order_id=order_id ) if order != None: if order.items.filter(item__pk=item.pk, order_id=order_id).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date, order_item=order_item) order.items.add(order_item) return redirect("order_summary") class CheckoutView(APIView): permission_classes = [IsAuthenticated] def post(self, request): order = get_object_or_404(Order,user=request.user, ordered=False) order.ordered = True order.save() serializer = CheckoutSerializer(order) response = {'message': 'Success checkout order'} response.update(serializer.data) return Response(response,status=status.HTTP_200_OK) class OrderHistoryView(APIView): def get(self,request): queryset = Order.objects.all().filter(user=request.user, ordered=True) serializer = OrderHistorySerializer(queryset,many=True) return Response(serializer.data)<file_sep>from django.urls import path from .views import HelloView, get_tokens from rest_framework_simplejwt.views import TokenRefreshView urlpatterns = [ path('',HelloView.as_view(), name='hello-view'), path('api/token/', get_tokens, name='token-pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ]<file_sep>from django.db import models class Product(models.Model): name = models.CharField(max_length=100) year = models.CharField(max_length=5) category = models.CharField(max_length=50) def __str__(self): return self.name <file_sep>from django.urls import path from .views import CartView, OrderSummaryView, CheckoutView, OrderHistoryView urlpatterns = [ path('api/v1/addtocart/', CartView.as_view() , name='add_cart'), path('api/v1/ordersummary/', OrderSummaryView.as_view(), name='order_summary'), path('api/v1/checkout/', CheckoutView.as_view(), name='order_checkout'), path('api/v1/orderhistory/', OrderHistoryView.as_view(), name='order_history'), ]<file_sep>from rest_framework import generics from rest_framework.permissions import IsAuthenticated from .serializers import ProductSerializer from .models import Product class ProductListView(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAuthenticated]<file_sep># Generated by Django 3.2.4 on 2021-06-28 17:54 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MyUser', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('email', models.EmailField(blank=True, default=None, max_length=60, null=True, unique=True, verbose_name='email')), ('username', models.CharField(blank=True, max_length=30, null=True, unique=True)), ], options={ 'abstract': False, }, ), ] <file_sep>from django.urls import path from .views import SearchView, ListCategoryView urlpatterns = [ path('api/v1/search', SearchView.as_view(), name='search'), path('api/v1/list', ListCategoryView.as_view(), name='list-view'), ]<file_sep>from django.contrib.auth.backends import BaseBackend from .models import MyUser class AuthenticationWithoutPassword(BaseBackend): def authenticate(self, request, username=None, email=None): if username is None: username = request.data.get('username', '') email = request.data.get('email', '') try: return MyUser.objects.get(username=username, email=email) except MyUser.DoesNotExist: return None def get_user(self, user_id): try: return MyUser.objects.get(pk=user_id) except MyUser.DoesNotExist: return None<file_sep>from django.contrib.auth import authenticate from django.conf import settings from rest_framework.response import Response from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.decorators import api_view, permission_classes from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.views import APIView @permission_classes([IsAuthenticated]) class HelloView(APIView): def get(self, request): content = {'message': 'Hello, world'} return Response(content) @api_view(['POST']) @permission_classes([AllowAny]) def get_tokens(request): username = request.data.get("username") email = request.data.get("email") user = authenticate(username=username, email=email) if user is not None: refresh_token = RefreshToken.for_user(user) return Response({ 'status': True, 'message': 'Authenticate successful', 'refresh': str(refresh_token), 'access': str(refresh_token.access_token), }) else: return Response({ 'message': 'Authenticate unsuccessful', 'status': False }) <file_sep>from rest_framework import serializers from .models import Order, OrderItem class OrderItemSerializer(serializers.ModelSerializer): item_name = serializers.CharField(source='item.name') year = serializers.CharField(source='item.year') class Meta: model = OrderItem fields = ['item_name','year','quantity'] class OrderSummarySerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) username = serializers.CharField(source='user.username') class Meta: model = Order fields = ('pk','username', 'items', 'ordered','ordered_date') class CheckoutSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) email = serializers.CharField(source='user.email') class Meta: model = Order fields = ('pk','email', 'items', 'ordered','ordered_date') def get_message(self, obj): return 'Success checkout order' class OrderHistorySerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') class Meta: model = Order fields = ('username','email','items','start_date','ordered_date','ordered')<file_sep># GameAPI Bilgisayar oyunları satan temel e-ticaret işlemlerini yapan bir REST-API **Dependencies:** Python 3.8.3, Pip, Virtualenv ### Create virtual environment ```sh git clone https://github.com/mertbilgic/GameAPI.git cd gameapi virtualenv venv ``` ### Install depedencies ```sh $ source venv/bin/activate $ pip install -r requirements.txt ``` ### Start ```sh $ python manage.py runserver ``` ##### Authentication API'ımıza ait end-point'leri kullanabilmek için authentication işlemi yapılmalıdır. Üç adet ön tanımlı kullanımız bulunmaktadır. User One | <EMAIL> User Two | <EMAIL> User Three | <EMAIL> Acces ve refresh token'a erişime için aşağıdaki komutu çalıştırınız. ```sh # POST /api/token/ curl -X POST 'http://127.0.0.1:8000/api/token/' \ -H 'Content-Type: application/json' \ -d '{ "username":"User One", "email":"<EMAIL>" }' ``` ##### Hello World API'ımızı token ile test ederek başlayalım.Root-endpoint'imize istek atabilmek için daha önce aldığımız token'a ihtiyacımız bulunmaktadır. Terminali açalım ve aşağıdaki komutu girelim. ```sh # GET / curl -X GET 'http://127.0.0.1:8000/' \ -H 'Authorization: Bearer **TOKEN**' {"message":"Hello, world"} ``` ##### Search Search işlemi büyük/küçük harf duyarlı değildir.Anahtar kelimeyi içeren sonuçları kullanıcıya döner. Kullanıcı bir oyun aramak istediğinde aşağıdaki şekilde bir istekte bulanabilir. Örneğin bir oyunu name özelliği ile aranmak isterse search_fields=name şeklinde, aradığı keyword'ü ise search=One şeklinde belirtilmelidir.Benzeri arama işlemleri category ve year özellikleri içinde yapılabilir. ```sh # GET api/search curl -X GET 'http://127.0.0.1:8000/api/v1/search?search=One&search_fields=name' \ -H 'Authorization: Bearer **TOKEN**' [ { "name":"One on One", "year":"1984", "category":"Basketbol" } ] ``` #### List Listeleme özelliği sadece category özelliğini desteklemektedir.Kullanıcı bir kategoriye ait bilgileri listelemek isterse category=futbol şeklinde query string eklemelidir.Belirtilen keyword büyük/küçük harf duyarlı değildir kullanıcı kategori ismini tam vermesi beklenir. ```sh # GET api/list curl -X GET 'http://127.0.0.1:8000/api/v1/list?category=futbol' \ -H 'Authorization: Bearer **TOKEN**' [ { "name": "<NAME>", "year": "1990", "category": "Futbol" }, { "name": "<NAME> International Soccer", "year": "1988", "category": "Futbol" } ] ``` #### Add To Cart Kullanıcı sepete ürün eklemek için almak istediği item id isi belirtip ürünü sepete ekleyebilir. ```sh # POST /api/v1/addtocart/ curl -X POST 'http://127.0.0.1:8000/api/v1/addtocart/' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer **TOKEN**' \ --data-raw '{ "item_id" : 5 }' { "pk": 16, "username": "User Three", "items": [ { "item_name": "One on One", "year": "1984", "quantity": 2 } ], "ordered": false, "ordered_date": "2021-06-29T20:20:21.726564Z" } ``` #### Checkout Kullanıcı siparişini checkout etmek istediğinde aşağıdaki gibi /api/v1/checkout end-point'ine istek atmalıdır. ```sh # GET /api/v1/checkout/ curl -X POST 'http://127.0.0.1:8000/api/v1/checkout/' \ -H 'Authorization: Bearer **TOKEN**' { "message": "Success checkout order", "pk": 17, "email": "<EMAIL>", "items": [ { "item_name": "One on One", "year": "1984", "quantity": 2 } ], "ordered": true, "ordered_date": "2021-06-29T20:49:32.218503Z" } ``` #### Order History Kullanıcıya ait eski siparişlerin listelenmesi için /api/v1/orderhistory/ end-point'ine istek atmalıdır. ```sh # POST /api/v1/orderhistory/ curl -X GET 'http://127.0.0.1:8000/api/v1/orderhistory/' \ -H 'Authorization: Bearer **TOKEN**' [ { "username": "User Three", "email": "<EMAIL>", "items": [ { "item_name": "One on One", "year": "1984", "quantity": 13 } ], "start_date": "2021-06-29T20:20:21.727272Z", "ordered_date": "2021-06-29T20:20:21.726564Z", "ordered": true }, { "username": "User Three", "email": "<EMAIL>", "items": [ { "item_name": "One on One", "year": "1984", "quantity": 2 } ], "start_date": "2021-06-29T20:49:32.219573Z", "ordered_date": "2021-06-29T20:49:32.218503Z", "ordered": true } ] ``` #### Product List Tüm ürünleri listelemek için /api/v1/productlist/ end-point'ine istek atmalıdır. ```sh # GET /api/v1/productlist/ curl -X GET 'http://127.0.0.1:8000/api/v1/productlist/' \ -H 'Authorization: Bearer **TOKEN**' [ { "name": "Kick Off II", "year": "1990", "category": "Futbol" }, { "name": "<NAME> International Soccer", "year": "1988", "category": "Futbol" }, ... ... ``` #### Refresh Token Access token refresh edilmek istendiğinde aşağıdaki komut kullanılabilir ```sh # GET /api/v1/productlist/ curl -X POST 'http://127.0.0.1:8000/api/token/refresh/' \ -H 'Content-Type: application/json' \ -d '{ "refresh":"<KEY> }' { "access": "<KEY>" } ```<file_sep>from django.db import models from django.conf import settings from product.models import Product class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) order_id = models.CharField(max_length=36) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.order_id}-{self.quantity}-{self.item.item_name}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() order_item = models.ForeignKey(OrderItem,on_delete=models.CASCADE,related_name='%(class)s_oder_id') ordered = models.BooleanField(default=False) def __str__(self): return self.user.username <file_sep>from django.urls import path from .views import ProductListView urlpatterns = [ path('api/v1/productlist/',ProductListView.as_view(), name='product-view'), ]
47f2278c3bd99f4c7982cca45d8acb382a7f71d4
[ "Markdown", "Python" ]
15
Python
mertbilgic/GameAPI
5cafeccedc56c04b94d59a42100f6275293c1a63
9bc83fb5d59299f05d090b1998cbc26951344b0c
refs/heads/master
<repo_name>MAD11877/mad21-practical-1---java-TeoWeiHao<file_sep>/Question4.java import java.util.Scanner; public class Question4 { public static void main(String[] args) { /** * Prints a right angle triangle with *. The base of the triangle depends on the integer given. * e.g. * > 5 * ***** * **** * *** * ** * * * * Hint: 2 loops are required. System.out.print(...) to print on single line. */ Scanner in = new Scanner(System.in); int x = in.nextInt(); for(int i = x; i > 0;i--){ String y = ""; for(int j = 0; j < i;j++){ y += "*"; } System.out.println(y); } } }
b7cf785b37566feeb96a616e03d1be3746d6b3d9
[ "Java" ]
1
Java
MAD11877/mad21-practical-1---java-TeoWeiHao
1f5a2b2b515e96da52e78e947aa072ff39a993d3
da2e71f2636d2e032c8239e04edd25153d3a9028
refs/heads/main
<file_sep>package com.sofka.app; import java.util.Scanner; public class Menu { Scanner s = new Scanner(System.in); public void crear() { System.out.println("1. para sumar"); System.out.println("2. para restar"); System.out.println("3. para multiplicar"); System.out.println("4. para dividir"); System.out.print("Ingrese la opcion del menu: "); int opcion = s.nextInt(); System.out.println("Ingrese numero 1"); int num1 = s.nextInt(); System.out.println("Ingrese numero 2"); int num2 = s.nextInt(); do { switch (opcion) { case 1: System.out.println(Operaciones.suma(num1, num2)); break; case 2: break; case 3: break; case 4: break; } }while (opcion>4 || opcion < 1); } }
94fe014360e7ab7dc6a8e2b3ca3abf09b9f6e064
[ "Java" ]
1
Java
Andres0x90/pull-request
ad9660367c12fb1c3747b4f8147118dfb8a9c97c
790c6f63671f6e9d1d5db4298edbd6d7507791e1
refs/heads/main
<file_sep>Adott egy input mappa, amiben van valamennyi txt fájl. Írjunk Node.js-ben egy olyan programot, ami az ebben a mappában lévő fájlok tartalmát beolvassa, majd összefűzi egy output fájlba. A megvalósításunk három féle legyen: - Callback-es - Promise-os - Async/await-es <file_sep>"use strict"; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable("Genres", { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER, }, name: { type: Sequelize.STRING, // A név nem lehet null érték (mindenképp legyen név) allowNull: false, // Egy név csak egyszer lehet a műfaj táblában unique: true, }, description: { type: Sequelize.STRING, }, createdAt: { allowNull: false, type: Sequelize.DATE, }, updatedAt: { allowNull: false, type: Sequelize.DATE, }, }); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable("Genres"); }, }; <file_sep># Csütörtök 19:30 - 21:00 #3-as és #4-es számú estis gyakorlat, összevonva<file_sep>module.exports = (io) => { io.on("connection", (socket) => { // console.log("Client connected"); // console.log(socket); // fv: paraméterek, ack - nyugtázás socket.on("test", (data, ack) => { console.log(data, ack); socket.emit("client-test", "szerverrol erkezett adat"); ack({ status: "OK" }) }) }) }<file_sep>const models = require("./models"); // index.js const { User, Genre, Movie, Rating, sequelize } = models; const faker = require("faker"); const { Op } = require("sequelize"); // Self-Invoke Function (async () => { /*const user = await User.create({ name: faker.name.findName(), email: faker.internet.email(), password: '<PASSWORD>', isAdmin: false, }); const genresCount = faker.datatype.number({ min: 5, max: 10 }); const genres = []; for (let i = 1; i <= genresCount; i++) { genres.push( await Genre.create({ name: faker.lorem.word(), description: faker.lorem.sentence(), }) ) } //console.log(user); const movie = await Movie.create({ title: faker.lorem.words(faker.datatype.number({ min: 1, max: 6 })), director: faker.name.findName(), description: faker.lorem.sentence(), year: faker.datatype.number({ min: 1870, max: new Date().getFullYear() }), length: faker.datatype.number({ min: 60*60, max: 60*60*3 }), imageUrl: faker.image.imageUrl(), ratingsEnabled: true //faker.datatype.boolean(), }); await movie.setGenres(faker.random.arrayElements(genres)); const rating = await Rating.create({ rating: faker.datatype.number({ min: 1, max: 5 }), comment: faker.datatype.boolean() ? faker.lorem.sentence() : '', UserId: user.id, MovieId: movie.id, }); //console.log(await rating.getMovie()); //console.log(await rating.getUser()); console.log(await movie.getRatings()); //console.log(genres.length, await movie.countGenres()); ^ Ebből seedert csináltunk */ // Összes film lekérése //console.log(await Movie.findAll()); // Filmek megszámolása //console.log(await Movie.count()); // Egy adott film lekérése, ID alapján //console.log(await Movie.findByPk(1)); //console.log(await Movie.findByPk(11111)); // null //console.log(await Movie.findOne({ where: { id: 1 } })); // Azon filmek lekérése, ahol az év nagyobb, mint 1950 /*console.log(await Movie.findAll({ where: { year: { [Op.gt]: 1950, } } }));*/ //await (await Movie.findByPk(1)).removeGenre(3); //console.log(await (await Movie.findByPk(1)).countGenres()); /*const m1 = await Movie.findByPk(1); console.log( (await m1.getGenres({ attributes: ['id'], joinTableAttributes: [], })).map(genre => genre.toJSON()) );*/ // Filmek lekérése a műfajokkal /*console.log( ( await Movie.findByPk(1, { include: [{ model: Genre, as: 'Genres', //attributes: ['id', 'name', 'description'], // csak ezeket szeretném attributes: { exclude: [ 'createdAt', 'updatedAt' ]}, // csak ezeket nem szeretném through: { attributes: [] }, }] }) ).toJSON() );*/ // Film lekérése, benne az értékelések átlagával /*console.log( ( await Movie.findByPk(1, { // Plusz mezők a meglévők mellé attributes: { include: [ [sequelize.fn('AVG', sequelize.col('Ratings.rating')), 'avgRating'] ] }, // Kapcsolódó modellek include: [ { model: Genre, as: 'Genres', //attributes: ['id', 'name', 'description'], // csak ezeket szeretném attributes: { exclude: [ 'createdAt', 'updatedAt' ]}, // csak ezeket nem szeretném through: { attributes: [] }, }, { model: Rating, attributes: [], } ] }) ).toJSON() );*/ /*console.log( ( await Movie.findAll({ // Plusz mezők a meglévők mellé attributes: { include: [ [sequelize.fn('AVG', sequelize.col('Ratings.rating')), 'avgRating'], // ÓÓ:PP:MP [sequelize.fn('TIME', sequelize.col('length'), "unixepoch"), 'lengthFormatted'] ] }, // Kapcsolódó modellek include: [ { model: Genre, as: 'Genres', //attributes: ['id', 'name', 'description'], // csak ezeket szeretném attributes: { exclude: [ 'createdAt', 'updatedAt' ]}, // csak ezeket nem szeretném through: { attributes: [] }, }, { model: Rating, attributes: [], } ], group: ["movie.id", "Genres.id"], order: sequelize.literal('avgRating DESC'), }) ).map(movie => movie.toJSON()) );*/ // A megadott jelszó tartozik-e az adott felhasználóhoz console.log((await User.findByPk(1)).comparePassword("<PASSWORD>")); // Felhasználó JSON-be konvertálása, tipiukusan, ha valamilyen válaszban // adjuk vissza a felhasználót, és ilyenkor nyilván nem lenne kedvező viselkedés, // ha a jelszót is elküldenénk, még akkor sem, ha hash-elve van console.log((await User.findByPk(1)).toJSON()); })(); <file_sep>require("dotenv").config(); const express = require("express"); require("express-async-errors"); const { StatusCodes, ReasonPhrases } = require("http-status-codes"); const fs = require("fs").promises; const date = require("date-and-time"); const AutoTester = require("./test/inject"); // Express app létrehozása const app = express(); // Middleware, ami parse-olja a JSON adatokat a request body-ból app.use(express.json()); // Routerek importálása const exampleRouter = require("./routers/example"); // ... // Routerek bind-olása adott végpontokhoz app.use("/example", exampleRouter); app.use("/games", require("./routers/games")); app.use("/genres", require("./routers/genres")); // Ide vedd fel a további routereket/végpontokat: // ... // Végső middleware a default error handler felülírásához, így az nem // HTML kimenetet fog adni, hanem JSON objektumot, továbbá egy log fájlba // is beleírja a hibákat. app.use(async (err, req, res, next) => { if (res.headersSent) { return next(err); } await fs.appendFile( "error.log", [`[${date.format(new Date(), "YYYY. MM. DD. HH:mm:ss")}]`, err.stack].join("\n") + "\n\n" ); return res.status(StatusCodes.INTERNAL_SERVER_ERROR).send({ httpStatus: ReasonPhrases.INTERNAL_SERVER_ERROR, errorDetails: { name: err.name, message: err.message, stack: [...err.stack.split("\n")], }, }); }); // App indítása a megadott porton (async () => { const port = process.env.PORT || 4000; app.listen(port, () => { console.log(`Az Express app fut, ezen a porton: ${port}`); // FONTOS! Erre szükség van, hogy az automata tesztelő megfelelően tudjon inicializálni! // Ehhez a sorhoz ne nyúlj a munkád közben: hagyd legalul, ne vedd ki, ne kommenteld ki, // különben elrontod az automata tesztelő működését! AutoTester.handleStart(); }); })(); <file_sep>// ilyenkor, ha csak a mappát adjuk meg, akkor az index.js-t fogja behúzni const models = require("./models"); const { User, Genre, Movie, Rating, sequelize } = models; const faker = require("faker"); const { Op } = require("sequelize"); // Self-invoke function (async () => { /*const genresCount = faker.datatype.number({ min: 5, max: 10 }); const genres = []; for (let i = 1; i < genresCount; i++) { genres.push( await Genre.create({ name: faker.lorem.word(), description: faker.lorem.sentence(), }) ); } const user = await User.create({ name: faker.name.findName(), email: faker.internet.email(), password: '<PASSWORD>', isAdmin: false, }); //console.log(user); const movie = await Movie.create({ title: faker.lorem.words(faker.datatype.number({ min: 1, max: 6})), director: faker.name.findName(), description: faker.lorem.sentence(), year: faker.datatype.number({ min: 1870, max: new Date().getFullYear() }), length: faker.datatype.number({ min: 60*60, max: 60*60*4 }), imageUrl: faker.image.imageUrl(), ratingsEnabled: true, }); await Rating.create({ rating: faker.datatype.number({ min: 1, max: 5}), comment: faker.datatype.boolean() ? faker.lorem.sentence() : '', UserId: user.id, MovieId: movie.id, }); console.log(await movie.getRatings()); await movie.setGenres(genres); console.log(await movie.countGenres());*/ // Összes film lekérése //console.log(await Movie.findAll()); // Filmek megszámolása //console.log(await Movie.count()); // Egy adott film lekérése //console.log(await Movie.findByPk(1)); // primary key //console.log(await Movie.findByPk(11111)); // null // Adott mezők lekérése csak /*console.log( (await Movie.findAll({ attributes: ['id', 'title'] })).map(movie => movie.toJSON()) );*/ // Bizonyos mezők kizárása /*console.log( (await Movie.findAll({ //attributes: ['id', 'title'] attributes: { exclude: ['createdAt', 'updatedAt'] } })).map(movie => movie.toJSON()) );*/ // Mező lekérése más néven /*console.log(await Movie.findAll({ attributes: ['id', ['title', 'cim']] }));*/ // Olyan filmek, amik 1950 után készültek /*console.log(await Movie.findAll({ where: { year: { [Op.gt]: 1950, } } }));*/ // Egy valamilyen rekord megkeresése valamilyen feltétel alapján /*console.log(await Movie.findOne({ where: { id: 2, } }));*/ /*console.log( (await (await Movie.findByPk(1)).getGenres({ attributes: { exclude: ['createdAt', 'updatedAt'] }, joinTableAttributes: [] })).map(genre => genre.toJSON()) );*/ /*console.log( JSON.stringify((await Movie.findAll({ attributes: { include: [ [sequelize.fn('AVG', sequelize.col('Ratings.rating')), 'avgRating'] ], }, include: [ { model: Genre, attributes: { exclude: ['createdAt', 'updatedAt'] }, through: { attributes: [] } }, { model: Rating, attributes: [], //attributes: { // exclude: ['createdAt', 'updatedAt'] //}, } ], group: ['movie.id', 'Genres.id'], order: sequelize.literal('avgRating DESC'), })).slice(0,3), null, 4) );*/ //console.log((await User.findByPk(1)).comparePassword('<PASSWORD>')); })(); <file_sep>var isEven = require('is-even'); console.log(isEven(12)); //=> true isEven('1'); //=> false isEven(2); //=> true isEven('3'); //=> false<file_sep># Szerveroldali webprogramozás 2021 ősz - [Szerveroldali webprogramozás 2021 ősz](#szerveroldali-webprogramozás-2021-ősz) - [Ismertető](#ismertető) - [Laravel](#laravel) - [Átmenet a Webprogramozásból](#átmenet-a-webprogramozásból) - [Szükséges programok](#szükséges-programok) - [Automatikus telepítő](#automatikus-telepítő) - [A Laravel](#a-laravel) - [Új Laravel projekt létrehozása](#új-laravel-projekt-létrehozása) - [A projekt első indítása](#a-projekt-első-indítása) - [Egy Laravel projekt felépítése](#egy-laravel-projekt-felépítése) - [Laravel Dokumentáció](#laravel-dokumentáció) - [Node.js, Express.js](#nodejs-expressjs) - [Szükséges programok](#szükséges-programok-1) - [Node.js](#nodejs) - [npm](#npm) - [Új projekt létrehozása](#új-projekt-létrehozása) - [npm csomagok telepítése](#npm-csomagok-telepítése) - [Egy alap Node.js program](#egy-alap-nodejs-program) - [Próbáljuk ki](#próbáljuk-ki) - [Hogy működik?](#hogy-működik) - [Mi ezzel a "probléma"?](#mi-ezzel-a-probléma) - [Express](#express) - [Express telepítése a projekthez](#express-telepítése-a-projekthez) - [Nodemon telepítése a projekthez](#nodemon-telepítése-a-projekthez) - [Az első Express alkalmazás](#az-első-express-alkalmazás) - [Próbáljuk ki](#próbáljuk-ki-1) - [Tulajdonképpen mi is történik itt?](#tulajdonképpen-mi-is-történik-itt) - [Miért jó ez nekünk?](#miért-jó-ez-nekünk) ## Ismertető Ebben a GitHub repository-ban találhatók a 2021 őszi félévben tartott Szerveroldali webprogramozás tárgyhoz tartozó gyakorlati anyagok és az egyéb segédanyagok is. A repository szerkezete: - csut_16_00: - Csütörtök 16:00-kor kezdődő nappalis csoporthoz tartozó anyagok - csut_19_30: - Csütörtök 19:30-kor kezdődő összevont estis csoportokhoz tartozó anyagok - Ami a fenti két mappán kívül van, azok pedig közös fájlok A tárgy követelményei és az oktatók elérhetőségei a Canvas-ben találhatók. ## Laravel Hasznos információk a Laravellel kapcsolatban. ### Átmenet a Webprogramozásból - Tegyük világossá, honnan hová tartunk. A webes vonal eddigi felépítése: - Web1 - nézet, HTML, CSS, érintőleges JS. Ezek még csak statikus oldalak - Web2 (Webprogramozás) - JS bővebben, majd natív PHP. Ezek már dinamikus oldalak. - Szerveroldali webprogramozás - csomagkezelők, keretrendszerek bevezetése, népszerű keretrendszerek alapjai. - Csomagkezelők - Nem szükséges mindent natívan megírni, hanem egy-egy részfeladat megoldására használhatunk csomagot, ami már tartalmazza azt a logikát, amire szükségünk van - Előnyei: - nem kell olyan dolgot lefejleszteni, ami már tulajdonképpen kész van és ingyenesen hozzáférhető - valószínűleg (főleg ha népszerűbb csomagról van szó), jobban ki van dolgozva, előjöttek már időközben problémák, amik meg lettek oldva <-> ezzel szemben mi lehet nem foglalkoznánk ezzel ennyit, főleg egy nagyobb projekt részeként, ami hibalehetőség lenne - kisebb a kódbázis, hiszen nálunk csak egy projektleíró fájl van, ami megmondja, melyik csomagból melyik verzió szükséges, ez alapján pedig a csomagkezelő egy távoli szerverről letölti a megfelelő fájlokat - A félév során két csomagkezelőt fogunk használni, az egyik a Composer, a másik az npm - Hasonló elven működnek - A Laravelben mindkettő megtalálható - Meg szokták kérdezni, hogy miért kellett akkor a natív PHP, miért nem lehetett rögtön csomagkezelőt használni? Szükséges bejárni az utat, hogy az ember értse az alapokat, ami a csomagok mögött is húzódik. Meg így jobban is értékeli a csomagokat :) ### Szükséges programok - A Laravel futtatásához szükséges a legfrisebb PHP, ill. Composer telepítése. Ezt Windows rendszeren elvégzi helyetted az automatikus telepítő. #### Automatikus telepítő - [https://github.com/totadavid95/PhpComposerInstaller](https://github.com/totadavid95/PhpComposerInstaller) - Csak le kell tölteni a jobb oldalon lévő [Releases-ből](https://github.com/totadavid95/PhpComposerInstaller/releases), majd futtatni az exe fájlt - Lehet, hogy a Smart Screen nem engedi elsőre futtatni (Run anyway lehetőséget kell választani), illetve a víruskeresők (tipikusan az AVG és az Avast) hibás működést idézhetnek elő, így ezeket érdemes a telepítés idejére kikapcsolni ### A Laravel A Laravel egy PHP MVC keretrendszer, azaz a kód strukurálására a Modell-Nézet-Vezérlő mintát ajánlja. Ebben a **modell** felelős az adatok tárolásáért és felületfüggetlen feldolgozásáért, a **nézet** az adatok megjelenítéséért, azaz a mi esetünkben a HTML előállításáért, és a **vezérlő** az, ami fogadja a HTTP kérést, beolvassa az adatokat, meghívja a Modellréteg feldolgozó függvényeit, majd ezek eredményét a kiírja a nézet meghívásával. A legtöbb MVC-s keretrendszernek központi eleme még a **routing**, amely során egy URL, egy végpontot a megfelelő vezérlőlogikához rendelünk. Egy egyszerű HTML oldal megjelenítéséhez nem kell adat, viszont végpont alatt jelennek az oldalak, azaz kell bele routing, ami egy vezérlőmetódushoz irányítja a végrehajtást, ami egyszerűen megjeleníti a nézetet, ami a HTML-ünket tartalmazza. Azaz ezt az egyszerű kis dolog elvégézéséhez rögtön három komponens kell: - routing - controller - view ### Új Laravel projekt létrehozása - Ajánlott rendszergazdai parancssorral dolgozni - Hozzunk létre egy új Laraveles projektet, az alábbi parancs segítségével: ```shell composer create-project --prefer-dist laravel/laravel PROJEKT NEVE ``` - Ez a megadott projektnévvel létre fog hozni egy könyvtárat (ott, ahol kiadtuk a parancsot), majd a távoli szerverről letölti a Laravelhez tartozó Composeres csomagokat, végül inicializálja a projektet (autoload, stb.) - A folyamat időigényes, és függ a hálózati viszonyoktól, illetve a munkaállomás konfigurációjától, pl. hogy SSD vagy HDD van-e, stb. ### A projekt első indítása - Nyissunk egy terminált / parancssort a projekt mappájában - Indítsuk el a projektet, erre két lehetőség is van: - `php artisan serve` - A port állítható így: `php artisan serve --port=8080` - `php -S 127.0.0.10:80 -t public/` - Ekkor ezt az IP-t hozzá is rendelhetjük egy domain-hez a host fájlban, pl. `127.0.0.10 szerveroldali.dev` - Ezt követően nyissuk meg a projektet a böngészőben: - `php artisan serve` esetén [http://localhost:8000](http://localhost:8000) - a másik lehetőségnél, ha van beállítva hosts fájl, akkor [http://szerveroldali.dev](http://szerveroldali.dev), ha pedig nincs, akkor a natív IP-t kell megadni: [http://127.0.0.10](http://127.0.0.10) - A második módszer előnye az `artisan serve` paranccsal szemben, hogy működik a gyorsítótárazás, ezért gyorsabb, illetve beszédesebb a domainnév is, valamint lehet játszani, hogy a vége 127.0.0.10, 11, 12, stb. legyen, így a különböző projektekhez lehet rendelni egyedi domainneveket. ### Egy Laravel projekt felépítése - Első ránézésre a Laravel projektszerkezete egyáltalán nem egyértelmű olyan embereknek, akik először látják azt. Erre igazán csak gyakorlati úton lehet ráérezni. - Nagyon nagy vonalakban a projekt szerkezete a következő: - **app**: - Gyakorlatilag az alkalmazás kódjának a magját tartalmazza - A félév során megkerülhetetlen lesz, fontos taglalni az almappákat is: - **app/Models**: - létre fogunk hozni modelleket, ezek ebben a mappában találhatók - **app/Http** - Tartalmazza a controllereket, middleware-ket, és a formokhoz tartozó request-eket - Mondhatni itt dolgozzuk fel szinte az összes kérést, ami az alkalmazáshoz érkezik a kliensektől - **app/Http/Controllers** - Különböző vezérlőlogikák, amiket hozzá tudunk rendelni az egyes végpontokhoz - **app/Http/Middleware** - A middleware fogalma gyakran elő fog jönni a félévben (a Node.js-nél is) - Amikor bejön egy kérés, middleware-k sora hajtódik végre, tehát ez úgymond egy köztes logika. - Például: - megvan a middleware-k sorrendje, ha bejön egy kérés, azt a web middleware veszi át, majd utána hajtódik végre a végpont mögött rejlő vezérlési logika. Azonban ha beállítunk egy autentikációt, akkor a web middleware után egy auth middleware hajtódik végre. Itt pedig ha nem sikerül a hitelesítés, akkor pl. átirányítja a felhasználót a login oldalra, nem pedig a végponthoz tartozó vezérlés következik. - [web mw] -> [auth mw] -> [kiszolgálás] - **app/Http/Requests** - Amikor form-okat (űrlapokat) küld el a felhasználó, akkor létre lehet hozni ilyen request objektumokat, amik egy-egy ilyen form logikáját le tudják kezelni. Ezek találhatók itt. - **bootstrap** - Ez a félév során számunkra érdektelen, ha bele is kell valaha nyúlni, akkor azt csak indokolt esetben és körültekintően érdemes megtenni. - Itt található az app.php fájl, ami kvázi "felállítja" (bootstrap-eli, bár erre nincs nagyon egyszavas értelmes magyar fordítás) az alkalmazást, illetve a gyorsítótárazás is itt van kezelve, ami arra szolgál, hogy segítsen optimalizálni a teljesítményt - **config** - Elég egyértelmű a neve alapján, és pontosan arra is való, amit az ember sejtene mögötte: itt van az alkalmazás konfigurációja - Elég érthetően kategóriákra van bontva a fájlok szerint, minimális szinten bele fogunk nézni a félév során - **database** - Ennek is egyértelmű a neve, az adatbázissal kapcsolatos dolgokat tartalmazza - Három almappát tartalmaz, mindegyik aktívan kelleni fog majd a félév során: - **migrations**: - itt írjuk le az adatbázis szerkezetét, fontos, hogy a fájlok neve előtt van egy timestamp (időbélyeg), a Laravel eszerint rendezi sorba őket - felfogható az adatbázis szerkezethez tartozó "verziókezelésként" is - **factories**: - modell"gyárak", egy megadott logika szerint generálhatunk modelleket - **seeders**: - A seeder arra való, hogy feltöltse az adatbázist adatokkal - A migration-ök, factory-k és a seederek egymásra épülnek, hiszen az adatbázis szerkezetét, a táblákat, kapcsolatokat a migration-ök adják meg, az egyes adatokat a factory-k, a factory-k által generált modelleket pedig a seederben tudjuk egy meghatározott logika szerint feltölteni - **public** - Itt található az index.php, ami az összes bejövő kérés belépési pontja, valamint meghatározza az alkalmazás autoload-ját - Ezen felül itt találhatók az "asset-ek": képek, JS és CSS fájlok - ha npm-et használunk és pl npm segítségével töltjük le a Bootstrap-et, a Laravel Mix build kimenetei is ide kerülnek tipikusan JS és CSS fájlok formájában - Ha egy hostingra töltjük fel az appot, ezt a mappát kell az úgynevezett _www_ vagy _public_html_ mappába tenni, és az alkalmazás többi részét egy szinttel feljebb - **resources** - Ez is egy fontos mappa lesz a félév során, már rögtön a legelején - Ez tartalmazza a css és js fájlok "natív" verzióit (a public mappába ezeknek a build-je kerül általában), a nyelvi fájlokat (lang), valamint a **view-okat** (az MVC logikából a V), ezekben fogjuk létrehozni a Blade template-ket - A későbbiekben nézünk példát a lang magyarosítására is - **routes** - Meghatározza az összes útvonalat, ami az alkalmazáshoz tartozik - Nekünk alapvetően ebből csak a **web.php** az, ami fontos lesz - De tulajdonképpen mik is vannak itt: - **web.php** - A `RouteServiceProvider`-re épül, ami biztosít session-t (munkamenetet), CSRF védelmet (OWASP top 10-ben is benne van, és EA anyag is lesz), valamint cookie titkosítást is - Ha az alkalmazás nem használ állapotmentes (stateless) RESTful API-t (márpedig a mienk nem fog a félévben), akkor kb. ezzel a fájllal le is fedtük az összes route-ot. - **api.php**: - Szintén a `RouteServiceProvider`-re épül, viszont ezek stateless (állapotmentes) útvonalak, ezért tokennel kell hitelesíteni őket. Ezt a fájlt kell(ene) használni, ha REST API-t készítünk és ahhoz veszünk fel route-okat, viszont azt mi a félév második felében nem Laravellel, hanem Express JS-el fogunk csinálni, Node.js környezetben. - **console.php** - Gyakorlatilag artisan parancsokat lehet felvenni, pl. `php artisan valami`, nem fogunk ilyet csinálni a félévben. - **channels.php** - Ez akkor lényeges, ha használunk valamilyen event broadcasting-ot, gyakorlatilag ezzel lehet live chatet, játékot stb. csinálni, de nagyon nem ennek a félévnek az anyaga. - **storage** - Ez a könyvtár elég sok minden tartalmaz, de csak érintőlegesen fogunk vele foglalkozni a gyakorlatokon - Például itt vannak a naplófájlok, illetve minden olyan fájl, amit az alkalmazás hoz létre / generál ki - Alapvetően három almappára van bontva: _app, framework, logs_ (alkalmazás és framework által generált dolgok, valamint a generált naplók) - A **storage/app/public** mappát fogjuk használni, ide berakhatók a felhasználókhoz köthető fájlok (pl. egy kép, amit feltölt valamihez). Ehhez a mappához lehet készíteni egy _symlink_-et (symbolic link), hogy hozzáférhető legyen a public mappából is, erre lesz majd a `php artisan storage:link` parancs, de ezt majd később... lehet olyat is csinálni, hogy egy végpont különböző fájlműveletekkel lekérjen innen célzottan egy fájlt és azt visszaadja, és akkor nem kell symlink. Legfeljebb ha nem létezik a lekérni kívánt fájl, akkor valami default oldalra irányít, vagy 404 választ ad. - **tests** - Itt találhatóak az automatikusan futtatható unit testek, a félév során erre nem lesz idő - **vendor** - Itt találhatóak a Composeres csomagok, amiket a _Composer_ a távoli szerverről töltött le a _composer.json_ fájl alapján. - **node_modules** - Itt találhatóak az npm-es csomagok, amiket a _Node Package Manager_ (röviden _npm_) a távoli szerverről töltött le a _package.json_ fájl alapján. - Az alkalmazás gyökérmappájában található fájlokról röviden, hogy mi micsoda: - **.env**: - environment, azaz környezeti fájl, leírja, hogy az alkalmazáshoz egy adott környezetben milyen konfiguráció tartozik (pl. más a fejlesztési környezet és az a környezet ahol az alkalmazás majd ténylegesen fut, más az adatbázis kapcsolódás, stb.) - Biztonsági okokból ez nincs verziókezelve a git által (a .gitignore része) - **.env.example** - Egy jó kiindulópont, ha _.env_ fájlt akarunk csinálni, csak lemásoljuk és átnevezzük _.env_-nek, az összes basic dolog benne van, csak minimálisan kell átírni, majd egy APP_KEY-t generálni a `php artisan key:generate` paranccsal. - **composer.json**, **package.json**, illetve a lock fájlok: - Ezek leírják, hogy a Composer és az npm milyen csomagokat telepítsen, a lock fájlokat csak ehhez generálják (a lock file csak annyit csinál, hogy az adott csomag milyen verziójú alcsomagokat követel meg, és mivel generált fájl, ezért nem szabad átírni) - **.gitattributes**, **.gitignore** - Git-hez tartozó beállításokat, kizárásokat tartalmazó fájlok - **.editorconfig** - Ez egy konfigurációs fájl, ami az editoroknak (VSCode, PHPStorm, stb) ad meg különböző beállításokat, pl. egyes fájlok, fájltípusok karakterkódolását, tab-ot/space-t használjanak, stb. - **webpack.mix.js** - Ezt az npm működteti, és a Laravel Mix konfigurációját adja meg, vagyis azt, hogy milyen logika szerint generálja ki a frontend oldali asset-eket - **artisan** - Az Artisan konzolt működteti - **server.php** - Hasonló a **public/index.php**-hoz, azonban az Apache "mod_rewrite" funkcionalitását szimulálja, így ezáltal "valódi" webszerver nélkül is tesztelhető az alkalmazás, a [PHP beépített dev webszerverét](https://www.php.net/manual/en/features.commandline.webserver.php) használva - **phpunit.xml** - Fentebb már volt szó a tesztelésről, ezt a _PHPUnit_ nevű csomag látja el, ez az XML fájl pedig annak a [konfigurációját](https://phpunit.readthedocs.io/en/9.5/configuration.html) írja le - **.styleci.yml** - A _phpunit.xml_-hez hasonlóan ez is egy konfigurációs fájl, a _StyleCI_ csomaghoz ### Laravel Dokumentáció - A Laravel jól dokumentált, és a dokumentációja jól forgatható. - A Laravelnek alapvetően kétféle dokumentációja van: - egy beszédesebb, amiben a főbb dolgok és az irányvonal le van írva, és ehhez számtalan példát is mutat: - [https://laravel.com/docs](https://laravel.com/docs) - ez a link mindig a legújabb kiadásra fog átirányítani - és van egy "szárazabb" verzió is, ami leírja az összes funkció felépítését: - [https://laravel.com/api/8.x/index.html](https://laravel.com/api/8.x/index.html) - értelemszerűen a listából mindig ki kell választani az aktuálisan legfrissebb verziót ## Node.js, Express.js A félév másik nagy anyagrésze a Node.js és az ehhez kapcsolódó különböző technológiák. Ez a leírás a Node.js-be való bevezetést, illetve a REST API anyagrész alapjait mutatja be. ### Szükséges programok Az alábbi programokat be kell szerezni, ha még nincsenek feltelepítve. - Node.js: [https://nodejs.org/en/download/](https://nodejs.org/en/download/) (az LTS verziót érdemes letölteni) - Firecamp: [https://firecamp.io/download](https://firecamp.io/download) (vagy [Chrome áruházból](https://chrome.google.com/webstore/detail/firecamp-a-campsite-for-d/eajaahbjpnhghjcdaclbkeamlkepinbl) egyszerűbb telepíteni) Mindkét program elérhető Windowsra, Linuxra és macOS-re. A telepítést ellenőrizhetjük az alábbi parancsok segítségével: ```powershell node --version npm --version ``` ### Node.js Egy nyílt forráskódú szoftverrendszer, amit skálázható webes alkalmazások írására hoztak létre. Az alkalmazásokat JavaScript nyelven tudjuk elkészíteni, a rendszer pedig a háttérben a Chrome által is használt V8 JS motor segítségével futtatja őket. Eseményalapú, aszinkron I/O-t használ, így minimalizálja a túlterhelést, és maximalizálja a skálázhatóságot. ### npm A Node.js mellett feltelepül az **npm** (ami a **Node Package Manager** rövidítése). Ez egy széles körben használt csomagkezelő rendszer, amihez rengeteg könyvtár érhető el. (Lásd a csomag repository-t itt: [https://www.npmjs.com/](https://www.npmjs.com/)) #### Új projekt létrehozása Amikor az npm segítségével készítünk egy projektet, akkor a projektünk adatait, valamint a benne használt csomagokat a **package.json** fájlban írjuk le. Új projektet úgy tudunk indítani, hogy a kívánt mappában kiadjuk az alábbi parancsot: `npm init` Ekkor a rendszer bekéri a csomag adatait (nevét, leírását, stb.). Az adatok bekérését követően pedig összeállítja belőlük a package.json fájlt. #### npm csomagok telepítése Két lehetőségünk van egy npm csomag telepítésekor. 1. Globálisan telepítjük - Ilyenkor a csomagot nem kell minden egyes projektünkhöz telepíteni, hanem bárhonnan hozzájuk tudunk férni. Tipikusan a CLI alapú csomagoknál érdemes ezt a telepítést választani, pl. Nodemon, Angular CLI, stb. A telepítéshez szükséges parancs: - `npm install -g <CSOMAG NEVE>` 2. Lokálisan telepítjük - Ilyenkor csak az adott projektből férünk hozzá a csomaghoz. Tipikusan keretrendszereket vagy különböző könyvtárakat érdemes ilyen módon telepíteni. A parancs ugyanaz, mint az előbb, csak itt nem kell a **-g** kapcsoló. - `npm install <CSOMAG NEVE>` A telepített csomagokat az `npm ls` parancssal tudjuk kilistázni. #### Egy alap Node.js program Itt látható egy példa az alap Node.js alkalmazásra. Készítsünk új projektet, majd az **index.js** fájlba másoljuk be az alábbi kódot: ```javascript const http = require("http"); http .createServer(function (req, res) { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Hello World!"); }) .listen(8080); ``` Ezt követően mentsük el a fájt, és indítsuk el a programot az alábbi paranccsal: `node index.js` #### Próbáljuk ki Egy tetszőleges böngészővel nyissuk meg a következő címet: [http://localhost:8080/](http://localhost:8080/) Ekkor a betöltött oldalon meg kell, hogy jelenjen a _Hello World!_ szöveg. #### Hogy működik? Beimportáljuk a Node **http modulját** ([doksi](https://nodejs.org/dist/latest-v14.x/docs/api/http.html)), amihez utána a **http változón** keresztül hozzáférünk. A http modul **createServer** metódusával létrehozunk egy szervert, amiben van egy úgynevezett callback function, aminek van egy request és egy response paramétere (vagyis a szerver felé beérkező kérés - ez a request, és a kliensnek adott válasz - ez a response). Ez a callback function minden egyes kérés alkalmával le fog futni, aszinkron módon. Tulajdonképpen annyit csinál, hogy 200-as állapotkóddal (ami azt jelenti, hogy a kérés rendben ki lett szolgálva, lásd [http állapotkódok](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)) egy plain text típusú választ ad, majd beírja a Hello World! szöveget a válaszba és elküldi azt a kliens felé. Végpontkezelés nincs benne, tehát bármilyen végponttal is hívom meg a szervert, ugyanazt a választ fogom kapni. Ki lehet próbálni mondjuk a [http://localhost:8080/valami](http://localhost:8080/valami) címmel. #### Mi ezzel a "probléma"? Az, hogy ez egy nagyon alacsony szintű kód. Igazából ebből a példából annyira nem is érzékelhető ez a probléma, viszont gondoljunk bele, ha szeretnénk kezelni sok összetett végpontot (vagyis egy végpont kezelhet mondjuk GET és POST kéréseket is, különböző adatokat kaphat, amiket fel kell dolgozzon, az URL-ből kell kinyerjen adatot, vagy az URL-nek egy adott mintára kell illeszkednie, stb.) Érezhető, hogy ez ilyen alacsony szintű eszközökkel elég sok munka lenne... Mi pedig nem szeretnénk ennek kitenni magunkat, tehát jó lenne nekünk egy olyan eszköz, ami egy magasabb szintű api-val elfedi ezt a sok alacsony szintű kódot, és ezáltal könnyebbé, átláthatóbbá tenné számunkra a fejlesztést. **Itt jön képbe az Express**, ami jóval magasabb szintű eszközöket ad nekünk. ### Express #### Express telepítése a projekthez Ha készen áll a projektünk, akkor hozzá kell adnunk az Express-t. Ezt a projektünk mappájában az alábbi parancs kiadásával tehetjük meg: `npm install --save express` Ekkor egy távoli szerverről letölti a csomaghoz szükséges fájlokat, amik a **node_modules** mappába kerülnek. A **--save** kapcsoló helyettesíthető az **-S** kapcsolóval is, és azt mondja meg, hogy az Express-t a **package.json** fájlhoz is hozzá szeretnénk adni a csomagot. Ez azt jelenti, hogy legközelebb elég kiadnunk az `npm install` (vagy rövidebben: `npm i`) parancsot, és a **package.json** fájlban leírt adatok alapján a rendszer automatikusan fel fogja telepíteni az ide mentett csomagokat (a dependencies rész alatt vannak listázva). Létezik a **--save** mellett egy **--save-dev** nevű opció is, ez annyiban különbözik a sima save-től, hogy a fejlesztéshez szükséges függőségek közé menti el a csomagot a package.json-ben (devDependencies). Ezek az eszközök tehát a fejlesztő munkáját segítik valamilyen módon, de ahhoz nem szükségesek, hogy az alkalmazás fusson és működjön, ellentétben a save kapcsolóval telepített csomagokkal, amik azonban mindenképpen szükségesek. #### Nodemon telepítése a projekthez Könnyítsük tovább a saját dolgunkat, és telepítsük a **nodemon**-t. Ez egy fejlesztői eszköz, és arra való, hogyha módosítunk egy fájlt, akkor automatikusan újraindítja a szerverünket a háttérben, hogy a változásokat azonnal láthassuk és ne nekünk kelljen minden egyes mentés után kézzel elvégezni az újraindítást. A következő paranccsal lehet telepíteni: `npm install -g nodemon` #### Az első Express alkalmazás Ha minden szükséges csomagot feltelepítettünk, elkezdhetjük az alkalmazásunk tényleges fejlesztését. Ehhez készítsünk egy **index.js** nevű fájlt, amibe írjuk bele az alábbi kódot: ```javascript const express = require("express"); const app = express(); app.get("/", (req, res) => { res.send("Hello World!"); }); app.listen(3000); ``` Miután elmentettük a fájlt, a következő paranccsal indítható az alkalmazás: `nodemon index.js` (Ha ez nem működik, mert a környezeti változók nem jól vannak beállítva, és ismeretlen parancsnak tekinti a rendszer, akkor az `npx nodemon index.js` parancsot érdemes megpróbálni). Ha azt szeretnénk, hogy az `npm start` vagy az `npm run dev` paranccsal induljon az alkalmazás (mivel a nodemon egy fejlesztői eszköz, célszerűbb az npm run dev), azt úgy tehetjük meg, hogy a package.json-ben a `scripts` részhez felvesszük: ```json { "scripts": { "dev": "npx nodemon index.js" } } ``` #### Próbáljuk ki Egy tetszőleges böngészővel nyissuk meg a következő címet: [http://localhost:3000/](http://localhost:3000/) Ekkor a betöltött oldalon meg kell, hogy jelenjen a _Hello World!_ szöveg. Próbáljunk meg olyan végpontot is meghívni, ami nem létezik: [http://localhost:3000/valami](http://localhost:3000/valami) A válasz ekkor egy értelmes hibaüzenet lesz. Kipróbálhatjuk azt is, hogy a Hello World!-öt átírjuk valami másra és elmentjük a fájlt. A szerver mindenféle manuális újraindítás nélkül az új szöveget fogja elküldeni. #### Tulajdonképpen mi is történik itt? A programunk első sora beimportálja az Express-t, amihez az **express** változón keresztül kapunk hozzáférést. Ennek segítségével csinálunk egy alkalmazást, amit az **app** nevű változóhoz kötünk. Majd pedig az alkalmazás az alábbi funkciókat használja: - app.get(route, callback függvény) - Azt írja le, hogy mi történjen, ha get metódussal hívjuk meg az adott route-ot. A callback funkciónak (ez értelemszerűen lehet sima function vagy arrow function) 2 paramétere van, a **request (req)**, illetve a **response (res)**. Ezek szabványos HTTP kéréseket reprezentálnak, amelyeknek vannak tulajdonságaik, paramétereik, fejléceik, törzsük, stb. - res.send() - Ez a funkció fog egy objektumot, és továbbítja a válaszban a kérést küldő kliens felé. Ezen a ponton küldjük át a kliensnek (jelen esetben pl. böngészőnek) a _Hello world!_ szöveget. - app.listen(port, [host], [backlog], [callback]]) - Ennek hatására a program elkezdi figyelni a kapcsolódásokat a megadott címen. A portot mindenképpen meg kell adni, a többi opcionális paraméter. #### Miért jó ez nekünk? Látszik, hogy a kód sokkal strukturáltabb, átláthatóbb, a végpontok pedig szépen elkülönülnek majd egymástól. Magasabb szinten tudunk fejleszteni, mintha csak a sima http modult használnánk. <file_sep>const { createServer } = require("http"); const { Server } = require("socket.io"); const { instrument } = require("@socket.io/admin-ui"); const events = require('./events'); const httpServer = createServer(); const io = new Server(httpServer, { // Külféle erőforrásokból is el tudjuk érni a szervert, pl a socket io hostolt admin felületéből cors: { origin: "*", methods: ["GET", "POST"], credentials: true }, // Lehetővé teszi, hogy olyan kliensekkel is kapcsolódjunk a szerverhez, // ami csak a socket.io 2-es verzióját támogatja allowEIO3: true, }); instrument(io, { auth: false }); events(io); httpServer.listen(3000, () => { console.log("A Socket.IO szerver fut!"); }); <file_sep><?php namespace Database\Seeders; use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; use App\Models\Category; class CategorySeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('categories')->truncate(); // Szúrjon be 8 db kategóriát az adatbázisba, amit a factoryval generált ki Category::factory(8)->create(); } } <file_sep>const models = require("../models"); const { sequelize, User, Genre, Movie, Rating } = models; const authMw = require("../middlewares/auth"); const auth = (fn) => { //console.log("auth"); // Wrapper fv: return async (parent, params, context, info) => { //console.log(context.headers); // Express middleware: (request, response, next) await new Promise((resolve, reject) => { authMw(context, null, (error) => { if (error) { reject(error); // await miatt ez error throw lesz } resolve(); // csak annyi, hogy működik, oké az auth }); }); // ha errort dob a promise, megáll a futás, egyébként pedig a contextbe // berakja a jwt token payloadját a context.user alá // Eredeti fv meghívása: return fn(parent, params, context, info); }; }; module.exports = { Query: { helloWorld: () => "Hello world", // (parent, params, context, info) helloName: (_, { name }) => `Hello ${name}!`, helloAuth: auth((parent, params, context) => `Hello ${context.user.name}!`), genres: () => Genre.findAll(), genre: (_, { id }) => Genre.findByPk(id), movies: () => Movie.findAll(), movie: (_, { id }) => Movie.findByPk(id), users: () => User.findAll(), user: (_, { id }) => User.findByPk(id), top: async (_, { limit }) => { return ( await Movie.findAll({ attributes: { include: [[sequelize.fn("AVG", sequelize.col("Ratings.rating")), "averageRating"]], }, include: [ { model: Rating, attributes: [], }, ], group: ["movie.id"], order: sequelize.literal("averageRating DESC"), }) ).slice(0, limit); }, }, Genre: { /*movies: async (genre) => { console.log(genre); return await genre.getMovies(); },*/ movies: (genre) => genre.getMovies(), }, Movie: { genres: (movie) => movie.getGenres(), ratings: (movie) => movie.getRatings(), averageRating: async (movie) => { const rating = await movie.getRatings({ attributes: [[sequelize.fn("AVG", sequelize.col("rating")), "averageRating"]], raw: true, }); return rating[0].averageRating; }, }, Rating: { user: (rating) => rating.getUser(), movie: (rating) => rating.getMovie(), }, User: { ratings: (user) => user.getRatings(), }, Mutation: { // Létrehozás és módosítás rate: auth(async (_, { movieId, rating, comment }, context) => { const movie = await Movie.findByPk(movieId); if (!movie) throw new Error("Nincs ilyen film"); if (movie.ratingsEnabled !== true) { throw new Error("A megadott filmhez nincsenek engedélyezve az értékelések!"); } // Ha van ilyen értékelés, akkor a user korábban már értékelte ezt a filmet let userRating = await Rating.findOne({ where: { UserId: context.user.id, MovieId: movieId } }); let newRating = false; if (userRating) { // A meglévő értékelést kell módosítani await userRating.update({ rating, comment }); } else { // Új értékelést hozunk létre userRating = await Rating.create({ rating, comment, UserId: context.user.id, MovieId: movieId }); newRating = true; } return { rating: userRating, isNewRating: newRating, }; }), deleteRating: auth(async (_, { movieId }, context) => { const movie = await Movie.findByPk(movieId); if (!movie) throw new Error("Nincs ilyen film"); if (movie.ratingsEnabled !== true) { throw new Error("A megadott filmhez nincsenek engedélyezve az értékelések!"); } // Ha van ilyen értékelés, akkor a user korábban már értékelte ezt a filmet let userRating = await Rating.findOne({ where: { UserId: context.user.id, MovieId: movieId } }); let deleted = false; if (userRating) { await userRating.destroy(); deleted = true; } return deleted; }), }, }; <file_sep>const models = require("../models"); const { sequelize, User, Shop, Warehouse, Item, Carrier } = models; const auth = require("./auth"); module.exports = { Query: { warehouses: () => Warehouse.findAll(), shop: (_, { id }) => Shop.findByPk(id), cheapestItem: () => Item.findOne({ order: ["price"] }), statistics: async (_, { shopId }) => { const s = await Shop.findByPk(shopId); if (!s) throw new Error("Shop not found"); const items = await s.getItems(); let count = 0, max = 0, min = Number.MAX_SAFE_INTEGER, sum = 0, oddSum = 0.0; // prettier-ignore for (const item of items) { sum += item.price; if (min > item.price) min = item.price; if (max < item.price) max = item.price; if (item.price % 2 !== 0) oddSum += item.price; count++; } return { count, max, min, average: sum / count, oddSumTenPercent: oddSum * 0.1, }; /*const count = await s.countItems(); const max = (await s.getItems({ order: [["price", "DESC"]] }))[0]?.price; const min = (await s.getItems({ order: [["price", "ASC"]] }))[0]?.price; const average = ( await s.getItems({ attributes: [[sequelize.fn("AVG", sequelize.col("price")), "avgPrice"]], raw: true, }) )[0].avgPrice; const items = await s.getItems(); let sum = 0; for (const item of items) { if (item.price % 2 !== 0) sum += item.price; } const oddSumTenPercent = sum * 0.1; return { count, max, min, average, oddSumTenPercent, };*/ }, }, Mutation: { // Feldolgozó fv paraméterezése: // parent, args (params), context, info updateWarehouse: async (_, { data }) => { const wh = await Warehouse.findByPk(data.id); if (!wh) throw new Error("Warehouse not found"); await wh.update(data); return wh; }, refillShelves: async (_, { id, items }) => { const s = await Shop.findByPk(id); if (!s) throw new Error("Shop not found"); // Jelenlegi itemek leválasztása //await s.setItems([]); // Mivel az item egyértelműen a bolthoz köthető, töröljük azokat, amik ehhez a bolthoz tartoznak await Item.destroy({ where: { shopId: id } }); for (const item of items) { await s.createItem(item); } return s; }, fireCarriers: async (_, { warehouseId }) => { const wh = await Warehouse.findByPk(warehouseId); // Carrier.numberOfCars - Carrier.carCapacity < Warehouse.capacity / 2 const cs = await wh.getCarriers(); let r = { fired: [], remainders: [], }; for (const c of cs) { if (c.numberOfCars - c.carCapacity < wh.capacity / 2) { r.fired.push(c); await wh.removeCarrier(c); } else { r.remainders.push(c); } } return r; }, }, Warehouse: { carriers: (warehouse) => warehouse.getCarriers(), }, Shop: { warehousesStartingWithVowel: async (shop) => { const w = await shop.getWarehouses(); const vowels = ["a", "e", "i", "o", "u"]; return w.filter((wh) => vowels.includes(wh.name.toLowerCase()[0])); }, warehouses: (shop) => shop.getWarehouses(), items: (shop) => shop.getItems(), }, Item: { shop: (item) => item.getShop(), }, }; <file_sep># Szerveroldali webprogramozás 2021/22/1 - Laravel beadandó ## Tartalomjegyzék - [Szerveroldali webprogramozás 2021/22/1 - Laravel beadandó](#szerveroldali-webprogramozás-2021221---laravel-beadandó) - [Tartalomjegyzék](#tartalomjegyzék) - [Feladat](#feladat) - [Adatmodellek](#adatmodellek) - [Relációk](#relációk) - [1. felvonás (30 pont)](#1-felvonás-30-pont) - [Seeder (3 pont)](#seeder-3-pont) - [Főoldal (5 pont)](#főoldal-5-pont) - [Toplista (2 pont)](#toplista-2-pont) - [Film adatlapja (10 pont)](#film-adatlapja-10-pont) - [Film értékelése (10 pont)](#film-értékelése-10-pont) - [2. felvonás (30 pont)](#2-felvonás-30-pont) - [Film hozzáadása (7 pont)](#film-hozzáadása-7-pont) - [Film módosítása (3 pont)](#film-módosítása-3-pont) - [Értékelések törlése (3 pont)](#értékelések-törlése-3-pont) - [Film törlése (3 pont)](#film-törlése-3-pont) - [Film helyreállítása (14 pont)](#film-helyreállítása-14-pont) - [Kezdőcsomag](#kezdőcsomag) - [Követelmények](#követelmények) - [Alkotói szabadság](#alkotói-szabadság) - [Segítségkérés, konzultációs alkalmak](#segítségkérés-konzultációs-alkalmak) - [Határidők, késés](#határidők-késés) - [A munka tisztasága](#a-munka-tisztasága) - [Hasznos hivatkozások](#hasznos-hivatkozások) ## Feladat A feladatod egy filmkatalógus elkészítése, ahol az admin kezeli a filmeket, a felhasználók pedig értékelhetik azokat. Az alkalmazást Laravel 8 keretrendszerben, SQLite adatbázis használatával kell megvalósítani. ### Adatmodellek - Movie - id - title (string) - director (string) - description (text, nullable) - year (integer) - length (integer, másodpercekben mérjük) - image (string, nullable) - ratings_enabled (boolean, default: true) - timestamps (created_at, updated_at, később deleted_at) - User _(ilyen van alapból a Laravelben, csak ki kell egészíteni egy is_admin-nel)_ - id - name (string) - email (string, unique) - email_verified_at (timestamp, nullable) - password (<PASSWORD>) - is_admin (boolean, default: false) - remember_token - timestamps (created_at, updated_at) - Rating - id - user_id (integer, foreign) - movie_id (integer, foreign) - rating (integer, 1-5) - comment (string, max 255, nullable) - timestamps (created_at, updated_at) ### Relációk - Movie 1 - N Rating - User 1 - N Rating ## 1. felvonás (30 pont) **Határidő: 2021. október 31. (vasárnap) 23:59** ### Seeder (3 pont) - Az alkalmazás legyen feltölthető adatokkal egy seeder / seeder-ek segítségével. Ez a feltöltés lehetőleg minél több mindent fedjen le. - Itt alapvetően a "mindent fedjen le" alatt arra gondolunk, hogy minden *esetet* fedjen le, tehát mindenféle model, ami az alkalmazásban van (user, movie, rating) kerüljön seedelésre, és a köztük lévő kapcsolatok is legyenek szépen, logikusan felépítve. - Nem szükséges sok adatot seedelni, bőven elég 2-3 user, vagy annyi film, értékelés, hogy menjen a pagination. - A seeder ezzel az egy paranccsal működjön: `php artisan db:seed` - A user fiókok az egyszerűség kedvéért **csak ezek lehetnek** (email - jelszó): - Admin: *<EMAIL> - password* - Sima user-ek: - *<EMAIL> - password* - *<EMAIL> - password* - .... ### Főoldal (5 pont) - Legyen egy főoldal, ahol a filmek listázva vannak valamilyen módon (card, lista, akármi) - Az egyes filmeknél a főoldalon mindenképp jelenjen meg a film címe, a hozzá tartozó kép (ha van, egyébként jó valami default placeholder kép is), és az értékelés (ez lehet számként / csillagokkal) - A főoldal lapozható legyen (pagination), egy oldalon max. 10 film jelenjen meg - Az egyes filmekre kattintva jöjjön be az adott film adatlapja ### Toplista (2 pont) - Legyen egy toplista nevű oldal, ami hasonló a főoldalhoz, azonban itt a legjobbra értékelt 6 film jelenik meg. ### Film adatlapja (10 pont) - Itt szintén jelenítsük meg valamilyen módon a filmhez tartozó képet, értékelést és írjuk ki a film minden adatát. - A film adatlapján jelenítsük meg az egyes értékeléseket, szintén pagination segítségével, vagyis egyszerre max 10 értékelés jelenjen meg. Az értékelések időrendi sorrendbe legyenek rendezve, úgy, hogy a legújabb legyen legelöl. ### Film értékelése (10 pont) - Ha be vagyunk jelentkezve, akkor a film adatlapján legyen lehetőség a film értékelésére. Ez egy form, ami két részből áll: - egy értékelés (1-5), és - egy opcionális komment beviteléből. - A form legyen állapottartó, a validációs hibákról adjon egyértelmű visszajelzést a felhasználónak. - Az értékelés során két eset lehet: - Ha még nem értékeltük az adott userrel a filmet, akkor új értékelést adunk hozzá. - Ha az adott user már értékelte a filmet, akkor a meglévő értékelését tudja módosítani. - Ha az admin is tud értékelni, az nem probléma. - Ha az értékelés sikerült, akkor térjünk vissza a film adatlapjára, ahol jelenjen meg egy üzenet, hogy sikerült az értékelés. - A filmet csak akkor lehessen értékelni, ha az értékelés engedélyezve van (`ratings_enabled` mező). Ha az értékelés le van tiltva, a form nem jelenhet meg, a végpontjára nem lehet értékelést küldeni, és a felhasználónak meg kell róla jeleníteni egy üzenetet. Ha az értékelés le van tiltva, az azt jelenti, hogy új értékelést nem lehet hozzáadni, de ha már vannak meglévő értékelések, azokat ugyanúgy jelenítsük meg. ## 2. felvonás (30 pont) **Határidő: 2021. november 7. (vasárnap) 23:59** A második felvonásban az admin funkciókat kell megcsinálni. - A felhasználó akkor számít adminnak, ha az _is_admin_ logikai mezőjének értéke igaz. - Az admin tudja kezelni az oldalon lévő filmeket, vagyis **hozzáadhat, módosíthat, törölhet és helyreállíthat** filmeket. ### Film hozzáadása (7 pont) - A filmeket listázó oldalon legyen egy "Új film" nevű gomb, amire rákattintva jöjjön be egy űrlap, amelyen lehet új filmet hozzáadni a film adatainak megadásával. - Validálási szabályok: - Cím kötelező, max 255 karakter - Rendező kötelező, max 128 karakter - Év kötelező, legalább 1870, legfeljebb a jelenlegi év - Leírás nem kötelező, de ha van, max 512 karakter - Film hossza - A feltöltött kép formátuma csak jpg és png lehet, maximum 2MB méretben. - A filmhez tartozó képfeltöltést rendesen implementálni kell (vagyis egy link megadása, majd annak átadása egy img tag-nek nem számít megoldásnak)! Fel kell tudni tölteni a képfájlt, azt eltárolni a storage-ben, majd onnan kiolvasni megjelenítéshez a movie image mezője alapján. - A form legyen állapottartó, a validációs hibákról adjon egyértelmű visszajelzést a felhasználónak. ### Film módosítása (3 pont) - A film adatlapján az adminnak megjelenik egy "Módosítás" gomb, ami az adott filmre behoz egy formot, ami előre ki van töltve a film adataival, a validálási szabályok pedig megegyeznek a létrehozással. - A kép helyes kezelése módosításnál: - A képet úgy tudod megoldani, hogy megjeleníted magát a képet, és ugyanúgy a fájlfeltöltő input mezőt is, és ha üresen hagyja a user, hagyod a régi képet, ha pedig feltölt egy másik képet, akkor kicseréled arra a képet, a régit pedig törlöd a disk-ről. - A kép alá rakj be egy checkbox-ot is, hogy "Kép eltávolítása". Ha ezt bejelöli a user, akkor csak simán törölni szeretné a meglévő képet, ahelyett, hogy újat töltene fel. Ha a "Kép eltávolítása" mezőt bejelöli, és úgy tölt fel új képet, akkor csak ugyanúgy cseréld le a képet az újra. - A form legyen állapottartó, a validációs hibákról adjon egyértelmű visszajelzést a felhasználónak. - A módosítás után meg kell jeleníteni a felhasználónak, hogy a módosítás sikeres volt. ### Értékelések törlése (3 pont) - A film adatlapján az adminnak megjelenik egy "Értékelések törlése" gomb, amelyre kattintva a filmhez tartozó összes értékelés törlésre kerül. - A törlés után meg kell jeleníteni a felhasználónak, hogy a törlés sikeres volt. ### Film törlése (3 pont) - A film adatlapján az adminnak megjelenik egy "Törlés" gomb, amelyre kattintva a film törlésre kerül. - A törlés után meg kell jeleníteni a felhasználónak, hogy a törlés sikeres volt. - A helyreállítás miatt [soft delete](https://laravel.com/docs/8.x/eloquent#soft-deleting) kell történjen. Tulajdonképpen ez azt jelenti, hogy a film nem is lett ténylegesen törölve, csak egy _deleted_at_ mezővel látta el a Laravel. ### Film helyreállítása (14 pont) - Az adminnak legyen lehetősége egy törölt filmet helyreállítani (restore). - A törölt film értelemszerűen a usereknek nem jelenhet meg, de az adminnak ugyanúgy jelenjen meg a filmek között (viszont legyen megkülönböztetve a nem törölt filmektől). - Az admin legyen képes megnyitni az adatlapját is, és az adatlapján állíthatja vissza egy "Visszaállítás" gombra kattintva. Innentől ismét rendes filmnek számít. - A helyreállítás után meg kell jeleníteni a felhasználónak, hogy a helyreállítás sikeres volt. ## Kezdőcsomag - A beadandóhoz kezdőcsomagot adunk. **A kompatibilitási problémák elkerülése érdekében kérünk mindenkit, hogy ezt a kezdőcsomagot használja, és ebbe dolgozzon!** - A kezdőcsomag a következő GitHub repositoryból tölthető le (clone vagy [download zip](https://github.com/szerveroldali/laravel_kezdocsomag/archive/refs/heads/main.zip)): https://github.com/szerveroldali/laravel_kezdocsomag - Letöltés után telepíteni kell a Composer-es csomagokat: `composer install` - A beadandót becsomagolni a `php artisan zip` paranccsal, majd annak utasításait követve lehet! Ilyenkor a `zipfiles` mappában meg fog jelenni a beadható fájl. ## Követelmények - A beadandót a Canvas rendszerben kell beadni a kiírt feladathoz. Mindkét felvonást külön-külön is be kell adni. - **Alapelvárás, hogy az alkalmazás a beadott zip-ből kicsomagolva az operációs rendszernek megfelelő `init.bat` / `init.sh` fájlokat futtatva elinduljon!** Ezek a fájlok tartalmazzák a projekt inicializálásához szükséges parancsokat. - Kötelező mellékelni a munka tisztaságáról szóló _STATEMENT.md_ nevű nyilatkozatot, a részleteket [lásd lentebb](#dolgozz-fair-módon). Az elfelejtett nyilatkozat utólag pótolható Canvas-on kommentben is. - Tilos mellékelni a vendor és a node_modules mappákat! - Elvárás az igényesen kidolgozott felhasználói felület, azaz, hogy felhasználóként, a kódban való kutatgatás nélkül is teljes mértékben használható legyen az alkalmazás; ki legyen dolgozva a menürendszer, a műveletekhez rendelkezésre álljanak a gombok, megjelenjenek a hiba/tájékoztató üzenetek, stb. A stílushoz használt CSS framework nincs megkötve, használhatsz Tailwind-ot, Bootstrap-et, vagy ami szimpatikus. - Az időzóna legyen magyarra állítva az alkalmazás konfigurációjában! - Az űrlapokon keresztül küldött adatokat minden esetben validálni kell szerveroldalon! HTML szintű validáció (pl. required attribútum) ne is legyen a kódban! Nem a HTML tag-ek ismeretét szeretnénk számonkérni egy szerveroldali tárgyon, hanem a [Laravel validációjának](https://laravel.com/docs/8.x/validation) megfelelő alkalmazását! - Bejelentkezés után ne a `/dashboard` oldalra kerüljünk, hanem az alkalmazás tényleges főoldalára! Ez a `RouteServiceProvider.php`-ben lévő HOME konstans átírásával valósítható meg. ## Alkotói szabadság - Szeretnénk, ha nem egy kötött dologként gondolnátok erre a feladatra, hanem kellő alkotói szabadsággal állnátok neki. - Tulajdonképpen alkalmazott tudást várunk el, hogy a tanultakat mélyebben megértsétek és akár tovább is tudjátok gondolni; vagyis nem kell mereven csak a tanult dolgokhoz ragaszkodni, kezdjétek el "élesben" használni a Laravelt, és ahogy foglalkoztok vele, úgy értitek majd meg egyre jobban és jobban a koncepcióját. - Egy jó tanács: mérlegeljétek az előttetek álló feladatokat, ne essetek olyan hibába, hogy sokkal bonyolultabb megoldást csináltok, mint amire szükség van. ## Segítségkérés, konzultációs alkalmak - Ha bárkinek bármilyen kérdése van a beadandóval kapcsolatban, pl. elakadt, támpontra van szüksége, kíváncsi, hogy jó-e egy ötlete, nem ért valamit a követelményekből, nem érti a feladat valamelyik pontját, akkor bátran keresse az oktatókat. Fontos, hogy NE tologassa maga előtt a beadandót, ha elakad, hogy "majd lesz valahogy", "majd később megoldom", mivel hamar elszáll az idő! Az elérhetőségek megtalálhatóak a Canvasben, az "Elérhetőség" oldalon. - A beadandóhoz az alábbi konzultációs lehetőségeket is biztosítjuk: - 2021. október 16. (szombat) 14:00, helyszín: Teams, Általános csatorna - 2021. október 28. (csütörtök) 21:00, helyszín: Teams, Általános csatorna - Ezek általános konzultációs alkalmak. A gyakorlatvezetők elmondanak általános dolgokat, tanácsokat, viszont az igazi az lenne, ha minél többen becsatlakoznátok, és hoznátok magatokkal kérdéseket, hogy a jelenlévő társaitok is tudjanak belőle tanulni, okulni, hogy mások miket kérdeznek, és azokra mi a válasz/lehetséges megközelítés. ## Határidők, késés - A beadandót igyekeztünk úgy kialakítani és olyan beadási határidőkkel ellátni, hogy azt mindenkinek legyen elegendő ideje rendesen, nyugodt körülmények között kidolgozni. - **Időben kezdj hozzá a beadandóhoz és oszd be az idődet! Sajnos gyakori tapasztalat, hogy sokan a határidő lejárta előtt pár nappal, vagy akár a határidő napján állnak neki a beadandónak, ezért NYOMATÉKOSAN kérünk mindenkit, hogy IDŐBEN kezdjen hozzá!** - A határidő lejárta után lehetőség van késésre: - **Minden, határidő után megkezdett nap (0:00-tól) 1.5 (azaz másfél) pont levonását jelenti.** - A határidő mindig 23:59-re esik, így aki az utolsó pillanatra hagyja a beadást, és 0:00-kor adja be, az is késésnek számít, és ugyanúgy pontlevonás jár érte. - Mivel legalább 40%-ot, vagyis 12 pontot el kell érni egy-egy felvonásból, így ez matematikailag legfeljebb 12 nap késést tesz lehetővé (12\*(-1.5) = -18 pont) egy felvonásban, ha azt feltételezzük, hogy a beadott munka a beadáskor hibátlan, vagyis a 30 pontból jön le a 18, hogy abból aztán megmaradjon a min. 40%, vagyis 12 pont. - **Nem éri meg késni, főleg nem sokat. Gondolj bele:** _Sokkal_ egyszerűbb időben elkészíteni és beadni egy 12-18 pontos beadandót, mint az utolsó pillanatban megcsinálni közel 30 pontosra úgy, hogy az a rengeteg munka a levonások miatt kb. 12 pontot fog érni. - **A beadandókat nem lehet utólag javítani (csak a zh-t)**, ezért a késésre fokozottan ügyeljetek, mivel **könnyen elbukható a beadandón a tárgy, ha nem veszed komolyan!** - Ha valaki _indokolt_ eset miatt nem tudja tartani a határidőt, akkor haladéktalanul keresse fel a gyakorlatvezetőjét, akivel ismertesse a problémáját, és _hitelt érdemlően igazolja_ is azt, hogy mi jött neki közbe! Ilyen egyedi esetekben lehetőség van a határidőtől a probléma súlyától függően eltérni az adott hallgatónál. **Ezzel a lehetőséggel ne éljetek vissza, az igazolatlan eseteket, mondvacsinált, kamu indokokat pedig azonnal elutasítjuk!** ## A munka tisztasága - **Kérjük, hogy a saját érdekedben csak olyan munkát adj be, amit Te készítettél!** - A "problémás" beadandók eredményes kiszűrése érdekében a beadott munkák szigorú, több lépcsőből álló plágiumellenőrzési folyamaton mennek keresztül, amely több automatizált gépi ciklusból és humán ellenőrzésből is áll. A csalásokat (konkrét példák: jelentős netről másolás, egyező beadandók, mások helyett leadott beadandók, stb) észre fogjuk venni. - Nyilvánvaló esetekben ez kérdés nélkül azonnali következményekkel jár, gyanús esetekben pedig az érintett hallgatók felkérhetők szóbeli védésre, ahol teljesen véletlenszerűen belekérdezünk az alkalmazásba, annak logikájába és működésébe. Ezzel tökéletesen fel tudjuk mérni, hogy az illető tisztában van-e azzal, hogy mit adott le. - Ha valaki becsületesen készíti el a beadandót, órai példákat használt, "rákeresett erre-arra a neten", megnézett pár stackoverflow, laracasts thread-et, akkor az itt leírtak miatt egyáltalán nem kell aggódnia. - A beadott feladatnak tartalmaznia kell egy STATEMENT.md nevű fájlt, a következő tartalommal (értelemszerűen az adataidat írd bele): ``` # Nyilatkozat Én, <NÉV> (Neptun kód: <NEPTUN KÓD>) kijelentem, hogy ezt a megoldást én küldtem be a Szerveroldali webprogramozás Laravel beadandó feladatához. A feladat beadásával elismerem, hogy tudomásul vettem a nyilatkozatban foglaltakat. - Kijelentem, hogy ez a megoldás a saját munkám. - Kijelentem, hogy nem másoltam vagy használtam harmadik féltől származó megoldásokat. - Kijelentem, hogy nem továbbítottam megoldást hallgatótársaimnak, és nem is tettem azt közzé. - Tudomásul vettem, hogy az Eötvös Loránd Tudományegyetem Hallgatói Követelményrendszere (ELTE szervezeti és működési szabályzata, II. Kötet, 74/C. §) kimondja, hogy mindaddig, amíg egy hallgató egy másik hallgató munkáját - vagy legalábbis annak jelentős részét - saját munkájaként mutatja be, az fegyelmi vétségnek számít. - Tudomásul vettem, hogy a fegyelmi vétség legsúlyosabb következménye a hallgató elbocsátása az egyetemről. ``` - Ha a nyilatkozat feltöltése elmarad, akkor pótolni kell egy újabb feltöltéssel, vagy a Canvasen komment formájában. - **Amíg a hallgató nem nyilatkozott munkája tisztaságáról, a feladatára kapott értékelés (ha addig megtörtént az értékelés) nem érvényes, egészen addig, amíg a nyilatkozat pótlásra nem kerül! A nyilatkozat pótlásáról értesíteni kell az oktatót is, aki az értékelést végzi (a saját gyakorlatvezetőt).** ## Hasznos hivatkozások Az alábbiakban adunk néhány hasznos hivatkozást, amiket érdemes szemügyre venni a beadandó elkészítésekor. - [Idei órai alkalmazás](https://github.com/szerveroldali/2021-22-1/tree/main/esti_3_4_csut_19_30/laravel) - [Tavalyi órai alkalmazás](https://github.com/totadavid95/szerveroldali-21-tavasz/tree/main/pentek/laravel/pentek) - [Laravel nyelvi csomag - magyarosításhoz](https://github.com/Laravel-Lang/lang) - Tantárgyi Laravel jegyzetek - [Kimenet generálása](http://webprogramozas.inf.elte.hu/#!/subjects/webprog-server/handouts/laravel-01-kimenet) - [Bemeneti adatok, űrlapfeldolgozás](http://webprogramozas.inf.elte.hu/#!/subjects/webprog-server/handouts/laravel-02-bemenet) - [Adattárolás, egyszerű modellek](http://webprogramozas.inf.elte.hu/#!/subjects/webprog-server/handouts/laravel-03-adatt%C3%A1rol%C3%A1s) - [Relációk a modellek között](http://webprogramozas.inf.elte.hu/#!/subjects/webprog-server/handouts/laravel-04-rel%C3%A1ci%C3%B3k) - [Hitelesítés és jogosultságkezelés](http://webprogramozas.inf.elte.hu/#!/subjects/webprog-server/handouts/laravel-05-hiteles%C3%ADt%C3%A9s) - [GitHub-os Laravel jegyzet](https://github.com/totadavid95/szerveroldali-21-tavasz/blob/main/Laravel.md) - Dokumentációk - [Laravel dokumentáció](https://laravel.com/docs) - [Blade direktívák](https://laravel.com/docs/8.x/blade) - [Resource Controllers](https://laravel.com/docs/8.x/controllers#resource-controllers) - [Validációs szabályok](https://laravel.com/docs/8.x/validation#available-validation-rules) - [Migrációknál elérhető mezőtípusok](https://laravel.com/docs/8.x/migrations#available-column-types) - [Laravel API dokumentáció](https://laravel.com/api/master/index.html) - [PHP dokumentáció](https://www.php.net/manual/en/) - [Bootstrap 4 dokumentáció](https://getbootstrap.com/docs/4.6/getting-started/introduction/) - Programok, fejlesztői eszközök - [Automatikus PHP és Composer telepítő](https://github.com/totadavid95/PhpComposerInstaller) - [Visual Studio Code](https://code.visualstudio.com/) - [Live Share](https://marketplace.visualstudio.com/items?itemName=MS-vsliveshare.vsliveshare) - [Laravel Extension Pack](https://marketplace.visualstudio.com/items?itemName=onecentlin.laravel-extension-pack) - [DB Browser for SQLite](https://sqlitebrowser.org/) - További CSS framework tippek - [Fontawesome ikonkészlet](https://fontawesome.com/) - [Tailwind CSS](https://tailwindcss.com/) - [Material Bootstrap](https://mdbootstrap.com/) - [Material UI, React-hez](https://material-ui.com/) - [Bulma](https://bulma.io/) <file_sep>"use strict"; const faker = require("faker"); const models = require("../models"); const { User, Shop, Warehouse, Item, Carrier } = models; const colors = require("colors"); module.exports = { up: async (queryInterface, Sequelize) => { try { // Felhasználók /*const usersCount = faker.datatype.number({ min: 1, max: 3 }); const users = []; users.push( await User.create({ name: "Admin", email: "<EMAIL>", password: "<PASSWORD>", isAdmin: true, }) ); for (let i = 1; i <= usersCount; i++) { users.push( await User.create({ name: faker.name.findName(), email: `<EMAIL>`, password: "<PASSWORD>", }) ); }*/ // Egyéb... const shops = []; const items = []; const warehouses = []; const carriers = []; for (let i = 0; i < 5; i++) { shops.push( await Shop.create({ name: faker.company.companyName(), city: faker.address.city(), }) ); } for (let i = 0; i < 10; i++) { items.push( await Item.create({ name: faker.company.companyName(), price: faker.datatype.number(), }) ); } for (let i = 0; i < 8; i++) { warehouses.push( await Warehouse.create({ name: faker.company.companyName(), city: faker.address.city(), capacity: faker.datatype.number(), }) ); carriers.push( await Carrier.create({ name: faker.company.companyName(), numberOfCars: faker.datatype.number(), carCapacity: faker.datatype.number(), }) ); } // shop - warehouse await Promise.all( shops.map((shop) => shop.addWarehouse(faker.random.arrayElement(warehouses, faker.datatype.number({ min: 1, max: 8 })))) ); // shop - item await Promise.all(items.map((item) => item.setShop(faker.random.arrayElement(shops, faker.datatype.number({ min: 1, max: 5 }))))); // carrier - warehouse await Promise.all( carriers.map((carrier) => carrier.setWarehouse(faker.random.arrayElement(warehouses, faker.datatype.number({ min: 1, max: 8 }))) ) ); console.log("A DatabaseSeeder lefutott".green); } catch (e) { // Ha a seederben valamilyen hiba van, akkor alapértelmezés szerint elég szegényesen írja // ki azokat a rendszer a seeder futtatásakor. Ezért ez Neked egy segítség, hogy láthasd a // hiba részletes kiírását. // Így ha valamit elrontasz a seederben, azt könnyebben tudod debug-olni. console.log("A DatabaseSeeder nem futott le teljesen, mivel az alábbi hiba történt:".red); console.log(colors.gray(e)); } console.log("A DatabaseSeeder lefutott"); }, down: async (queryInterface, Sequelize) => { /** * Add commands to revert seed here. * * Example: * await queryInterface.bulkDelete('People', null, {}); */ }, }; <file_sep>"use strict"; // Faker dokumentáció: http://marak.github.io/faker.js/faker.html const faker = require("faker"); const colors = require("colors"); const models = require("../models"); const { Developer, Genre, Game, Release } = models; module.exports = { up: async (queryInterface, Sequelize) => { try { // Ide dolgozd ki a seeder tartalmát: // ... const genres = []; const genresCount = faker.datatype.number({ min: 5, max: 10 }); for (let i = 0; i < genresCount; i++) { genres.push( await Genre.create({ name: faker.unique(faker.lorem.word), }) ); } const developers = []; const developersCount = faker.datatype.number({ min: 5, max: 10 }); for (let i = 0; i < developersCount; i++) { developers.push( await Developer.create({ name: faker.company.companyName(), website: faker.internet.url(), location: faker.address.country(), }) ); } const gamesCount = faker.datatype.number({ min: 5, max: 10 }); for (let i = 0; i < gamesCount; i++) { const writers = []; // ['a', 'b', 'c'].join(', ') = "a, b, c" const writersCount = faker.datatype.number({ min: 1, max: 3 }); for (let j = 0; j < writersCount; j++) { writers.push(faker.name.findName()); } const game = await Game.create({ title: faker.lorem.words(faker.datatype.number({ min: 1, max: 6 })), writers: writers.join(", "), description: faker.lorem.sentence(), singleplayer: faker.datatype.boolean(), multiplayer: faker.datatype.boolean(), engine: faker.lorem.word(), DeveloperId: faker.random.arrayElement(developers).id, }); // Műfajok hozzárendelése a játékhoz await game.setGenres(faker.random.arrayElements(genres)); // Kiadások hozzárendelése a játékhoz const releasesCount = faker.datatype.number({ min: 2, max: 6 }); for (let j = 0; j < releasesCount; j++) { await game.createRelease({ platform: faker.random.arrayElement(["win", "ps2", "ps3", "ps4", "ps5", "xbox360", "xboxone"]), date: faker.date.past(20, new Date()), version: faker.system.semver(), //GameId: game.id, }); } } console.log("A DatabaseSeeder lefutott".green); } catch (e) { // Ha a seederben valamilyen hiba van, akkor alapértelmezés szerint elég szegényesen írja // ki azokat a rendszer a seeder futtatásakor. Ezért ez Neked egy segítség, hogy láthasd a // hiba részletes kiírását. // Így ha valamit elrontasz a seederben, azt könnyebben tudod debug-olni. console.log("A DatabaseSeeder nem futott le teljesen, mivel az alábbi hiba történt:".red); console.log(colors.gray(e)); } }, // Erre alapvetően nincs szükséged, mivel a parancsok úgy vannak felépítve, // hogy tiszta adatbázist generálnak down: async (queryInterface, Sequelize) => {}, }; <file_sep><?php use Illuminate\Support\Facades\Route; use Illuminate\Http\Request; use App\Http\Controllers\PostController; use App\Models\Category; use App\Models\Post; /* |-------------------------------------------------------------------------- | 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'); return redirect()->route('posts.index'); }); Route::get( '/posts/{id}/attachment', [PostController::class, 'attachment'] )->name('posts.attachment'); // Resource route létrehozása a posts név köré (/posts /posts/id, stb lesz) // A route-ok megtekinthetők a php artisan route:list paranccsal Route::resource('posts', PostController::class); Route::get('/categories/create', function () { return view('categories.create'); })->name('categories.create'); Route::post('/categories/store', function (Request $request) { $validated = $request->validate([ 'name' => 'required|min:2', 'bg-color' => 'required|regex:/#([a-fA-F0-9]{8})/', 'text-color' => 'required|regex:/#([a-fA-F0-9]{8})/', ], [ 'name.required' => 'A név megadása kötelező', ]); Category::create([ 'name' => $validated['name'], 'bg_color' => $validated['bg-color'], 'text_color' => $validated['text-color'] ]); })->name('categories.store'); /* Route::get('/posts/create', function () { return view('posts.create'); })->name('posts.create'); Route::post('/posts/store', function (Request $request) { $data = $request->validate([ 'title' => 'required|min:2|max:255', 'text' => 'required|min:5', 'categories.*' => 'integer|distinct', // TODO! Ha lesz adatb //'disable_comments' => 'nullable|boolean', //'hide_post' => 'nullable|boolean', 'attachment' => 'nullable|file|mimes:txt,doc,docx,pdf,xls|max:4096', 'thumbnail' => 'nullable|file|mimes:jpg,png|max:4096', ], [ 'title.required' => 'A cím megadása kötelező', 'text.min' => 'A bejegyzés szövege legalább :min karakter legyen' ]); $data['disable_comments'] = false; $data['hide_post'] = false; if ($request->has('disable_comments')) { $data['disable_comments'] = true; } if ($request->has('hide_post')) { $data['hide_post'] = true; } if ($request->hasFile('attachment')) { $file = $request->file('attachment'); $data['attachment_hash_name'] = $file->hashName(); $data['attachment_file_name'] = $file->getClientOriginalName(); Storage::disk('public')->put('attachments/' . $data['attachment_hash_name'], $file->get()); } if ($request->hasFile('thumbnail')) { $file = $request->file('thumbnail'); $data['thumbnail_hash_name'] = $file->hashName(); Storage::disk('public')->put('thumbnails/' . $data['thumbnail_hash_name'], $file->get()); } //error_log(json_encode($data)); $post = Post::create($data); // TODO: redirect })->name('posts.store'); */ Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard'); require __DIR__.'/auth.php'; <file_sep><?php use Illuminate\Support\Facades\Route; use Illuminate\Http\Request; use App\Http\Controllers\PostController; use App\Models\Category; /* |-------------------------------------------------------------------------- | 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'); return redirect()->route('posts.index'); }); Route::get('/posts/{id}/attachment', [ PostController::class, 'attachment', ])->name('posts.attachment'); // Resource route létrehozása a posts név köré (/posts /posts/id, stb lesz) // A route-ok megtekinthetők a php artisan route:list paranccsal Route::resource('posts', PostController::class); // Category Route::get('/categories/create', function () { return view('categories.create'); })->name('categories.create'); Route::post('/categories/store', function (Request $request) { $data = $request->validate([ 'name' => 'required|min:2', 'bg-color' => 'required|regex:/^#([a-fA-F0-9]){8}$/', 'text-color' => 'required|regex:/^#([a-fA-F0-9]){8}$/', ], [ 'required' => 'A(z) :attribute mező megadása kötelező!', 'name.required' => 'A név megadása kötelező!', ]); Category::create([ 'name' => $data['name'], 'bg_color' => $data['bg-color'], 'text_color' => $data['text-color'], ]); })->name('categories.store'); // Post /*Route::get('/posts/create', function () { return view('posts.create'); })->name('posts.create'); Route::post('/posts/store', function (Request $request) { $request->validate([ 'title' => 'required|min:2', 'text' => 'required|min:5', 'categories.*' => 'integer|distinct', // TODO! Adatb esetén exists ]); })->name('posts.store'); */ // ---- Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard'); require __DIR__.'/auth.php'; <file_sep>const models = require("./models"); const { User, Genre, Movie, Rating } = models; const getModelAccessorMethods = (model) => { console.log(`${model.name}:`); Object.entries(model.associations).forEach(([_, associatedModel]) => { Object.entries(associatedModel.accessors).forEach(([action, accessor]) => { console.log(` ${action}: ${model.name}.${accessor}(...)`); }); }); }; (async () => { getModelAccessorMethods(User); getModelAccessorMethods(Movie); getModelAccessorMethods(Rating); })(); <file_sep>"use strict"; // Node.js projekt zippelő // Készítette <NAME> const glob = require("glob"); const inquirer = require("inquirer"); const fs = require("fs").promises; const { promisify } = require("util"); const colors = require("colors"); const date = require("date-and-time"); const Zip = require("adm-zip"); const path = require("path"); const slug = require("slug"); const filesize = require("filesize"); const _ = require("loadsh"); const config = require("./zip.config"); const pGlob = promisify(glob); const currentDate = new Date(); // Nyilatkozat sablon const statementTemplate = `NYILATKOZAT =========== Én, {NAME} (Neptun kód: {NEPTUN}) kijelentem, hogy ezt a megoldást én küldtem be a "{SUBJECT}" tárgy "{TASK}" nevű számonkéréséhez. A feladat beadásával elismerem, hogy tudomásul vettem a nyilatkozatban foglaltakat. - Kijelentem, hogy ez a megoldás a saját munkám. - Kijelentem, hogy nem másoltam vagy használtam harmadik féltől származó megoldásokat. - Kijelentem, hogy nem továbbítottam megoldást hallgatótársaimnak, és nem is tettem azt közzé. - Tudomásul vettem, hogy az Eötvös Loránd Tudományegyetem Hallgatói Követelményrendszere (ELTE szervezeti és működési szabályzata, II. Kötet, 74/C. §) kimondja, hogy mindaddig, amíg egy hallgató egy másik hallgató munkáját - vagy legalábbis annak jelentős részét - saját munkájaként mutatja be, az fegyelmi vétségnek számít. - Tudomásul vettem, hogy a fegyelmi vétség legsúlyosabb következménye a hallgató elbocsátása az egyetemről. Kelt: {DATE}`; // Reguláris kifejezés nevesített csoportokkal, amivel bekérhetők a nyilatkozatban lévő adatok const statementRegex = new RegExp( // A kiindulási pont a nyilatkozat sablonja, csak pár dolgot át kell benne írni, // hogy működjön a mintaillesztés statementTemplate // Speciális karakterek escape-lése .replace(/[-[\]()*+?.,\\^$|#\s]/g, "\\$&") // Adatok behelyettesítése .replace("{NAME}", "(?<name>[^,]+)") .replace("{NEPTUN}", "(?<neptun>[0-9a-zA-Z]{6})") .replace("{SUBJECT}", '(?<subject>[^"]+)') .replace("{TASK}", '(?<task>[^"]+)') .replace("{DATE}", "(?<date>[^\n]+)"), "gm" ); const getStatementData = async () => { let result = { name: null, neptun: null, exists: false, valid: false }; try { const statementContent = (await fs.readFile("./statement.txt")).toString(); const match = statementRegex.exec(statementContent); if (match && match.groups) { return _.merge({}, result, { exists: true, valid: true, ...match.groups }); } return _.merge({}, result, { exists: true }); } catch (e) {} return result; }; const collectFiles = async () => await pGlob("**", { ignore: config.ignore, dot: true, nodir: true, }); const zipFiles = async (files, { name, neptun }) => { const zip = new Zip(); for (const file of files) { process.stdout.write(` * becsomagolás: ${colors.grey(file)}... `); zip.addLocalFile(file, path.parse(file).dir); console.log(colors.green("OK.")); } const formattedDate = date.format(new Date(), "YYMMDDHHmmss"); const nameSlug = slug(name, { replacement: "_", lower: false }); const task = slug(config.task, { replacement: "_" }); const zipName = `${nameSlug}_${neptun}_${task}_${formattedDate}.zip`; const zipPath = `zipfiles/${zipName}`; process.stdout.write(" 3. Archívum mentése ide: " + colors.gray(zipPath) + "... "); zip.writeZip(zipPath); const zipSize = filesize((await fs.stat(zipPath)).size); console.log(colors.white(`${colors.green("OK")}, méret: ${colors.gray(zipSize)}.`)); }; const handleStatement = async () => { // Korábbi kitöltés ellenőrzése és validálása let data = await getStatementData(); if (data.exists) { if (data.valid) { console.log( colors.green( `>> A nyilatkozat (${colors.yellow("statement.txt")}) korábban ki lett töltve ${colors.yellow( data.name )} névre és ${colors.yellow(data.neptun)} Neptun kódra.` ) ); console.log(" "); // Ha korábban ki lett töltve, itt végeztünk is return { name: data.name, neptun: data.neptun }; } else { console.log( colors.yellow(`>> A nyilatkozat (${colors.white("statement.txt")}) létezik, de úgy értékeltük, hogy a tartalma érvénytelen.`) ); console.log(" "); } } // Nyilatkozat szövegének megjelenítése for (const line of statementTemplate.split("\n")) { console.log(`${line}`.gray); } console.log(" "); // Nyilatkozat elfogadása const { accepted } = await inquirer.prompt([ { type: "list", name: "accepted", message: "Elfogadod a fenti nyilatkozatot?", choices: ["Igen", "Nem"], filter(answer) { return answer.toLowerCase(); }, }, ]); if (accepted === "igen") { console.log(">> Elfogadtad a nyilatkozatot. Kérjük, add meg az adataidat, hogy be tudjuk azokat helyettesíteni a nyilatkozatba.".green); } else { console.log( ">> A tárgy követelményei szerint a nyilatkozat elfogadása és mellékelése kötelező, ezért ha nem fogadod el, akkor nem tudjuk értékelni a zárthelyidet." .red ); throw new Error("StatementDenied"); } // Adatok bekérése const questions = [ { type: "input", name: "name", message: "Mi a neved?", validate(name) { name = name.trim(); if (name.length < 2) { return "A név legalább 2 karakter hosszú kell, hogy legyen!"; } if (name.indexOf(" ") === -1) { return "A név legalább 2 részből kell álljon, szóközzel elválasztva!"; } return true; }, filter(name) { return name .split(" ") .filter((part) => part.length > 0) .map((part) => { let partLower = part.toLowerCase(); return partLower.charAt(0).toUpperCase() + partLower.slice(1); }) .join(" "); }, }, { type: "input", name: "neptun", message: "Mi a Neptun kódod?", validate(neptun) { neptun = neptun.trim(); if (neptun.length !== 6) { return "A Neptun kód hossza pontosan 6 karakter, hogy legyen!"; } if (!neptun.match(new RegExp("[0-9A-Za-z]{6}"))) { return "A Neptun kód csak számokból (0-9) és az angol ABC betűiből (A-Z) állhat!"; } return true; }, filter(neptun) { return neptun.toUpperCase(); }, }, ]; const { name, neptun } = await inquirer.prompt(questions); // Nyilatkozat kitöltése await fs.writeFile( "./statement.txt", statementTemplate .replace("{NAME}", name) .replace("{NEPTUN}", neptun) .replace("{SUBJECT}", config.subject) .replace("{TASK}", config.task) .replace("{DATE}", date.format(currentDate, "YYYY. MM. DD. HH:mm:ss")) ); console.log( colors.green( `>> A nyilatkozat (${colors.yellow("statement.txt")}) sikeresen ki lett töltve ${colors.yellow(name)} névre és ${colors.yellow( neptun )} Neptun kódra.` ) ); console.log(" "); return { name, neptun }; }; const handleZipping = async ({ name, neptun }) => { // zipfiles mappa elkészítése, ha még nem létezik try { await fs.mkdir("zipfiles"); } catch (e) {} // Fájlok listájának előállítása, majd az alapján becsomagolás process.stdout.write(" 1. Fájlok összegyűjtése... "); const files = await collectFiles(); console.log(colors.green("OK.")); console.log(" 2. Fájlok becsomagolása..."); await zipFiles(files, { name, neptun }); }; (async () => { try { console.log("1. lépés: Nyilatkozat".bgGray.black); console.log(" "); const { name, neptun } = await handleStatement(); console.log("2. lépés: Fájlok becsomagolása".bgGray.black); console.log(" "); await handleZipping({ name, neptun }); // Tudnivalók megjelenítése console.log(" "); console.log(colors.yellow(" * A feladatot a Canvas rendszeren keresztül kell beadni a határidő lejárta előtt.")); console.log(" "); console.log(colors.yellow(" * Az időkeret utolsó 15 percét a beadás nyugodt és helyes elvégzésére adjuk.")); console.log(colors.yellow(" * A feladat megfelelő, hiánytalan beadása a hallgató felelőssége!")); console.log(colors.yellow(" * Utólagos reklamációra nincs lehetőség! Mindenképp ellenőrizd a .zip fájlt, mielőtt beadod!")); } catch (e) { if (e.message === "StatementDenied") { return; } throw e; } })(); <file_sep>require('./bootstrap'); require('alpinejs'); require('./colorpicker'); <file_sep>require("dotenv").config(); const { createServer } = require("http"); const { Server } = require("socket.io"); const { instrument } = require("@socket.io/admin-ui"); let { db, events } = require("./events"); const AutoTester = require("./test/inject"); const httpServer = createServer(); const io = new Server(httpServer, { // Más erőforrásokból is el tudjuk érni a szervert, pl. ilyen a Sockcket.IO admin felülete, // ami ezen a domainen fut: admin.socket.io, de a localhost-on futó szerverünkre akarunk onnan // kapcsolódni cors: { origin: ["*"], credentials: true, }, // Ez a beállítás lehetővé teszi a szerver elérését olyan kliensekkel is, amelyek csak a Socket.IO 2-es // verzióját támogatják (pl. Firecamp). allowEIO3: true, }); // Inicializáljuk az admin felülethez szükséges szerveroldali logikát, és azon belül is // kikapcsoljuk a hitelesítést instrument(io, { auth: false, }); // Az events megkapja az io referenciát events(io); // Automata tesztelő eseménykezelőjének hozzáadása // FONTOS! Erre szükség van, hogy az automata tesztelő megfelelően tudja kezelni a végpontokat! AutoTester.handleSocketIO(io, db); // Elindítjuk a sima Node.js HTTP szervert, amin a Socket.io is fut const port = process.env.PORT || 3000; httpServer.listen(port, () => { console.log(`A Socket.IO szervere fut, ezen a porton: ${port}`); // FONTOS! Erre szükség van, hogy az automata tesztelő megfelelően tudjon inicializálni! AutoTester.handleStart(); }); <file_sep><?php namespace Database\Seeders; use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; use App\Models\User; use App\Models\Category; use App\Models\Post; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { /*$this->call(CategorySeeder::class); $this->call(PostSeeder::class);*/ // \App\Models\User::factory(10)->create(); DB::table('users')->truncate(); DB::table('categories')->truncate(); DB::table('posts')->truncate(); $users = collect(); $users_count = rand(5, 10); for ($i = 1; $i <= $users_count; $i++) { $users->add( User::factory()->create([ 'name' => 'user'.$i, 'email' => '<EMAIL>', ]) ); } $categories = Category::factory(rand(7, 14))->create(); $posts = Post::factory(rand(20, 40))->create(); // Kapcsolatok létrehozása a fent létrehozott modellek között $posts->each(function ($post) use ($users, $categories) { // 1. Szerzőt kell rendelni a bejegyzéshez if ($users->isNotEmpty()) { $post->author()->associate($users->random()); $post->save(); } // 2. Kategóriákat kell rendelni a bejegyzéshez if ($categories->isNotEmpty()) { $post->categories()->sync( $categories ->random( rand(1, $categories->count()) ) ->pluck('id') ->toArray() ); } }); } } <file_sep>const express = require("express"); const router = express.Router(); const models = require("../models"); const { Game, Genre } = models; // localhost:4000/genres router.get("/", async (req, res) => { const genres = await Genre.findAll({ include: [{ model: Game, attributes: ["id", "title"], through: { attributes: [] } }], }); res.send(genres); }); module.exports = router; <file_sep>const express = require("express"); const router = express.Router(); const models = require("../models"); const { Rating, Genre, Movie, sequelize } = models; const auth = require("../middlewares/auth"); // Összes film lekérése, a hozzájuk tartozó kategóriákkal együtt, átlagos értékelés szerint csökkenő sorrendbe rendezve router.get("/", async function (req, res) { const movies = await Movie.findAll({ attributes: { include: [[sequelize.fn("AVG", sequelize.col("Ratings.rating")), "avgRating"]], }, include: [ { model: Genre, attributes: { exclude: ["createdAt", "updatedAt"], }, through: { attributes: [] }, }, { model: Rating, attributes: [], //attributes: { // exclude: ['createdAt', 'updatedAt'] //}, }, ], group: ["movie.id", "Genres.id"], order: sequelize.literal("avgRating DESC"), }); res.send(movies); }); // POST localhost:3000/movies/:id/rate router.post("/:id/rate", auth, async function (req, res) { const { id } = req.params; if (isNaN(parseInt(id))) { // NaN - isNaN return res.status(400).send({ message: "A megadott ID nem szám!" }); } const movie = await Movie.findByPk(id); if (movie === null) { return res.status(404).send({ message: "A megadott ID-vel nem létezik film!" }); } // A filmhez engedélyezve vannak-e az értékelések? if (movie.ratingsEnabled !== true) { return res.status(403).send({ message: "A megadott filmhez nincsenek engedélyezve az értékelések!" }); } // Ha van ilyen értékelés, akkor a user korábban már értékelte ezt a filmet let rating = await Rating.findOne({ where: { UserId: req.user.id, MovieId: id } }); if (rating) { // A meglévő értékelést kell módosítani await rating.update(req.body); return res.status(200).send({ message: "Sikeresen módosítottad a korábbi értékelésedet!", rating }); } else { // Új értékelést hozunk létre rating = await Rating.create({ UserId: req.user.id, MovieId: id, ...req.body }); return res.status(201).send({ message: "Sikeresen értékelted ezt a filmet!", rating }); } }); router.delete("/:id/rate", auth, async function (req, res) { const { id } = req.params; if (isNaN(parseInt(id))) { // NaN - isNaN return res.status(400).send({ message: "A megadott ID nem szám!" }); } const movie = await Movie.findByPk(id); if (movie === null) { return res.status(404).send({ message: "A megadott ID-vel nem létezik film!" }); } // A filmhez engedélyezve vannak-e az értékelések? if (movie.ratingsEnabled !== true) { return res.status(403).send({ message: "A megadott filmhez nincsenek engedélyezve az értékelések!" }); } // Ha van ilyen értékelés, akkor a user korábban már értékelte ezt a filmet const rating = await Rating.findOne({ where: { UserId: req.user.id, MovieId: id } }); if (rating) { // Ha van értékelés, akkor törölni kell await rating.destroy(); return res.status(200).send({ message: "Sikeresen törölted az értékelésedet!" }); } else { return res.status(404).send({ message: "Te még nem értékelted ezt a filmet, nincs mit törölni!" }); } }); module.exports = router; <file_sep># Szerveroldali webprogramozás zh -- GRAPHQL + Websocket _2021. május 21._ ## Tudnivalók - Kommunikáció - **A Teams csoport Általános csatornáján lehetőleg lépj be a meetingbe, ami a ZH egész ideje alatt tart! Elsősorban ebben a meetingben válaszolunk a felmerülő kérdésekre, valamint az esetleges időközbeni javításokat is itt osztjuk meg!** - Ha a zárthelyi közben valamilyen problémád, kérdésed adódik, akkor keresd az oktatókat Teams chaten vagy a meetingben. - Időkeret - **A zárthelyi megoldására 2 óra áll rendelkezésre: _16:00-18:00_** - Oszd be az idődet! Ha egy feladat nagyon nem megy, akkor inkább ugord át (legfeljebb később visszatérsz rá), és foglalkozz a többivel, hogy ne veszíts pontot olyan feladatból, amit meg tudnál csinálni! - Beadás - **A beadásra további _15_ perc áll rendelkezésre: _18:00-18:15_. Ez a +15 perc _ténylegesen_ a beadásra van! _18:15_ után a Canvas lezár, és további beadásra nincs lehetőség!** - Ha előbb végzel, természetesen 16:00-tól 18:15-ig bármikor beadhatod a feladatot. - A feladatokat `node_modules` mappák nélkül kell becsomagolni egy .zip fájlba, amit a Canvas rendszerbe kell feltölteni! - Értékelés: - A legutoljára beadott megoldás lesz értékelve. - **A zárthelyin legalább a pontok 40%-át, vagyis legalább 12 pontot kell elérni**, ez alatt a zárthelyi sikertelen. - Vannak részpontok. - A pótzárthelyin nem lehet rontani a zárthelyi eredményéhez képest, csak javítani. - **Érvényes nyilatkozat (megfelelően kitöltött statement.txt) hiányában a kapott értékelés érvénytelen, vagyis 0 pont.** - Az elrontott, elfelejtett nyilatkozat utólag pótolható: Canvasen kommentben kell odaírni a feladathoz. - Egyéb: - A feladatokat JavaScript nyelven, Node.js környezetben kell megoldani! - **Minden feladat külön mappába kerüljön!** - Ha kell, akkor további csomagok telepíthetőek, de ezeket a `package.json` fájlban fel kell tüntetni! - Ellenőrzéskor a gyakorlatvezetők az alábbi parancsokat adják ki a feladatonkénti mappákban: ``` # Csomagok telepítése: npm install # Friss adatbázis létrehozása: npm run freshdb # Fejlesztői verzió futtatása: npm run dev ``` - Ellenőrzéshez és teszteléshez a Node.js _14.x_, az npm _7.x_, és a Firecamp _1.4.x_ verzióját fogjuk használni. ## Hasznos linkek - Dokumentációk - [GraphQL dokumentáció](https://graphql.org/learn/) - [Socket.IO dokumentáció](https://socket.io/docs/v4/server-api/) - [ExpressJS dokumentáció](https://expressjs.com/en/4x/api.html) - [Sequelize dokumentáció](https://sequelize.org/master/) - [Firecamp Chrome kiegészítő](https://chrome.google.com/webstore/detail/firecamp-a-campsite-for-d/eajaahbjpnhghjcdaclbkeamlkepinbl) - [DB Browser for SQLite](https://sqlitebrowser.org/) ## Tartalomjegyzék - [Szerveroldali webprogramozás zh -- GRAPHQL + Websocket](#szerveroldali-webprogramozás-zh----graphql + websocket) - [Tudnivalók](#tudnivalók) - [Hasznos linkek](#hasznos-linkek) - [Tartalomjegyzék](#tartalomjegyzék) - [Kezdőcsomag](#kezdőcsomag) - [Feladatsor](#feladatsor) ## Kezdőcsomag Segítségképpen készítettünk egy kezdőcsomagot a zárthelyi elkészítéséhez. Csak telepíteni kell a csomagokat, és kezdheted is a fejlesztést. - A kezdőcsomag az Általános csatornán folyó beszélgetésben érhető el. - **A kezdőcsomag tartalmaz egy nyilatkozatot (statement.txt), amelyben a <NÉV> és a <NEPTUN> részeket helyettesítsd be a saját neveddel és Neptun kódoddal! Ha beadod a feladatot, azzal elfogadod és magadra nézve kötelezőnek tekinted a nyilatkozatot.** ## GraphQL - Feladatok megoldása és értékelése - A szerver a 4000-es porton fusson! - Adott az alábbi GraphQL séma. Készíts GraphQL szervert Node.js-ben, amelyben implementálod a szükséges műveleteket. A boltokat (Shop), árucikkeket (Item), raktárakat (Warehouse) és beszállítókat (Carrier) lokális SQLite adatbázisban kell tárolni. Legyen elérhető a GraphiQL felület, amelyen keresztül tesztelhető a séma implementációja, pl. Apollo szerver esetén http://localhost:4000, express-graphql esetén http://localhost:4000/graphql. ```js scalar Date type Shop { id: ID! name: String! city: String! createdAt: Date! updatedAt: Date! } type Item { id: ID! name: String! price: Int! createdAt: Date! updatedAt: Date! } type Warehouse { id: ID! name: String! city: String! capacity: Int! carriers: [Carrier] createdAt: Date! updatedAt: Date! } type Carrier { id: ID! name: String! numberOfCars: Int! carCapacity: Int! createdAt: Date! updatedAt: Date! } ``` - Hozd létre az adatbázist, töltsd fel néhány adattal. - Oldd meg a következő feladatokat: - `warehouses`: összes raktár lekérése, a hozzá tartozó szállítókkal együtt **(2 pont)** - Kérés: ```js query { warehouses { id name city capacity createdAt updatedAt carriers { id name numberOfCars carCapacity createdAt updatedAt } } } ``` - Válasz: a raktárakhoz kapcsolt szállítókat listázni kell a példán látható módon ```json { "data": { "warehouses": [ { "id": 1, "name": "AmazInG", "city": "Lafabel", "capacity": 280, "createdAt": "2021-01-11...", "updatedAt": "2021-01-11...", "carriers": [ { "id": 1, "name": "Sétálár", "numberOfCars": 2, "carCapacity": 15, "createdAt": "2021-01-11...", "updatedAt": "2021-01-11..." }, { "id": 2, "name": "Rohanár", "numberOfCars": 5, "carCapacity": 30, "createdAt": "2021-01-11...", "updatedAt": "2021-01-11..." } ] }, { "id": 1, "name": "Ezbaj", "city": "Ibst", "capacity": 150, "createdAt": "2021-01-11...", "updatedAt": "2021-01-11...", "Carriers": [ { "id": 2, "name": "Rohanár", "numberOfCars": 5, "carCapacity": 30, "createdAt": "2021-01-11...", "updatedAt": "2021-01-11..." } ] } ] } } ``` - `updateWarehouse(data)`: egy raktár módosítása. Itt a data azokra a kulcs-érték párosokra utal, amit módosítani szeretnénk. Ennek kötelezően tartalmaznia kell az id-t is **(2 pont)** - Kérés ```js mutation { updateWarehouse(data: { id: 9, city: "Pheuhpolia", capacity: 50 }) { id name city capacity updatedAt createdAt } } ``` - Válasz ```json "data": { "updateWarehouse": { "id": 9, "name": "Holház", "city": "Pheuhpolia", "capacity": 50, "updatedAt": "2021-01-11...", "createdAt": "2021-01-11..." } } ``` - `shop(id)`: Egy bolt lekérdezése (erre még nem jár pont). Egészítsd ki egy olyan mezővel, ami visszaadja a hozzá tartozó olyan raktárakat, amik neve magánhangzóval kezdődik, és az azokhoz tartozó szállítókkal. **(2 pont)** - Kérés: ```js query { shop(id: 1) { warehousesStartingWithVowel { id name city capacity createdAt updatedAt carriers { id name numberOfCars carCapacity createdAt updatedAt } } } } ``` - Válasz: ```json { "data": { "shop": { "warehousesStartingWithVowel": [ { "id": "8", "name": "<NAME>", "city": "New Yoshiko", "capacity": 73669, "createdAt": "2021-05-16T17:51:45.071Z", "updatedAt": "2021-05-16T17:51:45.071Z", "carriers": [ { "id": "1", "name": "Turcotte - Bartoletti", "numberOfCars": 51442, "carCapacity": 14173, "createdAt": "2021-05-16T17:51:43.472Z", "updatedAt": "2021-05-16T17:51:47.630Z" } ] } ] } } } ``` - Segítség: a magánhangzók tömbje: `['a', 'e', 'i', 'o', 'u']` - `cheapestItem`: visszaadja az adatbázisban tárolt legolcsóbb terméket és az összes olyan raktárat, ahol lehetséges hogy megtalálható. **(2 pont)** - Kérés: ```js query { cheapestItem { id name price createdAt updatedAt shop { warehouses { id name city capacity createdAt updatedAt } } } } ``` - Válasz: ```json { "data": { "cheapestItem": { "id": "10", "name": "<NAME>", "price": 5119, "createdAt": "2021-05-16T17:51:43.104Z", "updatedAt": "2021-05-16T17:51:45.981Z", "shop": null } } } ``` - `refillShelves(id, items)`: egy megadott bolthoz rendel hozzá árucikkeket. Fontos, hogy az új árucikkek nem adódnak hozzá a már meglévőekhez, hanem a lekérés után csak ezek fognak a bolthoz tartozni. **(3 pont)** - Kérés: ```js mutation { refillShelves(id: 1, items: [ { name: "Víz", price: 100 } ]) { name city createdAt updatedAt items { id name price createdAt updatedAt } } } ``` - Válasz: A bolt objektum legyen, a hozzá tartozó árucikkekkel. ```json { "data": { "refillShelves": { "name": "<NAME>", "city": "Amarillo", "createdAt": "2021-05-16T13:17:56.013Z", "updatedAt": "2021-05-16T13:17:56.013Z", "items": [ { "id": "13", "name": "Víz", "price": 100, "createdAt": "2021-05-16T15:25:38.600Z", "updatedAt": "2021-05-16T15:25:38.787Z" } ] } } } ``` - `fireCarriers(warehouseId)`: Meghívása után minden olyan beszállító, ahol az autók száma _ autók kapacitása nem éri el a raktár kapacitásának felét, törölni kell a raktárból. Vagyis, ha `Carrier.numberOfCars _ Carrier.carCapacity < Warehouse.capacity / 2`, akkor a Carrier-ből törölni kell a hozzá tartozó warehouseId-t. **(5 pont)** - Kérés ```js mutation { fireCarriers(warehouseId: 1) { fired { id name numberOfCars carCapacity createdAt updatedAt } remainders { id name numberOfCars carCapacity createdAt updatedAt } } } ``` - Válasz ```json { "data": { "fireCarriers": { "fired": [ { "id": 1, "name": "Sétálár", "numberOfCars": 2, "carCapacity": 15, "createdAt": "2021-01-11...", "updatedAt": "2021-01-13..." } ], "remainders": [ { "id": 2, "name": "Rohanár", "numberOfCars": 5, "carCapacity": 30, "createdAt": "2021-01-11...", "updatedAt": "2021-01-13..." } ] } } } ``` - `statistics(shopId)`: egy boltban lévő árucikkekből készít statisztikát. **(4 pont)** - Kérés: ```js query { statistics(shopId: 1) { count max min average oddSumTenPercent } } ``` - Válasz: le kell kérni a bolthoz aktuálisan tartozó statisztikákat, A statisztika a következő mezőkből áll: árucikkek darabszáma (mennyi item tartozik a shop-hoz), legmagasabb árú termék ára, legalacsonyabb árú termék ára, a boltban lévő termékek átlagára, minden páratlan árú termék összegének 10%-a. Az alább példa szerint kell visszaadni a statisztikát: ```json { "data": { "statistics": { "count": 13, "max": 200, "min": 15, "average": 123.64, "oddSumTenPercent": 2.4 } } } ``` ## Websocket - Feladatok megoldása és értékelése (10 pont) Az alábbi egyszerű folyamat során a tanár feladatokat hirdet meg egy eseményhez, majd a diák megoldásokat küld be a feladatokhoz. A tanár értesülni szeretne, ha egy megoldás érkezik, a diák pedig arról kaphat értesítést, ha a megoldása ki lett értékelve. A megvalósítás során a felhasználókat a socket azonosítójukkal azonosítjuk (ami azt is jelenti, hogy ha újrakapcsolódnak, akkor az másik felhasználót jelent). A tanár és diák úgy van megkülönböztetve, hogy az eseményeknél elmentjük a létrehozó socketid-ját az eseményhez, a diák socketid-ját pedig a megoldáshoz mentjük el. Az adatokat lokális SQLite adatbázisban kell tárolni. A szükséges modelleket a keretrendszer tartalmazza. A feladatban három modell van: egy eseményhez több feladat tartozik, egy feladathoz több megoldás (Event 1-N Feladat 1-N Solution). - Event - id - name - uuid - socketid - createdAt - updatedAt - Task - id - description - eventId - createdAt - updatedAt - Solution - id - solution - evaluation - socketid - taskId - createdAt - updatedAt Egy tipikus folyamat a következő: 1. A tanár létrehozza az eseményt a feladatokkal (`create-event`), megkapja az esemény uuid-ját. 2. A diák valahogyan értesül a uuid-ról, és kapcsolódik az eseményhez (`join-event`) a uuid-val, és megkapja a feladatokat. 3. A diák megold egy feladatot, beküldi azt azonosítóval és megoldással (`send-solution`). 4. A tanár értesül a megoldásról (`solution-sent`), megkapja a megoldást, a feladatot és az eseményt 5. A tanár beküldi a megoldáshoz tartozó értékelést (`send-evaluation`) 6. A diák értesül az értékelésről (`evaluation-sent`), megkapja a megoldás objektumot. A következő üzenetek legyenek: - Kliens -> szerver - `create-event`: Esemény létrehozása. A létrehozó lesz a tanár. Fel kell küldeni az esemény nevét, és a feladatokat. Az eseményt el kell menteni a létrehozó socketid-jával. A feladatokat létre kell hozni a táblában és az eseményhez kell kapcsolni őket. Az esemény uuid-jával térünk vissza. **(2 pont)** - Paraméterek: 1. esemény neve 2. feladatok tömbje, pl. `[{"description": "task1"}, {"description": "task2"}]` - Válasz - Helyes: `{ status: 'ok', uuid: <uuid> }` - Hibás: `{ status: 'error', message: <hibaüzenet> }` - `join-event`: Csatlakozás eseményhez. A kapcsolódó megad egy uuid-t, és visszakapja a kapcsolódó esemény és feladatok részleteit. **(2 pont)** - Paraméterek: 1. uuid - Válasz - Helyes: `{ status: 'ok', event: <event>, tasks: [<task>] }` - Hibás: `{ status: 'error', message: <hibaüzenet> }` - `send-solution`: Megoldás küldése egy feladathoz. Meg kell adni egy feladatazonosítót (`taskId`) és egy megoldást szövegként. A `Solutions` táblába fel kell venni egy új rekordot a megoldással és a megoldó socketid-jával. A megfelelő feladathoz kell kapcsolni. A művelet hatására `solution-sent` üzenetet kell küldeni a megoldáshoz tartozó feladathoz tartozó eseményben tárolt socketid-ra az esemény, feladat és megoldás adataival. **(1 pont)** - Paraméterek: 1. taskId 2. megoldás szövege - Válasz - Helyes: `{ status: 'ok' }` - Hibás: `{ status: 'error', message: <hibaüzenet> }` - `send-evaluation`: Értékelés küldése egy megoldáshoz. Meg kell adni egy megoldásazonosítót (`solutionId`) és egy értékelést szövegként. A `Solutions` táblában az adott rekordhoz menteni kell az értékelést. A művelet hatására `evaluation-sent` üzenetet kell küldeni a megoldáshoz tartozó socketid-ra a megoldás adataival. **(2 pont)** - Paraméterek: 1. solutionId 2. értékelés szövege - Válasz - Helyes: `{ status: 'ok' }` - Hibás: `{ status: 'error', message: <hibaüzenet> }` - Szerver -> kliens - `solution-sent`: A diák megoldást adott be. A tanár értesül a megoldásról, a feladatról és az eseményről. **(2 pont)** ```js { event: {...}, task: {...}, solution: {...} } ``` - `evaluation-sent`: A tanár értékelést adott be. A diák értesül a megoldásról. **(1 pont)** ```js { solution: {...} } ``` <file_sep>## 3. feladat: Websocket - Tőzsde (10 pont) Socket.io segítségével készíts Websocket szervert, amely egy képzeletbeli tőzsde értékpapírjairól közöl valósidejű adatokat. A tőzsde pár előre megadott, beégetett értékpapírt tart nyilván. Mindegyiknek van egy kezdő értéke, és időről időre ezek közül véletlenszerűen valamelyik megváltozik ugyancsak egy véletlen értékkel. A kliensek le tudják kérni a szervertől, hogy milyen értékpapírokat tart nyilván, majd fel tudnak íratkozni értékpapírcsatornákra. Ilyenkor minden változásról automatikusan értesülnek. A feliratkozást meg is lehet szüntetni. A kliensek historikus adatokat is le tudnak kérni egy-egy értékpapírról. Egy értékpapír csatornájában egy kliens ajánlatot küldhet a többi csatornabeli kliensnek. Ekkor a szerver egy azonosítóval látja el az ajánlatot, majd elküldi a többieknek. Ha valamelyik kliens él az ajánlattal, akkor az ajánlatazonosítóval elfogadhatja, és erről az ajánlattevő és -fogadó is értesül. Szerveren használjuk a `setTimeout`-ot az értékpapír árfolyamának mozgatásához, pl. 1s-onként valamelyik értékpapír ára változzon! A klienseket a socket azonosítójukkal azonosítjuk. Az adatokat a szerver memóriájában tároljuk, nem kell adatbázis! Például az alábbi adatszerkezet használható az értékpapírok tárolására, de más is, ha van kényelmesebb: ```js const securities = { 'ELTE': { prices: [ {timestamp: 1610110943147, price: 1234}, {timestamp: 1610110969348, price: 1255}, {timestamp: 1610110976805, price: 1340}, ], offers: [ {clientId: 'client1', quantity: 0.65, intent: 'sell', active: true}, {clientId: 'client3', quantity: 2.0, intent: 'buy', active: false}, ] } 'TESLA': { // ... }, 'RICHTER': { // ... }, // ... } ``` A következő üzenetek legyenek: - **Kliens -> szerver** - `list-securities`: Ezzel kérdezhetjük le a szerverről, hogy milyen értékpapírokat tart nyilván. Hibát nem kell kezelni. (1 pont) - Paraméterek: nincs - Válasz (acknowledgement) ``` { status: 'ok', securities: ['ELTE', 'TESLA', ...] } ``` - `get-historic-data`: Egy adott értékpapírhoz tartozó előzményadatok lekérdezése. Paraméterként lehet megadni az értékpapír nevét, valamint az előzményadatok számát. Ha nincs ilyen értékpapír, vagy a szám nem szám vagy kisebb mint 0, akkor hibaüzenetet kapunk. (1 pont) - Paraméterek: - értékpapír azonosítója/neve, pl. `ELTE` - előzményadatok száma, pl. 7 - Válasz (acknowledgement) - Helyes: ```js { status: 'ok', prices: [ {timestamp: 1610110943147, price: 1234}, {timestamp: 1610110969348, price: 1255}, {timestamp: 1610110976805, price: 1340}, ]} ``` - Hibás: `{ status: 'error', message: <hibaüzenet>}` - `join-security`: Ezzel iratkozhatunk fel egy értékpapír csoportjába. Ha már feliratkoztunk, akkor az hibaüzenetként jelenik meg. Hiba az is, ha nem létező értékpapírnevet adunk meg. (1 pont) - Paraméterek: értékpapír azonosítója/neve, pl. `ELTE`. - Válasz (acknowledgement) - Helyes: `{ status: 'ok'}` - Hibás: `{ status: 'error', message: 'No such security in our system.'}` - Hibás: `{ status: 'error', message: 'You are already subscribed to this security.'}` - `leave-security`: Ezzel iratkozhatunk le egy értékpapír csoportjáról. Ha eleve nem figyeljük, akkor az hibaüzenetként jelenik meg. Hiba az is, ha nem létező értékpapírnevet adunk meg. (1 pont) - Paraméterek: értékpapír azonosítója/neve, pl. `ELTE`. - Válasz (acknowledgement) - Helyes: `{ status: 'ok'}` - Hibás: `{ status: 'error', message: 'No such security in our system.'}` - Hibás: `{ status: 'error', message: 'You do not follow this security.'}` - `send-offer`: Ajánlat küldése egy feliratkozott értékpapírhoz. Hiba, ha rossz értékpapírnevet adtunk meg, vagy nem vagyunk feliratkozva az értékpapírra. A szerver rendel hozzá egy azonosítót (ez lehet a tömbindex is), elmenti, majd a csoportba tartozó többi kliensnek `offer-sent` üzenetet kell küldeni az ajánlat adataival. (1 pont) - Paraméterek: - értékpapír azonosítója/neve, pl. `ELTE` - mennyiség, pl. 0.65 - szándék: `'buy'`/`'sell'` - Válasz (acknowledgement) - Helyes: `{ status: 'ok'}` - Hibás: `{ status: 'error', message: <hibaüzenet>}` - `accept-offer`: Az ajánlat elfogadása. Meg kell adni az ajánlat azonosítóját, a szerver az ajánlatot inaktívvá teszi (`active` flag beállításával), majd mindkét érintett kliensnek `offer-accepted` üzenetet küld. Hiba akkor van, ha nincs olyan értékpapír, illetve azon belül nincs olyan ajánlatazonosító. (1 pont) - Paraméterek: - értékpapír azonosítója/neve, pl. `ELTE` - ajánlatazonosító, pl. 2 - Válasz (acknowledgement) - Helyes: `{ status: 'ok'}` - Hibás: `{ status: 'error', message: <hibaüzenet>}` - **Szerver -> kliens** - `price-changed`: Akkor kapunk ilyen hibaüzenetet, ha egy figyelt értékpapír ára változik. Mindenki megkapja az értékpapír csoportjában. (2 pont) ```js { security: 'ELTE', price: 1635 } ``` - `offer-sent`: ha valaki egy értékpapírcsoportban ajánlatot tesz, akkor a többi csoporttag ilyen üzenetet kap. (1 pont) ```js { id: 2, security: 'ELTE', quantity: 0.65, intent: 'sell' } ``` - `offer-accepted`: Ha egy ajánlat elfogadásra kerül, akkor mind az ajánlattevő, mind a -fogadó ilyen üzenetet kap. (1 pont) ```js { id: 2, security: 'ELTE', quantity: 0.65, intent: 'sell' } ```<file_sep>const { createServer } = require("http"); const { Server } = require("socket.io"); const { instrument } = require("@socket.io/admin-ui"); const events = require('./events'); const httpServer = createServer(); const io = new Server(httpServer, { // Más erőforrásokból is el tudjuk érni a szervert, pl. ilyen a Sockcket.IO admin felülete, // ami ezen a domainen fut: admin.socket.io, de a localhost-on futó szerverünkre akarunk onnan // kapcsolódni cors: { origin: ["*"], credentials: true }, // Ennek az a lényege, hogy lehetővé teszi azt, hogy olyan kliensekkel is tudjunk a szerverhez // kapcsolódni, amelyek csak a Socket.IO 2-es verzióját támogatják (pl Firecamp) allowEIO3: true }); // Inicializáljuk az admin felülethez szükséges szerveroldali logikát, és azon belül is // kikapcsoljuk a hitelesítést instrument(io, { auth: false }); // Az events megkapja az io referenciát events(io); // Elindítjuk a sima kis Node.js http szervert, amin a Socket.io is fut httpServer.listen(3000, () => { console.log("A Socket.IO szervere fut"); });<file_sep>## 3. feladat: Websocket - Egyszámjáték (10 pont) Socket.io segítségével készíts Websocket szervert, amelyen keresztül a kapcsolódó klienseknek lehetőségük van egyszámjátékot játékot játszani! Ennek során a szerver időről időre indít egy új játékot. Minden játékban minden egyes kliensnek lehetősége van egy szám tippelésére. Az adott játékban az nyer, akinek a tippje a legkisebb olyan szám, amire mások nem szavaztak. Minden játékban egy adott ideig van nyitva, eddig lehet gyűjteni a tippeket, majd az idő lejártával a szerver mindenkit értesít, hogy győzött-e vagy vesztett, majd egy új játékot nyit. Ez egy szerveroldali folyamat, a klienseknek erre nincsen ráhatása. Szerveren használjuk a `setTimeout`-ot az időzítéshez! Minden kliens csak egyszer tippelhet egy adott játékban. A klienseket a socket azonosítójukkal azonosítjuk. A játékokat a szerver memóriájában tároljuk, nem kell adatbázis! Például az alábbi adatszerkezet használható, ahol a játékokat egy tömbben tároljuk, mindig az utolsó az aktív, és minden játéknál tároljuk, hogy melyik kliens milyen számra tippelt. ```js games = [ { startTime: 123456789, tips: [ { "client": "socketid1", "number": 12 }, { "client": "socketid2", "number": 1 }, { "client": "socketid3", "number": 1 }, { "client": "socketid4", "number": 2 }, { "client": "socketid5", "number": 12 }, ] } ] ``` A következő üzenetek legyenek: - Kliens -> szerver - `tip`: Tippelés, értéke a tippelt szám. Hiba akkor van, ha már tippeltünk az adott játékban, vagy ha nem számot küldtünk fel. **(4 pont)** - Paraméterek: tippelt szám - Válasz - Helyes: `{ status: 'ok' }` - Hibás: `{ status: 'error', message: <hibaüzenet> }` - Szerver -> kliens - `new-game-started`: Ha új játék kezdődik, akkor kapunk ilyen üzenetet. Adata nincs. **(1 pont)** - `game-over`: A játék végén generálódik automatikusan. Minden tippelő kliensnek elküldi, hogy nyert-e vagy sem. Elküldi az adott kliens által tippelt és a győztes számot is. **(5 pont)** ```js { won: false, tipped: 12, winner: 2 } ```<file_sep># Szerveroldali webprogramozás - REST API pótzárthelyi _2022. január 10. 16:00-19:15 (3 óra kidolgozás + 15 perc beadás)_ Tartalom: - [Szerveroldali webprogramozás - REST API pótzárthelyi](#szerveroldali-webprogramozás---rest-api-pótzárthelyi) - [Tudnivalók](#tudnivalók) - [Hasznos linkek](#hasznos-linkek) - [Kezdőcsomag](#kezdőcsomag) - [Feladatok](#feladatok) - [`1. feladat: Modellek és relációk (2 pont)`](#1-feladat-modellek-és-relációk-2-pont) - [`2. feladat: Seeder (2 pont)`](#2-feladat-seeder-2-pont) - [`3. feladat: GET /posts (2 pont)`](#3-feladat-get-posts-2-pont) - [`4. feladat: GET /posts/:id (2 pont)`](#4-feladat-get-postsid-2-pont) - [`5. feladat: POST /auth/login (2 pont)`](#5-feladat-post-authlogin-2-pont) - [`6. feladat: POST /posts (2 pont)`](#6-feladat-post-posts-2-pont) - [`7. feladat: PUT /posts (2 pont)`](#7-feladat-put-posts-2-pont) - [`8. feladat: DELETE /posts (2 pont)`](#8-feladat-delete-posts-2-pont) - [`9. feladat: POST /posts/:id/comments (2 pont)`](#9-feladat-post-postsidcomments-2-pont) - [`10. feladat: PUT /comments/:id (2 pont)`](#10-feladat-put-commentsid-2-pont) - [`11. feladat: GET /comments/:id/history (2 pont)`](#11-feladat-get-commentsidhistory-2-pont) - [`12. feladat: GET /comments/:id/reactions (3 pont)`](#12-feladat-get-commentsidreactions-3-pont) - [`13. feladat: POST /comments/:id/reaction (3 pont)`](#13-feladat-post-commentsidreaction-3-pont) - [`14. feladat: DELETE /comments/:id/reaction (2 pont)`](#14-feladat-delete-commentsidreaction-2-pont) ## Tudnivalók - Kommunikáció - **A Teams csoport Általános csatornáján a zárthelyi egész ideje alatt lesz egy meeting! Erősen ajánlott, hogy ehhez csatlakozzatok, hiszen elsősorban ebben a meetingben válaszolunk a felmerülő kérdésekre, valamint az esetleges időközben felmerülő információkat is itt osztjuk meg veletek!** - Ha a zárthelyi közben valamilyen problémád, kérdésed adódik, akkor keresd az oktatókat a meetingben vagy privát üzenetben (Teams chaten). - Időkeret - **A zárthelyi megoldására 3 óra áll rendelkezésre: *16:00-19:00*.** - Oszd be az idődet! Ha egy feladat nem megy, akkor inkább ugord át (legfeljebb később visszatérsz rá), és foglalkozz a többivel, hogy ne veszíts pontot olyan feladatból, amit meg tudnál csinálni! - Beadás - **A beadásra további *15* perc áll rendelkezésre: *19:00-19:15*. Ez a +15 perc *ténylegesen* a beadásra van! *19:15* után a Canvas lezár, és további beadásra nincs lehetőség!** - Ha előbb végzel, természetesen 19:15-ig bármikor beadhatod a feladatot. - A feladatokat `node_modules` mappa nélkül kell becsomagolni egy .zip fájlba, amit a Canvas rendszerbe kell feltölteni! - **A dolgozat megfelelő és hiánytalan beadása a hallgató felelőssége.** Mivel a dolgozat végén külön 15 perces időkeretet adunk a feladat megfelelő, nyugodt körülmények közötti beadására, ebből kifolyólag ilyen ügyekben nem tudunk utólagos reklamációknak helyt adni. Tehát ha valaki a zárthelyi után jelzi, hogy egy vagy több fájlt nem adott be, akkor azt sajnos nem tudjuk elfogadni. - Értékelés - A legutoljára beadott megoldás lesz értékelve. - **A zárthelyin legalább a pontok 40%-át, vagyis legalább 12 pontot kell elérni**, ez alatt a zárthelyi sikertelen. - Vannak részpontok. - **A pótzárthelyin nem lehet rontani a zárthelyi eredményéhez képest, csak javítani.** Ez azt jelenti, ha valaki egy adott témakörből (pl. REST API) megírja mindkét zárthelyit (a normált és a pótot is), akkor a jegyébe a kettő közül a jobbik eredményt fogjuk beszámítani. Azonban fontos, hogy ez a "jobbik eredmény" **legalább** 40%, vagyis 12 pont legyen, különben az illető nem teljesítette a tárgyat! - **Érvényes nyilatkozat (megfelelően kitöltött statement.txt) hiányában a kapott értékelés érvénytelen, vagyis 0 pont.** - Az elrontott, elfelejtett nyilatkozat utólag pótolható: Canvasen kommentben kell odaírni a feladathoz. - Egyéb - A feladatokat Node.js környezetben, JavaScript nyelven kell megoldani, a tantárgy keretein belül tanult technológiák használatával! - Ajánlott a Node.js LTS verziójának a használata. Ha a gépedre már telepítve van a Node.js és telepített példány legalább 2 főverzióval le van maradva az aktuálisan letölthető legfrissebbhez képest, akkor érdemes lehet frissíteni. ## Hasznos linkek - Dokumentációk - Sequelize: - [Sequelize dokumentáció](https://sequelize.org/master/) - [Model querying basics](https://sequelize.org/master/manual/model-querying-basics.html) - [Sequelize asszociációk](https://github.com/szerveroldali/2021-22-1/blob/main/SequelizeAssociations.md) (tantárgyi leírás) - Express: - [ExpressJS dokumentáció](https://expressjs.com/en/4x/api.html) - Eszközök: - [Postman](https://www.postman.com/) - [Firecamp Chrome kiegészítő](https://chrome.google.com/webstore/detail/firecamp-a-campsite-for-d/eajaahbjpnhghjcdaclbkeamlkepinbl) - [DB Browser for SQLite](https://sqlitebrowser.org/) - Gyakorlati anyagok: - [Tavalyi ZH mintamegoldása](https://github.com/szerveroldali/2021-22-1/tree/main/restapi_minta) - [Gyakorlati anyag](https://github.com/szerveroldali/2021-22-1/tree/main/esti_3_4_csut_19_30/restapi) ## Kezdőcsomag Segítségképpen biztosítunk egy kezdőcsomagot a zárthelyihez. Csak telepíteni kell a csomagokat, és kezdheted is a fejlesztést. - A kezdőcsomag elérhető ebben a GitHub repository-ban: - https://github.com/szerveroldali/restapi_kezdocsomag - Vagy: [Közvetlen letöltési link](https://github.com/szerveroldali/restapi_kezdocsomag/archive/refs/heads/main.zip) (zip fájl) - Automatikus tesztelő: `npm run test <FELADATOK SZÁMAI>` - Pl. 1. és 2. feladat tesztelése: `npm run test 1 2` - Minden feladat tesztelése: `npm run test` - Zippelő: `npm run zip` ## Feladatok Készíts egy REST API-t Node.js-ben, Express, Sequelize és SQLite3 segítségével, amelyben az alább részletezett feladatokat valósítod meg! A szerver a 4000-es porton fusson! ### `1. feladat: Modellek és relációk (2 pont)` > :warning: **A modelleket és a seedert odaadjuk obfuszkált formában (a Teams meeting-be feltöltött zip fájlban, amelyikben a tesztelő is van), így az első két feladat (modellek és relációk, ill. seeder) a dolgozat végére halasztható vagy akár ki is hagyható. Értelemszerűen a kihagyott feladatokra nem jár pont! Ha valamelyiket kihagyod, ott az obfuszkált verziókat add be!** Sequelize CLI segítségével hozd létre a következő modelleket! Az `id`, `createdAt`, `updatedAt` a Sequelize ORM szempontjából alapértelmezett mezők, így ezeket a feladat nem specifikálja. Alapesetben egyik mező értéke sem lehet null, hacsak nem adtunk külön `nullable` kikötést! Tehát alapértelmezés szerint a migration minden mezőjére ```js allowNull: false ``` van érvényben, kivéve ott, ahol ezt a feladat másképp nem kéri! A modellek az alábbiak: `User`: felhasználó - `id` - `username`: string, unique (a felhasználónév egyedi) - `createdAt` - `updatedAt` `Post`: bejegyzés - `id` - `text`: text - `commentsEnabled`: boolean - `UserId`: integer - `createdAt` - `updatedAt` `Comment`: bejegyzéshez fűzött hozzászólás - `id` - `text`: text - `PostId`: integer - `UserId`: integer - `createdAt` - `updatedAt` `History`: hozzászólás szerkesztési előzményei - `id` - `text`: text - `CommentId`: integer - `createdAt` - `updatedAt` `Reaction`: hozzászólásra adott reakció - `id` - `type`: enum, lehetséges értékei: LIKE,LOVE,HAHA,WOW,SAD,ANGRY - Vizuálisan: <img src="https://i.imgur.com/2g84kjg.jpg" alt="drawing" width="300"/> - `CommentId`: integer - `UserId`: integer - `createdAt` - `updatedAt` A fenti modellek közötti relációk pedig a következőképpen alakulnak: - `User` 1-N `Post` - `User` 1-N `Comment` - `User` 1-N `Reaction` - `Post` 1-N `Comment` - `Comment` 1-N `Reaction` - `Comment` 1-N `History` ### `2. feladat: Seeder (2 pont)` Hozz létre egy seedert, melynek segítségével feltölthető az adatbázis mintaadatokkal! A seeder minél több esetet fedjen le! A megoldás akkor számít teljes értékűnek, ha a seeder minden lehetséges esethez készít néhány adatot, és a relációkat is figyelembe veszi. A seedert az automata tesztelő nem értékeli, a gyakorlatvezető fogja kézzel javítani. ### `3. feladat: GET /posts (2 pont)` Lekéri az összes bejegyzést a hozzájuk tartozó hozzászólásokkal együtt, továbbá a hozzászólásokhoz is megadja a rájuk adott reakciókat. A reakciókhoz csak a `UserId` és a `type` mezőket adjuk meg. - Minta kérés: `GET http://localhost:4000/posts` - Válasz megfelelő kérés esetén: `200 OK` ```json [ { "id": 1, "text": "Bejegyzés szövege", "commentsEnabled": true, "UserId": 18, "createdAt": "2022-01-07T14:58:27.752Z", "updatedAt": "2022-01-07T14:58:27.752Z", "Comments": [ { "id": 4, "text": "Komment szövege", "PostId": 1, "UserId": 9, "createdAt": "2022-01-07T14:58:27.953Z", "updatedAt": "2022-01-07T14:58:27.953Z", "Reactions": [ { "UserId": 12, "type": "ANGRY" }, { "UserId": 8, "type": "HAHA" } ] } ] } ] ``` ### `4. feladat: GET /posts/:id (2 pont)` Lekér egy adott bejegyzést a hozzá tartozó hozzászólásokkal együtt, továbbá a hozzászólásokhoz is megadja a rájuk adott reakciókat. A reakciókhoz csak a `UserId` és a `type` mezőket adjuk meg. - Minta kérés: `GET http://localhost:4000/posts/1` - Válasz megfelelő kérés esetén: `200 OK` ```json { "id": 1, "text": "Bejegyzés szövege", "commentsEnabled": true, "UserId": 18, "createdAt": "2022-01-07T14:58:27.752Z", "updatedAt": "2022-01-07T14:58:27.752Z", "Comments": [ { "id": 4, "text": "Komment szövege", "PostId": 1, "UserId": 9, "createdAt": "2022-01-07T14:58:27.953Z", "updatedAt": "2022-01-07T14:58:27.953Z", "Reactions": [ { "UserId": 12, "type": "ANGRY" }, { "UserId": 8, "type": "HAHA" } ] } ] } ``` ### `5. feladat: POST /auth/login (2 pont)` Hitelesítés. Nincs semmilyen jelszókezelés, csak a felhasználónevet kell felküldeni a request body-ban. Ha a megadott felhasználónévvel létezik fiók az adatbázisban, azt sikeres loginnak vesszük és kiállítjuk a tokent. A user-t bele kell rakni a token payload-jába, továbbá a válaszban is vissza kell adni! A token aláírásához `HS256` algoritmust használj! A titkosító kulcs értéke `"secret"` legyen! - Minta kérés: `POST http://localhost:4000/auth/login` ```json { "username": "user1" } ``` - Válasz megfelelő kérés esetén: `200 OK` ```json { "token": "ey...", "user": { "id": 1, "username": "user1", "createdAt": "2022-01-10T...", "updatedAt": "2022-01-10T..." } } ``` - Válasz hiányos request body esetén: `400 Bad Request` ```json { "message": "Nem adtál meg felhasználónevet!" } ``` - Válasz nem létező felhasználó esetén: `404 Not Found` ```json { "message": "A megadott felhasználónévvel nem létezik felhasználó!" } ``` Tipp: A token ellenőrizhető a https://jwt.io/ oldalon. ### `6. feladat: POST /posts (2 pont)` Új bejegyzés létrehozása. **A végpont hitelesített**, hiszen a szerző a bejelentkezett felhasználó lesz. - Minta kérés: `POST http://localhost:4000/posts` ```json { "text": "Bejegyzés szövege", "commentsEnabled": true } ``` - Hitelesített végpontokra a következő fejléccel kell küldeni a kérést: ``` Authorization: Bearer <token> ``` Firecamp-ben ehhez az Auths fül alatt válaszd a "No Auth" felirattal induló menüből a Bearer-t. Ilyenkor elég csak a tokent megadni, és a fenti fejlécet fogja elküldeni: ![Bearer Firecamp](https://i.imgur.com/qduwew7.png) - Válasz megfelelő kérés esetén: `201 OK` ```json { "id": 30, "text": "Bejegyzés szövege", "commentsEnabled": true, "updatedAt": "2022-01-08T10:09:55.509Z", "createdAt": "2022-01-08T10:09:55.509Z" } ``` - Válasz hibás kérés esetén (pl. validációs hiba): `400 Bad Request` ```json { "message": "<hibaüzenet>" } - Válasz hitelesítetlen kérés esetén: `401 Unauthorized` `Tipp #1`: A `server.js`-ben van egy végső hibakezelő, ami alapértelmezés szerint 500-as hibát ad vissza válaszként. A validációs hibák ezért általánosan kezelhetők úgy, hogy ezt a hibakezelőt kibővíted a következő módon: ```js const { ValidationError } = require("sequelize"); // ... app.use(async (err, req, res, next) => { // ... if (err instanceof ValidationError) { // Ha Sequelize-os validációs hiba történt, // akkor milyen választ adjunk? return res.status(400).send({ // message: ... }); } // Ezen a ponton más típusú hibákat ugyanúgy // 500-as válasszal fog kezelni // ... }); ``` `Tipp #2`: Az auth middleware a token payload-ját berakja a `req.user`-be. A payload-ba pedig az előző feladatban beraktad a user adatait. ### `7. feladat: PUT /posts (2 pont)` Bejegyzés módosítása. **A végpont hitelesített**, hiszen a bejegyzést csak a szerző módosíthatja. Nem muszáj minden mezőt felküldeni, elég csak azokat, amiket frissíteni szeretnénk, a többinek változatlan marad majd az értéke. Például az alábbi mintában csak a `text`-et küldjük fel, vagyis a `disabledComments` nem fog megváltozni. - Minta kérés: `PUT http://localhost:4000/posts/2` ```json { "text": "Bejegyzés módosított szövege", } ``` - Válasz megfelelő kérés esetén: `200 OK` ```json { "id": 2, "text": "Bejegyzés módosított szövege", "commentsEnabled": false, "UserId": 1, "createdAt": "2022-01-08T10:14:03.012Z", "updatedAt": "2022-01-08T10:23:07.486Z" } ``` - Válasz illetéktelen módosítás esetén: `403 Forbidden` ```json { "message": "Csak a saját bejegyzésedet szerkesztheted!" } ``` - Válasz hibás kérés esetén (pl. validációs hiba): `400 Bad Request` ```json { "message": "<hibaüzenet>" } ``` - Válasz hitelesítetlen kérés esetén: `401 Unauthorized` ### `8. feladat: DELETE /posts (2 pont)` Bejegyzés törlése. **A végpont hitelesített**, hiszen a bejegyzést csak a szerző törölheti. - Minta kérés: `DELETE http://localhost:4000/posts/2` - Válasz megfelelő kérés esetén: `200 OK` - Válasz illetéktelen módosítás esetén: `403 Forbidden` ```json { "message": "Csak a saját bejegyzésedet törölheted!" } ``` - Válasz hitelesítetlen kérés esetén: `401 Unauthorized` ### `9. feladat: POST /posts/:id/comments (2 pont)` Hozzászólás egy bejegyzéshez. **A végpont hitelesített**, hiszen a hozzászólást a felhasználóhoz rendeljük, mint szerzőhöz. Mivel a hozzászólások korábbi szövegeit megőrizzük a History-ban, ezért az itt megadott szöveg a hozzászólás létrehozását követően rögtön kerüljön be a History-ba is! - Minta kérés: `POST http://localhost:4000/posts/2/comments` ```json { "text": "Hozzászólás szövege", } ``` - Válasz megfelelő kérés esetén: `201 Created` ```json { "id": 134, "text": "Hozzászólás szövege", "UserId": 1, "PostId": 3, "updatedAt": "2022-01-08T10:50:00.772Z", "createdAt": "2022-01-08T10:50:00.772Z" } ``` - Válasz illetéktelen művelet esetén: `403 Forbidden` ```json { "message": "Le van tiltva a hozzászólás lehetősége!" } ``` - Válasz hibás kérés esetén (pl. validációs hiba): `400 Bad Request` ```json { "message": "<hibaüzenet>" } ``` - Válasz hitelesítetlen kérés esetén: `401 Unauthorized` ### `10. feladat: PUT /comments/:id (2 pont)` Hozzászólás szerkesztése. **A végpont hitelesített**, hiszen a hozzászólást csak a szerző szerkesztheti. Mivel a hozzászólások korábbi szövegeit megőrizzük a History-ban, ezért az itt megadott szöveg a hozzászólás módosítását követően rögtön kerüljön be a History-ba is! A hozzászólás akkor is módosítható, ha a bejegyzéshez időközben letiltásra kerültek a hozzászólások. - Minta kérés: `PUT http://localhost:4000/comments/134` ```json { "text": "Hozzászólás módosított szövege", } ``` - Válasz megfelelő kérés esetén: `200 OK` ```json { "id": 134, "text": "Hozzászólás módosított szövege", "PostId": 3, "UserId": 1, "createdAt": "2022-01-08T10:50:00.772Z", "updatedAt": "2022-01-08T10:56:12.399Z" } ``` - Válasz nem létező entitás esetén: `404 Not Found` ```json { "message": "A megadott ID-vel nem létezik komment!" } ``` - Válasz illetéktelen művelet esetén: `403 Forbidden` ```json { "message": "Csak a saját hozzászólásodat szerkesztheted!" } ``` - Válasz hibás kérés esetén (pl. validációs hiba): `400 Bad Request` ```json { "message": "<hibaüzenet>" } ``` - Válasz hitelesítetlen kérés esetén: `401 Unauthorized` ### `11. feladat: GET /comments/:id/history (2 pont)` Megadja a hozzászólás szerkesztési előzményeit. Amikor a hozzászólás létrejön vagy módosul, a szövege (`text` mező) mindig eltárolásra kerül a history-ba is, ezáltal követhető, hogy egy kommentnek mik voltak a korábbi szövegei, és azt mikor rendelték hozzá. - Minta kérés: GET http://localhost:4000/comments/134/history - Válasz megfelelő kérés esetén: `200 OK` ```json [ { "text": "Hozzászólás szövege", "date": "2022-01-08 10:50:00.792 +00:00" }, { "text": "Hozzászólás módosított szövege", "date": "2022-01-08 10:56:12.417 +00:00" } ] ``` - Válasz nem létező entitás esetén: `404 Not Found` ```json { "message": "A megadott ID-vel nem létezik komment!" } ``` ### `12. feladat: GET /comments/:id/reactions (3 pont)` A hozzászólásra adott reakciók statisztikája. Először az `all` property-ben megadja, hogy mennyi hozzászólásra adott összes reakciók száma. A `details` property-hez pedig egy olyan object-et rendel, amely kategóriák szerinti bontásban is megmutatja, melyik típusú reakcióból mennyi van az adott hozzászóláson. - Minta kérés: `GET http://localhost:4000/comments/10/reactions` - Válasz megfelelő kérés esetén: `200 OK` ```json { "all": 9, "details": { "like": 0, "love": 0, "haha": 5, "wow": 0, "sad": 1, "angry": 3 } } ``` - Válasz nem létező entitás esetén: `404 Not Found` ```json { "message": "A megadott ID-vel nem létezik komment!" } ``` ### `13. feladat: POST /comments/:id/reaction (3 pont)` Ezen a végponton keresztül lehet reagálni egy hozzászólásra, vagy a korábban adott reakciót módosítani. Reakció akkor is adható/módosítható, ha a bejegyzéshez időközben letiltásra kerültek a hozzászólások. **A végpont hitelesített**, hiszen a reakciók a felhasználókhoz vannak rendelve. Ha a request-ből kinyert felhasználó korábban már reagált a megadott hozzászólásra, akkor elég a reakcióját módosítani (update), egyébként pedig új reakciót kell létrehozni (create). Saját kommentre is lehet reagálni. - Minta kérés: `POST http://localhost:4000/comments/10/reaction` ```json { "type": "LIKE" } ``` - Válasz megfelelő kérés esetén: - Ha új reakciót kellett létrehoni: `201 Created` - Ha meglévő reakciót kellett módosítani: `200 OK` ```json { "id": 50, "type": "LIKE", "CommentId": 10, "UserId": 1, "createdAt": "2022-01-08T10:14:05.608Z", "updatedAt": "2022-01-08T11:10:36.312Z" } ``` - Válasz nem létező entitás esetén: `404 Not Found` ```json { "message": "A megadott ID-vel nem létezik komment!" } ``` - Válasz hitelesítetlen kérés esetén: `401 Unauthorized` ### `14. feladat: DELETE /comments/:id/reaction (2 pont)` A megadott hozzászólásra adott reakció visszavonása (törlése). **A végpont hitelesített**, hiszen tudnunk kell, hogy melyik felhasználó reakciójáról van szó. - Minta kérés: `DELETE http://localhost:4000/comments/10/reaction` - Válasz megfelelő kérés esetén: `200 OK` - Válasz nem létező entitás esetén: `404 Not Found` ```json { "message": "A megadott ID-vel nem létezik komment!" } ``` ```json { "message": "Még nem reagáltál erre a kommentre!" } ```<file_sep>"use strict"; module.exports = { up: async (queryInterface, Sequelize) => { // Tábla létrehozása await queryInterface.createTable("GenreGame", { // ID mező, ugyanaz, mint bármelyik másik generált modellnél id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER, }, GenreId: { type: Sequelize.INTEGER, // Nem vehet fel NULL értéket, mindenképpen valamilyen INTEGER-nek kell lennie allowNull: false, // Megadjuk, hogy ez egy külső kulcs, ami a "Categories" táblán belüli "id"-re hivatkozik // https://sequelize.org/master/class/lib/dialects/abstract/query-interface.js~QueryInterface.html#instance-method-createTable references: { model: "Genres", key: "id", }, // Ha pedig a kategória (Category) törlődik, akkor a kapcsolótáblában lévő bejegyzésnek is törlődnie kell, // hiszen okafogyottá válik, hiszen egy nem létező kategóriára hivatkozik onDelete: "cascade", }, GameId: { type: Sequelize.INTEGER, // Nem vehet fel NULL értéket, mindenképpen valamilyen INTEGER-nek kell lennie allowNull: false, // Megadjuk, hogy ez egy külső kulcs, ami a "Posts" táblán belüli "id"-re hivatkozik references: { model: "Games", key: "id", }, // Ha pedig a bejegyzés (Post) törlődik, akkor a kapcsolótáblában lévő bejegyzésnek is törlődnie kell, // hiszen okafogyottá válik, hiszen egy nem létező kategóriára hivatkozik onDelete: "cascade", }, // Időbélyegek createdAt: { allowNull: false, type: Sequelize.DATE, }, updatedAt: { allowNull: false, type: Sequelize.DATE, }, }); // Megkötés a kapcsolótáblára, amelyben megmondjuk, hogy egy CategoryId - PostId páros csak egyszer szerepelhet a kapcsolótáblában await queryInterface.addConstraint("GenreGame", { fields: ["GenreId", "GameId"], type: "unique", }); }, down: async (queryInterface, Sequelize) => { // Ha visszavonásra kerül a migration, egyszerűen töröljük ki a táblát await queryInterface.dropTable("GenreGame"); }, }; <file_sep>const express = require("express"); const router = express.Router(); const models = require("../models"); const jwt = require("jsonwebtoken"); const auth = require("../middlewares/auth"); const { User } = models; // localhost:4000/auth/login router.post("/login", async function (req, res) { const { email, password } = req.body; if (!email || !password) { return res.status(400).send({ message: "Nem adtál meg emailt vagy jelszót!" }); } const user = await User.findOne({ where: { email } }); if (!user) { return res.status(404).send({ message: "A megadott email címmel nem létezik felhasználó!" }); } if (user.comparePassword(password)) { //return res.status(200).send({ message: "Sikeres bejelentkezés" }); const token = jwt.sign(user.toJSON(), "secret", { algorithm: "HS256" }); return res.send({ token }); // = res.send({ token: token }); } return res.status(401).send({ message: "A megadott jelszó helytelen!" }); }); // localhost:4000/auth/who router.get("/who", auth, async function (req, res) { //console.log(req.headers); res.send(req.user); }); // localhost:4000/auth/register router.post("/register", async function (req, res) { const { name, email, password } = req.body; if (!name || !email || !password) { return res.status(400).send({ message: "Nem adtál meg nevet, emailt vagy jelszót!" }); } const user = await User.create({ name, email, password }); // A regisztráció egyben egy bejelentkezés is, tehát egy tokent is aláírunk és elküldjük const token = jwt.sign(user.toJSON(), "secret", { algorithm: "HS256" }); return res.status(201).send({ token }); }); module.exports = router; <file_sep>module.exports = (schema, fn) => { // Deep copy a fv-ről const fnOriginal = fn.bind({}); // Fv kibővítése a validálással, majd az eredeti fv meghívása a bővítetten belül fn = async (data, ack) => { try { const result = schema.validate(data); if (result.hasOwnProperty("error")) { // Error details logolása, pl. custom hibaüzenetekhez //console.log(result.error); throw result.error; } return await fnOriginal(data, ack); // Automatikus { status: "error", "message": <hibaüzenet> } válasz generálása hiba esetén } catch (error) { ack({ status: "error", message: error.message, }); } }; // Kibővített fv visszaadása return fn; }; <file_sep>const fs = require('fs'); // fs.readdir('./inputs', function (err, files) { ... }); // arrow function fs.readdir('./inputs', (err, filenames) => { console.log(err); if (err) throw err; console.log(filenames); let contents = []; filenames.forEach(filename => { fs.readFile(`./inputs/${filename}`, (err, content) => { if (err) throw err; console.log(`${filename}:`, content.toString()); contents.push(content.toString()); if (contents.length === filenames.length) { // Ezen a ponton már tudom, hogy az összes fájlnak // a tartalma megvan a contents tömbben, így eljött // az idő, hogy kiírjuk azokat egy output fájlba console.log(contents); fs.writeFile('./concat-output.txt', contents.join('\n'), (err) => { if (err) throw err; console.log('Vége'); }) } }) }) }); // Mi ezzel a gond? Callback hell. //console.log('Vége');<file_sep>require('./bootstrap'); require('alpinejs'); import Picker from 'vanilla-picker'; window.Picker = Picker; <file_sep><?php namespace Database\Factories; use App\Models\Post; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class PostFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Post::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ /* Str::ucfirst() - Str Upper Case First - első betű nagybetűsítése, ez egy Laravel Helper function (https://laravel.com/docs/8.x/helpers) $this->faker->numberBetween(2,6) - Random szám 2 és 6 között, a 2-t és a 6-ot is beleértve $this->faker->words() - 3 szót ad, tömbként $this->faker->words(N) - N szót ad, tömbként $this->faker->words(N, true) - N szót ad, stringgé joinolva (szóközökkel elválasztva) Ezeket kell kombinálni, hogy 2-6 szót adjon, majd azt nagybetűsíteni A paragraphs nagyon hasonló, Tinkerben ki lehet próbálni */ 'title' => Str::ucfirst($this->faker->words($this->faker->numberBetween(2,6), true)), 'text' => $this->faker->paragraphs($this->faker->numberBetween(2,5), true), ]; } } <file_sep># Adatbázis mappa A debugoláshoz célszerű a [DB Browser for SQLite](https://sqlitebrowser.org/dl/) használata. A `tester_database.sqlite` fájlt az automatikus tesztelő hozza létre és seedeli fel minden tesztelés elején. Ha nem tudod megírni a seedert, csak nevezd át `database.sqlite`-ra, és lesz egy adatbázisod. <file_sep>const bcrypt = require("bcrypt"); const password = "<PASSWORD>"; // password + SALT -> <PASSWORD> const hash1 = bcrypt.hashSync(password, bcrypt.genSaltSync(12)); const hash2 = bcrypt.hashSync(password, bcrypt.genSaltSync(12)); console.log(hash1); console.log(hash2); console.log(bcrypt.compareSync(password, hash1)); console.log(bcrypt.compareSync(password, hash2)); console.log(bcrypt.compareSync("asd", hash2)); <file_sep># Szerveroldali webprogramozás - REST API zárthelyi _2021. december 03._ Tartalom: - [Szerveroldali webprogramozás - REST API zárthelyi](#szerveroldali-webprogramozás---rest-api-zárthelyi) - [Tudnivalók](#tudnivalók) - [Hasznos linkek](#hasznos-linkek) - [Kezdőcsomag](#kezdőcsomag) - [Zárthelyi](#zárthelyi) - [Modellek](#modellek) - [Modellek közötti relációk](#modellek-közötti-relációk) - [Modellek felépítése](#modellek-felépítése) - [Feladatok](#feladatok) - [`Migrationok, Seeder`](#migrationok-seeder) - [`POST /storages`](#post-storages) - [`GET /storages`](#get-storages) - [`GET /storages/:id`](#get-storagesid) - [`POST /auth`](#post-auth) - [`POST /ingredients`](#post-ingredients) - [`GET /ingredients`](#get-ingredients) - [`GET /ingredients/:id`](#get-ingredientsid) - [`PUT /ingredients/:id`](#put-ingredientsid) - [`POST /recipes`](#post-recipes) - [`GET /recipes`](#get-recipes) - [`GET /recipes/:id`](#get-recipesid) - [`PUT /recipes/:id`](#put-recipesid) - [`POST /appliances/changeName`](#post-applianceschangename) - [`GET /recipes/statistics`](#get-recipesstatistics) - [`GET /storages/:id/clean`](#get-storagesidclean) ## Tudnivalók - Kommunikáció - **A Teams csoport Általános csatornáján a zárthelyi egész ideje alatt lesz egy meeting! Erősen ajánlott, hogy ehhez csatlakozzatok, hiszen elsősorban ebben a meetingben válaszolunk a felmerülő kérdésekre, valamint az esetleges időközben felmerülő információkat is itt osztjuk meg veletek!** - Ha a zárthelyi közben valamilyen problémád, kérdésed adódik, akkor keresd az oktatókat a meetingben vagy privát üzenetben (Teams chaten). - Időkeret - **A zárthelyi megoldására 2 óra áll rendelkezésre: *16:15-18:15*.** - Oszd be az idődet! Ha egy feladat nem megy, akkor inkább ugord át (legfeljebb később visszatérsz rá), és foglalkozz a többivel, hogy ne veszíts pontot olyan feladatból, amit meg tudnál csinálni! - Beadás - **A beadásra további *15* perc áll rendelkezésre: *18:15-18:30*. Ez a +15 perc *ténylegesen* a beadásra van! *18:30* után a Canvas lezár, és további beadásra nincs lehetőség!** - Ha előbb végzel, természetesen 18:30-ig bármikor beadhatod a feladatot. - A feladatokat `node_modules` mappa nélkül kell becsomagolni egy .zip fájlba, amit a Canvas rendszerbe kell feltölteni! - **A dolgozat megfelelő és hiánytalan beadása a hallgató felelőssége.** Mivel a dolgozat végén külön 15 perces időkeretet adunk a feladat megfelelő, nyugodt körülmények közötti beadására, ebből kifolyólag ilyen ügyekben nem tudunk utólagos reklamációknak helyt adni. Tehát ha valaki a zárthelyi után jelzi, hogy egy vagy több fájlt nem adott be, akkor azt sajnos nem tudjuk elfogadni. - Értékelés - A legutoljára beadott megoldás lesz értékelve. - **A zárthelyin legalább a pontok 40%-át, vagyis legalább 12 pontot kell elérni**, ez alatt a zárthelyi sikertelen. - Vannak részpontok. - A pótzárthelyin nem lehet rontani a zárthelyi eredményéhez képest, csak javítani. - **Érvényes nyilatkozat (megfelelően kitöltött statement.txt) hiányában a kapott értékelés érvénytelen, vagyis 0 pont.** - Az elrontott, elfelejtett nyilatkozat utólag pótolható: Canvasen kommentben kell odaírni a feladathoz. - Egyéb - A feladatokat JavaScript nyelven, Node.js környezetben kell megoldani! - Ha kell, akkor további csomagok telepíthetőek, de ezeket a `package.json` fájlban fel kell tüntetni! - Ellenőrzéskor a gyakorlatvezetők az alábbi parancsokat adják ki a feladatonkénti mappákban: ``` # Csomagok telepítése: npm install # Friss adatbázis létrehozása: npm run db # Fejlesztői verzió futtatása: npm run dev ``` - Ellenőrzéshez és teszteléshez a Node.js *16.x*, az npm *8.x*, és a Firecamp *2.3.x* verzióját fogjuk használni. ## Hasznos linkek - [ExpressJS dokumentáció](https://expressjs.com/en/4x/api.html) - [Sequelize dokumentáció](https://sequelize.org/master/) - [Sequelize API referencia](https://sequelize.org/master/identifiers.html) - [Firecamp Chrome kiegészítő](https://chrome.google.com/webstore/detail/firecamp-a-campsite-for-d/eajaahbjpnhghjcdaclbkeamlkepinbl) - [DB Browser for SQLite](https://sqlitebrowser.org/) ## Kezdőcsomag Segítségképpen készítettünk egy kezdőcsomagot a zárthelyi elkészítéséhez. Csak telepíteni kell a csomagokat, és kezdheted is a fejlesztést. - A kezdőcsomag elérhető itt: - https://github.com/szerveroldali/restapi_kezdocsomag - Automatikus tesztelő: `npm run test <FELADATOK SZÁMAI>` - Pl. 1. és 2. feladat tesztelése: `npm run test 1 2` - Minden feladat tesztelése: `npm run test` - Zippelő: `npm run zip` ## Zárthelyi Készíts egy REST API-t Node.js-ben, Express, Sequelize és SQLite3 segítségével, amelyben az alább részletezett feladatokat valósítod meg! A szerver a 4000-es porton fusson! ### Modellek - Recipes: receptek - Ingredients: hozzávalók - Appliances: (konyhai) berendezések - Storages: tárolók #### Modellek közötti relációk - Recipe N - N Ingredient - Appliance 1 - N Recipe - Storage 1 - N Ingredient #### Modellek felépítése - Storage - name: string, unique (tehát egyedi, vagyis ugyanaz a név nem szerepelhet kétszer) - capacity: number - Appliance - name: string - Ingredient - name: string - amount: number - **S**torageId (összekapcsolásból jön) - **NAGYON FONTOS**, hogy Pascal case-ben legyen, tehát kezdődjön nagybetűvel! - Recipe - name: string, unique (tehát egyedi, vagyis ugyanaz a név nem szerepelhet egyszerre több beszállítónál) - isVegetarian: boolean - doneCount: number _(vagyis hányszor készítették már el)_ - **A**pplianceId (összekapcsolásból jön) - **NAGYON FONTOS**, hogy Pascal case-ben legyen, tehát kezdődjön nagybetűvel! ### Feladatok - Hozd létre az adatbázist, töltsd fel néhány adattal. Pár végpont védett. Ha nem tudod megoldani az authentikációt, akkor is készítsd el a végpontot! Hitelesített végpontokra a következő fejléccel kell küldeni a kérést: ``` Authorization: Bearer <token> ``` - Firecamp-ben az Auths fül alatt válaszd a "No Auth" felirattal induló menüből a Bearer-t, és akkor elég csak a tokent megadni, a megfelelő fejlécet fogja elküldeni: ![Bearer Firecamp](https://i.imgur.com/qduwew7.png) #### `Migrationok, Seeder` - Az adatbázis tartalmazza a megfelelő táblákat néhány példaadattal. **(2 pont)** - Néhány, vagy akár mindegyik adathoz legyen megoldva a megfelelő reláció is! **(2 pont)** #### `POST /storages` - Egy név és kapacitás párost küldünk fel JSON objektumként, az adatokat elmentjük a storages táblába, majd visszatérünk az adatbázis rekordnak megfelelő JSON objektummal: pl. id, name, capacity mezőkkel. **(1 pont)** - Kérés ```json { "name": "Shelf", "capacity": 50 } ``` - Válasz: - 400 Bad request: hibás adat küldése esetén, pl. ha az adatbázis hibát dob ugyanolyan név beszúrása esetén. - 201 Created: siker esetén ```json { "id": 11, "name": "Shelf", "capacity": 50, "updatedAt": "2021-12-03...", "createdAt": "2021-12-03..." } ``` #### `GET /storages` - Összes tároló lekérdezése **(1 pont)** - Válasz - 200 OK ```json [ { "id": 1, "name": "nisi", "capacity": 46, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." }, { "id": 2, "name": "nesciunt", "capacity": 48, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." }, ... ] ``` #### `GET /storages/:id` - Adott azonosítójú tároló lekérdezése **(1 pont)** - Válasz - 404 Not found: ha a megadott id-vel nem létezik tároló - 200 OK: ha létezik az adott id, akkor visszatérünk a megfelelő storage objektummal JSON formában, pl. id, name, capacity mezőkkel. ```json { "id": 1, "name": "nisi", "capacity": 46, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." } ``` #### `POST /auth` - Hitelesítés. A példában megadott email-t (`<EMAIL>`) kell beégetni a kódba, hogy csak erre adjon vissza token-t, tehát nem kell adatbázis-beli user-eket kezelni! **(3 pont)** - Kérés: ```json { "email": "<EMAIL>" } ``` - Válasz: - 401 Unauthorized: nem létező email cím esetén - 200 OK: létező email cím esetén. Ekkor egy JWT-t kell generálni és elküldeni az `accessToken` mezőben: ```json { "accessToken": "eyJh..." } ``` - Egyéb: - A token aláírásához `HS256` algoritmust használj! - A titkosító kulcs értéke "`secret`" legyen! - A token payloadjába kerüljön bele az email az alábbi módon: ```json { "email": "<EMAIL>" } ``` - A tokent itt tudod ellenőrizni: [jwt.io](https://jwt.io/) #### `POST /ingredients` - Új hozzávaló felvitele **(1 pont)** - Kérés: egy hozzávaló JSON formában felküldve. ```json { "name": "Répa", "amount": 30, "StorageId": 2 } ``` - Válasz - 201 Created: siker esetén, valamint adja vissza a létrehozott hozzávalót ```json { "id": 16, "name": "Répa", "amount": 30, "StorageId": 2, "updatedAt": "2021-12-03...", "createdAt": "2021-12-03..." } ``` #### `GET /ingredients` - Összes hozzávaló lekérése **(1 pont)** - Válasz: 200 OK ```json [ { "id": 1, "name": "molestias", "amount": 36, "StorageId": 10, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." }, { "id": 2, "name": "et", "amount": 4, "StorageId": 1, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." }, ... ] ``` #### `GET /ingredients/:id` - Egy adott hozzávaló lekérdezése **(1 pont)** - Válasz - 404 Not found: ha a megadott id-vel nem létezik hozzávaló - 200 OK ```json { "id": 1, "name": "molestias", "amount": 36, "StorageId": 10, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." } ``` #### `PUT /ingredients/:id` - Egy hozzávaló módosítása **(1 pont)** - Kérés: egy hozzávaló JSON formában felküldve. ```json { "name": "Uborka" } ``` - Válasz - 404 Not found: ha a megadott id-vel nem létezik hozzávaló - 200 OK: siker esetén, és a módosított hozzávaló rekordja. ```json { "id": 1, "name": "Uborka", "amount": 36, "StorageId": 10, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." } ``` #### `POST /recipes` - Új recept felvitele **(1 pont)** - Kérés: egy recept JSON formában felküldve. ```json { "name": "Carbonara", "isVegetarian": false, "doneCount": 1, "ApplianceId": 3 } ``` - Válasz - 201 Created: siker esetén, és az adott recept ```json { "id": 16, "name": "Carbonara", "isVegetarian": false, "doneCount": 1, "ApplianceId": 3, "updatedAt": "2021-12-03...", "createdAt": "2021-12-03..." } ``` #### `GET /recipes` - Összes recept lekérése **(2 pont)** - Válasz: 200 OK, a recepthez kapcsolt hozzávalókat listázni kell a példán látható módon ```json [ { "id": 1, "name": "dignissimos", "isVegetarian": false, "doneCount": 69, "ApplianceId": 5, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "Ingredients": [ { "id": 9, "name": "suscipit", "amount": 94, "StorageId": 10, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "StorageId": 10, "Recipes_Ingredients": { "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "IngredientId": 9, "RecipeId": 1 } }, { "id": 11, "name": "facilis", "amount": 38, "StorageId": 3, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "StorageId": 3, "Recipes_Ingredients": { "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "IngredientId": 11, "RecipeId": 1 } } ] }, ... ] ``` #### `GET /recipes/:id` - Egy adott recept lekérdezése **(2 pont)** - Válasz - 404 Not found: ha a megadott id-vel nem létezik recept - 200 OK, a recepthez kapcsolt hozzávalókat listázni kell a példán látható módon ```json { "id": 1, "name": "dignissimos", "isVegetarian": false, "doneCount": 69, "ApplianceId": 5, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "Ingredients": [ { "id": 11, "name": "facilis", "amount": 38, "StorageId": 3, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "StorageId": 3, "Recipes_Ingredients": { "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "IngredientId": 11, "RecipeId": 1 } }, { "id": 9, "name": "suscipit", "amount": 94, "StorageId": 10, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "StorageId": 10, "Recipes_Ingredients": { "createdAt": "2021-12-03...", "updatedAt": "2021-12-03...", "IngredientId": 9, "RecipeId": 1 } } ] } ``` #### `PUT /recipes/:id` - Egy recept módosítása **(1 pont)** - Kérés: egy recept módosítani kívánt mezői JSON formában felküldve (nem muszáj minden mezőt felküldeni a frissítéshez). ```json { "name": "Saláta" } ``` - Válasz - 404 Not found: ha a megadott id-vel nem létezik recept - 200 OK: siker esetén, és a módosított recept rekordja. ```json { "id": 1, "name": "Saláta", "isVegetarian": false, "doneCount": 69, "ApplianceId": 5, "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." } ``` #### `POST /appliances/changeName` - Minden olyan berendezés nevét lecseréli, aminek a neve a kérésben meg lett adva (`oldName`), a szintén kérésben megadott új berendezés nevére (`newName`). **(3 pont)** - Kérés: ```json { "oldName": "mikró", "newName": "sütő" } ``` - Válasz - 200 OK: siker esetén megadja az összes berendezést, aminek megváltozott a neve, az alábbi példán látható módon: ```json [ { "id": 1, "name": "sütő", "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." }, { "id": 3, "name": "sütő", "createdAt": "2021-12-03...", "updatedAt": "2021-12-03..." } ] ``` #### `GET /recipes/statistics` - A receptekről készít statisztikát. **(3 pont)** - Válasz - 200 OK: vissza kell adni az összes recepthez tartozó statisztikákat. A statisztika a következő mezőkből áll: - popularVegetarianRecipeCount: hány olyan vegetáriánus recept van (`isVegetarian`) amit több mint 10 ember csinált meg (`doneCount`) - mostPopularRecipeName: annak a receptnek a neve (`name`), aminek a legmagasabb a `doneCount`-ja. Ha több, egyforma doneCount-ú recept van, akkor a legkisebb id-jút kell visszaadni - mostExpensiveRecipeName: a legtöbb hozzávalóval (`ingredient`) rendelkező recept neve ```json { "popularVegetarianRecipeCount": 2, "mostPopularRecipeName": "dolorem", "mostExpensiveRecipeName": "amet", } ``` #### `GET /storages/:id/clean` - Ez a végpont **HITELESÍTETT**. Meghívása után az adott tárolóhoz tartozó hozzávalók számát valamilyen módszerrel csökkenteni kell, úgy, hogy az összegük ne haladja meg a tároló kapacitását. Vagyis: - ha `Storage.capacity >= sum(a Storage-on lévő összes Ingredient.amount)`, akkor nem kell csinálni semmit, csak a helyesen formázott választ elküldeni, **0** értékkel - ha `Storage.capacity < sum(a Storage-on lévő összes Ingredient.amount)`, akkor ki kell törölni `sum(a Storage-on lévő összes Ingredient.amount) - Storage.capacity` darab Ingredient-et, az adott storage-ról, és ugyanezt a számot el kell küldeni a válaszban - Az elküldendő darabszám elküldése a válaszban, még nem teljes értékű megoldás! Segítség: - A törlés bárhogy megoldható: amount csökkentéssel (akár negatívba is mehet! én ezt ajánlanám), más tárolóba rakással vagy tényleges törléssel. A lényeg, hogy végül annyi hozzávaló legyen a tárolóban, amennyi a kapacitása. **(4 pont)** - Válasz - 401 Unauthorized: nincs megadva, vagy érvénytelen a token - 404 Not Found: ha a megadott id-vel nem létezik tároló - 200 OK: illetve vissza kell adni, hogy hány hozzávaló lett kiszedve a tárolóból, az alábbi példa szerint: ```json { "removedIngredientCount": 2 } ```<file_sep>const bcrypt = require("bcrypt"); const plainTextPassword = "<PASSWORD>"; const hash1 = bcrypt.hashSync(plainTextPassword, bcrypt.genSaltSync(12)); const hash2 = bcrypt.hashSync(plainTextPassword, bcrypt.genSaltSync(12)); console.log(hash1); console.log(hash2); console.log(bcrypt.compareSync(plainTextPassword, hash1)); console.log(bcrypt.compareSync(plainTextPassword, hash2)); console.log(bcrypt.compareSync("Password", hash2)); <file_sep>/*const fs = require('fs'); console.log(fs.readdirSync('./inputs'));*/ const { readdirSync } = require('fs'); console.log(readdirSync('./inputs')); console.log('Vége');<file_sep>const fs = require('fs'); const { promisify } = require('util'); const pReadDir = promisify(fs.readdir); const pReadFile = promisify(fs.readFile); const pWriteFile = promisify(fs.writeFile); // async, await /*async function valami() { // ... } valami();*/ /* // ezért kell a pontosvessző a self invoke elé: let asd = { aa: 1 }*/ // Self invoke function ;(async () => { const filenames = await pReadDir('./inputs'); console.log(filenames); let contents = []; for (let filename of filenames) { contents.push( await pReadFile(`./inputs/${filename}`) ); } await pWriteFile( './concat-output.txt', contents .map(content => content.toString()) .join('\n') ); console.log('Vége'); })(); /* pReadDir('./inputs') .then(filenames => { console.log(filenames); const promises = filenames.map(filename => pReadFile(`./inputs/${filename}`)); //console.log(promises); return Promise.all(promises); }) .then(contents => { contents = contents.map(content => content.toString()); //console.log(contents); return contents.join('\n'); }) // Output kiírása lesz .then(output => pWriteFile('./concat-output.txt', output)) .then(() => console.log('Vége')) .catch(err => console.log(err)); */ <file_sep>const { makeExecutableSchema } = require("@graphql-tools/schema"); const { graphqlHTTP } = require("express-graphql"); const { readFileSync } = require("fs"); const { join } = require("path"); const { typeDefs: scalarsTypeDefs, resolvers: scalarsResolvers } = require("graphql-scalars"); const ourTypeDefs = readFileSync(join(__dirname, "./typedefs.graphql")).toString(); const ourResolvers = require("./resolvers"); const schema = makeExecutableSchema({ typeDefs: [scalarsTypeDefs, ourTypeDefs], resolvers: [scalarsResolvers, ourResolvers], }); module.exports = graphqlHTTP({ schema, // = schema: schema, graphiql: { // HTTP fejlécelemeket is tudjunk küldeni a kérésekkel együtt headerEditorEnabled: true, }, }); <file_sep># Szerveroldali webprogramozás - GraphQL, Websocket zárthelyi _2021. december 17._ Tartalom: - [Szerveroldali webprogramozás - GraphQL, Websocket zárthelyi](#szerveroldali-webprogramozás---graphql-websocket-zárthelyi) - [Tudnivalók](#tudnivalók) - [Hasznos linkek](#hasznos-linkek) - [Kezdőcsomag](#kezdőcsomag) - [GraphQL (15 pont)](#graphql-15-pont) - [Modellek](#modellek) - [Típusdefiníció](#típusdefiníció) - [1. feladat: `recipes` (2 pont)](#1-feladat-recipes-2-pont) - [2. feladat: `updateIngredient` (2 pont)](#2-feladat-updateingredient-2-pont) - [3. feladat: `ingredient` (1 pont)](#3-feladat-ingredient-1-pont) - [4. feladat: `smallestStorage` (2 pont)](#4-feladat-smalleststorage-2-pont) - [5. feladat: `storeIngredients` (2 pont)](#5-feladat-storeingredients-2-pont) - [6. feladat: `changeApplianceName` (3 pont)](#6-feladat-changeappliancename-3-pont) - [7. feladat: `statistics` (3 pont)](#7-feladat--statistics-3-pont) - [Websocket/Socket.io (15 pont)](#websocketsocketio-15-pont) - [1. feladat: `list-rooms` (1 pont)](#1-feladat-list-rooms-1-pont) - [2. feladat: `create-room` (2 pont)](#2-feladat-create-room-2-pont) - [3. feladat: `join-room` (1 pont)](#3-feladat-join-room-1-pont) - [4. feladat: `mute-client` (5 pont)](#4-feladat-mute-client-5-pont) - [5. feladat: `send-message` (6 pont)](#5-feladat-send-message-6-pont) ## Tudnivalók - Kommunikáció - **A Teams csoport Általános csatornáján a zárthelyi egész ideje alatt lesz egy meeting! Erősen ajánlott, hogy ehhez csatlakozzatok, hiszen elsősorban ebben a meetingben válaszolunk a felmerülő kérdésekre, valamint az esetleges időközben felmerülő információkat is itt osztjuk meg veletek!** - Ha a zárthelyi közben valamilyen problémád, kérdésed adódik, akkor keresd az oktatókat a meetingben vagy privát üzenetben (Teams chaten). - Időkeret - **A zárthelyi megoldására 2 óra áll rendelkezésre: *16:15-18:15*.** - Oszd be az idődet! Ha egy feladat nem megy, akkor inkább ugord át (legfeljebb később visszatérsz rá), és foglalkozz a többivel, hogy ne veszíts pontot olyan feladatból, amit meg tudnál csinálni! - Beadás - **A beadásra további *15* perc áll rendelkezésre: *18:15-18:30*. Ez a +15 perc *ténylegesen* a beadásra van! *18:30* után a Canvas lezár, és további beadásra nincs lehetőség!** - Ha előbb végzel, természetesen 18:30-ig bármikor beadhatod a feladatot. - A feladatokat `node_modules` mappa nélkül kell becsomagolni egy .zip fájlba, amit a Canvas rendszerbe kell feltölteni! - **A dolgozat megfelelő és hiánytalan beadása a hallgató felelőssége.** Mivel a dolgozat végén külön 15 perces időkeretet adunk a feladat megfelelő, nyugodt körülmények közötti beadására, ebből kifolyólag ilyen ügyekben nem tudunk utólagos reklamációknak helyt adni. Tehát ha valaki a zárthelyi után jelzi, hogy egy vagy több fájlt nem adott be, akkor azt sajnos nem tudjuk elfogadni. - Értékelés - A legutoljára beadott megoldás lesz értékelve. - **A zárthelyin legalább a pontok 40%-át, vagyis legalább 12 pontot kell elérni**, ez alatt a zárthelyi sikertelen. A GraphQL-re vagy Websocket-re **nincs** külön-külön minimumpont, összesen kell elérni legalább a 12 pontot, ami akár úgy is összetevődhet, hogy a GraphQL feladat 12 pontos, a Websocket pedig 0 pontos. - Vannak részpontok. - A pótzárthelyin nem lehet rontani a zárthelyi eredményéhez képest, csak javítani. - **Érvényes nyilatkozat (megfelelően kitöltött statement.txt) hiányában a kapott értékelés érvénytelen, vagyis 0 pont.** - Az elrontott, elfelejtett nyilatkozat utólag pótolható: Canvasen kommentben kell odaírni a feladathoz. - Egyéb - A feladatokat Node.js környezetben, JavaScript nyelven kell megoldani, a tantárgy keretein belül tanult technológiák használatával! - Ajánlott a Node.js LTS verziójának a használata. Ha a gépedre már telepítve van a Node.js és telepített példány legalább 2 főverzióval le van maradva az aktuálisan letölthető legfrissebbhez képest, akkor érdemes lehet frissíteni. ## Hasznos linkek - Dokumentációk - Sequelize: - [Sequelize dokumentáció](https://sequelize.org/master/) - [Model querying basics](https://sequelize.org/master/manual/model-querying-basics.html) - [Sequelize asszociációk](https://github.com/szerveroldali/2021-22-1/blob/main/SequelizeAssociations.md) (tantárgyi leírás) - GraphQL: - [GraphQL dokumentáció](https://graphql.org/learn/) - [GraphQL scalars](https://www.graphql-scalars.dev/docs) (a kezdőcsomag tartalmazza) - Socket.IO: - [Socket.IO dokumentáció](https://socket.io/docs) - [Socket.IO szobák működése](https://socket.io/docs/v4/rooms/) - [Socket.IO emit cheatsheet](https://socket.io/docs/v4/emit-cheatsheet/) - Eszközök: - [Postman](https://www.postman.com/) - [Firecamp Chrome kiegészítő](https://chrome.google.com/webstore/detail/firecamp-a-campsite-for-d/eajaahbjpnhghjcdaclbkeamlkepinbl) - [DB Browser for SQLite](https://sqlitebrowser.org/) - Gyakorlati anyagok: - [Tavalyi ZH mintamegoldása](https://github.com/szerveroldali/2021-22-1/tree/main/graphql_websocket_minta) - [GraphQL gyakorlati anyag](https://github.com/szerveroldali/2021-22-1/tree/main/esti_3_4_csut_19_30/restapi/graphql) - [Socket.IO gyakorlati anyag](https://github.com/szerveroldali/2021-22-1/tree/main/esti_3_4_csut_19_30/websocket) ## Kezdőcsomag Segítségképpen készítettünk egy kezdőcsomagot a zárthelyihez. Csak telepíteni kell a csomagokat, és kezdheted is a fejlesztést. - A kezdőcsomag elérhető itt: - https://github.com/szerveroldali/graphql_websocket_kezdocsomag - Automatikus tesztelő (`gql:` és `ws:` prefix): `npm run gql:test <FELADATOK SZÁMAI>` - Pl. 1. és 2. feladat tesztelése: `npm run gql:test 1 2` - Minden feladat tesztelése: `npm run gql:test` - Zippelő: `npm run zip` ## GraphQL (15 pont) A feladatot a kezdőcsomagon belül a `graphql/graphql/typedefs.gql`, `graphql/graphql/resolvers.js` fájlokba kell kidolgozni. A kezdőcsomag két grafikus felületet is biztosít a GraphQL-hez, ezek az alábbi linkeken érhetők el: - [localhost:4000/graphql](http://localhost:4000/graphql): GraphiQL - [localhost:4000/playground](http://localhost:4000/playground): GraphQL Playground (ajánlott) ### Modellek Az alábbi modelleket készen kapod, ami tartalmazza a következőket: migration, model, seeder. **Tehát nem neked kell őket megírni, neked csak annyi a feladatod, hogy a készen kapott fájlokat bemásolod és inicializálod az adatbázist (`npm run db`), hogy használni tudd!** Az adatokat lokális SQLite adatbázisban kell tárolni. Segítségképppen a modellek felépítése az alábbi módon néz ki: - Modellek: - `Storage`: tárolók - `name`: string, unique (tehát egyedi, vagyis ugyanaz a név nem szerepelhet kétszer) - `capacity`: number - `Appliance`: konyhai berendezések - `name`: string - `Ingredient`: hozzávalók - `name`: string - `amount`: number - `StorageId` (összekapcsolásból jön) - `Recipe`: receptek - `name`: string, unique (tehát egyedi, vagyis ugyanaz a név nem szerepelhet egyszerre több beszállítónál) - `isVegetarian`: boolean - `doneCount`: number _(vagyis hányszor készítették már el)_ - Relációk - `Recipe` N - N `Ingredient` - `Appliance` 1 - N `Recipe` - `Storage` 1 - N `Ingredient` ### Típusdefiníció Adott az alábbi GraphQL típusdefiníció. Másold be a kezdőcsomagba, ezt követően pedig implementálod a szükséges műveleteket. A műveletek implementálása során a típusdefiníciót értelemszerűen ki kell egészíteni, hiszen az alábbi csak egy kezdeti állapot. ```graphql # Ezt majd feladatról feladatra haladva ki kell egészíteni type Recipe { id: ID! name: String isVegetarian: Boolean doneCount: Int appliance: Appliance ingredients: [Ingredient] createdAt: DateTime! updatedAt: DateTime! } type Ingredient { id: ID! name: String amount: Int isInBigStorage: Boolean createdAt: DateTime! updatedAt: DateTime! } type Appliance { id: ID! name: String createdAt: DateTime! updatedAt: DateTime! } type Storage { id: ID! name: String capacity: Int createdAt: DateTime! updatedAt: DateTime! } ``` ### 1. feladat: `recipes` (2 pont) - Összes recept lekérése, a hozzá tartozó berendezéssel és hozzávalókkal együtt - Kérés: ```graphql query { recipes { id, name, isVegetarian, doneCount, createdAt, updatedAt, appliance { id, name }, ingredients { id, name, amount } } } ``` - Válasz: a recepthez kapcsolt berendezést és hozzávalókat listázni kell a példán látható módon ```json { "data": { "recipes": [ { "id": "1", "name": "molestiae", "isVegetarian": false, "doneCount": 40, "createdAt": "2021-12-17T...", "updatedAt": "2021-12-17T...", "appliance": { "id": "5", "name": "expedita" }, "ingredients": [ { "id": "13", "name": "corrupti", "amount": 42 } ] }, { "id": "2", "name": "omnis", "isVegetarian": false, "doneCount": 67, "createdAt": "2021-12-17T...", "updatedAt": "2021-12-17T...", "appliance": { "id": "3", "name": "ea" }, "ingredients": [] }, ... } ``` ### 2. feladat: `updateIngredient` (2 pont) - `updateIngredient(ingredientId, input)` - Egy hozzávaló módosítása. Itt az input azokra a kulcs-érték párosokra utal, amit módosítani szeretnénk. - Kérés ```graphql mutation { updateIngredient(ingredientId: 1, input: { name: "UJ_NEV" }) { id name updatedAt } } ``` - Válasz ```json { "data": { "updateIngredient": { "id": "1", "name": "UJ_NEV", "updatedAt": "2021-12-17T..." } } } ``` ### 3. feladat: `ingredient` (1 pont) - `ingredient(id)` - Egy hozzávaló lekérdezése (erre még nem jár pont). Implementáld a `isInBigStorage` mezőt, ami visszaadja, hogy a hozzá tartozó tároló kapacitása nagyobb-e **20**-nál. - Kérés: ```graphql query { ingredient(id: 1) { id, name, isInBigStorage } } ``` - Válasz: ```json { "data": { "ingredient": { "id": "1", "name": "UJ_NEV", "isInBigStorage": true } } } ``` ### 4. feladat: `smallestStorage` (2 pont) - Visszaadja az adatbázisban tárolt legkisebb kapacitású tárolót és az összes olyan hozzávalót, amivel ebben található (tehát amikkel relációban van). - Kérés: ```graphql query { smallestStorage { id, name, capacity, ingredients { id, name, amount } } } ``` - Válasz: ```json { "data": { "smallestStorage": { "id": "9", "name": "quod", "capacity": 2, "ingredients": [ { "id": "8", "name": "est", "amount": 54 }, { "id": "9", "name": "omnis", "amount": 80 } ] } } } ``` ### 5. feladat: `storeIngredients` (2 pont) - `storeIngredients(storageId, ingredients)` - Egy megadott tárolóhoz rendel hozzá plusz hozzávalókat. Fontos, hogy az `ingredients` mezőben a hozzávalók mezői vannak (`name`, `amount`) és nem cserélik le a tárolóban lévőeket, hanem kiegészítik azokat (tehát csak hozzáadódnak a tárolóhoz). - Kérés: ```graphql mutation { storeIngredients(storageId: 4, ingredients: [ { name: "ingredient1" }, { name: "ingredient2", amount: 3 } ] ) { id, name, amount } } ``` - Válasz: A tárolóban lévő hozzávalók. ```json { "data": { "storeIngredients": [ { "id": "8", "name": "occaecati", "amount": 44 }, { "id": "24", "name": "ingredient1", "amount": null }, { "id": "25", "name": "ingredient2", "amount": 3 } ] } } ``` ### 6. feladat: `changeApplianceName` (3 pont) - `changeApplianceName(applianceId, newName)` - Az `applianceId` mezőben megadott id-jú berendezés nevét lecseréli a `newName` mező értékére, **DE** csak akkor, ha a berendezéshez a receptek kevesebb mint 30%-a tartozik. Tehát: - ha `BERENDEZÉSHEZ_TARTOZÓ_RECEPTEK_SZÁMA < ÖSSZES_RECEPT_30_SZÁZALÉKA`, akkor megváltozik a neve - ha `BERENDEZÉSHEZ_TARTOZÓ_RECEPTEK_SZÁMA >= ÖSSZES_RECEPT_30_SZÁZALÉKA`, akkor nem történik semmi - Kérés ```graphql mutation { changeApplianceName(applianceId: 1, newName: "MEGVALTOZOTT") { id, name } } ``` - Válasz ```json { "data": { "changeApplianceName": { "id": "1", "name": "MEGVALTOZOTT" } } } ``` ### 7. feladat: `statistics` (3 pont) - A receptekről készít statisztikát. - Kérés: ```graphql query { statistics { popularVegetarianRecipeCount mostPopularRecipeName leastPopularRecipeName averageDoneCount } } ``` - Válasz: le kell kérni a receptekhez aktuálisan tartozó statisztikákat. A statisztika a következő mezőkből áll: - `popularVegetarianRecipeCount`: hány olyan vegetáriánus recept van (`isVegetarian`) amit több mint 10 ember csinált meg (`doneCount`) - `mostPopularRecipeName`: annak a receptnek a neve (`name`), aminek a legmagasabb a `doneCount`-ja. Ha több, doneCount-ú recept van, akkor a legkisebb id-jút kell visszaadni - `leastPopularRecipeName`: annak a receptnek a neve (`name`), aminek a legalacsonyabb a `doneCount`-ja. Ha több, doneCount-ú recept van, akkor a legkisebb id-jút kell visszaadni - `averageDoneCount`: az összes recept `doneCount` mezőjéből vett átlag (lefelé kerekítve, egész számra) Az alább példa szerint kell visszaadni a statisztikát: - Megjegyzés: Ehhez már új típust is létre kell hozni ```json { "data": { "statistics": { "popularVegetarianRecipeCount": 8, "mostPopularRecipeName": "ut", "leastPopularRecipeName": "ipsum", "averageDoneCount": 60 } } } ``` ## Websocket/Socket.io (15 pont) A feladatod egy chat elkészítése. A klienseknek legyen lehetősége belépni chatszobákba, ahol üzenetet tudnak küldeni a többi tagnak. Egy kliens saját szobát is csinálhat, ahová más kliensek csatlakozhatnak. Ha valaki létrehoz egy szobát, automatikusan a saját szobája adminjává válik, és jogában áll lenémítani tagokat, így ők onnantól kezdve nem írhatnak a többieknek abban a szobában. Az adatokat a szerver memóriájában kell tárolni, az alábbi minta szerint: ```js let db = { rooms: { room1: { admin: "socket1", members: ["socket1", "socket2", "socket3"], muted: ["socket2"], messages: [ { timestamp: 123456789, client: "socket1", message: "sziasztok" }, { timestamp: 123456789, client: "socket3", message: "hali" }, ], }, "Másik szoba": { admin: "socket2", members: ["socket2"], muted: [], messages: [{ timestamp: 123456789, client: "socket2", message: "foreveralone" }], }, }, }; ``` **Ezekre figyelj, hogy a tesztelő működjön:** - *Az adatokat a `db`-be tárold és onnan is olvasd ki.* - *A fenti példa elnevezéseit és felépítését kövesd. Pl: a `muted` maradjon `muted`, NE legyen pl. `mutedMembers`!* - *A végpontoknak két paramétere legyen, ahogy gyakorlatokon tanultuk: `data` és `ack`, ahol a `data` egy objektum, ami tartalmazza az összes bemenő adatot.* - *Pontosan kövesd a feladatokban megadott hibaüzeneteket.* A feladatot a kezdőcsomagon belül a `websocket/events.js` fájlba kell kidolgozni. ### 1. feladat: `list-rooms` (1 pont) - Elérhető chat szobák listázása - Paraméterek: - - Válasz (acknowledgement): - Jó esetben: `{ status: 'ok', rooms: ['room1', 'room2', ...] }` - Hiba esetén: `{ status: 'error', message: '<hibaüzenet>'}` ### 2. feladat: `create-room` (2 pont) - Szoba létrehozása. Ilyenkor aki létrehozza a szobát, automatikusan csatlakozik hozzá, illetve az adminjává is válik. A kliens csatlakozását és admin jogát az adatbázisban le kell tárolni, továbbá SocketIO szinten is hozzá kell őt adni a szobához. - Paraméterek - `room`: a létrehozandó szoba neve - Válasz (acknowledgement): - Jó esetben: `{ status: 'ok' }` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - A megadott névvel már létezik szoba: `{ status: 'error', message: 'This name is already taken!'}` ### 3. feladat: `join-room` (1 pont) - Csatlakozás egy chatszobához. A kliens csatlakozását az adatbázisban is le kell tárolni, továbbá SocketIO szinten is hozzá kell őt adni a szobához. - Paraméterek - `room`: a szoba neve, amihez csatlakozni szeretnénk - Válasz (acknowledgement): - Jó esetben: `{ status: 'ok' }` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - Nem létező szoba: `{ status: 'error', message: 'No such room in our system!'}` - A kliens már a szoba tagja: `{ status: 'error', message: 'You are already subscribed to this room!'}` ### 4. feladat: `mute-client` (5 pont) - Az adminnak legyen lehetősége lenémítani egy klienst, aki az ő szobájában van. - Paraméterek - `room`: a szoba neve, amelyben némítani szeretnénk - `clientId`: a némítandó kliens SocketIO azonosítója - `reason`: a némítás oka (opcionális) - Válasz (acknowledgement): - Jó esetben: - `{ status: 'ok' }` - Továbbá a lenémított kliensnek el kell küldeni a `muted` üzenetet, a következő adatokkal (minta): - `{ room: 'room1', admin: 'socket1', reason: 'káromkodtál' }` - Ha nem volt `reason` megadva, az értéke legyen `"Nincs indok"` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - Nem létező szoba: `{ status: 'error', message: 'No such room in our system!'}` - A kliens nem a szoba tagja: `{ status: 'error', message: 'You are not subscribed to this room!'}` - A kliens nem admin a szobában: `{ status: 'error', message: 'You have no power here, Gandalf the Grey!'}` - A kliens saját magát akarja némítani: `{ status: 'error', message: 'You can't mute yourself!'}` - A célpont nem tagja a szobának: `{ status: 'error', message: 'The target is not a member of the room!'}` - A célpont már némítva van: `{ status: 'error', message: 'The target is already muted!'}` ### 5. feladat: `send-message` (6 pont) - Üzenet küldése a chat szoba tagjainak, ha nem vagyunk némítva. - Paraméterek - `room`: a szoba neve, amelyben üzenni szeretnénk - `message`: üzenet tartalma - Válasz (acknowledgement): - Jó esetben: - `{ status: 'ok' }` - Továbbá a szobában lévő összes kliensnél (de csak náluk) `message-received` eseményt kell kiváltani, a következő adatokkal (minta): - `{ room: 'room1', timestamp: 123456789, client: 'socket1', message: 'sziasztok' }` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - Nem létező szoba: `{ status: 'error', message: 'No such room in our system!'}` - A kliens nem a szoba tagja: `{ status: 'error', message: 'You are not subscribed to this room!'}` - A kliens némítva van: `{ status: 'error', message: 'You are muted!'}` <file_sep>const faker = require('faker'); const Joi = require('joi'); const { v4: uuidv4 } = require('uuid'); const validate = require('./validate'); module.exports = (io) => { const securities = { 'ELTE': { prices: [ { timestamp: 1610110943147, price: 1234 }, { timestamp: 1610110969348, price: 1255 }, { timestamp: 1610110976805, price: 1340 }, ], offers: [ { clientId: 'client1', quantity: 0.65, intent: 'sell', active: true }, { clientId: 'client3', quantity: 2.0, intent: 'buy', active: false }, ] }, } io.on("connection", (socket) => { //console.log(socket); socket.on("list-securities", (_, ack) => { ack({ status: "ok", securities: Object.keys(securities), }); }); socket.on("get-historic-data", validate( Joi.object({ security: Joi.string().trim().min(1).required(), count: Joi.number().integer().min(0).required() }), ({ security, count }, ack) => { if (!Object.keys(securities).includes(security)) throw new Error('No such security in our system.'); ack({ status: "ok", prices: securities[security].prices.slice(0, count), }); }) ); socket.on("join-security", validate( Joi.object({ security: Joi.string().trim().min(1).required(), }), ({ security }, ack) => { if (!Object.keys(securities).includes(security)) throw new Error('No such security in our system.'); if (socket.rooms.has(security)) throw new Error('You are already subscribed to this security.'); socket.join(security); ack({ status: "ok" }); //console.log(socket); }) ); socket.on("leave-security", validate( Joi.object({ security: Joi.string().trim().min(1).required(), }), ({ security }, ack) => { if (!Object.keys(securities).includes(security)) throw new Error('No such security in our system.'); if (!socket.rooms.has(security)) throw new Error('You do not follow this security.'); socket.leave(security); ack({ status: "ok" }); //console.log(socket); }) ); socket.on("send-offer", validate( Joi.object({ security: Joi.string().trim().min(1).required(), quantity: Joi.number().min(0).required(), intent: Joi.string().trim().valid('buy', 'sell').required(), }), ({ security, quantity, intent }, ack) => { if (!Object.keys(securities).includes(security)) throw new Error('No such security in our system.'); if (!socket.rooms.has(security)) throw new Error('You do not follow this security.'); const id = uuidv4(); securities[security].offers.push({ id, clientId: socket.id, quantity, intent, active: true }); io.in(security).emit("offer-sent", { id, security, quantity, intent, }); ack({ status: "ok" }); }) ); socket.on("accept-offer", validate( Joi.object({ security: Joi.string().trim().min(1).required(), id: Joi.string().guid({ version: ['uuidv4']}), }), ({ security, id }, ack) => { if (!Object.keys(securities).includes(security)) throw new Error('No such security in our system.'); if (!socket.rooms.has(security)) throw new Error('You do not follow this security.'); // Az offers tömb hanyadik indexe const offerIdx = securities[security].offers.findIndex(offer => offer.id === id); // Ha nem létezik az offer if (offerIdx === -1) throw new Error('No such offer in our system.'); // Ezen a ponton már biztos létezik az offer if (securities[security].offers[offerIdx].active === false) throw new Error('Inactive offer.'); securities[security].offers[offerIdx].active = false; // Üzenet küldése az eladónak és a vevőnek const { clientId, quantity, intent } = securities[security].offers[offerIdx]; io.to([socket.id, clientId]).emit("offer-accepted", { id, security, quantity, intent, }); ack({ status: "ok" }); }) ); }); priceChange = () => { const securityNames = Object.keys(securities); // tömb const security = faker.random.arrayElement(securityNames); // random elem egy tömbből const price = faker.datatype.number({ min: 500, max: 5000 }); securities[security].prices.push({ timestamp: Date.now(), price, }); io.in(security).emit("price-changed", { security, price }); setTimeout(priceChange, 1000); console.log(securities); } priceChange(); }<file_sep># Becsomagolt feladatok Az `npm run zip` parancs kiadása után ebben a mappában találod meg a becsomagolt feladatokat, amiket be tudsz adni Canvasen. <file_sep>const faker = require('faker'); module.exports = (io) => { games = []; io.on("connection", (socket) => { socket.on("tip", (data, ack) => { try { // Elvárás: data = { number: 3 } const { number } = data; if (!number) { throw new Error("No number specified"); } // Hibás: data = { number: 'asd' } if (isNaN(parseInt(number))) { throw new Error("Not a number"); } // Aktuális játék: games[games.length - 1] if (games[games.length - 1].tips.find((tip) => tip.client === socket.id)) { throw new Error("Already tipped"); } games[games.length - 1].tips.push({ client: socket.id, number, // = number: number, }); ack({ status: "ok" }) } catch (error) { ack({ status: "error", message: error.message, }) } }) }); gameOver = () => { const sorted = games[games.length - 1].tips.sort((a, b) => a.number - b.number); // Nyertes szám const winner = sorted.find(tip => sorted.filter((anotherTip) => tip.number === anotherTip.number).length === 1); console.log(sorted); console.log(winner); for (const { client, number } of games[games.length - 1].tips) { io.to(client).emit("game-over", { won: number === winner.number, tipped: number, winner, }) } } // Mennyi ideig tartson a játék (mp) newGame = () => { // game-over if (games.length > 0) gameOver(); // Mindig a games tömb legutolsó eleme (object) az aktuális játék games.push({ startTime: Date.now(), tips: [] }); // new-game-started io.emit("new-game-started"); const time = faker.datatype.number({ min: 10, max: 20 }); console.log(`Új játék lett indítva, következő játék ${time} mp múlva`); setTimeout(newGame, time * 1000); } // 1. játék indítása newGame(); }<file_sep>import Picker from 'vanilla-picker'; window.Picker = Picker; <file_sep><?php require_once 'vendor/autoload.php'; // use the factory to create a Faker\Generator instance $faker = Faker\Factory::create(); // generate data by calling methods echo $faker->name() . PHP_EOL; // '<NAME>' echo $faker->email() . PHP_EOL; // '<EMAIL>' echo $faker->text(); // 'Numquam ut mollitia at consequuntur inventore dolorem.'<file_sep># Szerveroldali webprogramozás - GraphQL, Websocket pótzárthelyi _2022. január 13. 16:00-19:15 (3 óra kidolgozás + 15 perc beadás)_ Tartalom: - [Szerveroldali webprogramozás - GraphQL, Websocket pótzárthelyi](#szerveroldali-webprogramozás---graphql-websocket-pótzárthelyi) - [Tudnivalók](#tudnivalók) - [Hasznos linkek](#hasznos-linkek) - [Kezdőcsomag](#kezdőcsomag) - [GraphQL (15 pont)](#graphql-15-pont) - [Modellek és relációk](#modellek-és-relációk) - [Típusdefiníció](#típusdefiníció) - [1. feladat: ```info``` (1 pont)](#1-feladat-info-1-pont) - [2. feladat ```availableBooks``` (4 pont)](#2-feladat-availablebooks-4-pont) - [3. feladat ```userLoans``` (3 pont)](#3-feladat-userloans-3-pont) - [4. feladat ```bookLend``` (4 pont)](#4-feladat-booklend-4-pont) - [5. feladat ```bookReturn``` (3 pont)](#5-feladat-bookreturn-3-pont) - [Websocket/Socket.io (15 pont)](#websocketsocketio-15-pont) - [1. feladat: `list-rooms` (1 pont)](#1-feladat-list-rooms-1-pont) - [2. feladat: `create-room` (2 pont)](#2-feladat-create-room-2-pont) - [3. feladat: `join-room` (1 pont)](#3-feladat-join-room-1-pont) - [4. feladat: `mute-client` (5 pont)](#4-feladat-mute-client-5-pont) - [5. feladat: `send-message` (6 pont)](#5-feladat-send-message-6-pont) ## Tudnivalók - Kommunikáció - **A Teams csoport Általános csatornáján a zárthelyi egész ideje alatt lesz egy meeting! Erősen ajánlott, hogy ehhez csatlakozzatok, hiszen elsősorban ebben a meetingben válaszolunk a felmerülő kérdésekre, valamint az esetleges időközben felmerülő információkat is itt osztjuk meg veletek!** - Ha a zárthelyi közben valamilyen problémád, kérdésed adódik, akkor keresd az oktatókat a meetingben vagy privát üzenetben (Teams chaten). - Időkeret - **A zárthelyi megoldására 3 óra áll rendelkezésre: *16:00-19:00*.** - Oszd be az idődet! Ha egy feladat nem megy, akkor inkább ugord át (legfeljebb később visszatérsz rá), és foglalkozz a többivel, hogy ne veszíts pontot olyan feladatból, amit meg tudnál csinálni! - Beadás - **A beadásra további *15* perc áll rendelkezésre: *19:00-19:15*. Ez a +15 perc *ténylegesen* a beadásra van! *19:15* után a Canvas lezár, és további beadásra nincs lehetőség!** - Ha előbb végzel, természetesen 19:15-ig bármikor beadhatod a feladatot. - A feladatokat `node_modules` mappa nélkül kell becsomagolni egy .zip fájlba, amit a Canvas rendszerbe kell feltölteni! - **A dolgozat megfelelő és hiánytalan beadása a hallgató felelőssége.** Mivel a dolgozat végén külön 15 perces időkeretet adunk a feladat megfelelő, nyugodt körülmények közötti beadására, ebből kifolyólag ilyen ügyekben nem tudunk utólagos reklamációknak helyt adni. Tehát ha valaki a zárthelyi után jelzi, hogy egy vagy több fájlt nem adott be, akkor azt sajnos nem tudjuk elfogadni. - Értékelés - A legutoljára beadott megoldás lesz értékelve. - **A zárthelyin legalább a pontok 40%-át, vagyis legalább 12 pontot kell elérni**, ez alatt a zárthelyi sikertelen. - A GraphQL-re vagy Websocket-re **nincs** külön-külön minimumpont, összesen kell elérni legalább a 12 pontot, ami akár úgy is összetevődhet, hogy a GraphQL feladat 12 pontos, a Websocket pedig 0 pontos. - Vannak részpontok. - **A pótzárthelyin nem lehet rontani a zárthelyi eredményéhez képest, csak javítani.** Ez azt jelenti, ha valaki egy adott témakörből (pl. REST API) megírja mindkét zárthelyit (a normált és a pótot is), akkor a jegyébe a kettő közül a jobbik eredményt fogjuk beszámítani. Azonban fontos, hogy ez a "jobbik eredmény" legalább 40% (vagyis legalább 12 pont) legyen, különben az illető nem teljesítette a tárgyat, hiszen az adott témakörből nem érte el a minimális 40%-ot, még a jobb eredménnyel sem! - **Érvényes nyilatkozat (megfelelően kitöltött statement.txt) hiányában a kapott értékelés érvénytelen, vagyis 0 pont.** - Az elrontott, elfelejtett nyilatkozat utólag pótolható: Canvasen kommentben kell odaírni a feladathoz. - Egyéb - A feladatokat Node.js környezetben, JavaScript nyelven kell megoldani, a tantárgy keretein belül tanult technológiák használatával! - Ajánlott a Node.js LTS verziójának a használata. Ha a gépedre már telepítve van a Node.js és telepített példány legalább 2 főverzióval le van maradva az aktuálisan letölthető legfrissebbhez képest, akkor érdemes lehet frissíteni. ## Hasznos linkek - Dokumentációk - Sequelize: - [Sequelize dokumentáció](https://sequelize.org/master/) - [Model querying basics](https://sequelize.org/master/manual/model-querying-basics.html) - [Sequelize asszociációk](https://github.com/szerveroldali/2021-22-1/blob/main/SequelizeAssociations.md) (tantárgyi leírás) - GraphQL: - [GraphQL dokumentáció](https://graphql.org/learn/) - [GraphQL scalars](https://www.graphql-scalars.dev/docs) (a kezdőcsomag tartalmazza) - Socket.IO: - [Socket.IO dokumentáció](https://socket.io/docs) - [Socket.IO szobák működése](https://socket.io/docs/v4/rooms/) - [Socket.IO emit cheatsheet](https://socket.io/docs/v4/emit-cheatsheet/) - Eszközök: - [Postman](https://www.postman.com/) - [Firecamp Chrome kiegészítő](https://chrome.google.com/webstore/detail/firecamp-a-campsite-for-d/eajaahbjpnhghjcdaclbkeamlkepinbl) - [DB Browser for SQLite](https://sqlitebrowser.org/) - Gyakorlati anyagok: - [Tavalyi ZH mintamegoldása](https://github.com/szerveroldali/2021-22-1/tree/main/graphql_websocket_minta) - [GraphQL gyakorlati anyag](https://github.com/szerveroldali/2021-22-1/tree/main/esti_3_4_csut_19_30/restapi/graphql) - [Socket.IO gyakorlati anyag](https://github.com/szerveroldali/2021-22-1/tree/main/esti_3_4_csut_19_30/websocket) ## Kezdőcsomag Segítségképpen biztosítunk egy kezdőcsomagot a zárthelyihez. Csak telepíteni kell a csomagokat, és kezdheted is a fejlesztést. - A kezdőcsomag elérhető itt: - https://github.com/szerveroldali/graphql_websocket_kezdocsomag - Automatikus tesztelő (`gql:` és `ws:` prefix): `npm run gql:test <FELADATOK SZÁMAI>` - Pl. 1. és 2. feladat tesztelése: `npm run gql:test 1 2` - Minden feladat tesztelése: `npm run gql:test` - Zippelő: `npm run zip` ## GraphQL (15 pont) A feladatot a kezdőcsomagon belül a `graphql/graphql/typedefs.gql`, `graphql/graphql/resolvers.js` fájlokba kell kidolgozni. A kezdőcsomag két grafikus felületet is biztosít a GraphQL-hez, ezek az alábbi linkeken érhetők el: - [localhost:4000/graphql](http://localhost:4000/graphql): GraphiQL - [localhost:4000/playground](http://localhost:4000/playground): GraphQL Playground (ajánlott) ### Modellek és relációk Az alábbi modelleket készen kapod, ami tartalmazza a következőket: migration, model, seeder. **Tehát nem neked kell őket megírni, neked csak annyi a feladatod, hogy a készen kapott fájlokat bemásolod és inicializálod az adatbázist (`npm run gql:db`), hogy használni tudd!** Az adatokat lokális SQLite adatbázisban kell tárolni. Az `id`, `createdAt`, `updatedAt` a Sequelize ORM szempontjából alapértelmezett mezők, így ezeket a feladat nem specifikálja. Alapesetben egyik mező értéke sem lehet null, hacsak nem adtunk külön `nullable` kikötést! Tehát alapértelmezés szerint a migration minden mezőjére ```js allowNull: false ``` van érvényben, kivéve ott, ahol ezt a feladat másképp nem kéri! A modellek az alábbiak: - User: felhasználó - `id`: integer, autoIncrement, primaryKey - `name`: string - `email`: string, unique - `password`: string - `MembershipId`: integer, nullable - `createdAt`: date - `updatedAt`: date - `Book`: könyv - `id`: integer, autoIncrement, primaryKey - `author`: string, nullable - `title`: string, nullable - `description`: string, nullable - `numberOfCopies`: integer, nullable - `createdAt`: date - `updatedAt`: date - `Loan`: kölcsönzés - `id`: integer, autoIncrement, primaryKey - `UserId`: integer - `BookId`: integer - `expire`: date - `createdAt`: date - `updatedAt`: date - `Membership`: tagság - `id`: integer, autoIncrement, primaryKey - `name`: string - `maxLoans`: integer - `fine`: integer - `createdAt`: date - `updatedAt`: date A fenti modellek közötti relációk pedig a következőképpen alakulnak: - `User` 1-N `Loan` - `Membership` 1-N `User` - `Book` 1-N `Loan` ### Típusdefiníció Adott az alábbi GraphQL típusdefiníció. Másold be a kezdőcsomagba, ezt követően pedig implementálod a szükséges műveleteket. A műveletek implementálása során a típusdefiníciót értelemszerűen ki kell egészíteni, hiszen az alábbi csak egy kezdeti állapot. ```graphql type Query { info: InfoResult! availableBooks: [availableBookResult] userLoans(userId: Int!): [userLoanResult] } type Mutation { bookLend(userId: Int!, bookId: Int!): Date! bookReturn(userId: Int!, bookId: Int!): Int! } type availableBookResult { book: Book! numberOfAvailableCopies: Int! } type userLoanResult { book: Book expire: Date fine: Int } type InfoResult { name: String! neptun: String! email: String! } # Tagsági szint type Membership { id: ID! name: String! # A tagsági szint neve maxLoans: Int! # Maximálisan kölcsönözhető könyvek száma fine: Int! # Késedelmes visszaadás esetén a napi birság összege createdAt: Date! updatedAt: Date! } # Felhasználó type User { id: ID! name: String! email: String! createdAt: Date! updatedAt: Date! # Asszociációk membership: Membership! } # Könyv type Book { id: ID! author: String! # A könyv szerzője title: String! # A könyv címe description: String! # A könyv fülszövege (leírása) numberOfCopies: Int! # Példányszám, a könyvtár ennyi példánnyal rendelkezik ebből a könyvből createdAt: Date! updatedAt: Date! } # Kölcsönzések type Loan { id: ID! expire: Date! # A kölcsönzés lejárati dátuma, ezt követően napi bírságot kell fizetni a késedelmes visszaadásért createdAt: Date! updatedAt: Date! # Asszociációk user: User! book: Book! } ``` ### 1. feladat: ```info``` (1 pont) **Query:** Írasd ki a nevedet, neptun kódodat és az egyetemi email címedet! **Kérés:** ```graphql query { info { name neptun email } } ``` **Minta válasz:** (a saját adataiddal) ```json { "data": { "info": { "name": "<NAME>", "neptun": "LX12AG", "email": "<EMAIL>" } } } ``` ### 2. feladat ```availableBooks``` (4 pont) **Query:** Összes könyv lekérése, az elérhető (tehát ki nem vett) példányok számával. **Kérés:** ```graphql query { availableBooks { book { title numberOfCopies } numberOfAvailableCopies } } ``` **Minta válasz:** ```json { "data": { "availableBooks": [ { "book": { "title": "qui", "numberOfCopies": 16 }, "numberOfAvailableCopies": 5 }, { "book": { "title": "ut dignissimos", "numberOfCopies": 0 }, "numberOfAvailableCopies": 0 }, { "book": { "title": "recusandae harum distinctio", "numberOfCopies": 7 }, "numberOfAvailableCopies": 0 }, {...} ] } } ``` ### 3. feladat ```userLoans``` (3 pont) **Query:** Egy adott felhasználó által kikölcsönzött könyvek megjelenítése, a kölcsönzés lejáratának idejével és a mai napig fizetendő bírság összegével (ha még nem járt le a kölcsönzés, akkor a ```fine``` legyen 0). Ha a ```userId``` nem létezik, dobj hibát! A napi birság összegét a felhasználóhoz tartozó Membership-ből tudod kinyerni (```Membership.fine```)! Tipp: Két dátum között eltelt nap meghatározásához az alábbi segédfüggvény használható: ```js /** * Kiszámítja a két dátum között eltelt időt. * * @param {String | Date} firstDate A kölcsönzés lejárati dátuma. * @param {String | Date} secondDate Alapértelmezetten az aktuális időpont. * @returns {Integer} A két dátum között eltelt napok száma. Értéke negatív is lehet! */ function daysBetweenDates(firstDate, secondDate = new Date()) { return Math.round((new Date(firstDate).setHours(12,0,0,0) - new Date(secondDate).setHours(12,0,0,0)) / (1000*3600*24)); } ``` **Kérés:** ```graphql query { userLoans(userId: 2) { expire fine book { author title } } } ``` **Minta válasz:** *Tfh.:* aktuális dátum: **2021-12-11**, felhasználó tagsága alapján a napi bírság: **50** ``` json { "data": { "userLoans": [ { "book": { "author": "<NAME>", "title": "magni nam esse" }, "expire": "2021-12-09", "fine": 100 }, { "book": { "author": "<NAME>", "title": "quas nostrum rerum" }, "expire": "2021-12-08", "fine": 150 }, { "book": { "author": "<NAME>", "title": "quia porro" }, "expire": "2021-12-15", "fine": 0 } ] } } ``` ### 4. feladat ```bookLend``` (4 pont) **Mutation:** Egy könyv kikölcsönzése. A felhasználó és a könyv id-ját paraméteresen adjuk át, sikeres kölcsönzés esetén a visszavétel határidejét kapjuk meg. A határidő mindig az aktuális napot követő **14 nap**. Tipp: Egy adott időponthoz a következő segédfüggvénnyel lehet hozzáadni tetszőleges napot. ```js /** * Egy dátumhoz a paraméterben megadott napok számát adja hozzá. * * @param {Integer} days A hozzáadandó napok száma. * @param {String | Date} date A kiindulási dátum, melyhez a napokat hozzá akarjuk adni. Alapértelmezetten az aktuális időpont. * @returns {Date} A megadott napszámmal későbbi dátum. */ function addDays(days, date = new Date()) { return new Date(new Date(date).setHours(12,0,0,0) + (1000*3600*24*days)); } ``` Validáció: - Ellenőrizd, hogy a megadott ```userId``` és ```bookId``` helyesek-e, ha valamelyik rekord nem létezik, dobj értelmes hibát! - Ellenőrizd, hogy a felhasználó elérte-e már a tagsági szintje alapján (```Membership.maxLoans```) maximális egyidejű kölcsönzések számát. Ha igen, akkor dobj értelmes hibát! - Ellenőrizd, hogy van-e szabad példány a kikölcsönözni kívánt könyvből (```Book.numberOfCopies``` – ```[*már kikölcsönzött példányok száma*]```)! Ha nincs, dobj értelmes hibát! Ha nem került dobásra hiba, akkor vegyél fel egy új rekordot a ```Loans``` táblába a megfelelő adatokkal és add vissza a visszahozási határidőt! **Kérés:** ```graphql mutation { bookLend(userId: 1, bookId: 2) } ``` **Minta válasz:** *Tfh.:* az aktuális dátum: **2021-12-11** ``` json { "data": { "bookLend": "2021-12-25" } } ``` ### 5. feladat ```bookReturn``` (3 pont) **Mutation:** Egy könyv visszavétele. A felhasználó és a könyv id-ja paraméteresen kerül átadásra, sikeres visszavétel esetén a késedelmi birság összegét add meg! Ha időben lett visszaadva, térj vissza 0-ával! Validáció: - Ellenőrizd, hogy a megadott ```userId``` és ```bookId``` helyesek-e, ha valamelyik rekord nem létezik, dobj értelmes hibát! - Ellenőrizd, hogy a megadott felhasználó kikölcsönözte-e a megadott könyvet (tartozik-e rekord a ```Loans``` táblában a megadott ```userId``` és ```bookId``` pároshoz)! Ha nem, dobj értelmes hibát! Ha nem került dobásra hiba, akkor töröld a megfelelő rekordot a ```Loans``` táblából és add vissza a késedelmes visszavétel birságának összegét (napi birság díja a felhasználóhoz tartozó: ```Membership.fine```). Ha a visszavétel nem volt késedelmes, térj vissza 0-ával! **Kérés:** ```graphql mutation { bookReturn(userId: 10, bookId: 13) } ``` **Minta válasz:** ``` json { "data": { "bookReturn": 200 } } ``` ## Websocket/Socket.io (15 pont) A feladatod egy chat elkészítése. A klienseknek legyen lehetősége belépni chatszobákba, ahol üzenetet tudnak küldeni a többi tagnak. Egy kliens saját szobát is csinálhat, ahová más kliensek csatlakozhatnak. Ha valaki létrehoz egy szobát, automatikusan a saját szobája adminjává válik, és jogában áll lenémítani tagokat, így ők onnantól kezdve nem írhatnak a többieknek abban a szobában. Az adatokat a szerver memóriájában kell tárolni, az alábbi minta szerint: ```js let db = { rooms: { room1: { admin: "socket1", members: ["socket1", "socket2", "socket3"], muted: ["socket2"], messages: [ { timestamp: 123456789, client: "socket1", message: "sziasztok" }, { timestamp: 123456789, client: "socket3", message: "hali" }, ], }, "Másik szoba": { admin: "socket2", members: ["socket2"], muted: [], messages: [{ timestamp: 123456789, client: "socket2", message: "foreveralone" }], }, }, }; ``` **Ezekre figyelj, hogy a tesztelő működjön:** - *Az adatokat a `db`-be tárold és onnan is olvasd ki.* - *A fenti példa elnevezéseit és felépítését kövesd. Pl: a `muted` maradjon `muted`, NE legyen pl. `mutedMembers`!* - *A végpontoknak két paramétere legyen, ahogy gyakorlatokon tanultuk: `data` és `ack`, ahol a `data` egy objektum, ami tartalmazza az összes bemenő adatot.* - *Pontosan kövesd a feladatokban megadott hibaüzeneteket.* A feladatot a kezdőcsomagon belül a `websocket/events.js` fájlba kell kidolgozni. ### 1. feladat: `list-rooms` (1 pont) - Elérhető chat szobák listázása - Paraméterek: - - Válasz (acknowledgement): - Jó esetben: `{ status: 'ok', rooms: ['room1', 'room2', ...] }` - Hiba esetén: `{ status: 'error', message: '<hibaüzenet>'}` ### 2. feladat: `create-room` (2 pont) - Szoba létrehozása. Ilyenkor aki létrehozza a szobát, automatikusan csatlakozik hozzá, illetve az adminjává is válik. A kliens csatlakozását és admin jogát az adatbázisban le kell tárolni, továbbá SocketIO szinten is hozzá kell őt adni a szobához. - Paraméterek - `room`: a létrehozandó szoba neve - Válasz (acknowledgement): - Jó esetben: `{ status: 'ok' }` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - A megadott névvel már létezik szoba: `{ status: 'error', message: 'This name is already taken!'}` ### 3. feladat: `join-room` (1 pont) - Csatlakozás egy chatszobához. A kliens csatlakozását az adatbázisban is le kell tárolni, továbbá SocketIO szinten is hozzá kell őt adni a szobához. - Paraméterek - `room`: a szoba neve, amihez csatlakozni szeretnénk - Válasz (acknowledgement): - Jó esetben: `{ status: 'ok' }` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - Nem létező szoba: `{ status: 'error', message: 'No such room in our system!'}` - A kliens már a szoba tagja: `{ status: 'error', message: 'You are already subscribed to this room!'}` ### 4. feladat: `mute-client` (5 pont) - Az adminnak legyen lehetősége lenémítani egy klienst, aki az ő szobájában van. - Paraméterek - `room`: a szoba neve, amelyben némítani szeretnénk - `clientId`: a némítandó kliens SocketIO azonosítója - `reason`: a némítás oka (opcionális) - Válasz (acknowledgement): - Jó esetben: - `{ status: 'ok' }` - Továbbá a lenémított kliensnek el kell küldeni a `muted` üzenetet, a következő adatokkal (minta): - `{ room: 'room1', admin: 'socket1', reason: 'káromkodtál' }` - Ha nem volt `reason` megadva, az értéke legyen `"Nincs indok"` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - Nem létező szoba: `{ status: 'error', message: 'No such room in our system!'}` - A kliens nem a szoba tagja: `{ status: 'error', message: 'You are not subscribed to this room!'}` - A kliens nem admin a szobában: `{ status: 'error', message: 'You have no power here, <NAME>!'}` - A kliens saját magát akarja némítani: `{ status: 'error', message: 'You can't mute yourself!'}` - A célpont nem tagja a szobának: `{ status: 'error', message: 'The target is not a member of the room!'}` - A célpont már némítva van: `{ status: 'error', message: 'The target is already muted!'}` ### 5. feladat: `send-message` (6 pont) - Üzenet küldése a chat szoba tagjainak, ha nem vagyunk némítva. - Paraméterek - `room`: a szoba neve, amelyben üzenni szeretnénk - `message`: üzenet tartalma - Válasz (acknowledgement): - Jó esetben: - `{ status: 'ok' }` - Továbbá a szobában lévő összes kliensnél (de csak náluk) `message-received` eseményt kell kiváltani, a következő adatokkal (minta): - `{ room: 'room1', timestamp: 123456789, client: 'socket1', message: 'sziasztok' }` - Hiba esetén: - Hiányzó, rossz paraméter: `{ status: 'error', message: '<hibaüzenet>'}` - Nem létező szoba: `{ status: 'error', message: 'No such room in our system!'}` - A kliens nem a szoba tagja: `{ status: 'error', message: 'You are not subscribed to this room!'}` - A kliens némítva van: `{ status: 'error', message: 'You are muted!'}` <file_sep><?php namespace Database\Seeders; use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; class PostSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Truncate futtatása, ez gyakorlatilag reseteli a táblát: mindent alapértékekre állít és törli az adatokat // Ugyanez működik delete-el is, de akkor az id-k nem 1-ről fognak indulni, hiszen az csak az adatokat törli, // és az id tovább fog inkrementálódni DB::table('posts')->truncate(); // 25 db post létrehozása \App\Models\Post::factory(25)->create(); } } <file_sep>const express = require("express"); const models = require("../models"); // index.js const { Genre } = models; const router = express.Router(); // lekérések router.get("/", async function (req, res) { //throw new Error("valami"); const genres = await Genre.findAll(); res.send(genres); }); router.get("/:id", async function (req, res) { //console.log(req.params); const { id } = req.params; if (isNaN(parseInt(id))) { return res.sendStatus(400); // Bad request - rossz kérés } const genre = await Genre.findByPk(id); if (genre === null) { return res.sendStatus(404); // Not found - nem található } res.send(genre); }); // létrehozás, módosítás, törlés router.post("/", async function (req, res) { console.log(req.body); //console.log(req.asd); const genre = await Genre.create(req.body); res.send(genre); }); router.put("/:id", async function (req, res) { const { id } = req.params; if (isNaN(parseInt(id))) { return res.status(400).send({ message: "A megadott ID nem szám" }); } const genre = await Genre.findByPk(id); if (genre === null) { return res.status(404).send({ message: "A megadott műfaj nem létezik" }); } await genre.update(req.body); res.send(genre); }); router.delete("/:id", async function (req, res) { const { id } = req.params; if (isNaN(parseInt(id))) { return res.status(400).send({ message: "A megadott ID nem szám" }); } const genre = await Genre.findByPk(id); if (genre === null) { return res.status(404).send({ message: "A megadott műfaj nem létezik" }); } await genre.destroy(); res.sendStatus(200); }); // TODO: async hibakezelés, validálás, Genre CRUD után strukturálás /* Create Read Update Delete */ module.exports = router; <file_sep>module.exports = { tabWidth: 4, endOfLine: "lf", printWidth: 144, }; <file_sep>const faker = require("faker"); const Joi = require("joi"); const { v4: uuidv4 } = require("uuid"); const validate = require("./validate"); // Socket.IO emit cheat sheet: https://socket.io/docs/v4/emit-cheatsheet/ // Joi dokumentáció, példák: https://joi.dev/api/?v=17.5.0#general-usage let db = { events: { "esemény 1": { uuid: "1111-2222-3333", socketId: "teacherSocket1", tasks: [ { uuid: "1111-2222-4444", description: "task leírása", solutions: [ { solution: "megoldás szövege", evaluation: "értékelés szövege", socketId: "studentSocket1", }, ], }, ], }, }, }; module.exports = { db, events: (io) => { io.on("connection", (socket) => { socket.on( "create-event", validate( Joi.object({ name: Joi.string().trim().min(1).required(), tasks: Joi.array().items( Joi.object({ description: Joi.string().trim().min(1).required(), }) ), }), // Feldolgozó fv ({ name, tasks }, ack) => { const uuid = uuidv4(); db.events[name] = { uuid, // uuid: uuid, socketId: socket.id, tasks: tasks.map((task) => ({ ...task, uuid: uuidv4(), solutions: [] })), }; console.log(JSON.stringify(db.events, null, 4)); ack({ status: "ok", uuid, }); } ) ); socket.on( "join-event", validate( Joi.object({ uuid: Joi.string().guid({ version: ["uuidv4"], }), }), // Feldolgozó fv ({ uuid }, ack) => { let event = null; for (const [name, details] of Object.entries(db.events)) { if (details.uuid === uuid) { event = { name, ...details }; break; } } if (!event) throw new Error("Event not found!"); ack({ status: "ok", event: { name: event.name, uuid: event.uuid, socketId: event.socketId, }, tasks: event.tasks, }); } ) ); socket.on( "send-solution", validate( Joi.object({ taskUUID: Joi.string().guid({ version: ["uuidv4"], }), solution: Joi.string().trim().min(1).required(), }), // Feldolgozó fv ({ taskUUID, solution }, ack) => { let found = false; const solutionEntry = { // Megoldás szövege solution, // Kezdetben nincs értékelés evaluation: "", // Aki beküldte socketId: socket.id, }; for (const [name, details] of Object.entries(db.events)) { for (task of details.tasks) { if (task.uuid === taskUUID) { task.solutions.push(solutionEntry); // Tanár értesítése io.to(details.socketId).emit("solution-sent", { event: name, task: task.description, solution: solutionEntry, }); // Nyugtázás a hallgatónak: ack({ status: "ok", }); found = true; break; } } } console.log(JSON.stringify(db.events, null, 4)); if (!found) throw new Error("Task not found!"); } ) ); }); }, }; <file_sep>const express = require("express"); const router = express.Router(); const models = require("../models"); const { Genre, Game, Release } = models; const { ValidationError } = require("sequelize"); // localhost:4000/games/titles router.get("/titles", async (req, res) => { const titles = (await Game.findAll({ attributes: ["title"] })).map((game) => game.title); res.send(titles); }); router.get("/:id", async (req, res) => { const game = await Game.findByPk(req.params.id, { include: [ { model: Genre, through: { attributes: [] } }, { model: Release }, // itt nem kell a through, mert nincs kapcsolótábla, mivel 1-N ], }); if (!game) return res.sendStatus(404); return res.send(game); }); router.post("/", async (req, res) => { try { const game = await Game.create(req.body.game); const exists = [], created = []; for (const name of req.body.genres) { const genre = await Genre.findOne({ where: { name } }); // name: name if (genre) { await game.addGenre(genre); exists.push(genre); } else { created.push(await game.createGenre({ name })); } } return res.status(201).send({ game, genres: { exists, created, }, }); } catch (e) { if (e instanceof ValidationError) { return res.sendStatus(400); } throw e; } }); router.patch("/:id/genres", async (req, res) => { const game = await Game.findByPk(req.params.id); if (!game) return res.sendStatus(404); const exists = [], created = []; for (const name of req.body.genres) { const genre = await Genre.findOne({ where: { name } }); // name: name if (genre) { exists.push(genre); } else { created.push(await game.createGenre({ name })); } } await game.setGenres([...exists, ...created]); return res.send({ game, genres: { exists, created, }, }); }); router.post("/:id/releases", async (req, res) => { const game = await Game.findByPk(req.params.id); if (!game) return res.sendStatus(404); /*if (!["win", "ps2", "ps3", "ps4", "ps5", "xbox360", "xboxone"].includes(req.body.platform)) return res.sendStatus(400); res.send(await game.createRelease(req.body));*/ try { res.send(await game.createRelease(req.body)); } catch (e) { if (e instanceof ValidationError) { return res.sendStatus(400); } throw e; } }); router.delete("/", async (req, res) => { const { id } = req.body; if (!id) return res.sendStatus(400); const game = await Game.findByPk(id); if (!game) return res.sendStatus(404); await game.destroy(); res.send(game); }); module.exports = router; <file_sep># Csütörtök 16:00 - 17:30 Neptunban #3-as gyakorlati csoport<file_sep># Sequelize asszociációk Ez a leírás bemutatja, hogy néznek ki Sequelize-ban az adatmodellek közötti kapcsolatok (a Sequelize ezeket nem relációknak, hanem asszociációknak hívja), és milyen metódusokkal tudjuk ezeket létrehozni, elérni, kezelni. Tartalom: - [Sequelize asszociációk](#sequelize-asszociációk) - [Lehetséges relációk](#lehetséges-relációk) - [Relációk megadása](#relációk-megadása) - [Elérhető metódusok](#elérhető-metódusok) - [Metódusok használata](#metódusok-használata) - [Sok-Sok kapcsolat kiépítése](#sok-sok-kapcsolat-kiépítése) - [Elméleti háttér](#elméleti-háttér) - [Modellek generálása, táblák beállítása](#modellek-generálása-táblák-beállítása) - [Adatmodellek beállítása](#adatmodellek-beállítása) - [Sok-sok kapcsolat tesztelése](#sok-sok-kapcsolat-tesztelése) - [Elérhető metódusok lekérése](#elérhető-metódusok-lekérése) - [Részletes példa a metódusok használatára](#részletes-példa-a-metódusok-használatára) ## Lehetséges relációk - 1-1 (One to One, vagyis Egy-Egy kapcsolat) - Egyértelmű kapcsolatot teremt két entitás között. - Példa: ha egyik oldalt személyeket tartunk nyilván (Person), másik táblában pedig jogosítványokat (DrivingLicense), akkor egy adott személynek csak egy jogosítványa lehet és egy adott jogosítványhoz is csak egy személy tartozhat. - Részletes dokumentáció: https://sequelize.org/master/manual/assocs.html#one-to-one-relationships - Ha A és B között 1-1 kapcsolat van, akkor az alábbi metódusokat kapják: - A: [hasOne](https://sequelize.org/master/class/lib/associations/has-one.js~HasOne.html) (neki van egy B-je) - B: [belongsTo](https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html) (ő pedig A-hoz tartozik) - 1-N (One to Many, vagyis Egy-Sok kapcsolat) - Egy entitáshoz akár több másik eintitás is tartozhat. - Példa: ha van egy személy (Person), akinek a nyilvántartás szerint lehetnek a nevén autók. Ez lehet egy autó is, lehet kettő, három, de igazából technikailag akárhány, tehát N db autó lehet a nevén. Innen jön az elnevezés, 1 személyhez N db autó kapcsolódhat, tehát 1-N. - Részletes dokumentáció: https://sequelize.org/master/manual/assocs.html#one-to-many-relationships - Ha A és B között 1-N kapcsolat van, akkor az alábbi metódusokat kapják: - A: [hasMany](https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html) (neki van valamennyi B-je) - B: [belongsTo](https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html) (ő pedig A-hoz tartozik) - N-N / N-M (Many to Many, vagyis Sok-Sok kapcsolat) - Egy entitáshoz akár több másik entitás is tartozhat, akárcsak az előző 1-N-es példában, azonban míg az egy oldalú volt, itt ez visszafelé is igaz. - Hívják N-M kapcsolatnak is, hiszen nem feltétlen kell, hogy ugyannyi kötődés legyen a két oldalon, csak technikailag lehet több, mint egy bármelyik oldalról. - Példa: Egy személy (Person), ha autót akar venni, akkor azt több szalonból (Shop) is megteheti, de egy szalon is többféle személynek adhat el autót. - Részletes dokumentáció: https://sequelize.org/master/manual/assocs.html#many-to-many-relationships - Ha A és B között N-N kapcsolat van, akkor az alábbi metódusokat kapják: - A: [belongsToMany](https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html) (többszörösen kötődhet B-hez) - B: [belongsToMany](https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html) (többszörösen kötődhet A-hoz) ## Relációk megadása A relációkat a Sequelize modellek `associate` nevű statikus metódusán keresztül adjuk meg a fent említett metódusok segítségével. Ehhez generáljunk ki mondjuk egy Shop és egy Item modelt: ```shell npx sequelize model:generate --name Shop --attributes name:string,address:string npx sequelize model:generate --name Item --attributes name:string,price:integer ``` Majd a `models` mappában adjuk meg a relációkat: ```js class Shop extends Model { // A models objektumot megkapja paraméterben, ebből elérhető az összes többi model static associate(models) { // A this a jelenlegi model, vagyis a "Shop" // Ha itt adunk mondjuk egy hasMany-t a Items-re, azzal azt mondjuk, hogy a Shop-hoz tartozik valamennyi Item (1-N) this.hasMany(models.Item); } } ``` Ilyenkor az Item modell a következőképpen néz ki: ```js class Item extends Model { static associate(models) { // A this a jelenlegi model, vagyis a "Item" // Mivel ez a "Item" a "Shop"-hoz tartozik, ide belongsTo()-t adunk, amiben megjelöljük a "Shop" modelt this.belongsTo(models.Shop); } } ``` Mivel itt 1-N kapcsolatot mutattunk be, vagyis, hogy a bolthoz tartozik egy árukészlet, nyilvánvalóan valahogy az adatbázisban ábrázolni is kell ezt a függést. Az "Item" nevű modelben szokott lenni egy plusz mező, ami a "Shop"-ra hivatkozik, jellemzően a "Shop"-nak az ID mezőjére. Tehát az "Item" migration-jébe kell, hogy rakjuk még valami ilyesmit: ```js // ... ShopId: { type: Sequelize.INTEGER, }, // ... ``` Felmerül a kérdés, hogy fogja a Sequelize megtalálni egy a `ShopId` nevű külső kulcsot? Úgy, hogy megnézi, az Item-nél a belongsTo-nak milyen modelt adtunk paraméterül, annak lekéri a nevét és az elsődleges kulcsát (primary key) és CamelCase szerűen egymás után írja őket: ModelNeveElsodlegesKulcsNeve, vagyis ha a model neve Shop, az elsődleges kulcsé pedig id, akkor ShopId fog előállni. Lásd például [itt](https://github.com/sequelize/sequelize/blob/main/lib/associations/belongs-to.js#L34-L48). Ettől természetesen el lehet térni, tehát nem muszáj, hogy ez `ShopId` néven szerepeljen, akkor viszont meg kell mondani a hasMany-nek és a belongsTo-nak is az érintett modellekben, hogy mit állítottunk be egyedileg külső kulcsnak, mivel eltértünk az elnevezési konvencióktól. Tehát ha például a `ShopId`-t átírjuk a migration-ben `CustomShopId`-ra, akkor ki kell egészíteni a metódusokat a modelfájlokban is, hogy tudja az ORM, milyen külső kulcsot keressen: Ez a Shop esetében: ```js this.hasMany(models.Item, { foreignKey: "CustomShopId", }); ``` Mivel a dolog oda-vissza működik, ne felejtsük el a másik oldalt sem, az Items-t: ```js this.belongsTo(models.Shop, { foreignKey: "CustomShopId", }); ``` Mint az látszik, itt is fontosak az elnevezési konvenciók, akárcsak Laravelben. A Sequelize ugyanis egy [Inflection](https://github.com/dreamerslab/node.inflection) nevű library-t használ az elnevezések nyelvtani kezeléséhez, hasonlóan, ahogy ezt a Laravel is teszi, csak PHP-s környezetben. Ennek a működését valahogy így kell elképzelni: ```js const inflection = require('inflection'); // A pluralize többes számba rakja az item-et, vagyis items lesz // A capitalize pedig nagybetűsíti, tehát az items Items lesz console.log(inflection.capitalize(inflection.pluralize('item'))); // Items // Ez egy picit bonyolultabb eset, mivel a category többes száma categories lesz, // ez a fv. valóban ezt is fogja visszaadni console.log(inflection.pluralize('category')); // categories // Ez is azt adja vissza, hogy categories, ha már többes számban van, // akkor egyszerűen abban is fogja hagyni. console.log(inflection.pluralize('categories')); // categories // Ez a többes számot alakítja egyes számmá, vagyis category lesz console.log(inflection.singularize('categories')); // category // Továbbá tudja kezelni az úgynevezett snake_case és CamelCase módokat is. // A snake_case neve onnan ered, hogy a _ karakter olyan, mint egy kígyó (snake). // A CamelCase pedig onnan, hogy a nagybetű olyan, mint a teve (camel) púpja. console.log(inflection.camelize('first_second')); // FirstSecond console.log(inflection.underscore('FirstSecond')); // first_second ``` Tehát a Sequelize fogja a model nevét, bedobja ebbe az Inflection-be, ami kiadja mondjuk a többesszámát, de igény szerint bármi mást is tehet vele, mint láttuk. ## Elérhető metódusok Ha megteremtettük a relációkat a fenti módon, akkor különböző metódusok válnak elérhetővé, mint például ilyenek: ```js const db = require("./models"); const { Shop } = db; const faker = require("faker"); ;(async () => { // Shop létrehozása const shop = await Shop.create({ name: faker.lorem.word(), address: faker.address.secondaryAddress(), }); // Item-ek létrehozása a Shop-hoz await shop.createItem({ name: faker.lorem.word(), price: faker.datatype.number({ min: 500, max: 20000 }), }); const secondItem = await shop.createItem({ name: faker.lorem.word(), price: faker.datatype.number({ min: 500, max: 20000 }), }); // Shop-hoz tartozó Item-ek lekérése és kiírása a konzolra console.log(await shop.getItems({ raw: true })); // Shop-hoz tartozó Item-ek számának lekérése és kiírása a konzolra console.log(await shop.countItems()); // A 2. Item eltávolítása a Shop-ból await shop.removeItem(secondItem); console.log("Item eltávolítva"); // Shop-hoz tartozó Item-ek számának lekérése és kiírása a konzolra // Ez már csak egy Item-et fog jelezni, hiszen a másodikkal megszüntettük // a kapcsolatot (nem az Item-et töröltük, csak a shopId mezőjét állítottuk át) console.log(await shop.countItems()); })(); ``` Itt el is érkeztünk egy további érdekes pontra, hogy hogyan kerülnek kigenerálásra ezek a metódusok, amiket a reláció valamelyik oldaláról elérünk. Látszik, hogy az elnevezésük függ a modelljeinktől és az általunk megadott nevektől, mégis honnan jön a nevük? Nos, alapvetően itt is a model nevét veszi alapul a rendszer, hacsak a fenti hasMany, belongsTo metódusoknál nem adunk meg valamilyen "aliast" ("as" property). [Lásd itt.](https://github.com/sequelize/sequelize/blob/main/lib/associations/belongs-to.js#L24-L32) A model neve egyes- és többesszámban így kérhető le (fontos, hogy magát a models mappából jövő model-t kell megadni, és nem annak egy példányát): ```js console.log(Shop.options.name); ``` Ez a következőt fogja kiírni: ```js { plural: 'Shops', singular: 'Shop' } ``` Az elnevezések a következő módon néznek ki: - belongsTo oldalról: - Dokumentáció: https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html - Forráskód: https://github.com/sequelize/sequelize/blob/main/lib/associations/belongs-to.js#L73 - Metódusok: - get: `get${egyes szám}`, - set: `set${egyes szám}`, - create: `create${egyes szám}` - belongsToMany oldalról: - Dokumentáció: http://docs.sequelizejs.com/class/lib/associations/belongs-to-many.js~BelongsToMany.html - Forráskód: https://github.com/sequelize/sequelize/blob/main/lib/associations/belongs-to-many.js#L209 - Metódusok: - get: `get${többes szám}`, - set: `set${többes szám}`, - addMultiple: `add${többes szám}`, - add: `add${egyes szám}`, - create: `create${egyes szám}`, - remove: `remove${egyes szám}`, - removeMultiple: `remove${többes szám}`, - hasSingle: `has${egyes szám}`, - hasAll: `has${többes szám}`, - count: `count${többes szám}` - hasMany oldalról: - Dokumentáció: http://docs.sequelizejs.com/class/lib/associations/has-many.js~HasMany.html - Forráskód: https://github.com/sequelize/sequelize/blob/main/lib/associations/has-many.js#L98 - Metódusok: - get: `get${többes szám}`, - set: `set${többes szám}`, - addMultiple: `add${többes szám}`, - add: `add${egyes szám}`, - create: `create${egyes szám}`, - remove: `remove${egyes szám}`, - removeMultiple: `remove${többes szám}`, - hasSingle: `has${egyes szám}`, - hasAll: `has${többes szám}`, - count: `count${többes szám}` Az alábbi segédfüggvénnyel ki is lehet listázni egy adott modellhez tartozó metódusokat: ```js const db = require("./models"); const { Shop, Item } = db; const getModelAccessorMethods = (model) => { console.log(`${model.name}:`); Object.entries(model.associations).forEach(([_, associatedModel]) => { Object.entries(associatedModel.accessors).forEach(([action, accessor]) => { console.log(` ${action}: ${model.name}.${accessor}(...)`); }); }); }; ;(async () => { getModelAccessorMethods(Shop); getModelAccessorMethods(Item); })(); ``` Ez valami ilyesmit fog kiírni: ``` Shop: get: Shop.getItems(...) set: Shop.setItems(...) addMultiple: Shop.addItems(...) add: Shop.addItem(...) create: Shop.createItem(...) remove: Shop.removeItem(...) removeMultiple: Shop.removeItems(...) hasSingle: Shop.hasItem(...) hasAll: Shop.hasItems(...) count: Shop.countItems(...) Item: get: Item.getShop(...) set: Item.setShop(...) create: Item.createShop(...) ``` ## Metódusok használata A fenti metódusok gyakorlati működését az alábbi kommentekkel ellátott példa mutatja. ```js const models = require("./models"); const { Shop } = models; const faker = require("faker"); ;(async () => { const shop = await Shop.findByPk(1); // A Shop a hasMany oldalon van, tehát... // 1.) Item-ek lekérése: get${többes szám}, tehát getItems console.log(await shop.getItems()); // 2.) Item-ek beállítása (ezentúl csak ezek az Item-ek lesznek hozzárendelve): set${többes szám}, tehát setItems([Item-ek tömbje, lehet id-k tömbje, vagy konkrét modelleké]) console.log(await shop.setItems([1,2])); // 3.) Egy Item hozzáadása (a meglévő Item-ek mellé): add${egyes szám}, tehát addItem(Item id / Item modell) console.log(await shop.addItem(3)); // 4.) Több Item hozzáadása (a meglévő Item-ek mellé): add${többes szám}, tehát addItems([Item-ek tömbje, lehet id-k tömbje, vagy konkrét modelleké]) console.log(await shop.addItems([4,5])); // 5.) Új Item létrehozása, majd a modellhez rendelése (a meglévő Item-ek mellé): create${egyes szám}, tehát createItem({ Item mezői }) console.log(await shop.createItem({ name: faker.commerce.productName(), price: faker.commerce.price(), })); // 6.) Egy Item eltávolítása (a többi megmarad): remove${egyes szám}, tehát removeItem(Item id / item modell) console.log(await shop.removeItem(3)); // 7.) Több Item eltávolítása (a többi megmarad): remove${többes szám}, tehát removeItems([Item-ek tömbje, lehet id-k tömbje, vagy konkrét modelleké]) console.log(await shop.removeItems([4,5])); // 8.) Egy adott Item hozzá van-e rendelve a Shop-hoz: has${egyes szám}, tehát hasItem(Item id / Item modell) console.log(await shop.hasItem(1)); // true console.log(await shop.hasItem(4)); // false, hiszen a 4 az előbb el lett távolítva a kapcsolatból // 9.) Az összes megadott Item hozzá van-e rendelve a Shop-hoz: has${többes szám}, tehát hasItems([Item-ek tömbje, lehet id-k tömbje, vagy konkrét modelleké]) console.log(await shop.hasItems([1,2])); // true console.log(await shop.hasItems([1,2,4])); // false, hiszen a 4 az előbb el lett távolítva a kapcsolatból, tehát nincs mind hozzárendelve // 10.) A Shop-hoz kapcsolt Item-ek számának lekérése: count${többes szám}, tehát countItems() console.log(await shop.countItems()); })(); ``` ## Sok-Sok kapcsolat kiépítése ### Elméleti háttér Az 1-1, 1-N kapcsolatoknál elég az A-hoz kötötdő B-nek megadni egy mezőt, ami az A elsődleges kulcsára hivatkozik, a fenti példánál a Shop-hoz tartoztak Item-ek, ezért az Item-ben meg kellett adni a Shop ID-ját, ami a Shop elsődleges kulcsa. A sok-sok kapcsolat esetében azonban ez így nem elegendő adatbázis reprezentáció, mivel nem lehetne vele rendesen ábrázolni egy ilyen összetett kapcsolatot. Ezért a sok-sok kapcsolat esetében nem az egyes modellekhez veszünk fel plusz mezőket, hanem hagyjuk őket, és bevezetünk egy plusz táblát, az úgynevezett "kapcsolótáblát". A kapcsolótáblába bejegyzések kerülnek, amelyben egy bejegyzés azt reprezentálja, hogy A és B között kapcsolat van. A tábla szerkezete az alábbi módon néz ki. - Kapcsolótábla - id: a bejegyzés ID-ja - AId: Az "A" model ID-ja - BId: A "B" model ID-ja - CreatedAt: Mikor jött létre a bejegyzés a kapcsolótáblában - UpdatedAt: Mikor módosult a bejegyzés a kapcsolótáblában Továbbá érdemes egy olyan megkötést is alkalmazni a táblán, hogy egy páros csak egyszer kerülhet bele, vagyis egy "AId" és "BId" páros csak egyszer szerepelhet a táblában, így a bejegyzések egyértelműek lesznek. Ez pongyolán ábrázolva valahogy így néz ki: - Unique [AId, BId] Nyilván a pontos implementáció attól a keretrendszertől függ, amiben dolgozunk, ezt mindjárt látjuk picit később. Vegyük mondjuk azt a példát, hogy van egy blogunk, amiben vannak kategóriáink és bejegyzéseink. Ezek között sok-sok kapcsolat van, hiszen egy kategóriához akármennyi bejegyzés tartozhat és egy bejegyzéshez is akármennyi kategória tartozhat. Így lehetőségünk van megjeleníteni egy kategóriához az összes hozzá tartozó bejegyzést, és a bejegyzés oldalán is az összes hozzá tartozó kategóriát. ### Modellek generálása, táblák beállítása Sequelize-ban ennek a megvalósítása a következőképpen néz ki. Először is ki kell generálni a Kategória és Bejegyzés modelleket az alábbi parancsokkal: ```shell npx sequelize model:generate --name Category --attributes name:string,color:string npx sequelize model:generate --name Post --attributes title:string,text:string ``` Ennek a két parancsnak a hatására alapvetően két irányból történik változás: 1. Létrejön a `models` mappában a `category.js` és a `post.js` 2. Létrejön a `migrations` mappában a `${timestamp}-create-category.js` és a `${timestamp}-create-post.js` A sok-sok kapcsolat implementációját először a migration oldalról kezdjük, ehhez ki kell generálni a kapcsolótáblához tartozó migration-t: ```shell npx sequelize migration:generate --name create-category-post ``` Ennek az elnevezése egyébként nincs kőbe vésve, de célszerű követni a szokásokat, és a `create-{táblanév}` modellt követni. Miután ezt a parancsot kiadtuk, a `migrations` mappában megjelenik a `${timestamp}-create-category-post.js`, aminek a tartalma valami ilyesmi lesz: ```js "use strict"; module.exports = { up: async (queryInterface, Sequelize) => { // Ez akkor fut le, amikor feltöltjük a migrationt (migrate) }, down: async (queryInterface, Sequelize) => { // Ez pedig akkor amikor visszavonjuk (undo) } }; ``` A feladat most az, hogy a fentebb már ismertetett kapcsolótábla felépítés szerint kialakítsuk a Sequelize-os eszközökkel a migrationt. Ez így fog kinézni: ```js "use strict"; module.exports = { up: async (queryInterface, Sequelize) => { // Tábla létrehozása await queryInterface.createTable("CategoryPost", { // ID mező, ugyanaz, mint bármelyik másik generált modellnél id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER, }, // Kategória ID, Bejegyzés ID // Kategória ID, Bejegyzés ID CategoryId: { type: Sequelize.INTEGER, // Nem vehet fel NULL értéket, mindenképpen valamilyen INTEGER-nek kell lennie allowNull: false, // Megadjuk, hogy ez egy külső kulcs, ami a "Categories" táblán belüli "id"-re hivatkozik // https://sequelize.org/master/class/lib/dialects/abstract/query-interface.js~QueryInterface.html#instance-method-createTable references: { model: "Categories", key: "id", }, // Ha pedig a kategória (Category) törlődik, akkor a kapcsolótáblában lévő bejegyzésnek is törlődnie kell, // hiszen okafogyottá válik, hiszen egy nem létező kategóriára hivatkozik onDelete: "cascade", }, PostId: { type: Sequelize.INTEGER, // Nem vehet fel NULL értéket, mindenképpen valamilyen INTEGER-nek kell lennie allowNull: false, // Megadjuk, hogy ez egy külső kulcs, ami a "Posts" táblán belüli "id"-re hivatkozik references: { model: "Posts", key: "id", }, // Ha pedig a bejegyzés (Post) törlődik, akkor a kapcsolótáblában lévő bejegyzésnek is törlődnie kell, // hiszen okafogyottá válik, hiszen egy nem létező kategóriára hivatkozik onDelete: "cascade", }, // Időbélyegek createdAt: { allowNull: false, type: Sequelize.DATE, }, updatedAt: { allowNull: false, type: Sequelize.DATE, }, }); // Megkötés a kapcsolótáblára, amelyben megmondjuk, hogy egy CategoryId - PostId páros csak egyszer szerepelhet a kapcsolótáblában await queryInterface.addConstraint("CategoryPost", { fields: ["CategoryId", "PostId"], type: "unique", }); }, down: async (queryInterface, Sequelize) => { // Ha visszavonásra kerül a migration, egyszerűen töröljük ki a táblát await queryInterface.dropTable("CategoryPost"); }, }; ``` Ezt követően fel kell tölteni a három létrehozott táblát az adatbázisba, vagyis meg kell hívni a migrate parancsot: ```shell npx sequelize-cli db:migrate ``` Ez valami ilyesmi eredményt kell, hogy adjon sikeres migration esetén: ``` D:\szerveroldali\teszt>npx sequelize-cli db:migrate Sequelize CLI [Node: 14.15.1, CLI: 6.3.0, ORM: 6.9.0] Loaded configuration file "config\config.json". Using environment "development". == 20211112111029-create-category: migrating ======= == 20211112111029-create-category: migrated (0.027s) == 20211112111041-create-post: migrating ======= == 20211112111041-create-post: migrated (0.017s) == 20211112111100-create-category-post: migrating ======= == 20211112111100-create-category-post: migrated (0.010s) ``` ### Adatmodellek beállítása Ezen a ponton sikeresen megcsináltuk az adatbázis részt, az `sqlite` fájlunkban szerepel minden tábla. Eljött az ideje, hogy a Sequelize adatmodelljeinek a szintjén is implementáljuk a sok-sok kapcsolatot. Ehhez alapvetően két dolgot kell tenni: a `models` mappán belül a `category.js` és a `post.js`-ben lévő `association` metódusokban megadni a relációkat. Mivel sok-sok kapcsolatunk van, mindkét oldalról (mindkét fájlban) az `belongsToMany`-t fogjuk használni. Példa, hogy kell kinézzen a két fájl: `category.js`: ```js "use strict"; const { Model } = require("sequelize"); module.exports = (sequelize, DataTypes) => { class Category extends Model { static associate(models) { this.belongsToMany(models.Post, { through: "CategoryPost", }); } } Category.init( { name: DataTypes.STRING, color: DataTypes.STRING, }, { sequelize, modelName: "Category", } ); return Category; }; ``` `post.js`: ```js "use strict"; const { Model } = require("sequelize"); module.exports = (sequelize, DataTypes) => { class Post extends Model { static associate(models) { this.belongsToMany(models.Category, { through: "CategoryPost", }); } } Post.init( { title: DataTypes.STRING, text: DataTypes.STRING, }, { sequelize, modelName: "Post", } ); return Post; }; ``` Fontos, hogy a `belongsToMany`-nek meg kell adni második paraméterben egy objektumot, ami a beállításokat tartalmazza, és itt mindenképp értéket kell adni a `through`-nak, ez mondja meg, hogy melyik az a kapcsolótábla, amelyiken keresztül össze vannak kötve. Ezen kívül a Category a Post-hoz kötődik (tehát ott az 1. paraméter a Post), míg a Post a Category-hoz kötődik, tehát a Post-on belüli belongsToMany 1. paramétere a Category lesz. Ha eddig mindent jól csináltunk, akkor sikeresen implementáltuk a sok-sok kapcsolatot. ## Sok-sok kapcsolat tesztelése ### Elérhető metódusok lekérése A leírásban korábban említve volt egy függvény, amivel le lehet kérni a relációk kezelésére vonatkozó metódusokat. Ez a script így néz ki átírva Category-ra és a Post-ra: ```js const db = require("./models"); const { Category, Post } = db; const getModelAccessorMethods = (model) => { console.log(`${model.name}:`); Object.entries(model.associations).forEach(([_, associatedModel]) => { Object.entries(associatedModel.accessors).forEach(([action, accessor]) => { console.log(` ${action}: ${model.name}.${accessor}(...)`); }); }); }; ;(async () => { getModelAccessorMethods(Category); getModelAccessorMethods(Post); })(); ``` Ha lefuttatjuk, kiírja, hogy milyen metódusok érhetők el `Category` illetve `Post` alatt: ``` D:\szerveroldali\teszt>node accessors.js Category: get: Category.getPosts(...) set: Category.setPosts(...) addMultiple: Category.addPosts(...) add: Category.addPost(...) create: Category.createPost(...) remove: Category.removePost(...) removeMultiple: Category.removePosts(...) hasSingle: Category.hasPost(...) hasAll: Category.hasPosts(...) count: Category.countPosts(...) Post: get: Post.getCategories(...) set: Post.setCategories(...) addMultiple: Post.addCategories(...) add: Post.addCategory(...) create: Post.createCategory(...) remove: Post.removeCategory(...) removeMultiple: Post.removeCategories(...) hasSingle: Post.hasCategory(...) hasAll: Post.hasCategories(...) count: Post.countCategories(...) ``` Látszik itt is, hogy van egyes- és többes szám, és az is, hogy az Inflection pl. a Category-ból Categories-t csinált, tehát a többesszámosítás nem csak annyiból áll, hogy utána biggyeszt egy s betűt, ennél sokkal hatékonyabb. ### Részletes példa a metódusok használatára Innentől kezdve már csak az a dolgunk, hogy használjuk ezeket a metódusokat. Ehhez itt egy részletes "playground" példa script: ```js const db = require("./models"); const { Category, Post } = db; ;(async () => { // Korábbi kategóriák, bejegyzések törlése // Ez ilyen SQL kéréseket fog kiadni: // Executing (default): DELETE FROM `Categories`; DELETE FROM `sqlite_sequence` WHERE `name` = 'Categories'; // Executing (default): DELETE FROM `Posts`; DELETE FROM `sqlite_sequence` WHERE `name` = 'Posts'; // A kapcsolótábla adatai a CASCADE miatt fognak törlődni // A "restartIdentity" elméletileg azt jelentené, hogy az ID ismét 1-ről induljon (az sqlite_sequence-ből törli a táblát), // de ez nem működik alapból SQLite-al: https://github.com/sequelize/sequelize/issues/11152 await Category.destroy({ truncate: true, restartIdentity: true }); await Post.destroy({ truncate: true, restartIdentity: true }); // Három kategória létrehozása: c1,c2,c3 const c1 = await Category.create({ name: "category1", color: "red", }); const c2 = await Category.create({ name: "category2", color: "white", }); const c3 = await Category.create({ name: "category3", color: "green", }); // Két bejegyzés létrehozása: p1,p2 const p1 = await Post.create({ title: "post1", text: "post1 content", }); const p2 = await Post.create({ title: "post2", text: "post2 content", }); // Összes bejegyzés lekérése //console.log(await Post.findAll()); // Egy adott bejegyzés lekérése a primary key (elsődleges kulcs) alapján, ami alapból az id //console.log(await Post.findByPk(1)); // 1. kategória hozzáadása az 1. bejegyzéshez await p1.addCategory(c1); // vagy await c1.addPost(p1); // 1. bejegyzéshez tartozó kategóriák neveinek listázása console.log((await p1.getCategories({ attributes: ["name"], raw: true })).map((entry) => entry.name)); // 1. bejegyzéshez tartozó kategóriák megszámolása, ez 1 lesz console.log(await p1.countCategories()); // 1. kategória és 1. bejegyzés közötti kapcsolat megszüntetése // Ez nem törli se a bejegyzést se a kategóriát, csak a kapcsolatot szünteti meg köztük, // vagyis a kapcsolótáblából törli ki a bejegyzést, ami rájuk vonatkozik console.log(await p1.removeCategory(c1)); // vagy await c1.removePost(p1) // Ezután ha listázni akarjuk a kategóriák neveit üres tömböt kapunk console.log((await p1.getCategories({ attributes: ["name"], raw: true })).map((entry) => entry.name)); // Adjuk hozzá a p1 bejegyzéshez a c2,c3 kategóriákat await p1.addCategories([c2, c3]); console.log((await p1.getCategories({ attributes: ["name"], raw: true })).map((entry) => entry.name)); // Az add mindig csak hozzáad, de a set beállít, tehát ha azt mondjuk, hogy // a p1-hez tartozzon a c1 és a c2, nem kell a c3-at eltávolítani, csak azt mondjuk, // hogy set c1,c2: await p1.setCategories([c1, c2]); console.log((await p1.getCategories({ attributes: ["name"], raw: true })).map((entry) => entry.name)); // Tudunk akár egy 4. kategóriát is csinálni közvetlenül a bejegyzésből: await p1.createCategory({ name: "category4", color: "navy", }); // Ilyenkor a Category létrejön a Categories táblában, illetve hozzá is kapcsolódik a bejegyzéshez. console.log((await p1.getCategories({ attributes: ["name"], raw: true })).map((entry) => entry.name)); // Ez úgy is mehet, hogy a kategória alatt hozunk létre bejegyzést: const p3 = await c1.createPost({ title: "post3", text: "post3 content", }); // Ilyenkor a Posts táblában létrejön egy új bejegyzés, és hozzá lesz csatolva a c1 kategóriához // Ha le akarjuk kérni a c1 kategóriához tartozó bejegyzések címeit, azt így tehetjük meg: console.log((await c1.getPosts({ attributes: ["title"], raw: true })).map((entry) => entry.title)); // Ugye például most a post1 is hozzá van rendelve a c1-hez, de ha ezt ellenőrizni akarjuk, // akkor arra ott a "has": console.log(await c1.hasPost(p1)); // Ez true értéket adott, de ha mondjuk a 2. postot nézzük, az már false lesz: console.log(await c1.hasPost(p2)); // A has is megy több posttal, pl most az 1 és a 3 van hozzárendelve a c1-hez, tehát ez truet ad: console.log(await c1.hasPosts([p1, p3])); // De ha bevesszük a p2-t is, akkor hiába van a p1 és a p3 hozzárendelve, mivel p2 nincs, ez false lesz: console.log(await c1.hasPosts([p1, p2, p3])); // Ha el akarjuk az összes bejegyzést távolítani a c1-ből, azt így tehetjük meg: //console.log(await c1.removePosts(await c1.getPosts())); // Nyilván ez egy tömböt vár ilyenkor, a getPosts pedig az aktuális postokat adja meg // Konzolra egy kettest fog kiírni, hogy 2 postot vett le // Azonban ha kézzel adjuk meg, mondjuk ezt: console.log(await c1.removePosts([p1, p2, p3])); // Akkor ez is kettőt fog logolni, de a p2-t skipeli, hiszen az nem volt hozzárendelve console.log((await c1.getPosts({ attributes: ["title"], raw: true })).map((entry) => entry.title)); // Kérjük le úgy a Postokat, hogy egyúttal megjelenítsük a hozzájuk tartozó kategóriákat! // A findAll, de a többi lekérő metódus tud fogadni egy options objektumot, amiben be tudjuk állítani // mondjuk azt, hogy tartalmazzon-e még valamit, ahogy alább tesszük is. console.log( JSON.stringify( await Post.findAll({ include: [ { model: Category, // "as" tulajdonképpen nem kell, ha a models-ben nem adtunk meg alias-t }, ], }), // JSON.stringify testreszabása null, 4 ) ); // Ugyanez, picit jobban testreszabva: console.log( JSON.stringify( await Post.findAll({ // A bejegyzésből csak az id, title és text mezők jelenjenek meg attributes: ["id", "title", "text"], // És a bejegyzés tartalmazza még... include: [ { // ... a kategória modelt ... model: Category, // ... mint "Categories" alias ... as: "Categories", // ... és ezeket a mezőit kérje le: attributes: ["id", "name"], // Ez pedig azért kell, hogy a kapcsolótáblát ne szemetelje bele, // a legjobb ha kikommentezed az alábbi sort és megnézed, mi változik through: { attributes: [] }, }, ], }), // JSON.stringify testreszabása null, 4 ) ); //await p2.addCategory(c1); // Alapból csak az 1-es bejegyzéshez tartozik, de itt megnézhetjük, mi történik, ha a 2-eshez is rendelünk kategóriát // Csak azon bejegyzések lekérése, amelyekhez tartozik legalább egy kategória console.log( JSON.stringify( await Post.findAll({ // A bejegyzés minden mezőjét lekérjük, kivéve a timestamp-eket attributes: { exclude: ["createdAt", "updatedAt"], }, include: [ { model: Category, // Megköveteljük, hogy a szülőhöz tartozzon a gyerek (Post-hoz a Category, hiszen a Post-ra hívtuk a findAll-t) required: true, // Továbbá megmondjuk, hogy a gyerekből (Category) semmilyen mezőt nem akarunk látni, csak a bejegyzésre vagyunk kíváncsiak attributes: [], //through: { attributes: [] }, }, ], }), // JSON.stringify testreszabása null, 4 ) ); })(); ``` <file_sep>module.exports = { handleStart: () => {}, handleSocketIO: (a, b) => {}, }; <file_sep>const jwt = require("express-jwt"); module.exports = jwt({ secret: process.env.JWT_SECRET || "secret", algorithms: [process.env.JWT_ALGO || "HS256"], }); <file_sep>const fs = require('fs'); //const { promisify } = require('util'); // Ez a kis függvény szemlélteti, hogy kb. mégis mi van a promisify mögött. // Egy függvényt (fn) kap paraméterül const promisify2 = (fn) => { // Egy ún. wrapper fv-t ad vissza. Pl. alul látszik, hogy a pReadDir // a promisify2(fs.readdir)-rel lesz egyenlő, tehát a pReadDir-be ez a // wrapper fv kerül, ezért amikor a pReadDir-t hívjuk, azt fogjuk paraméterezni // és ezek a paraméterek kerülnek ide az args-be. // A ...args egy ún. spread operátor, ami akárhány paramétert tud fogadni, // és gyakorlatilag egy tömbként kezeli őket, ki is lehet console.log()-olni // az args-et. return (...args) => { //console.log(args); // Itt a wrapper fv-en belül egy Promise-ot adunk vissza... return new Promise((resolve, reject) => { // ...amiben csinálunk egy callback fv-t, hasonlóan a callback-es // feladatban látottakhoz, annyi különbséggel, hogy a hibát nem // throw-oljuk, csak reject-eljük a promise-t, míg minden más esetben // a resolve segítségével feloldjuk a kapott eredményt. // A logika full ugyanaz, mint a callback-es feladatnál. const callbackFn = (err, res) => { if (err) reject(err); else resolve(res); } // Az argumentumok között alapból még nincs callback fv, ezért a push // segítségével berakjuk azt az utolsó helyre, ahová egyébként is való, // szintén lásd a callback-es feladatot... :) args.push(callbackFn); // Legvégül meghívjuk az fn fv-t az argumentumokkal (ebben már a fenti // callback is benne van!) // Ez majd valamikor visszahívja a callback-et, ha elkészült, és mivel mindez // a Promise belsejében történik, mindaddig a promise "pending" állapotban lesz. fn(...args); }); } } const pReadDir = promisify2(fs.readdir); const pReadFile = promisify2(fs.readFile); const pWriteFile = promisify2(fs.writeFile); pReadDir('./inputs') .then(filenames => { console.log(filenames); const promises = filenames.map(filename => pReadFile(`./inputs/${filename}`)); //console.log(promises); // Mind pending, de valahogy meg kéne várni mindet return Promise.all(promises); }) .then(contents => { contents = contents.map(content => content.toString()); console.log(contents); return contents.join('\n'); }) .then(output => pWriteFile('./concat-output.txt', output)) .then(() => console.log('Vége')) .catch(err => { console.log(err); }) /*const p = new Promise((resolve, reject) => { setTimeout(() => { reject('foo'); // resolve('ok') }, 300); }).then( val => { console.log(val); }, err => { console.log(err); } )//.catch(err => console.log(err)) console.log(p);*/<file_sep>"use strict"; const { Model } = require("sequelize"); module.exports = (sequelize, DataTypes) => { class Movie extends Model { /** * Helper method for defining associations. * This method is not a part of Sequelize lifecycle. * The `models/index` file will call this method automatically. */ static associate(models) { this.hasMany(models.Rating); this.belongsToMany(models.Genre, { through: "GenreMovie", }); } } Movie.init( { title: DataTypes.STRING, director: DataTypes.STRING, description: DataTypes.TEXT, year: DataTypes.INTEGER, length: DataTypes.INTEGER, imageUrl: DataTypes.STRING, ratingsEnabled: DataTypes.BOOLEAN, }, { sequelize, modelName: "Movie", } ); return Movie; }; <file_sep># GraphQL & Websocket ZH kezdőcsomag Kezdőcsomag a Szerveroldali webprogramozás tárgy GraphQL & Websocket (Socket.IO) zárthelyi feladatához. - [GraphQL & Websocket ZH kezdőcsomag](#graphql--websocket-zh-kezdőcsomag) - [Függőségek telepítése](#függőségek-telepítése) - [Csomagok telepítése](#csomagok-telepítése) - [Node.js telepítése](#nodejs-telepítése) - [Hiba a csomagok telepítéskor](#hiba-a-csomagok-telepítéskor) - [SQLite hiba](#sqlite-hiba) - [Kezdőcsomag parancsok](#kezdőcsomag-parancsok) - [Ajánlott kliensek](#ajánlott-kliensek) - [Ajánlott kiegészítők](#ajánlott-kiegészítők) - [Automatikus formázás mentéskor](#automatikus-formázás-mentéskor) - [Automatikus tesztelő, tudnivalók](#automatikus-tesztelő-tudnivalók) - [Tesztelő telepítése a zárthelyi elején](#tesztelő-telepítése-a-zárthelyi-elején) - [Fontos tudnivalók](#fontos-tudnivalók) - [Automatikus zippelő, beadás](#automatikus-zippelő-beadás) ## Függőségek telepítése ### Csomagok telepítése Ez a kezdőcsomag teljes mértékben elő van készítve, ezért a használatba vételéhez mindössze az NPM-es csomagok telepítésére van szükség, amit az alábbi parancsok valamelyikének kiadásával tehetsz meg: ``` npm i VAGY npm install ``` A csomagok telepítését érdemes jóval a ZH kezdete előtt elvégezni, hogyha bármilyen okból nem sikerül, akkor legyen időd megoldani a hibát, vagy felvenni a gyakorlatvezetőddel a kapcsolatot. ### Node.js telepítése Ha a gépeden nem elérhető az `npm` parancs, akkor telepítened kell a [Node.js](https://nodejs.org/en/)-t, ehhez elég az LTS verzió. Telepítéskor érdemes előre feltenni a kiegészítő tool-okat (lásd a későbbi hibák fejezetet): ![Build tools](https://i.imgur.com/pgNyM4Z.png) ### Hiba a csomagok telepítéskor #### SQLite hiba Ha az SQLite modulra hibát ír a telepítéskor, az többnyire azért van, mert nem tudja letölteni az előre build-elt binárisokat tartalmazó zip-et az Amazon AWS szerveréről, emiatt automatikusan a gépeden szeretne csinálni egy buildet a forráskódról, azonban ehhez nincsenek telepítve a megfelelő függőségek. Ilyenkor az alábbiakat kell telepíteni: - [Visual Studio Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools) - Ez nem egy Visual Studio, csak azok a build eszközök, amiket a Visual Studio is használ - [A Python3 legfrissebb stable kiadását](https://www.python.org/downloads/windows/) - Telepítéskor ezt hozzá kell adni a környezeti változókhoz (`PYTHON` néven) Bővebben lásd itt: [node-gyp Windows függőségek](https://github.com/nodejs/node-gyp#on-windows) ## Kezdőcsomag parancsok Miután telepítetted az NPM-es csomagokat, az alábbi parancsok érhetők el a kezdőcsomagon belül: - GraphQL: - `npm run gql:db`: Migrációk és a seeder futtatása nulláról (tiszta adatbázis) - `npm run gql:dev`: GraphQL szerver futtatása (fejlesztői) - `npm run gql:test`: Automata tesztelő futtatása a GraphQL feladatra - `npm run gql:test 1 2`: Automata tesztelő futtatása a GraphQL feladat konkrét részfeladataira a feladatok sorszáma alapján - Websocket: - `npm run ws:dev`: Websocket (Socket.IO) szerver futtatása (fejlesztői) - `npm run ws:test`: Automata tesztelő futtatása a Websocket feladatra - `npm run ws:test 1 2`: Automata tesztelő futtatása a Websocket feladat konkrét részfeladataira a feladatok sorszáma alapján - `npm run zip`: ZH becsomagolása (automatikus nyilatkozat ellenőrzéssel és kitöltéssel) - `npm run prettier`: A projektben lévő összes `.js`, `.json` és `.graphql` fájl formázása Prettier-el ## Ajánlott kliensek - GraphQL: Ehhez két beépített klienst is ad a kezdőcsomag, javasolt a Playground használata - GraphiQL: http://localhost:4000/graphql - Playground: http://localhost:4000/playground - Websocket (Socket.IO): - Postman - Firecamp ## Ajánlott kiegészítők A kezdőcsomaghoz vannak ajánlott VSCode kiegészítők (lásd `./vscode/extensions.json`). Amikor először megnyitod VSCode-al a kezdőcsomagot, jobb alul felkínálja, hogy telepítsd őket. Ha nem, utólag is megtalálod őket a kiegészítők között "Workspace recommendations" néven: ![Workspace recommendations](https://i.imgur.com/NVjs2RX.png) ## Automatikus formázás mentéskor Ha telepítetted az ajánlott kiegészítőket, köztük a Prettier plugint, akkor ha a kiegészítő beállításai között vagy a `./vscode/settings.json`-ben módosítod az automatikus mentést így (formatOnSave legyen true): ```json "[javascript]": { "editor.formatOnSave": true } ``` Akkor ha elmentesz egy fájlt a VSCode-ban, a Prettier automatikusan meghívásra kerül rá és megformázza a fájlban lévő kódot. ## Automatikus tesztelő, tudnivalók A zárthelyihez automata tesztelőt biztosítunk, ami segít gyors visszajelzést adni a munkádról. ![Tesztelő](https://imgur.com/7nJ6XvT.png) ### Tesztelő telepítése a zárthelyi elején A kezdőcsomagban alapból csak üres tesztelők vannak. A konkrét zárthelyi feladatokhoz tartozó tesztelőket a kezdés időpontjában osztjuk meg. A tartalmát be kell másolni a kezdőcsomag főmappájába, felülírva a már ott lévő fájlokat. Ez alapvetően két fájlt jelent tesztelőnként: - `inject.js` - A kezdőcsomag használja szerveroldalon, annak érdekében, hogy a tesztelő megfelelően el tudja indítani a teszt szervert és a kliens oldali tesztelést is hatékonyan elvégezhesse. Ez eltérő megoldásokat jelenthet REST API-nál, GraphQL-nél vagy Websocket-nál. - `tester.js` - Maga a tesztelő Ha zárthelyi közben valamiért módosítjuk és újra kiadjuk a tesztelőt, mondjuk egy időközben javított hiba miatt, akkor ugyanígy felül kell írni ismét. ### Fontos tudnivalók Az alábbiakat vedd figyelembe a tesztelő használatakor: - A tesztelő által adott eredmények csak tájékoztató jellegűek, melyektől a végleges értékelés pozitív és negatív irányba is eltérhet. - **Nem az a feladat, hogy addig futtasd a tesztelőt, amíg minden át nem megy, hanem az, hogy a dolgozatot oldd meg a legjobb tudásod szerint! Ehhez a tesztelő csak egy segédlet, ami lehetőség szerint egy gyors visszajelzést ad a munkádról azáltal, hogy leteszteli a főbb eseteket, és ha azokon átmegy, akkor *valószínűleg* jó.** - A tesztelőt igyekeztünk legjobb tudásunk és szándékunk szerint összeállítani, ennek ellenére elképzelhető, hogy egy hallgatónál valamilyen előre nem látott hiba miatt abszolút nem fut a tesztelő, vagy egyes részfeladatokat hibásan tesztel. - Ilyenkor megköszönjük, ha ezt jelzitek felénk, mivel így a jövőben elkerülhetővé tudunk tenni egy hibalehetőséget, illetve még a zh közben megpróbáljuk kijavítani a hibát is. - Fontos, ha ilyen történik, ne essetek kétségbe, hanem nyugodtan folytassátok a dolgozatot, hiszen azt az automata tesztelő nélkül, a gyakorlatokon tanult eszközökkel is meg kell tudni oldani! A feladat időkeretét is úgy szabjuk meg, hogy ebben az esetben is kényelmesen be lehet fejezni. - Mivel a tesztelő csak egy segédlet, nem pedig a dolgozat kötelező része, ezért nem tudjuk elfogadni azt indoknak, hogy a zárthelyin a tesztelő miatt bármilyen hátrány ért! ## Automatikus zippelő, beadás A zárthelyihez automatikus zippelőt biztosítunk, ami segít gyorsan és megfelelően kitölteni a nyilatkozatot, valamint összegyűjteni és becsomagolni a beadáshoz szükséges fájlokat. A program először ellenőrzi, hogy létezik-e már szabályosan kitöltött `statement.txt`. Ha nem, akkor felkínálja a nyilatkozatot elfogadásra, majd segít azt kitölteni. Ha a nyilatkozatfájl érvényes, akkor ezt a részt onnantól átugorja. Végül becsomagolja a fájlokat: ![Zipper](https://i.imgur.com/EPTy6GW.png) Az alábbiakat vedd figyelembe a zippelő használatakor, illetve a beadásnál: - A zippelőt igyekeztünk legjobb tudásunk és szándékunk szerint összeállítani, többszörösen teszteltük, ennek ellenére fontos, hogy beadás előtt nyisd meg a zip fájlt és ellenőrizd, hogy minden benne van-e, amin dolgoztál és amit be szeretnél adni! Ezt akkor is tedd meg, ha nem a mi zippelőnket használod, hiszen egy váratlan hiba bármikor történhet! - A dolgozat megfelelő és hiánytalan beadása a hallgató felelőssége. Erre mindig időben fel is szoktuk hívni a figyelmet, illetve a dolgozat végén külön 15 perces időkeretet adunk a feladat megfelelő, nyugodt körülmények közötti beadására. Ebből kifolyólag ilyen ügyben nem tudunk utólagos reklamációknak helyt adni. Tehát ha valaki a zh után jelzi, hogy egy fájlt nem adott be, akkor azt sajnos nem tudjuk elfogadni. <file_sep>"use strict"; const models = require("../models"); const { User, Genre, Movie, Rating } = models; const faker = require("faker"); module.exports = { up: async (queryInterface, Sequelize) => { // Műfajok const genresCount = faker.datatype.number({ min: 5, max: 10 }); const genres = []; for (let i = 1; i < genresCount; i++) { genres.push( await Genre.create({ name: faker.lorem.word(), description: faker.lorem.sentence(), }) ); } // Felhasználók const usersCount = faker.datatype.number({ min: 15, max: 30 }); const users = []; users.push( await User.create({ name: "Admin", email: `<EMAIL>`, password: "<PASSWORD>", isAdmin: true, }) ); for (let i = 1; i < usersCount; i++) { users.push( await User.create({ name: faker.name.findName(), //email: faker.internet.email(), email: `<EMAIL>`, password: "<PASSWORD>", //isAdmin: false, }) ); } // Filmek const moviesCount = faker.datatype.number({ min: 5, max: 10 }); const movies = []; for (let i = 1; i < moviesCount; i++) { movies.push( await Movie.create({ title: faker.lorem.words(faker.datatype.number({ min: 1, max: 6 })), director: faker.name.findName(), description: faker.lorem.sentence(), year: faker.datatype.number({ min: 1870, max: new Date().getFullYear() }), length: faker.datatype.number({ min: 60 * 60, max: 60 * 60 * 4 }), imageUrl: faker.image.imageUrl(), ratingsEnabled: faker.datatype.boolean(), }) ); } // Relációk, értékelések // - Genre-Movie összekötés (N-N / N-M) // - Movie-Rating for (let movie of movies) { // 1. Műfajokat hozzá kell rendelni a filmhez await movie.setGenres(faker.random.arrayElements(genres)); // 2. Értékeléseket kell rendelni a filmhez, ha az értékelések engedélyezve vannak ehhez a filmhez const randomUsers = faker.random.arrayElements(users); for (let user of randomUsers) { await Rating.create({ rating: faker.datatype.number({ min: 1, max: 5 }), comment: faker.datatype.boolean() ? faker.lorem.sentence() : "", UserId: user.id, MovieId: movie.id, }); } } }, down: async (queryInterface, Sequelize) => {}, }; <file_sep># Automata tesztelő Ebben a mappában található az automata tesztelő (`tester.js`), illetve egy olyan szerveroldalon injektált és használt szkript (`inject.js`), ami javítja/elősegíti az alapvetően kliensoldali automata tesztelő működését. <file_sep>module.exports = { subject: "Szerveroldali webprogramozás", task: "GraphQL & Websocket ZH", ignore: [ ".git/**", ".idea/**", ".vscode/**", "node_modules/**", "package-lock.json", "zip.js", "zipfiles/**", "zip.config.js", "prettier.config.js", "**/*.sqlite", "graphql/test/**", "websocket/test/**", "**/error.log", "LICENSE", "**/*.md", "**/.gitignore", "**/.editorconfig", "**/.prettierignore", "**/.prettierrc", ], }; <file_sep>const fs = require('fs'); // arrow function fs.readdir('./inputs', (err, filenames) => { //console.log(err); if (err) throw err; console.log(filenames); let contents = []; filenames.forEach(filename => { fs.readFile(`./inputs/${filename}`, (err, content) => { console.log(`${filename}:`, content.toString()); contents.push(content.toString()); if (contents.length === filenames.length) { console.log(contents); fs.writeFile('./concat-output.txt', contents.join('\n'), (err) => { if (err) throw err; console.log('Vége'); }) } }); }); }); // Ezzel az a baj, hogy "callback hell" jön létre //console.log('Vége');<file_sep>console.log('Helló'); <file_sep><?php namespace Database\Seeders; use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; use App\Models\User; use App\Models\Category; use App\Models\Post; use Faker; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { /*$this->call(CategorySeeder::class); $this->call(PostSeeder::class); error_log('Database Seeder');*/ // \App\Models\User::factory(10)->create(); $faker = Faker\Factory::create(); DB::table('users')->truncate(); DB::table('categories')->truncate(); DB::table('posts')->truncate(); $users = collect(); $users_count = $faker->numberBetween(5, 10); for ($i = 1; $i <= $users_count; $i++) { $users->add( User::factory()->create([ 'name' => 'user'.$i, 'email' => '<EMAIL>', ]) ); } $categories = Category::factory($faker->numberBetween(7, 14))->create(); $posts = Post::factory($faker->numberBetween(20, 40))->create(); // Adatbázis kapcsolatok $posts->each(function ($post) use (&$users, &$categories, &$faker) { // Szerző hozzácsatolása if ($users->isNotEmpty()) { $post->author()->associate($users->random()); $post->save(); } // Kategóriák hozzácsatolása if ($categories->isNotEmpty()) { $category_ids = Category::all() ->random( $faker->numberBetween(1, $categories->count()) ) ->pluck('id') ->toArray(); $post->categories()->sync($category_ids); } }); } } <file_sep>Adott egy inputs mappa, benne valamennyi txt fájl. Írjunk egy olyan Nodejs programot, amely fogja az itt lévő összes txt fájlt, beolvassa őket, és a tartalmukat összefűzi valamilyen output.txt fájlba. A programot 3 féle módon írjuk meg: - callback-ekkel - promise-okkal - async/await-ekkel<file_sep>const isEven = require('is-even'); console.log(isEven(1)); console.log(isEven(2));<file_sep>const fs = require('fs'); const { promisify } = require('util'); const pReadDir = promisify(fs.readdir); const pReadFile = promisify(fs.readFile); const pWriteFile = promisify(fs.writeFile); /* await-et (async wait-et) csak async fv-en belül tudunk hívni async function valami() { például itt } valami(); De ahelyett, hogy írunk egy fv-t, majd meghívjuk, van egy egyszerűbb mód, amit úgy hívnak, hogy - Self-Invoking Functions (SIF) vagy - Immediately Invoked Function Expressions (IIFE). Ez az alábbi módon néz ki: ;(async () => { fv törzse... })(); A ; elé csak biztonsági okokból kell, hogy ne legyen syntax error, ill. be kell zárójelezni magát a fv-t, majd ami úgy kiértékelődik, azt rögtön lehet fv-ként hívni. Egyébként a pontosvesszőket erősen ajánlott kitenni a kódban, éles fejlesztésnél érdemes valamilyen lintert is használni. */ ;(async () => { const filenames = await pReadDir('./inputs'); console.log(filenames); let contents = []; for (const filename of filenames) { contents.push(await pReadFile(`./inputs/${filename}`)); } contents = contents.map(content => content.toString()); await pWriteFile('./concat-output.txt', contents.join('\n')); })(); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use App\Models\Category; use App\Models\Post; use Storage; use Auth; /* A resource controller így épül fel, a postokkal (bejegyzésekkel) elmagyarázva: index: az összes post megjelenítése (főoldal) create: a create oldal behozása, ahol a post-ot létrehozó form van store: a create oldalon lévő formot ide küldjük el, ez validálja az adatokat, majd tárolja el a postot edit: ugyanaz, mint a create, csak egy már létező post-ot módosító form-ot ad be update: ugyanaz, mint a store, csak az edit form-ját fogadja, és a módosításokat validálja, tárolja le destroy: post törlése */ class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $users_count = User::count(); $categories_count = Category::count(); $posts_count = Post::count(); //$posts = Post::all(); $posts = Post::paginate(9); return view('posts.index', compact('users_count','categories_count','posts_count','posts')); /* A compact-ot valahogy így kell elképzelni: $a = 1; $b = 2; compact('a','b') az lesz, hogy ['a' => 1, 'b' => 2], Tinkerben is ki lehet próbálni A view-nak 2. paraméterben lehet adatot átadni egy tömbben: view('posts.index', [ 'users_count' => $users_count, 'categories_count' => $categories_count, 'posts_count' => $posts_count ]); Gondolj bele, a compact is ezzel ekvivalens dolgot csinál, csak "kompaktabb" :) */ } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { if (!Auth::user()) { return redirect()->route('login'); } $categories = Category::all(); return view('posts.create', compact('categories')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if (!Auth::user()) { return abort(403); } $data = $request->validate([ 'title' => 'required|min:2|max:255', 'text' => 'required|min:5', 'categories.*' => 'integer|distinct', // TODO! Ha lesz adatb //'disable_comments' => 'nullable|boolean', //'hide_post' => 'nullable|boolean', 'attachment' => 'nullable|file|mimes:txt,doc,docx,pdf,xls|max:4096', 'thumbnail' => 'nullable|file|mimes:jpg,png|max:4096', ], [ 'title.required' => 'A cím megadása kötelező', 'text.min' => 'A bejegyzés szövege legalább :min karakter legyen' ]); // Ezek az adatok csak akkor érkeznek meg a request-ben, ha a user a böngészőben // kijelölte a checkbox-ot. A request->has() azt mondja meg, hogy az adott névvel // szerepel-e a request-ben az input mező, vagyis, hogy el lett-e küldve. $data['disable_comments'] = false; $data['hide_post'] = false; if ($request->has('disable_comments')) { $data['disable_comments'] = true; } if ($request->has('hide_post')) { $data['hide_post'] = true; } // Ha a requestben az attachment nevű inputon érkezett fájl, akkor lekérjük a fájlt // (a request->file() egy UploadedFile-t ad vissza, lásd api reference), aminek aztán // le tudjuk kérni a hash-elt nevét és az eredeti nevét (vagyis ha a kliens pl egy // valami.txt-t töltött fel, akkor az az eredeti név). // Ezután a public nevű disk-re (disk-eket lásd config/filesystems.php) rakjuk a put-tal // a fájlt, megadva az útvonalát és a tartalmát (file->get az UploadedFile tartalmát // adja meg) if ($request->hasFile('attachment')) { $file = $request->file('attachment'); $data['attachment_hash_name'] = $file->hashName(); $data['attachment_file_name'] = $file->getClientOriginalName(); Storage::disk('public')->put('attachments/' . $data['attachment_hash_name'], $file->get()); } // Ugyanaz kb, mint a fenti, csak itt nem tároljuk el az erdeti nevet, mivel nincs jelentősége // Az attachment-nél az oldalon megjelenik majd a fájlnév, ott azért van, de itt csak egy képet // töltünk be, és kész if ($request->hasFile('thumbnail')) { $file = $request->file('thumbnail'); $data['thumbnail_hash_name'] = $file->hashName(); Storage::disk('public')->put('thumbnails/' . $data['thumbnail_hash_name'], $file->get()); } // Debug //error_log(json_encode($data)); // Hozzá kell rendelni az aktuálisan autentikált usert a posthoz, mint szerző //$data['author_id'] = Auth::user()->id; $data['author_id'] = Auth::id(); // A postot létrehozzuk a data-val (ez egy tömb, amiben megvannak a kulcsok) $post = Post::create($data); // Kategóriák hozzárendelése a bejegyzéshez if (isset($data['categories'])) $post->categories()->attach($data['categories']); // Be flash-eljük a session-be a post_created logikai értéket, ez arra kell, hogy // eszerint feltételesen meg tudjunk jeleníteni egy alert-et, hogy a post létrehozása // sikerült $request->session()->flash('post_created', true); // Átirányítunk a létrehozott post oldalára, ennek két szerepe is van: // 1. a form nem küldhető el újra reloaddal // 2. innentől nem "fehér oldalt" látunk, hanem a létrejött bejegyzés oldalára navigálunk // A route-nak átadjuk a post-ot, a resource routing ebből ki fogja szedni az // "id" nevű mezőt, és az alapján fogja azonosítani a post-ot return redirect()->route('posts.show', $post); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Post $post) { return view('posts.show', compact('post')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, Post $post) { /*if ($post->author_id !== null && Auth::id() !== $post->author_id * 1) { return abort(403); }*/ $this->authorize('delete', $post); $deleted = $post->delete(); if (!$deleted) { return abort(500); } $request->session()->flash('post_deleted', $post); return redirect()->route('posts.index'); } public function attachment($id) { $post = Post::find($id); if ($post === null || $post->attachment_hash_name === null || $post->attachment_file_name === null) { return abort(404); } return Storage::disk('public')->download('attachments/' . $post->attachment_hash_name, $post->attachment_file_name); } }
dfb1c0bc34520ad16bb293bcbe4899782df1447f
[ "Markdown", "JavaScript", "PHP" ]
72
Markdown
szerveroldali/2021-22-1
6d7847d6208b5bea4aa1913ed95dd6c12644f5e4
447b55c0d37f4cdd7a540f3ab23afff1bacdef43
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2018/11/27 18:39 #@Author: zhangdelong #@File : anytextlog.py import os import os.path import string # txt_path = 'D:/youxinProjections/trafic-youxin/MobileNet_v1/obtain_qq_json_new/Crop_Ocr_txt/' # des_txt_path = 'D:/youxinProjections/trafic-youxin/MobileNet_v1/obtain_qq_json_new/1000_simple_OCRtxts/' txt_path = 'D:/cnnwork/pppp/old/' des_txt_path = 'D:/cnnwork/pppp/new/' txt_files = os.listdir(txt_path) # txt_files能得到该目录下的所有txt文件的文件名 def select_simples(): for txtfile in txt_files: if not os.path.isdir(txtfile): in_file = open(txt_path + txtfile, 'r') out_file = open(des_txt_path + txtfile, 'a') # 此处自动新建一个文件夹和txtfile的文件名相同,'a'为自动换行写入 lines = in_file.readlines() tempLine ='' tempIndex=0 for index in range(len(lines)): line = lines[index] str = int(line.split('.')[0].split(':')[2]) if str==00: str = 60 if index==0: tempIndex = str -1 if '[5.5.1]' in line: if str != tempIndex+1: out_file.write(tempLine) # 若包含子串,则将该行内容全部重新写入新的txt文件 out_file.write(line) # 若包含子串,则将该行内容全部重新写入新的txt文件 out_file.write('--------------------\n') # 若包含子串,则将该行内容全部重新写入新的txt文件 print(tempLine) print(line) tempIndex = str tempLine = line out_file.close() if __name__ == '__main__': select_simples() <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2018/9/12 16:04 #@Author: zhangdelong #@File : demo1.py name = input("Please input your name:") # 打印输出有下面三种方法,最常用的是第一种 print("hello {0}".format(name)) print("hello" + name) print("hello %s" %name)<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2019/1/23 15:09 #@Author: zhangdelong #@File : clienthps.py # 导入 socket、sys 模块 import socket import sys # 创建 socket 对象 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 获取本地主机名 host = socket.gethostname() # 设置端口号 port = 80 # 连接服务,指定主机和端口 s.connect((host, port)) while True: user_input = input('请输入要传输的信息:') s.sendall(bytes(user_input, encoding="utf-8")) msg = s.recv(1024) #recv方法用于接收数据,后面1024是每次接收数据的最大长度,可以自己设定 print (msg.decode('utf-8')) #打印服务器端传输过来的内容 s.close() #关闭连接<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2019/1/23 15:06 #@Author: zhangdelong #@File : serverhps.py # 导入 socket、sys 模块 import socket import sys import json import logging filelog = True path = r'messagelog.txt' logger = logging.getLogger('log') logger.setLevel(logging.DEBUG) # 调用模块时,如果错误引用,比如多次调用,每次会添加Handler,造成重复日志,这边每次都移除掉所有的handler,后面在重新添加,可以解决这类问题 while logger.hasHandlers(): for i in logger.handlers: logger.removeHandler(i) # file log formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') if filelog: fh = logging.FileHandler(path,encoding='utf-8') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) # console log formatter = logging.Formatter('%(message)s') ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) # 创建 socket 对象 serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # 获取本地主机名 host = socket.gethostname() port = 80 # 绑定端口号 serversocket.bind((host, port)) # 设置最大连接数,超过后排队 serversocket.listen(5) data = { 'code': "10000", 'msg': "2222" } while True: # 建立客户端连接 clientsocket, addr = serversocket.accept() # print("连接地址: %s" % str(addr)) logger.info("连接地址: %s" % str(addr)) content = clientsocket.recv(2048) if not content: break # 如果客户端传输过来的信息为空,关闭连接 logger.info(str(content.decode('utf-8'))) # clientsocket.send(Data) # 把客户端传来的信息传给客户端 # print("接收到的内容: %s" % str(content.decode('utf-8'))) # logging.info(content) msg = json.dumps(data) clientsocket.send(msg.encode('utf-8')) clientsocket.close() #关闭套接字,可以把close写在循环外面,这样就可以一直通信,直到客户端主动断开
3db162acb02316c0c6926c3267a32c809129c94d
[ "Python" ]
4
Python
Dylandelon/myfirst
2e0da758a77ec61d5d1455785ba9aec293e50eb5
92738a59e2d9641e0358b8daa7e93a95f4e5d356